SAPS: Sorted Adaptive Prediction Sets

This example demonstrates SAPS (Sorted Adaptive Prediction Sets), a nonconformity score function designed for deep classifiers where probability estimates may be miscalibrated.

Key insight: SAPS uses only the maximum probability and the rank of the true class, discarding other probability values that may be unreliable.

Key Takeaways:

Reference: Huang et al. (2024). “Conformal Prediction for Deep Classifier via Label Ranking.” ICML.

Setup and Data Generation

We create a multiclass classification problem to analyze SAPS scores.

Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

from conformalpy.nonconformity.classification import (
    aps_nonconformity,
    lac_nonconformity,
    raps_nonconformity,
    saps_nonconformity,
)

# Generate multiclass data
np.random.seed(42)
n_classes = 10
X, y = make_classification(
    n_samples=3000,
    n_features=20,
    n_classes=n_classes,
    n_informative=15,
    n_clusters_per_class=1,
    random_state=42,
)

# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=42)

print(f"Dataset: {n_classes} classes")
print(f"Train: {len(y_train)}, Test: {len(y_test)}")
Dataset: 10 classes
Train: 2100, Test: 900

Train Models

We train both a RandomForest (well-calibrated) and an MLP (potentially miscalibrated) to see how different score functions perform.

Code
# Well-calibrated model
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
print(f"RandomForest accuracy: {rf.score(X_test, y_test):.1%}")

# Potentially miscalibrated model (neural network without calibration)
mlp = MLPClassifier(hidden_layer_sizes=(100, 50), max_iter=500, random_state=42)
mlp.fit(X_train, y_train)
print(f"MLP accuracy: {mlp.score(X_test, y_test):.1%}")

# Get probabilities
rf_probs = rf.predict_proba(X_test)
mlp_probs = mlp.predict_proba(X_test)
RandomForest accuracy: 76.2%
MLP accuracy: 86.6%

Compare Score Functions

Let’s compute scores from different nonconformity functions.

Code
print("\n=== Score Statistics (RandomForest) ===")
print(f"{'Score':<10} {'Mean':>10} {'Std':>10} {'Min':>10} {'Max':>10}")
print("-" * 50)

score_results = {}
for name, func, kwargs in [
    ("LAC", lac_nonconformity, {}),
    ("APS", aps_nonconformity, {"random_state": 42}),
    ("RAPS", raps_nonconformity, {"k_reg": 1, "lambda_reg": 0.1, "random_state": 42}),
    ("SAPS", saps_nonconformity, {"lambda_reg": 0.01, "random_state": 42}),
]:
    scores = func(y_test, rf_probs, **kwargs)
    score_results[name] = {"rf": scores}
    print(
        f"{name:<10} {np.mean(scores):>10.4f} {np.std(scores):>10.4f} {np.min(scores):>10.4f} {np.max(scores):>10.4f}"
    )

print("\n=== Score Statistics (MLP) ===")
print(f"{'Score':<10} {'Mean':>10} {'Std':>10} {'Min':>10} {'Max':>10}")
print("-" * 50)

for name, func, kwargs in [
    ("LAC", lac_nonconformity, {}),
    ("APS", aps_nonconformity, {"random_state": 42}),
    ("RAPS", raps_nonconformity, {"k_reg": 1, "lambda_reg": 0.1, "random_state": 42}),
    ("SAPS", saps_nonconformity, {"lambda_reg": 0.01, "random_state": 42}),
]:
    scores = func(y_test, mlp_probs, **kwargs)
    score_results[name]["mlp"] = scores
    print(
        f"{name:<10} {np.mean(scores):>10.4f} {np.std(scores):>10.4f} {np.min(scores):>10.4f} {np.max(scores):>10.4f}"
    )

=== Score Statistics (RandomForest) ===
Score            Mean        Std        Min        Max
--------------------------------------------------
LAC            0.6470     0.1523     0.1500     0.9900
APS            0.2751     0.1925     0.0007     0.9929
RAPS           0.3183     0.2726     0.0007     1.7929
SAPS           0.2279     0.1350     0.0007     0.7289

