Coverage by Class: Visualizing Conformal Prediction Performance

This example demonstrates how to use plot_conformal_coverage_by_class to visualize the performance of conformal prediction across different confidence levels, broken down by true class.

The plot shows:

This visualization helps identify:

  1. At which confidence levels the model makes reliable single-class predictions
  2. How prediction set sizes vary with confidence
  3. Whether coverage guarantees hold across different confidence levels

Setup and Data Loading

We use the breast cancer dataset, a classic binary classification problem.

Code
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

from conformalpy.classifier import ConformalClassifier
from conformalpy.nonconformity.classification import lac_nonconformity
from conformalpy.plots.classification import plot_conformal_coverage_by_class

# Load data
X, y = load_breast_cancer(return_X_y=True)
print(f"Dataset: {X.shape[0]} samples, {X.shape[1]} features")
print(f"Class distribution: {np.bincount(y)}")
Dataset: 569 samples, 30 features
Class distribution: [212 357]

Train-Calibration-Test Split

Conformal prediction requires a separate calibration set. We split: 60% train, 20% calibration, 20% test.

Code
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, random_state=42, stratify=y)
X_calib, X_test, y_calib, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42, stratify=y_temp)

print(f"Train: {len(y_train)}, Calibration: {len(y_calib)}, Test: {len(y_test)}")
Train: 341, Calibration: 114, Test: 114

Train Base Model

We train a logistic regression classifier as our base model.

Code
model = LogisticRegression(max_iter=5000, random_state=42)
model.fit(X_train, y_train)

accuracy = model.score(X_test, y_test)
print(f"Base model accuracy: {accuracy:.3f}")
Base model accuracy: 0.947

Create Conformal Classifier

Wrap the trained model with conformal prediction capabilities.

Code
conformal_clf = ConformalClassifier(
    model=model,
    alpha=0.1,  # 90% confidence level
    nonconformity_function=lac_nonconformity,
)

# Calibrate using the calibration set
conformal_clf.calibrate(X_calib, y_calib)
print(f"Calibration complete. q_hat = {conformal_clf.get_qhat():.4f}")
Calibration complete. q_hat = 0.1623

Get Predictions for Visualization

We need the calibration scores and test probabilities for the plot.

Code
calibration_scores = conformal_clf._calibration_scores
probs_test = model.predict_proba(X_test)

Visualize Coverage by Class

The plot shows how prediction sets behave across confidence levels, with separate tracking for each true class.

Code
plot_conformal_coverage_by_class(
    calibration_scores=calibration_scores,
    probs_test=probs_test,
    y_test=y_test,
    alphas=np.arange(0.01, 1.0, 0.01),
    cutoff_confidence=0.9,
)
(<Figure size 960x672 with 1 Axes>,
 <Axes: title={'center': 'Coverage and Prediction Set Types by Class'}, xlabel='Confidence Level (1 - α)', ylabel='Proportion'>)

Interpretation

  • Green areas (Correct class 0/1): Single-class predictions that are correct. Larger green area = more confident, accurate predictions.

  • Red areas (Incorrect class 0/1): Single-class predictions that are wrong. Should be minimal for a well-calibrated model.

  • Blue areas (Two-set): Prediction includes both classes (uncertain). Expected to grow as confidence level increases.

  • Gray areas (Empty): No prediction made. Should be rare.

  • Black line should follow the red dashed line (ideal coverage) for a well-calibrated conformal predictor.

Mondrian Conformal Prediction

Mondrian conformal prediction computes separate thresholds per class, which can improve coverage for imbalanced datasets.

Code
conformal_mondrian = ConformalClassifier(
    model=model,
    alpha=0.1,
    nonconformity_function=lac_nonconformity,
    mondrian=True,
)
conformal_mondrian.calibrate(X_calib, y_calib)

plot_conformal_coverage_by_class(
    calibration_scores=conformal_mondrian._calibration_scores,
    probs_test=probs_test,
    y_test=y_test,
    alphas=np.arange(0.01, 1.0, 0.01),
    cutoff_confidence=0.9,
    mondrian=True,
    y_calib=y_calib,
)
(<Figure size 960x672 with 1 Axes>,
 <Axes: title={'center': 'Coverage and Prediction Set Types by Class (Mondrian)'}, xlabel='Confidence Level (1 - α)', ylabel='Proportion'>)