Operational Decision Framework

This example demonstrates how to use the framework module to create operational decision rules for real-world applications like P2P lending.

The framework translates conformal predictions into actionable decisions:

Setup

Create a lending-like scenario with synthetic data.

Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

from conformalpy.classifier import ConformalClassifier
from conformalpy.framework import (
    # Impact analysis
    CostMatrix,
    automation_rate,
    # Zones
    classify_zones,
    compute_expected_cost,
    compute_impact_summary,
    # Decision rules
    create_lending_framework,
    decision_proportions,
    zone_proportions,
    zone_summary,
)
from conformalpy.nonconformity.classification import lac_nonconformity

# Generate synthetic lending data
np.random.seed(42)
X, y = make_classification(
    n_samples=5000,
    n_features=10,
    n_informative=5,
    n_classes=2,
    weights=[0.85, 0.15],  # 15% default rate
    random_state=42,
)

# Split data
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 model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# Conformal classifier
conf_clf = ConformalClassifier(
    model=model,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
)
conf_clf.calibrate(X_cal, y_cal)

# Get predictions
prediction_sets = conf_clf.predict(X_test)
y_pred = model.predict(X_test)

print(f"Test samples: {len(y_test)}")
print(f"Default rate: {y_test.mean():.1%}")
print(f"Model accuracy: {(y_pred == y_test).mean():.1%}")
Test samples: 1000
Default rate: 16.6%
Model accuracy: 94.9%

Zone Classification

Classify samples into operational zones.

Code
zones = classify_zones(prediction_sets, y_test)
zone_props = zone_proportions(prediction_sets, y_test)

print("\nZone Distribution:")
print("-" * 30)
for zone, prop in zone_props.items():
    print(f"  {zone:15} {prop:6.1%}")

Zone Distribution:
------------------------------
  safe             89.5%
  uncertain         0.0%
  problematic       3.0%
  unclassified      7.5%

Visualize Zone Distribution

Code
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 in zip(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()

Zone Summary with Accuracy

Compute per-zone metrics including accuracy.

Code
summary = zone_summary(prediction_sets, y_test, y_pred)

print("\nZone Summary:")
print("-" * 50)
print(f"{'Zone':<15} {'Count':>8} {'Coverage':>10} {'Accuracy':>10}")
print("-" * 50)
for zone in zones_order:
    count = summary["counts"][zone]
    cov = summary["coverage_per_zone"].get(zone, float("nan"))
    acc = summary["accuracy_per_zone"].get(zone, float("nan"))
    cov_str = f"{cov:.1%}" if not np.isnan(cov) else "N/A"
    acc_str = f"{acc:.1%}" if not np.isnan(acc) else "N/A"
    print(f"{zone:<15} {count:>8} {cov_str:>10} {acc_str:>10}")

Zone Summary:
--------------------------------------------------
Zone               Count   Coverage   Accuracy
--------------------------------------------------
safe                 895     100.0%     100.0%
uncertain              0        N/A        N/A
problematic           30       0.0%       0.0%
unclassified          75       0.0%      72.0%

Apply Decision Rules

Use the lending framework to make operational decisions.

Code
framework = create_lending_framework()
decisions = framework.apply(prediction_sets, y_pred)

dec_props = decision_proportions(prediction_sets, y_pred, framework)
auto_rate = automation_rate(prediction_sets, y_pred, framework)

print("\nDecision Distribution:")
print("-" * 30)
for dec, prop in dec_props.items():
    if prop > 0:
        print(f"  {dec:15} {prop:6.1%}")

print(f"\nAutomation rate: {auto_rate:.1%}")

Decision Distribution:
------------------------------
  auto_approve     81.9%
  auto_reject      10.6%
  manual_review     7.5%

Automation rate: 92.5%

Visualize Decisions

Code
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 in zip(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 costs
costs = 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-off
fig, (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()

Comprehensive Impact Summary

Get all metrics in one call.

Code
conf_clf.alpha = 0.10
conf_clf.calibrate(X_cal, y_cal)
pred_sets = conf_clf.predict(X_test)

impact = compute_impact_summary(pred_sets, y_pred, y_test, costs, framework)

print("\nImpact Summary:")
print("=" * 50)
print(f"Samples: {impact['n_samples']}")
print(f"Overall accuracy: {impact['overall_accuracy']:.1%}")
print(f"Automated accuracy: {impact['automated_accuracy']:.1%}")
print(f"Automation rate: {impact['automation_rate']:.1%}")
print(f"Cost per sample: ${impact['cost_analysis']['cost_per_sample']:.2f}")

Impact Summary:
==================================================
Samples: 1000
Overall accuracy: 94.9%
Automated accuracy: 96.8%
Automation rate: 92.5%
Cost per sample: $-52.27

Interpretation

Key takeaways from this framework:

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