=== Score Statistics (MLP) ===
Score            Mean        Std        Min        Max
--------------------------------------------------
LAC            0.1581     0.3054     0.0000     1.0000
APS            0.5313     0.3076     0.0012     1.0000
RAPS           0.5514     0.3395     0.0012     1.9000
SAPS           0.5206     0.2990     0.0012     1.0829

Visualize Score Distributions

Compare how different score functions distribute across test samples.

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

for idx, (name, model_name) in enumerate(
    [
        ("RandomForest", "rf"),
        ("MLP", "mlp"),
    ]
):
    ax = axes[idx, 0]
    for score_name in ["LAC", "APS", "RAPS", "SAPS"]:
        scores = score_results[score_name][model_name]
        ax.hist(scores, bins=30, alpha=0.5, label=score_name, density=True)
    ax.set_xlabel("Nonconformity Score")
    ax.set_ylabel("Density")
    ax.set_title(f"{name}: Score Distributions")
    ax.legend()

    ax = axes[idx, 1]
    for score_name in ["LAC", "SAPS"]:
        scores = score_results[score_name][model_name]
        sorted_scores = np.sort(scores)
        ax.plot(np.arange(len(sorted_scores)) / len(sorted_scores), sorted_scores, label=score_name, linewidth=2)
    ax.set_xlabel("Quantile")
    ax.set_ylabel("Score Value")
    ax.set_title(f"{name}: Score CDFs (LAC vs SAPS)")
    ax.legend()
    ax.axhline(y=0.9, color="red", linestyle="--", alpha=0.5, label="Typical qhat")

plt.tight_layout()
plt.suptitle("Comparison of Nonconformity Score Functions", fontsize=14, y=1.02)
plt.show()

SAPS Score by Rank

Show how SAPS scores vary with the rank of the true class.

Code
def get_ranks(y_true, probs):
    """Get the rank of the true class for each sample."""
    ranks = []
    for i in range(len(y_true)):
        sorted_idx = np.argsort(probs[i])[::-1]
        rank = np.where(sorted_idx == y_true[i])[0][0] + 1
        ranks.append(rank)
    return np.array(ranks)


rf_ranks = get_ranks(y_test, rf_probs)
mlp_ranks = get_ranks(y_test, mlp_probs)

saps_rf = score_results["SAPS"]["rf"]
saps_mlp = score_results["SAPS"]["mlp"]

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

# RF
ax = axes[0]
for rank in [1, 2, 3, 4, 5]:
    mask = rf_ranks == rank
    if np.sum(mask) > 5:
        scores = saps_rf[mask]
        ax.scatter(
            np.full(len(scores), rank) + np.random.uniform(-0.1, 0.1, len(scores)),
            scores,
            alpha=0.3,
            s=20,
            label=f"Rank {rank} (n={np.sum(mask)})",
        )

ax.set_xlabel("True Class Rank")
ax.set_ylabel("SAPS Score")
ax.set_title("RandomForest: SAPS Score by True Class Rank")
ax.legend(loc="upper left")

# MLP
ax = axes[1]
for rank in [1, 2, 3, 4, 5]:
    mask = mlp_ranks == rank
    if np.sum(mask) > 5:
        scores = saps_mlp[mask]
        ax.scatter(
            np.full(len(scores), rank) + np.random.uniform(-0.1, 0.1, len(scores)),
            scores,
            alpha=0.3,
            s=20,
            label=f"Rank {rank} (n={np.sum(mask)})",
        )

ax.set_xlabel("True Class Rank")
ax.set_ylabel("SAPS Score")
ax.set_title("MLP: SAPS Score by True Class Rank")
ax.legend(loc="upper left")

plt.tight_layout()
plt.show()

# Print statistics
print("\n=== SAPS Score by Rank ===")
print("\nRandomForest:")
print(f"{'Rank':<10} {'Count':>10} {'Mean Score':>15} {'Std Score':>15}")
print("-" * 50)
for rank in range(1, 6):
    mask = rf_ranks == rank
    if np.sum(mask) > 0:
        print(f"{rank:<10} {np.sum(mask):>10} {np.mean(saps_rf[mask]):>15.4f} {np.std(saps_rf[mask]):>15.4f}")

