Clustered Conformal Prediction for Many Classes

This example demonstrates Clustered Conformal Prediction, which provides class-conditional coverage guarantees for multi-class problems with many classes (K > 20) and limited calibration data per class.

Use case: When standard Mondrian CP would require too many samples per class, Clustered CP pools similar classes to achieve better coverage.

Key Takeaways:

Reference: Ding et al. (2023). “Class-Conditional Conformal Prediction with Many Classes.” NeurIPS.

Setup and Data Generation

We create a synthetic dataset with 30 classes and varying difficulty levels across classes.

Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

from conformalpy.classifier import ClusteredConformalClassifier, ConformalClassifier
from conformalpy.evaluation import average_set_size, coverage_score
from conformalpy.nonconformity.classification import lac_nonconformity

# Generate many-class data
np.random.seed(42)
n_classes = 30
n_samples_per_class = 100
n_samples = n_classes * n_samples_per_class
n_features = 20

# Create features with class-specific signal
rng = np.random.default_rng(42)
X = rng.standard_normal((n_samples, n_features))
y = np.repeat(np.arange(n_classes), n_samples_per_class)

# Add class-specific signal (some classes harder than others)
for c in range(n_classes):
    mask = y == c
    # Varying signal strength: harder classes have weaker signal
    signal_strength = 1.5 + (c % 5) * 0.3  # Classes cycle through difficulty
    X[mask, c % n_features] += signal_strength

# Shuffle data
perm = rng.permutation(n_samples)
X, y = X[perm], y[perm]

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

print(f"Dataset: {n_classes} classes, {n_features} features")
print(f"Train: {len(y_train)}, Calibration: {len(y_calib)}, Test: {len(y_test)}")
print(f"Samples per class in calibration: ~{len(y_calib) // n_classes}")
Dataset: 30 classes, 20 features
Train: 1500, Calibration: 750, Test: 750
Samples per class in calibration: ~25

Train Base Model

Fit a RandomForest classifier on training data.

Code
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
print(f"Model accuracy: {model.score(X_test, y_test):.1%}")
Model accuracy: 34.4%

Standard Marginal Conformal Prediction

First, standard CP with a single global threshold.

Code
cc_standard = ConformalClassifier(
    model=model,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
    mondrian=False,
)

cc_standard.calibrate(X_calib, y_calib)
pred_sets_standard = cc_standard.predict(X_test)

print("\n=== Standard Conformal (Single Threshold) ===")
print(f"Overall coverage: {coverage_score(pred_sets_standard, y_test):.1%}")
print(f"Average set size: {average_set_size(pred_sets_standard):.2f}")
print(f"Global qhat: {cc_standard.qhat_:.4f}")

=== Standard Conformal (Single Threshold) ===
Overall coverage: 94.3%
Average set size: 20.08
Global qhat: 0.9900

Standard Mondrian (Class-Conditional)

Mondrian CP with per-class thresholds. With limited samples per class, this may have high variance.

Code
cc_mondrian = ConformalClassifier(
    model=model,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
    mondrian=True,
)

cc_mondrian.calibrate(X_calib, y_calib)
pred_sets_mondrian = cc_mondrian.predict(X_test)

print("\n=== Standard Mondrian (Per-Class Thresholds) ===")
print(f"Overall coverage: {coverage_score(pred_sets_mondrian, y_test):.1%}")
print(f"Average set size: {average_set_size(pred_sets_mondrian):.2f}")
print(f"Number of qhats: {len(cc_mondrian.qhat_per_class_)}")

=== Standard Mondrian (Per-Class Thresholds) ===
Overall coverage: 92.4%
Average set size: 20.97
Number of qhats: 30

Clustered Conformal Prediction

Now apply Clustered CP, which groups similar classes for more stable coverage guarantees.

Code
cc_clustered = ClusteredConformalClassifier(
    model=model,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
    n_clusters="auto",  # Will use min(K//2, 10) = 10 clusters
    gamma="auto",  # Will use K/(K+75) for split ratio
    random_state=42,
)

cc_clustered.calibrate(X_calib, y_calib)
pred_sets_clustered = cc_clustered.predict(X_test)

print("\n=== Clustered Conformal Prediction ===")
print(f"Overall coverage: {coverage_score(pred_sets_clustered, y_test):.1%}")
print(f"Average set size: {average_set_size(pred_sets_clustered):.2f}")
print(f"Number of clusters: {cc_clustered.n_clusters_}")
print(f"Null cluster classes: {len(cc_clustered.null_cluster_classes_)}")

=== Clustered Conformal Prediction ===
Overall coverage: 92.9%
Average set size: 20.89
Number of clusters: 10
Null cluster classes: 0

Inspect Clustering

Let’s see how classes were grouped into clusters.

