Classification with Conformal Prediction

Understanding Conformal Prediction

The Coverage Guarantee

Conformal prediction provides a finite-sample coverage guarantee:

\[P(Y_{test} \in C(X_{test})) \geq 1 - \alpha\]

This means: if you set alpha=0.10, the prediction set will contain the true label at least 90% of the time, regardless of the underlying distribution.

Inductive Conformal Prediction (ICP)

conformalpy uses the split conformal (ICP) approach:

  1. Train a base classifier on training data
  2. Calibrate nonconformity scores on held-out calibration data
  3. Predict by including all classes with score below the threshold

The calibration step computes a threshold q such that 1-α of calibration samples have nonconformity scores below q.

Nonconformity Functions

conformalpy provides four nonconformity functions for classification:

LAC (default)

from conformalpy.nonconformity.classification import lac_nonconformity

The LAC (Least Ambiguous Classifier) score uses 1 - p_y where p_y is the probability of the true class. Produces the smallest prediction sets on average for well-calibrated models. Note: In binary classification, LAC is equivalent to the Hinge score.

APS (Adaptive Prediction Sets)

from conformalpy.nonconformity.classification import aps_nonconformity

Cumulative probability approach that never produces empty sets. Sums probabilities from highest to lowest until the true class is reached.

RAPS (Regularized APS)

from conformalpy.nonconformity.classification import raps_nonconformity

APS with regularization to further reduce set sizes. Useful when you want to minimize two-sets at the cost of slightly lower coverage.

SAPS (Sorted Adaptive Prediction Sets)

from conformalpy.nonconformity.classification import saps_nonconformity

SAPS uses only the maximum probability and the rank of the true class, making it more robust to probability miscalibration common in deep learning models. Recommended for neural networks and large-scale classification.

# SAPS formula:
# If true class is rank 1: score = u * max_prob
# Otherwise: score = max_prob + (rank - 2 + u) * lambda

def saps_func(y, p):
    return saps_nonconformity(y, p, lambda_reg=0.01, random_state=42)

cc = ConformalClassifier(
    model=model,
    alpha=0.1,
    nonconformity_function=saps_func,
)

Choosing a Score Function:

Score Best For Pros Cons
LAC Well-calibrated models Smallest sets May produce empty sets
APS General use No empty sets Larger sets for uncertain samples
RAPS Reducing set size Smaller than APS Requires tuning k_reg, lambda
SAPS Deep learning models Robust to miscalibration Requires tuning lambda

See the score functions comparison example for a detailed comparison, and the SAPS comparison example for SAPS-specific analysis.

Multiclass Classification

conformalpy fully supports multiclass classification (K > 2 classes). All features work seamlessly with any number of classes.

Basic Usage

The API is identical to binary classification:

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from conformalpy.classifier import ConformalClassifier
from conformalpy.nonconformity.classification import lac_nonconformity

# Load and split data
X, y = load_iris(return_X_y=True)
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, random_state=42)
X_calib, X_test, y_calib, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)

# Train base classifier
model = RandomForestClassifier().fit(X_train, y_train)

# Create conformal classifier (same as binary)
cc = ConformalClassifier(
    model=model,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
)

# Calibrate and predict
cc.calibrate(X_calib, y_calib)
prediction_sets = cc.predict(X_test)

# Access class information
print(f"Number of classes: {cc.n_classes_}")
print(f"Classes: {cc.classes_}")

Coverage Guarantee

The coverage guarantee holds for any number of classes:

\[P(Y_{test} \in C(X_{test})) \geq 1 - \alpha\]

Verify with:

from conformalpy.evaluation import coverage_score, class_conditional_coverage

# Marginal coverage
print(f"Coverage: {coverage_score(prediction_sets, y_test):.1%}")

# Per-class coverage
for cls, cov in class_conditional_coverage(prediction_sets, y_test).items():
    print(f"  Class {cls}: {cov:.1%}")

Outcomes for Multiclass

For multiclass, prediction sets are categorized as:

Outcome Condition Meaning
SC Singleton containing true class Confident and correct
SI Singleton NOT containing true class Confident but wrong
MC Multi-set containing true class Uncertain but covered
MU Multi-set NOT containing true class Uncertain and uncovered (coverage failure)
Empty Empty set No class passed threshold

For binary classification (K=2), multi-sets use TS0 (true=0) and TS1 (true=1) instead of MC/MU.

from conformalpy.outcomes import categorize_outcomes, outcome_summary

outcomes = categorize_outcomes(prediction_sets, y_test)
summary = outcome_summary(prediction_sets, y_test)

print(f"SC rate: {summary['proportions']['SC']:.1%}")
print(f"SI rate: {summary['proportions']['SI']:.1%}")
print(f"Confidence rate: {summary['confidence_rate']:.1%}")

Efficiency Metric

For multiclass, the efficiency score measures how informative predictions are:

from conformalpy.evaluation import efficiency_score

eff = efficiency_score(prediction_sets, n_classes=cc.n_classes_)
print(f"Efficiency: {eff:.1%}")
  • Efficiency = 1.0 when all predictions are singletons
  • Efficiency = 1/K when all predictions are full sets (K classes)

High coverage with high efficiency indicates a well-calibrated predictor.

Zones for Multiclass

The operational framework works identically for multiclass:

from conformalpy.framework import classify_zones, zone_summary

zones = classify_zones(prediction_sets, y_test)
summary = zone_summary(prediction_sets, y_test)

for zone, prop in summary['proportions'].items():
    print(f"  {zone}: {prop:.1%}")

Zone assignments:

  • Safe: SC predictions (singleton, correct)
  • Uncertain: Multi-set predictions (2+ classes)
  • Problematic: SI predictions (singleton, incorrect)
  • Unclassified: Empty predictions

See the multiclass Iris example for a complete multiclass workflow with the Iris dataset.

References

Angelopoulos, Anastasios N., Stephen Bates, Jitendra Malik, and Michael I. Jordan. 2021. “Uncertainty Sets for Image Classifiers Using Conformal Prediction.” International Conference on Learning Representations.
Huang, Jianguo, Huajun Xi, Linjun Zhang, Huaxiu Yao, Yue Qiu, and Hongxin Wei. 2024. “Conformal Prediction for Deep Classifier via Label Ranking.” International Conference on Machine Learning.
Papadopoulos, Harris, Kostas Proedrou, Volodya Vovk, and Alex Gammerman. 2002. “Inductive Confidence Machines for Regression.” European Conference on Machine Learning (ECML), 345–56. https://doi.org/10.1007/3-540-36755-1_29.
Romano, Yaniv, Matteo Sesia, and Emmanuel Candès. 2020. “Classification with Valid and Adaptive Coverage.” Advances in Neural Information Processing Systems 33: 3581–91.
Sadinle, Mauricio, Jing Lei, and Larry Wasserman. 2019. “Least Ambiguous Set-Valued Classifiers with Bounded Error Levels.” Journal of the American Statistical Association 114 (525): 223–34. https://doi.org/10.1080/01621459.2017.1395341.
Vovk, Vladimir, Alexander Gammerman, and Glenn Shafer. 2005. Algorithmic Learning in a Random World. Springer. https://doi.org/10.1007/b106715.