# Create figure with two subplots side by side
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# ROC Curve
fpr, tpr, _ = roc_curve(y_test, y_pred)
roc_auc = auc(fpr, tpr)
ax1.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (AUC = {roc_auc:.2f})')
ax1.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
ax1.set_xlim([0.0, 1.0])
ax1.set_ylim([0.0, 1.05])
ax1.set_xlabel('False Positive Rate')
ax1.set_ylabel('True Positive Rate')
ax1.set_title('Receiver Operating Characteristic (ROC)')
ax1.legend(loc="lower right")
ax1.grid(True)
# Precision-Recall Curve
precision, recall, _ = precision_recall_curve(y_test, y_pred)
pr_auc = average_precision_score(y_test, y_pred)
# Calculate baseline for PR curve (proportion of positive class)
baseline = np.mean(y_test)
ax2.plot(recall, precision, color='darkgreen', lw=2, label=f'PR curve (AP = {pr_auc:.2f})')
ax2.axhline(y=baseline, color='navy', linestyle='--', label=f'Baseline ({baseline:.2f})')
ax2.set_xlim([0.0, 1.0])
ax2.set_ylim([0.0, 1.05])
ax2.set_xlabel('Recall')
ax2.set_ylabel('Precision')
ax2.set_title('Precision-Recall Curve')
ax2.legend(loc="lower left")
ax2.grid(True)
plt.tight_layout()
plt.show()
return roc_auc, pr_auc, baseline
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from sklearn.calibration import calibration_curve
def compute_ece(y_true, y_pred_proba, n_bins=12):
"""
Computes Expected Calibration Error (ECE).
"""
prob_true, prob_pred = calibration_curve(y_true, y_pred_proba, n_bins=n_bins, strategy="quantile")
ece = 0
for i in range(len(prob_true)):
bin_size = len([p for p in y_pred_proba if prob_pred[i] <= p < (prob_pred[i] + 1 / n_bins)])
ece += bin_size * abs(prob_true[i] - prob_pred[i])
ece /= len(y_true)
return ece
def plot_calibration_side_by_side(
y_val, val_proba, y_test, test_proba, title="Calibration Curves",
overconfident_color="rgba(200,100,0,0.3)", underconfident_color="rgba(0, 100, 200,0.3)",
model_color="rgba(250, 30, 70, 0.9)"
):
"""
Plots calibration curves for validation and test datasets side by side.
Parameters:
y_val: True labels for the validation set.
val_proba: Predicted probabilities for the validation set.
y_test: True labels for the test set.
test_proba: Predicted probabilities for the test set.
title: Title of the combined plot.
overconfident_color: Color for the over-confident region.
underconfident_color: Color for the under-confident region.
model_color: Color for the model calibration curve.
"""
# Compute calibration curve and ECE for validation and test sets
val_prob_true, val_prob_pred = calibration_curve(y_val, val_proba, n_bins=12, strategy="quantile")
test_prob_true, test_prob_pred = calibration_curve(y_test, test_proba, n_bins=12, strategy="quantile")
val_ece = compute_ece(y_val, val_proba, n_bins=12)
test_ece = compute_ece(y_test, test_proba, n_bins=12)
# Create subplots
fig = make_subplots(rows=1, cols=2, subplot_titles=("Validation Set", "Test Set"))
# Add over-/under-confidence zones for both subplots
for col in [1, 2]:
fig.add_shape(
type="path",
path="M0,0 L1,0 L1,1 Z",
fillcolor=overconfident_color,
line=dict(width=0),
layer="below",
xref=f"x{col}",
yref=f"y{col}"
)
fig.add_trace(
go.Scatter(
x=[None], y=[None],
mode='markers',
marker=dict(size=15, color=overconfident_color),
showlegend=(col == 1), # Only show legend for the first subplot
name='Over-confident region'
),
row=1, col=col
)
fig.add_shape(
type="path",
path="M0,0 L0,1 L1,1 Z",
fillcolor=underconfident_color,
line=dict(width=0),
layer="below",
xref=f"x{col}",
yref=f"y{col}"
)
fig.add_trace(
go.Scatter(
x=[None], y=[None],
mode='markers',
marker=dict(size=15, color=underconfident_color),
showlegend=(col == 1), # Only show legend for the first subplot
name='Under-confident region'
),
row=1, col=col
)
# Add perfectly calibrated line for both subplots
for col in [1, 2]:
fig.add_trace(
go.Scatter(
x=[0, 1], y=[0, 1],
mode="lines",
line=dict(dash="dash", color="black"),
name="Perfectly calibrated",
showlegend=(col == 1) # Only show legend for the first subplot
),
row=1, col=col
)
# Add calibration curves for validation and test sets
fig.add_trace(
go.Scatter(
x=val_prob_pred, y=val_prob_true,
mode="lines+markers",
line=dict(color=model_color, width=4),
marker=dict(size=12),
name="Model (Validation)",
showlegend=True
),
row=1, col=1
)
fig.add_trace(
go.Scatter(
x=test_prob_pred, y=test_prob_true,
mode="lines+markers",
line=dict(color=model_color, width=4),
marker=dict(size=12),
name="Model (Test)",
showlegend=True
),
row=1, col=2
)
# Add ECE annotations
fig.add_annotation(
x=0.05, y=0.95,
xref="x1", yref="y1",
xanchor="left", yanchor="top",
text=f"<b>Expected Calibration Error:</b> {val_ece:.3f}",
showarrow=False,
font=dict(size=14, color="black")
)
fig.add_annotation(
x=0.05, y=0.95,
xref="x2", yref="y2",
xanchor="left", yanchor="top",
text=f"<b>Expected Calibration Error:</b> {test_ece:.3f}",
showarrow=False,
font=dict(size=14, color="black")
)
# Update layout
fig.update_layout(
title=title,
xaxis_title="Mean predicted probability",
yaxis_title="Fraction of positives (True probability)",
xaxis=dict(range=[0, 1]),
yaxis=dict(range=[0, 1]),
xaxis2=dict(range=[0, 1]),
yaxis2=dict(range=[0, 1]),
width=1200,
height=600,
template="simple_white",
legend=dict(
yanchor="bottom",
y=0.8,
xanchor="right",
x=1.4
)
)
# Show the figure
fig.show()