# Colors matching the PDP modulecolors = {"SC": "#2ecc71", # Green"SI": "#e74c3c", # Red"TS0": "#3498db", # Blue"TS1": "#9b59b6", # Purple"Empty": "#95a5a6", # Gray}fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))# Pie chartlabels = [k for k in props.keys() if props[k] >0]sizes = [props[k] for k in labels]pie_colors = [colors[k] for k in labels]ax1.pie(sizes, labels=labels, colors=pie_colors, autopct="%1.1f%%", startangle=90)ax1.set_title("Outcome Distribution (α=0.10)")# Bar chartoutcomes_order = ["SC", "SI", "TS0", "TS1", "Empty"]bar_heights = [props[k] for k in outcomes_order]bar_colors = [colors[k] for k in outcomes_order]bars = ax2.bar(outcomes_order, bar_heights, color=bar_colors)ax2.set_ylabel("Proportion")ax2.set_xlabel("Outcome")ax2.set_title("Outcome Distribution (α=0.10)")ax2.set_ylim(0, 1)# Add value labelsfor bar, height inzip(bars, bar_heights): ax2.text(bar.get_x() + bar.get_width() /2, height +0.02, f"{height:.1%}", ha="center", va="bottom")plt.tight_layout()plt.show()
Outcome Summary:
Total samples: 400
Confidence rate (SC+SI): 60.8%
Uncertainty rate (TS0+TS1): 39.2%
Accuracy when confident: 86.4%
Coverage: 91.8%
Compare Different Alpha Values
See how outcomes change with different confidence levels.
Code
alpha_values = [0.05, 0.10, 0.15, 0.20]results = []for alpha in alpha_values: conf_clf.alpha = alpha conf_clf.calibrate(X_cal, y_cal) pred_sets = conf_clf.predict(X_test) props = outcome_proportions(pred_sets, y_test) props["alpha"] = alpha results.append(props)# Plotfig, ax = plt.subplots(figsize=(10, 6))x = np.arange(len(alpha_values))width =0.15for i, outcome inenumerate(["SC", "SI", "TS0", "TS1"]): heights = [r[outcome] for r in results] offset = (i -1.5) * width ax.bar(x + offset, heights, width, label=outcome, color=colors[outcome])ax.set_xlabel("Alpha (α)")ax.set_ylabel("Proportion")ax.set_title("Outcome Distribution by Confidence Level")ax.set_xticks(x)ax.set_xticklabels([f"α={a}"for a in alpha_values])ax.legend()ax.set_ylim(0, 1)plt.tight_layout()plt.show()
SI Error Analysis
Single Incorrect (SI) outcomes are the failure mode of conformal prediction: the model was confident but wrong. Understanding the breakdown helps identify which types of errors dominate.
Code
# Reset to α=0.10 for SI analysisconf_clf.alpha =0.10conf_clf.calibrate(X_cal, y_cal)prediction_sets = conf_clf.predict(X_test)# Get SI error breakdownsi_result = si_error_analysis(prediction_sets, y_test, class_names={0: "negative", 1: "positive"})print("\n"+"="*50)print("SI Error Analysis")print("="*50)print(f"Total SI errors: {si_result['n_si']} ({si_result['si_rate']:.1%} of samples)")print("\nBreakdown:")print(f" False positives (pred=1, true=0): {si_result['confusion']['false_positive']}")print(f" False negatives (pred=0, true=1): {si_result['confusion']['false_negative']}")
==================================================
SI Error Analysis
==================================================
Total SI errors: 33 (8.2% of samples)
Breakdown:
False positives (pred=1, true=0): 13
False negatives (pred=0, true=1): 20
SI Error Report
Generate a formatted text report similar to sklearn’s classification_report.
SI Error Analysis
=================
Total SI errors: 33 (8.25% of samples)
By predicted class:
Predicted negative: 20 (60.61%)
Predicted positive: 13 (39.39%)
Confusion breakdown:
False negatives (pred=negative, true=positive): 20 (60.61%)
False positives (pred=positive, true=negative): 13 (39.39%)
Visualize SI Error Breakdown
See which type of confident-but-wrong error is more common.
Code
if si_result["n_si"] >0: fig, ax = plt.subplots(figsize=(8, 4)) error_types = ["False Negative\n(pred=0, true=1)", "False Positive\n(pred=1, true=0)"] error_counts = [ si_result["confusion"]["false_negative"], si_result["confusion"]["false_positive"], ] error_colors = ["#e74c3c", "#c0392b"] # Different red shades bars = ax.bar(error_types, error_counts, color=error_colors, edgecolor="black") ax.set_ylabel("Count") ax.set_title("SI Error Breakdown: Confident but Wrong Predictions")# Add value labelsfor bar, count inzip(bars, error_counts): prop = count / si_result["n_si"] *100 ax.text( bar.get_x() + bar.get_width() /2, bar.get_height() +0.5,f"{count} ({prop:.0f}%)", ha="center", va="bottom", ) plt.tight_layout() plt.show()else:print("No SI errors to visualize.")
Singleton Confusion Matrix
The singleton confusion matrix provides a complete breakdown of all singleton (confident) predictions, including both SC (correct) and SI (incorrect). This answers: “When the model is confident, how is it performing?”