zone_colors = {"safe": "#2ecc71","uncertain": "#f39c12","problematic": "#e74c3c","unclassified": "#95a5a6",}fig, ax = plt.subplots(figsize=(8, 6))zones_order = ["safe", "uncertain", "problematic", "unclassified"]heights = [zone_props[z] for z in zones_order]colors = [zone_colors[z] for z in zones_order]bars = ax.bar(zones_order, heights, color=colors)ax.set_ylabel("Proportion")ax.set_title("Decision Zone Distribution (α=0.10)")ax.set_ylim(0, 1)for bar, h inzip(bars, heights):if h >0.01: ax.text(bar.get_x() + bar.get_width() /2, h +0.02, f"{h:.1%}", ha="center", va="bottom")plt.tight_layout()plt.show()
decision_colors = {"auto_approve": "#27ae60","auto_reject": "#c0392b","manual_review": "#f39c12","audit": "#8e44ad","undefined": "#95a5a6",}fig, ax = plt.subplots(figsize=(10, 6))dec_order = ["auto_approve", "auto_reject", "manual_review", "audit"]heights = [dec_props.get(d, 0) for d in dec_order]colors = [decision_colors[d] for d in dec_order]labels = ["Auto-Approve", "Auto-Reject", "Manual Review", "Audit"]bars = ax.bar(labels, heights, color=colors)ax.set_ylabel("Proportion")ax.set_title(f"Decision Distribution (Automation Rate: {auto_rate:.1%})")ax.set_ylim(0, 1)for bar, h inzip(bars, heights):if h >0.01: ax.text(bar.get_x() + bar.get_width() /2, h +0.02, f"{h:.1%}", ha="center", va="bottom")plt.tight_layout()plt.show()
Cost-Benefit Analysis
Define costs and compute expected impact.
Code
# Realistic lending costscosts = CostMatrix( true_negative_cost=-100, # Profit from good loan true_positive_cost=0, # Avoided loss from rejected default false_positive_cost=50, # Opportunity cost of rejecting good borrower false_negative_cost=1000, # Loss from approved default manual_review_cost=25, # Labor cost for manual review audit_cost=100, # Investigation cost)cost_result = compute_expected_cost(prediction_sets, y_pred, y_test, costs, framework)print("\nCost Analysis:")print("-"*40)print(f"Total cost: ${cost_result['total_cost']:,.0f}")print(f"Cost per sample: ${cost_result['cost_per_sample']:.2f}")print("\nCost Breakdown by Outcome:")for outcome, cost in cost_result["cost_by_outcome"].items():if cost !=0:print(f" {outcome:20} ${cost:>10,.0f}")
Cost Analysis:
----------------------------------------
Total cost: $-52,275
Cost per sample: $-52.27
Cost Breakdown by Outcome:
true_negative $ -79,400
false_positive $ 250
false_negative $ 25,000
manual_review $ 1,875
Compare Different Alpha Values
See how automation vs cost trade-off changes with confidence level.
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) auto_rate = automation_rate(pred_sets, y_pred) cost = compute_expected_cost(pred_sets, y_pred, y_test, costs) results.append( {"alpha": alpha,"automation_rate": auto_rate,"cost_per_sample": cost["cost_per_sample"], } )# Plot trade-offfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))alphas = [r["alpha"] for r in results]auto_rates = [r["automation_rate"] for r in results]costs_per_sample = [r["cost_per_sample"] for r in results]ax1.plot(alphas, auto_rates, "o-", linewidth=2, markersize=8)ax1.set_xlabel("Alpha (α)")ax1.set_ylabel("Automation Rate")ax1.set_title("Automation Rate vs Confidence Level")ax1.grid(True, alpha=0.3)ax2.plot(alphas, costs_per_sample, "o-", linewidth=2, markersize=8, color="red")ax2.set_xlabel("Alpha (α)")ax2.set_ylabel("Cost per Sample ($)")ax2.set_title("Expected Cost vs Confidence Level")ax2.grid(True, alpha=0.3)plt.tight_layout()plt.show()
Zones: - Safe zone (SC) -> High confidence, correct predictions - Uncertain zone (TS) -> Model hedges, needs review - Problematic zone (SI) -> Model failures, need investigation
Decisions: - Auto-approve/reject saves labor cost - Manual review catches uncertain cases - Trade-off between automation and accuracy
Costs: - Higher α -> More automation but higher error risk - Lower α -> More manual review but safer - Optimal α depends on cost structure
Recommendations: - Set α based on business cost tolerance - Monitor SI rate for model degradation - Use zones to prioritize review queue