Accuracy-Coverage Curve for Selective Prediction

This example demonstrates how to use the accuracy-coverage curve to analyze the trade-off between automation rate and prediction accuracy in conformal prediction-based selective prediction systems.

Selective Prediction refers to systems where predictions are only made when the model is sufficiently confident. For conformal prediction, this means only acting on singleton prediction sets (predictions containing exactly one class).

The key trade-off is:

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.evaluation import (
    compute_accuracy_coverage_curve,
    compute_accuracy_coverage_from_sets,
    plot_accuracy_coverage_curve,
)
from conformalpy.nonconformity.classification import lac_nonconformity

# Generate synthetic data with some class imbalance
np.random.seed(42)
X, y = make_classification(
    n_samples=2000,
    n_features=10,
    n_informative=5,
    n_classes=2,
    weights=[0.65, 0.35],
    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)

# Create conformal classifier
conf_clf = ConformalClassifier(
    model=model,
    alpha=0.10,  # 90% confidence level
    nonconformity_function=lac_nonconformity,
)

# Get baseline accuracy
y_pred_baseline = model.predict(X_test)
baseline_acc = np.mean(y_pred_baseline == y_test)

print(f"Test samples: {len(y_test)}")
print(f"Baseline model accuracy (full automation): {baseline_acc:.1%}")
Test samples: 400
Baseline model accuracy (full automation): 74.5%

Compute Accuracy-Coverage Curve

The curve shows how accuracy varies with the automation rate (coverage) as we change the confidence level (alpha).

Code
curve = compute_accuracy_coverage_curve(
    conf_clf,
    X_cal,
    y_cal,
    X_test,
    y_test,
    alpha_range=(0.01, 0.30),
    n_points=30,
)

print("\nAccuracy-Coverage Curve Data:")
print(f"  Alpha range: [{curve['alpha'].min():.2f}, {curve['alpha'].max():.2f}]")
print(f"  Coverage range: [{curve['coverage'].min():.1%}, {curve['coverage'].max():.1%}]")
print(f"  Accuracy range: [{np.nanmin(curve['accuracy']):.1%}, {np.nanmax(curve['accuracy']):.1%}]")
print(f"  Baseline accuracy: {curve['baseline_accuracy']:.1%}")

Accuracy-Coverage Curve Data:
  Alpha range: [0.01, 0.30]
  Coverage range: [21.2%, 98.5%]
  Accuracy range: [74.9%, 97.6%]
  Baseline accuracy: 74.5%

Plot the Curve

Visualize the trade-off between coverage (automation) and accuracy.

Code
fig, ax = plot_accuracy_coverage_curve(
    curve,
    show_baseline=True,
    show_alpha_labels=True,
    n_alpha_labels=5,
    title="Selective Prediction: Accuracy vs Coverage",
)
plt.show()

Understanding the Curve

The curve demonstrates several key insights:

  • Baseline point (red star): Full automation using point predictions
  • Curve points: Performance at different confidence levels
  • Lower coverage (left): More selective, typically higher accuracy
  • Higher coverage (right): Less selective, approaches baseline

A good conformal predictor should show accuracy above the baseline at all coverage levels.

Code
# Show specific operating points
print("\nOperating Points:")
print("-" * 60)
print(f"{'Alpha':>8} {'Coverage':>12} {'Accuracy':>12} {'n_singletons':>12}")
print("-" * 60)

for i in [0, 9, 19, 29]:  # Sample a few points
    if i < len(curve["alpha"]):
        alpha = curve["alpha"][i]
        cov = curve["coverage"][i]
        acc = curve["accuracy"][i]
        n_sing = curve["n_singletons"][i]
        print(f"{alpha:8.2f} {cov:12.1%} {acc:12.1%} {n_sing:12d}")

print("-" * 60)
print(f"{'Baseline':>8} {1.0:12.1%} {baseline_acc:12.1%} {len(y_test):12d}")

Operating Points:
------------------------------------------------------------
   Alpha     Coverage     Accuracy n_singletons
------------------------------------------------------------
    0.01        21.2%        97.6%           85
    0.10        61.3%        86.9%          245
    0.20        86.8%        77.8%          347
    0.30        91.0%        76.9%          364
------------------------------------------------------------
Baseline       100.0%        74.5%          400

Using Pre-computed Prediction Sets

If you’ve already computed prediction sets at multiple alpha values, use compute_accuracy_coverage_from_sets for efficiency.

Code
# Pre-compute prediction sets at specific alphas
alpha_values = [0.05, 0.10, 0.15, 0.20, 0.25]
sets_by_alpha = []

for alpha in alpha_values:
    conf_clf.alpha = alpha
    conf_clf.calibrate(X_cal, y_cal)
    sets_by_alpha.append(conf_clf.predict(X_test))

# Get point predictions
y_pred = model.predict(X_test)

# Compute curve from sets
curve_from_sets = compute_accuracy_coverage_from_sets(sets_by_alpha, y_test, y_pred, alpha_values)