Code
cluster_info = cc_clustered.get_cluster_info()

print("\n=== Cluster Information ===")
print("Classes per cluster:")
for cluster_id, classes in sorted(cluster_info["classes_per_cluster"].items()):
    qhat = cluster_info["qhat_per_cluster"].get(cluster_id, "N/A")
    if cluster_id == -1:
        print(f"  Null cluster (ID={cluster_id}): {classes}, qhat={qhat}")
    else:
        print(f"  Cluster {cluster_id}: {len(classes)} classes, qhat={qhat:.4f}")

=== Cluster Information ===
Classes per cluster:
  Cluster 0: 1 classes, qhat=1.0000
  Cluster 1: 6 classes, qhat=0.9808
  Cluster 2: 2 classes, qhat=0.9506
  Cluster 3: 4 classes, qhat=0.9900
  Cluster 4: 4 classes, qhat=1.0000
  Cluster 5: 2 classes, qhat=1.0000
  Cluster 6: 2 classes, qhat=0.9811
  Cluster 7: 6 classes, qhat=0.9900
  Cluster 8: 2 classes, qhat=1.0000
  Cluster 9: 1 classes, qhat=1.0000

Compare Per-Class Coverage

Compare coverage for each class across the three methods.

Code
def compute_per_class_coverage(pred_sets, y_true, n_classes):
    """Compute coverage for each class."""
    coverages = []
    for c in range(n_classes):
        mask = y_true == c
        if np.sum(mask) == 0:
            coverages.append(np.nan)
        else:
            covered = [y_true[i] in pred_sets[i] for i in np.where(mask)[0]]
            coverages.append(np.mean(covered))
    return np.array(coverages)


cov_standard = compute_per_class_coverage(pred_sets_standard, y_test, n_classes)
cov_mondrian = compute_per_class_coverage(pred_sets_mondrian, y_test, n_classes)
cov_clustered = compute_per_class_coverage(pred_sets_clustered, y_test, n_classes)

print("\n=== Per-Class Coverage Summary ===")
print(f"{'Method':<15} {'Min':>8} {'Max':>8} {'Mean':>8} {'Std':>8}")
print("-" * 47)
print(
    f"{'Standard':<15} {np.nanmin(cov_standard):>8.1%} {np.nanmax(cov_standard):>8.1%} "
    f"{np.nanmean(cov_standard):>8.1%} {np.nanstd(cov_standard):>8.1%}"
)
print(
    f"{'Mondrian':<15} {np.nanmin(cov_mondrian):>8.1%} {np.nanmax(cov_mondrian):>8.1%} "
    f"{np.nanmean(cov_mondrian):>8.1%} {np.nanstd(cov_mondrian):>8.1%}"
)
print(
    f"{'Clustered':<15} {np.nanmin(cov_clustered):>8.1%} {np.nanmax(cov_clustered):>8.1%} "
    f"{np.nanmean(cov_clustered):>8.1%} {np.nanstd(cov_clustered):>8.1%}"
)

=== Per-Class Coverage Summary ===
Method               Min      Max     Mean      Std
-----------------------------------------------
Standard           84.0%   100.0%    94.3%     4.2%
Mondrian           60.0%   100.0%    92.4%     9.7%
Clustered          76.0%   100.0%    92.9%     6.4%

Visualize Coverage Comparison

Plot per-class coverage for all three methods.

Code
fig, axes = plt.subplots(2, 2, figsize=(14, 10))

# Per-class coverage bar chart
ax = axes[0, 0]
x = np.arange(n_classes)
width = 0.25
ax.bar(x - width, cov_standard, width, label="Standard", alpha=0.8)
ax.bar(x, cov_mondrian, width, label="Mondrian", alpha=0.8)
ax.bar(x + width, cov_clustered, width, label="Clustered", alpha=0.8)
ax.axhline(y=0.90, color="red", linestyle="--", linewidth=2, label="Target (90%)")
ax.set_xlabel("Class")
ax.set_ylabel("Coverage")
ax.set_title("Per-Class Coverage Comparison")
ax.legend(loc="lower right")
ax.set_ylim(0.5, 1.05)
ax.set_xticks(x[::5])  # Show every 5th class

# Coverage distribution histogram
ax = axes[0, 1]
bins = np.linspace(0.5, 1.0, 11)
ax.hist(cov_standard, bins=bins, alpha=0.5, label="Standard", edgecolor="black")
ax.hist(cov_mondrian, bins=bins, alpha=0.5, label="Mondrian", edgecolor="black")
ax.hist(cov_clustered, bins=bins, alpha=0.5, label="Clustered", edgecolor="black")
ax.axvline(x=0.90, color="red", linestyle="--", linewidth=2, label="Target")
ax.set_xlabel("Coverage")
ax.set_ylabel("Number of Classes")
ax.set_title("Distribution of Per-Class Coverage")
ax.legend()