print("\nMLP:")
print(f"{'Rank':<10} {'Count':>10} {'Mean Score':>15} {'Std Score':>15}")
print("-" * 50)
for rank in range(1, 6):
    mask = mlp_ranks == rank
    if np.sum(mask) > 0:
        print(f"{rank:<10} {np.sum(mask):>10} {np.mean(saps_mlp[mask]):>15.4f} {np.std(saps_mlp[mask]):>15.4f}")


=== SAPS Score by Rank ===

RandomForest:
Rank            Count      Mean Score       Std Score
--------------------------------------------------
1                 686          0.2052          0.1401
2                 119          0.2972          0.0722
3                  55          0.3072          0.1013
4                  21          0.2862          0.0753
5                   8          0.3256          0.0942

MLP:
Rank            Count      Mean Score       Std Score
--------------------------------------------------
1                 779          0.4733          0.2853
2                  90          0.8128          0.1894
3                  19          0.8182          0.1662
4                   5          0.8550          0.1135
5                   4          0.9230          0.0643

SAPS Lambda Sensitivity

Explore how the lambda parameter affects SAPS scores.

Code
lambdas = [0.001, 0.005, 0.01, 0.05, 0.1, 0.5]
lambda_results = []

print("\n=== SAPS Lambda Sensitivity ===")
print(f"{'Lambda':<10} {'Mean Score':>15} {'Score @ 90%':>15}")
print("-" * 45)

for lam in lambdas:
    scores = saps_nonconformity(y_test, mlp_probs, lambda_reg=lam, random_state=42)
    q90 = np.quantile(scores, 0.9)
    lambda_results.append({"lambda": lam, "mean": np.mean(scores), "q90": q90})
    print(f"{lam:<10} {np.mean(scores):>15.4f} {q90:>15.4f}")

=== SAPS Lambda Sensitivity ===
Lambda          Mean Score     Score @ 90%
---------------------------------------------
0.001               0.5194          0.9249
0.005               0.5199          0.9265
0.01                0.5206          0.9273
0.05                0.5260          0.9371
0.1                 0.5327          0.9538
0.5                 0.5862          0.9921

Visualize Lambda Effect

Code
fig, ax = plt.subplots(figsize=(8, 5))

lam_vals = [r["lambda"] for r in lambda_results]
means = [r["mean"] for r in lambda_results]
q90s = [r["q90"] for r in lambda_results]

ax.semilogx(lam_vals, means, "o-", markersize=8, linewidth=2, label="Mean Score")
ax.semilogx(lam_vals, q90s, "s--", markersize=8, linewidth=2, label="90th Percentile")
ax.set_xlabel("Lambda")
ax.set_ylabel("Score Value")
ax.set_title("SAPS: Score Statistics vs Lambda (MLP)")
ax.legend()
ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Summary

SAPS (Sorted Adaptive Prediction Sets) is a nonconformity score designed for deep learning classifiers:

SAPS Formula:

\[s(x, y) = \begin{cases} u \cdot \pi_{\max} & \text{if true class is rank 1} \\ \pi_{\max} + (o(y) - 2 + u) \cdot \lambda & \text{otherwise} \end{cases}\]

Key Properties:

  • Uses only max probability (ignores potentially miscalibrated lower probabilities)
  • Scores increase with the rank of the true class
  • Lambda controls the penalty for lower-ranked true classes
  • Robust to probability miscalibration common in deep learning

Recommended lambda values:

  • ImageNet-scale: lambda_reg=0.01
  • Smaller problems: lambda_reg=0.01 to 0.1

Note on Usage:

SAPS is designed as a nonconformity score function. For full conformal prediction with SAPS, a custom predictor that computes SAPS scores at prediction time (for each candidate class) would be needed, rather than the standard ConformalClassifier which uses LAC-style scoring.