print("\nCurve from Pre-computed Sets:")
for i, alpha in enumerate(alpha_values):
    cov = curve_from_sets["coverage"][i]
    acc = curve_from_sets["accuracy"][i]
    print(f"  α={alpha:.2f}: Coverage={cov:.1%}, Accuracy={acc:.1%}")

Curve from Pre-computed Sets:
  α=0.05: Coverage=40.2%, Accuracy=90.7%
  α=0.10: Coverage=61.3%, Accuracy=86.9%
  α=0.15: Coverage=75.8%, Accuracy=80.5%
  α=0.20: Coverage=86.8%, Accuracy=77.8%
  α=0.25: Coverage=95.0%, Accuracy=76.1%

Compare Different Models

The accuracy-coverage curve is useful for comparing different models or nonconformity functions.

Code
from sklearn.ensemble import GradientBoostingClassifier

# Train a GradientBoosting model
gb_model = GradientBoostingClassifier(n_estimators=50, random_state=42)
gb_model.fit(X_train, y_train)

gb_clf = ConformalClassifier(
    model=gb_model,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
)

# Compute curves for both models
curve_lr = compute_accuracy_coverage_curve(
    conf_clf, X_cal, y_cal, X_test, y_test, alpha_range=(0.01, 0.30), n_points=20
)
curve_gb = compute_accuracy_coverage_curve(gb_clf, X_cal, y_cal, X_test, y_test, alpha_range=(0.01, 0.30), n_points=20)

# Plot comparison
fig, ax = plt.subplots(figsize=(10, 6))

# Filter NaN values
lr_valid = ~np.isnan(curve_lr["accuracy"])
gb_valid = ~np.isnan(curve_gb["accuracy"])

ax.plot(
    curve_lr["coverage"][lr_valid],
    curve_lr["accuracy"][lr_valid],
    "b-o",
    markersize=4,
    label=f"Logistic Regression (baseline: {curve_lr['baseline_accuracy']:.1%})",
)
ax.plot(
    curve_gb["coverage"][gb_valid],
    curve_gb["accuracy"][gb_valid],
    "g-s",
    markersize=4,
    label=f"Gradient Boosting (baseline: {curve_gb['baseline_accuracy']:.1%})",
)

# Add baseline points
ax.scatter([1.0], [curve_lr["baseline_accuracy"]], color="blue", s=100, marker="*", zorder=5)
ax.scatter([1.0], [curve_gb["baseline_accuracy"]], color="green", s=100, marker="*", zorder=5)

ax.set_xlabel("Coverage (automation rate)")
ax.set_ylabel("Accuracy on automated decisions")
ax.set_title("Model Comparison: Accuracy-Coverage Curves")
ax.legend(loc="lower right")
ax.grid(True, alpha=0.3)
ax.set_xlim(0, 1.05)

plt.tight_layout()
plt.show()

Area Under the Curve (AUC-AC)

The area under the accuracy-coverage curve can serve as a single summary metric for selective prediction performance.

Code
def compute_auc_ac(curve_data):
    """Compute area under accuracy-coverage curve."""
    valid = ~np.isnan(curve_data["accuracy"])
    coverage = curve_data["coverage"][valid]
    accuracy = curve_data["accuracy"][valid]

    # Sort by coverage
    sort_idx = np.argsort(coverage)
    coverage = coverage[sort_idx]
    accuracy = accuracy[sort_idx]

    # Trapezoidal integration
    return np.trapezoid(accuracy, coverage)


auc_lr = compute_auc_ac(curve_lr)
auc_gb = compute_auc_ac(curve_gb)

print("\nArea Under Accuracy-Coverage Curve:")
print(f"  Logistic Regression: {auc_lr:.4f}")
print(f"  Gradient Boosting: {auc_gb:.4f}")
print(f"  Improvement: {(auc_gb - auc_lr) / auc_lr * 100:+.1f}%")

Area Under Accuracy-Coverage Curve:
  Logistic Regression: 0.6612
  Gradient Boosting: 0.2582
  Improvement: -60.9%

Interpretation

Key insights from accuracy-coverage analysis:

What the curve tells us:

  • A curve that stays high (close to 1.0) across all coverage levels indicates a well-calibrated conformal predictor
  • A curve that rises steeply at low coverage shows the model can identify a subset of “easy” cases with high confidence
  • A curve that drops below baseline suggests the conformal method is miscalibrated or the model has systematic biases

Practical implications:

  • Choose an operating point based on your accuracy vs automation needs
  • If high accuracy is critical, accept lower coverage (more manual review)
  • If automation rate matters, accept slightly lower accuracy
  • The breakeven point shows where CP matches full automation

Using the curve for decisions:

  • Find the coverage level that achieves your minimum accuracy requirement
  • Calculate the expected review workload at that coverage level
  • Compare models/methods using AUC-AC as a summary metric