Top-K Prediction Sets

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:

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 plt
import numpy as np
from sklearn.datasets import load_digits
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

X, y = load_digits(return_X_y=True)
class_names = [str(i) for i in range(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 prediction
pred_sets = conf_clf.predict(X_test)
threshold_sizes = [len(s) for s in pred_sets]

# Top-K predictions for different values of k
top_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 in range(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%}")

Coverage comparison:
  Threshold (α=0.10): 90.0%
  Top-1: 95.6%
  Top-3: 100.0%
  Top-5: 100.0%

Visualize Coverage vs Set Size Trade-off

Code
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# Left: Coverage comparison
ax = axes[0]
methods = list(coverages.keys())
covs = list(coverages.values())
colors = ["#3498db", "#e74c3c", "#f39c12", "#2ecc71"]
bars = ax.bar(methods, covs, color=colors)
ax.axhline(0.90, color="red", linestyle="--", alpha=0.7, label="Target (90%)")
ax.set_ylabel("Coverage")
ax.set_title("Coverage by Method")
ax.set_ylim(0, 1.05)
ax.legend()

# Add value labels
for bar, cov in zip(bars, covs):
    ax.text(
        bar.get_x() + bar.get_width() / 2,
        bar.get_height() + 0.02,
        f"{cov:.1%}",
        ha="center",
        fontsize=10,
    )

# Right: Set size distribution
ax = axes[1]

# Compute set size distribution for threshold method
size_counts = {}
for size in threshold_sizes:
    size_counts[size] = size_counts.get(size, 0) + 1

sizes = sorted(size_counts.keys())
counts = [size_counts[s] for s in sizes]

ax.bar(sizes, counts, color="#3498db", alpha=0.7, label="Threshold-based")

# Add markers for Top-K fixed sizes
for k, color, label in [(1, "#e74c3c", "Top-1"), (3, "#f39c12", "Top-3"), (5, "#2ecc71", "Top-5")]:
    ax.axvline(k, color=color, linestyle="--", linewidth=2, label=label)

ax.set_xlabel("Prediction Set Size")
ax.set_ylabel("Count")
ax.set_title("Set Size Distribution")
ax.legend()

plt.tight_layout()
plt.show()

Top-K Coverage Across All K Values

See how coverage increases monotonically with K.

Code
k_values = range(1, 11)
top_k_coverages = []

for k in k_values:
    top_k_sets = conf_clf.predict_top_k(X_test, k=k)
    cov = compute_coverage(top_k_sets, y_test)
    top_k_coverages.append(cov)

fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(k_values, top_k_coverages, "o-", color="#3498db", linewidth=2, markersize=8)
ax.axhline(0.90, color="red", linestyle="--", alpha=0.7, label="Target coverage (90%)")

# Find the smallest k that achieves target coverage
for k, cov in zip(k_values, top_k_coverages):
    if cov >= 0.90:
        ax.axvline(k, color="#2ecc71", linestyle=":", alpha=0.7, label=f"Min k for 90%: k={k}")
        ax.scatter([k], [cov], color="#2ecc71", s=150, zorder=5, edgecolors="black")
        break

ax.set_xlabel("K (number of classes in set)")
ax.set_ylabel("Coverage")
ax.set_title("Top-K Coverage vs K")
ax.set_xticks(k_values)
ax.set_ylim(0, 1.05)
ax.legend()
ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Example Predictions

Show some example predictions comparing methods.

Code
print("\nExample predictions (first 5 samples):")
print("-" * 60)

for i in range(5):
    true_label = y_test[i]
    point_pred = model.predict([X_test[i]])[0]

    threshold_set = pred_sets[i]
    top1_set = top_1[i]
    top3_set = top_3[i]

    threshold_str = ",".join(str(c) for c in sorted(threshold_set))
    top3_str = ",".join(str(c) for c in top3_set)

    print(f"Sample {i}: True={true_label}, Point={point_pred}")
    print(f"  Threshold: {{{threshold_str}}} (size={len(threshold_set)})")
    print(f"  Top-3:     {{{top3_str}}} (always size=3)")
    print()

Example predictions (first 5 samples):
------------------------------------------------------------
Sample 0: True=9, Point=9
  Threshold: {9} (size=1)
  Top-3:     {9,7,1} (always size=3)

Sample 1: True=4, Point=4
  Threshold: {4} (size=1)
  Top-3:     {4,9,7} (always size=3)

Sample 2: True=9, Point=9
  Threshold: {9} (size=1)
  Top-3:     {9,5,8} (always size=3)

Sample 3: True=9, Point=9
  Threshold: {9} (size=1)
  Top-3:     {9,8,5} (always size=3)

Sample 4: True=7, Point=7
  Threshold: {7} (size=1)
  Top-3:     {7,4,1} (always size=3)

When to Use Top-K

Use threshold-based predict() when:

  • You need guaranteed coverage (1 - α)
  • Variable set sizes are acceptable
  • Statistical validity is important

Use predict_top_k() when:

  • Fixed output sizes are required
  • You’re computing “Top-K accuracy” metrics
  • You need consistent processing for downstream tasks
  • Coverage guarantees are less important than set size