# Coverage by cluster (for Clustered CP)
ax = axes[1, 0]
cluster_coverages = []
cluster_labels = []
for cluster_id, classes in sorted(cluster_info["classes_per_cluster"].items()):
    if cluster_id == -1:
        continue
    mask = np.isin(y_test, classes)
    if np.sum(mask) > 0:
        covered = [y_test[i] in pred_sets_clustered[i] for i in np.where(mask)[0]]
        cluster_coverages.append(np.mean(covered))
        cluster_labels.append(f"C{cluster_id}\n({len(classes)})")

bars = ax.bar(range(len(cluster_coverages)), cluster_coverages, color="coral", edgecolor="black")
ax.axhline(y=0.90, color="red", linestyle="--", linewidth=2, label="Target (90%)")
ax.set_xlabel("Cluster (# classes)")
ax.set_ylabel("Coverage")
ax.set_title("Clustered CP: Coverage by Cluster")
ax.set_xticks(range(len(cluster_labels)))
ax.set_xticklabels(cluster_labels)
ax.set_ylim(0.7, 1.0)
ax.legend()

# Summary comparison
ax = axes[1, 1]
methods = ["Standard", "Mondrian", "Clustered"]
overall_coverage = [
    coverage_score(pred_sets_standard, y_test),
    coverage_score(pred_sets_mondrian, y_test),
    coverage_score(pred_sets_clustered, y_test),
]
avg_set_sizes = [
    average_set_size(pred_sets_standard),
    average_set_size(pred_sets_mondrian),
    average_set_size(pred_sets_clustered),
]
worst_class_coverage = [
    np.nanmin(cov_standard),
    np.nanmin(cov_mondrian),
    np.nanmin(cov_clustered),
]

x = np.arange(len(methods))
width = 0.25

bars1 = ax.bar(x - width, overall_coverage, width, label="Overall Coverage", color="steelblue")
bars2 = ax.bar(x, worst_class_coverage, width, label="Worst-Class Coverage", color="coral")
ax.axhline(y=0.90, color="red", linestyle="--", linewidth=2, alpha=0.7)
ax.set_ylabel("Coverage")
ax.set_xlabel("Method")
ax.set_title("Coverage Summary")
ax.set_xticks(x)
ax.set_xticklabels(methods)
ax.legend(loc="lower right")
ax.set_ylim(0.6, 1.0)

# Add value labels
for bar in bars1:
    ax.annotate(
        f"{bar.get_height():.1%}",
        xy=(bar.get_x() + bar.get_width() / 2, bar.get_height()),
        xytext=(0, 3),
        textcoords="offset points",
        ha="center",
        va="bottom",
        fontsize=9,
    )
for bar in bars2:
    ax.annotate(
        f"{bar.get_height():.1%}",
        xy=(bar.get_x() + bar.get_width() / 2, bar.get_height()),
        xytext=(0, 3),
        textcoords="offset points",
        ha="center",
        va="bottom",
        fontsize=9,
    )

plt.tight_layout()
plt.suptitle(f"Clustered Conformal Prediction ({n_classes} Classes)", fontsize=14, y=1.02)
plt.show()

Runtime Alpha Support

Clustered CP also supports runtime alpha adjustment.

Code
alphas = [0.05, 0.10, 0.15, 0.20]
print("\n=== Runtime Alpha Support ===")
print(f"{'Alpha':<10} {'Coverage':>12} {'Avg Set Size':>15}")
print("-" * 37)

for alpha in alphas:
    pred_sets = cc_clustered.predict(X_test, alpha=alpha)
    cov = coverage_score(pred_sets, y_test)
    size = average_set_size(pred_sets)
    print(f"{alpha:<10} {cov:>12.1%} {size:>15.2f}")

=== Runtime Alpha Support ===
Alpha          Coverage    Avg Set Size
-------------------------------------
0.05              97.2%           25.78
0.1               92.9%           20.89
0.15              87.5%           14.06
0.2               82.8%            9.64

Summary

Clustered Conformal Prediction addresses the challenge of class-conditional coverage in many-class problems:

  • Standard CP: Single threshold, may have uneven per-class coverage
  • Mondrian CP: Per-class thresholds, but high variance with few samples
  • Clustered CP: Groups similar classes, balances coverage and stability

When to use Clustered CP:

  • Many classes (K > 20)
  • Limited calibration samples per class (< 50)
  • Need class-conditional coverage guarantees
  • Want to balance efficiency and coverage stability

Key parameters:

  • n_clusters="auto": Uses min(K//2, 10) clusters
  • gamma="auto": Uses K/(K+75) for the clustering/quantile split
  • min_samples_per_class: Threshold for null cluster assignment