This example demonstrates the predict_top_k method which returns fixed-size prediction sets containing exactly K classes.
Unlike threshold-based conformal prediction, Top-K always returns the same number of classes per sample, which can be useful when:
You need consistent output sizes for downstream processing
You want “Top-5 accuracy” style evaluation
Fixed set sizes are more important than coverage guarantees
Note: Top-K sets do NOT provide the same coverage guarantees as standard conformal prediction. Use threshold-based predict() when coverage guarantees are required.
Load the Digits Dataset
We use the digits dataset (10 classes) to demonstrate Top-K prediction.
Code
import matplotlib.pyplot as pltimport numpy as npfrom sklearn.datasets import load_digitsfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom conformalpy.classifier import ConformalClassifierfrom conformalpy.nonconformity.classification import lac_nonconformityX, y = load_digits(return_X_y=True)class_names = [str(i) for i inrange(10)]X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, random_state=42, stratify=y)X_cal, X_test, y_cal, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42, stratify=y_temp)print(f"Train: {len(X_train)}, Calibration: {len(X_cal)}, Test: {len(X_test)}")print(f"Number of classes: {len(np.unique(y))}")
Train: 1078, Calibration: 359, Test: 360
Number of classes: 10
Train and Calibrate
Train a base model and create a conformal classifier.
Code
model = LogisticRegression(max_iter=1000, random_state=42)model.fit(X_train, y_train)conf_clf = ConformalClassifier( model=model, alpha=0.10, nonconformity_function=lac_nonconformity,)conf_clf.calibrate(X_cal, y_cal)print(f"Base model accuracy: {model.score(X_test, y_test):.1%}")
Base model accuracy: 95.6%
Compare Threshold-Based vs Top-K
Standard conformal prediction returns variable-size sets based on a threshold. Top-K returns exactly K classes.
Code
# Threshold-based predictionpred_sets = conf_clf.predict(X_test)threshold_sizes = [len(s) for s in pred_sets]# Top-K predictions for different values of ktop_1 = conf_clf.predict_top_k(X_test, k=1)top_3 = conf_clf.predict_top_k(X_test, k=3)top_5 = conf_clf.predict_top_k(X_test, k=5)print("\nSet size comparison:")print(f" Threshold-based: mean={np.mean(threshold_sizes):.2f}, range=[{min(threshold_sizes)}, {max(threshold_sizes)}]")print(" Top-1: exactly 1 class per sample")print(" Top-3: exactly 3 classes per sample")print(" Top-5: exactly 5 classes per sample")
Set size comparison:
Threshold-based: mean=0.92, range=[0, 1]
Top-1: exactly 1 class per sample
Top-3: exactly 3 classes per sample
Top-5: exactly 5 classes per sample
Coverage Analysis
Compare coverage between threshold-based and Top-K methods.
Code
def compute_coverage(pred_sets, y_true):"""Compute proportion of samples where true label is in prediction set."""return np.mean([y_true[i] in pred_sets[i] for i inrange(len(y_true))])coverages = {"Threshold (α=0.10)": compute_coverage(pred_sets, y_test),"Top-1": compute_coverage(top_1, y_test),"Top-3": compute_coverage(top_3, y_test),"Top-5": compute_coverage(top_5, y_test),}print("\nCoverage comparison:")for method, cov in coverages.items():print(f" {method}: {cov:.1%}")