This example demonstrates how to quantify the operational value of using conformal prediction compared to full automation with point predictions.
The analysis compares three scenarios:
- Baseline: Full automation without CP - all predictions automated
- CP + Perfect Review: CP with perfect human review on uncertain cases
- CP + Realistic Review: CP with realistic human accuracy on uncertain cases
This helps answer: βIs conformal prediction worth implementing?β
Setup
Create synthetic data and train a conformal classifier.
Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from conformalpy.classifier import ConformalClassifier
from conformalpy.framework import (
CostMatrix,
compute_cp_value_analysis,
compute_human_accuracy_sensitivity,
cp_value_report,
plot_cp_value_comparison,
plot_human_accuracy_sensitivity,
)
from conformalpy.nonconformity.classification import lac_nonconformity
# Generate synthetic data with class imbalance (like P2P lending)
np.random.seed(42)
X, y = make_classification(
n_samples=2000,
n_features=10,
n_informative=5,
n_classes=2,
weights=[0.75, 0.25], # 25% positive class (e.g., defaults)
random_state=42,
)
# Split: train / calibration / test
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, random_state=42)
X_cal, X_test, y_cal, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)
# Train base model
model = LogisticRegression(random_state=42, max_iter=1000)
model.fit(X_train, y_train)
# Get point predictions
y_pred = model.predict(X_test)
# Create and calibrate conformal classifier
conf_clf = ConformalClassifier(
model=model,
alpha=0.10, # 90% confidence level
nonconformity_function=lac_nonconformity,
)
conf_clf.calibrate(X_cal, y_cal)
# Get prediction sets
prediction_sets = conf_clf.predict(X_test)
print(f"Test samples: {len(y_test)}")
print(f"Positive class rate: {y_test.mean():.1%}")
print(f"Model accuracy: {(y_pred == y_test).mean():.1%}")
Test samples: 400
Positive class rate: 28.2%
Model accuracy: 74.0%
Define Cost Matrix
For P2P lending, false negatives (approved defaults) are typically much more costly than false positives (rejected good loans).
Code
costs = CostMatrix(
true_negative_cost=0, # Correctly approved good loan
true_positive_cost=0, # Correctly rejected default
false_negative_cost=1000, # Approved default - principal loss!
false_positive_cost=100, # Rejected good loan - opportunity cost
manual_review_cost=50, # Cost to manually review a loan
)
print("Cost Matrix:")
print(f" FN cost (approved default): ${costs.false_negative_cost}")
print(f" FP cost (rejected good loan): ${costs.false_positive_cost}")
print(f" Review cost: ${costs.manual_review_cost}")
print(f" Cost ratio FN/FP: {costs.false_negative_cost / costs.false_positive_cost:.1f}x")
Cost Matrix:
FN cost (approved default): $1000
FP cost (rejected good loan): $100
Review cost: $50
Cost ratio FN/FP: 10.0x
CP Value Analysis
Compare the three operational scenarios.
Code
analysis = compute_cp_value_analysis(
prediction_sets,
y_test,
y_pred,
costs,
human_accuracy=0.85, # Assume reviewers are 85% accurate
)
print("\n" + "=" * 60)
print("CP VALUE ANALYSIS RESULTS")
print("=" * 60)
for scenario in analysis["scenarios"]:
print(f"\n{scenario.name}:")
print(f" Automation rate: {scenario.automation_rate:.1%}")
print(f" Accuracy: {scenario.accuracy:.1%}")
print(f" FN errors: {scenario.fn_count}")
print(f" FP errors: {scenario.fp_count}")
print(f" Total cost: ${scenario.total_cost:,.0f}")
print(f"\n{'=' * 60}")
print("VALUE OF CONFORMAL PREDICTION")
print(f"{'=' * 60}")
print(f"Cost reduction: ${analysis['delta_cost']:,.0f} ({analysis['delta_cost_pct']:.1%})")
print(f"FN errors avoided: {analysis['errors_avoided_fn']}")
print(f"FP errors avoided: {analysis['errors_avoided_fp']}")
print(f"Breakeven human accuracy: {analysis['breakeven_accuracy']:.1%}")
============================================================
CP VALUE ANALYSIS RESULTS
============================================================
Baseline (Full Automation):
Automation rate: 100.0%
Accuracy: 74.0%
FN errors: 64
FP errors: 40
Total cost: $68,000
CP + Perfect Review:
Automation rate: 63.0%
Accuracy: 91.8%
FN errors: 23
FP errors: 10
Total cost: $31,400
CP + Realistic Review (85%):
Automation rate: 63.0%
Accuracy: 86.2%
FN errors: 35
FP errors: 20
Total cost: $44,825
============================================================
VALUE OF CONFORMAL PREDICTION
============================================================
Cost reduction: $23,175 (34.1%)
FN errors avoided: 29
FP errors avoided: 20
Breakeven human accuracy: 59.1%
Text Report
Generate a formatted text report.
Code
print("\n")
print(cp_value_report(prediction_sets, y_test, y_pred, costs, human_accuracy=0.85))
CP Value Analysis\n=================\nSamples: 400\nHuman reviewer accuracy: 85.00%\n\nScenario Comparison:\n----------------------------------------------------------------------\nScenario Auto% Accuracy FN FP Cost\n----------------------------------------------------------------------\nBaseline (Full Automation) 100.00% 74.00% 64 40 68,000\nCP + Perfect Review 63.00% 91.75% 23 10 31,400\nCP + Realistic Review (85%) 63.00% 86.20% 35 20 44,825\n----------------------------------------------------------------------\n\nValue of Conformal Prediction:\n Cost reduction: $23,175 (34.08%)\n Cost per sample reduction: $57.94\n FN errors avoided: 29\n FP errors avoided: 20\n Breakeven human accuracy: 59.13%\n ROI: 318.92%
Visualize Scenario Comparison
Bar chart comparing the three scenarios.
Code
fig, ax = plot_cp_value_comparison(
analysis, show_breakdown=True, title="Cost Comparison: Full Automation vs CP with Human Review"
)
plt.show()
Sensitivity Analysis
How does the total cost vary with human reviewer accuracy?
Code
sensitivity = compute_human_accuracy_sensitivity(
prediction_sets,
y_test,
y_pred,
costs,
accuracy_range=(0.50, 1.00),
n_points=25,
)
fig, ax = plot_human_accuracy_sensitivity(
sensitivity, show_baseline=True, show_breakeven=True, title="Sensitivity: Total Cost vs Human Reviewer Accuracy"
)
plt.show()
Key Metrics Summary
Summarize the key findings.
Code
print("\n" + "=" * 60)
print("KEY FINDINGS")
print("=" * 60)
print(f"""
1. AUTOMATION REDUCTION
- Baseline: 100% automated
- With CP: {analysis["realistic_review"].automation_rate:.1%} automated
- Two-sets requiring review: {100 - analysis["realistic_review"].automation_rate * 100:.1f}%
2. ERROR REDUCTION
- FN errors reduced: {analysis["baseline"].fn_count} -> {analysis["realistic_review"].fn_count} ({analysis["errors_avoided_fn"]} avoided)
- FP errors reduced: {analysis["baseline"].fp_count} -> {analysis["realistic_review"].fp_count} ({analysis["errors_avoided_fp"]} avoided)
3. COST IMPACT
- Baseline cost: ${analysis["baseline"].total_cost:,.0f}
- CP cost: ${analysis["realistic_review"].total_cost:,.0f}
- Savings: ${analysis["delta_cost"]:,.0f} ({analysis["delta_cost_pct"]:.1%})
4. BREAKEVEN ANALYSIS
- Breakeven accuracy: {analysis["breakeven_accuracy"]:.1%}
- CP is profitable if human reviewers are better than {analysis["breakeven_accuracy"]:.0%} accurate
""")
============================================================
KEY FINDINGS
============================================================
1. AUTOMATION REDUCTION
- Baseline: 100% automated
- With CP: 63.0% automated
- Two-sets requiring review: 37.0%
2. ERROR REDUCTION
- FN errors reduced: 64 -> 35 (29 avoided)
- FP errors reduced: 40 -> 20 (20 avoided)
3. COST IMPACT
- Baseline cost: $68,000
- CP cost: $44,825
- Savings: $23,175 (34.1%)
4. BREAKEVEN ANALYSIS
- Breakeven accuracy: 59.1%
- CP is profitable if human reviewers are better than 59% accurate
Interpretation
Key insights from CP value analysis:
When is CP valuable?
- When FN costs >> FP costs (asymmetric risk)
- When the model struggles with a subset of cases (uncertainty is informative)
- When human review cost is manageable relative to error costs
Breakeven accuracy:
- If reviewers are BELOW breakeven accuracy, CP is not cost-effective
- If reviewers are ABOVE breakeven accuracy, CP saves money
- Lower breakeven = more robust value proposition
Practical considerations:
- Start with a pilot to estimate actual human reviewer accuracy
- Track the proportion of two-sets to size the review team
- Monitor SI rate - high SI indicates model calibration issues