Runtime Alpha: Predict at Multiple Confidence Levels

This example demonstrates the runtime alpha feature introduced in v0.3.0, which allows specifying alpha at prediction time without recalibration.

This is useful when you want to:

Key Insight

Calibrate once, predict at any alpha level. The qhat threshold is recomputed from stored calibration scores, maintaining the coverage guarantee.

Classification: Runtime Alpha

Calibrate once, then predict at different alpha levels.

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 conformalpy.classifier import ConformalClassifier
from conformalpy.evaluation import coverage_score
from conformalpy.nonconformity import lac_nonconformity

# Generate data
X, y = make_classification(
    n_samples=2000,
    n_features=10,
    n_informative=5,
    n_classes=2,
    random_state=42,
)

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 and calibrate ONCE
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

cc = ConformalClassifier(
    model=model,
    alpha=0.1,  # Default alpha
    nonconformity_function=lac_nonconformity,
)
cc.calibrate(X_calib, y_calib)

print("Classification: Calibrated once, predicting at multiple alphas")
print("=" * 60)
Classification: Calibrated once, predicting at multiple alphas
============================================================

Predict at Different Alpha Levels (Scalar)

Pass a scalar alpha to override the default.

Code
alphas = [0.05, 0.10, 0.15, 0.20]

print(f"\n{'Alpha':>8}  {'Coverage':>10}  {'Avg Size':>10}  {'Singletons':>12}")
print("-" * 45)

for alpha in alphas:
    # Override alpha at prediction time - no recalibration needed!
    pred_sets = cc.predict(X_test, alpha=alpha)

    cov = coverage_score(pred_sets, y_test)
    avg_size = np.mean([len(s) for s in pred_sets])
    singleton_rate = np.mean([len(s) == 1 for s in pred_sets])

    print(f"{alpha:>8.2f}  {cov:>10.1%}  {avg_size:>10.2f}  {singleton_rate:>12.1%}")

   Alpha    Coverage    Avg Size    Singletons
---------------------------------------------
    0.05       92.5%        1.06         94.0%
    0.10       87.0%        0.96         96.5%
    0.15       81.0%        0.85         85.2%
    0.20       74.5%        0.77         77.0%

Predict at Multiple Alphas Simultaneously

Pass an array of alphas to get predictions for all at once. Returns a (n_samples, n_classes, n_alphas) boolean array.

Code
alphas = [0.05, 0.10, 0.20]
result = cc.predict(X_test, alpha=alphas)

print("\nMultiple alphas at once:")
print(f"  Input shape: X_test = {X_test.shape}")
print(f"  Output shape: {result.shape}  (n_samples, n_classes, n_alphas)")
print(f"  dtype: {result.dtype}")

# Extract coverage for each alpha
print(f"\n{'Alpha':>8}  {'Coverage':>10}")
print("-" * 20)
for i, alpha in enumerate(alphas):
    # result[:, y_test[j], i] tells us if true class is in set for sample j
    covered = [result[j, y_test[j], i] for j in range(len(y_test))]
    coverage = np.mean(covered)
    print(f"{alpha:>8.2f}  {coverage:>10.1%}")

Multiple alphas at once:
  Input shape: X_test = (400, 10)
  Output shape: (400, 2, 3)  (n_samples, n_classes, n_alphas)
  dtype: bool

   Alpha    Coverage
--------------------
    0.05       92.5%
    0.10       87.0%
    0.20       74.5%

Regression: Runtime Alpha

The same feature works for regressors.

Code
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor

from conformalpy.evaluation import average_interval_width, interval_coverage_score
from conformalpy.regressor import ConformalRegressor

# Load data
housing = fetch_california_housing()
X, y = housing.data, housing.target

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 and calibrate ONCE
model = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)

cr = ConformalRegressor(model=model, alpha=0.1)
cr.calibrate(X_calib, y_calib)

print("\n\nRegression: Calibrated once, predicting at multiple alphas")
print("=" * 60)


Regression: Calibrated once, predicting at multiple alphas
============================================================

Predict Intervals at Different Alpha Levels

Code
alphas = [0.05, 0.10, 0.15, 0.20]

print(f"\n{'Alpha':>8}  {'Target':>10}  {'Coverage':>10}  {'Avg Width':>12}")
print("-" * 45)

for alpha in alphas:
    # Override alpha at prediction time
    intervals = cr.predict_interval(X_test, alpha=alpha)

    cov = interval_coverage_score(y_test, intervals)
    width = average_interval_width(intervals)

    print(f"{alpha:>8.2f}  {1 - alpha:>10.1%}  {cov:>10.1%}  ${width * 100:>10.0f}k")

   Alpha      Target    Coverage     Avg Width
---------------------------------------------
    0.05       95.0%       94.6%  $       218k
    0.10       90.0%       90.7%  $       163k
    0.15       85.0%       85.8%  $       130k
    0.20       80.0%       81.2%  $       108k

Multiple Alphas Simultaneously

Returns (n_samples, 2, n_alphas) array.

Code
alphas = [0.05, 0.10, 0.20]
intervals = cr.predict_interval(X_test, alpha=alphas)

print("\nMultiple alphas at once:")
print(f"  Output shape: {intervals.shape}  (n_samples, 2, n_alphas)")
print("  intervals[:, 0, i] = lower bounds for alpha[i]")
print("  intervals[:, 1, i] = upper bounds for alpha[i]")

Multiple alphas at once:
  Output shape: (4128, 2, 3)  (n_samples, 2, n_alphas)
  intervals[:, 0, i] = lower bounds for alpha[i]
  intervals[:, 1, i] = upper bounds for alpha[i]

Visualize Intervals at Multiple Confidence Levels

Code
fig, axes = plt.subplots(1, 3, figsize=(15, 5))

# Sort samples by true value for visualization
n_show = 50
sort_idx = np.argsort(y_test[:n_show])
y_sorted = y_test[:n_show][sort_idx]

for ax_idx, (ax, alpha) in enumerate(zip(axes, [0.05, 0.10, 0.20])):
    intervals_alpha = cr.predict_interval(X_test[:n_show], alpha=alpha)
    intervals_sorted = intervals_alpha[sort_idx]

    x_pos = np.arange(n_show)

    # Plot intervals
    ax.fill_between(x_pos, intervals_sorted[:, 0], intervals_sorted[:, 1], alpha=0.3, color="blue", label="Interval")

    # Plot true values
    covered = (y_sorted >= intervals_sorted[:, 0]) & (y_sorted <= intervals_sorted[:, 1])
    ax.scatter(x_pos[covered], y_sorted[covered], color="green", s=15, zorder=5)
    ax.scatter(x_pos[~covered], y_sorted[~covered], color="red", s=15, zorder=5)

    cov = np.mean(covered)
    width = np.mean(intervals_sorted[:, 1] - intervals_sorted[:, 0])

    ax.set_title(f"α={alpha} (Target: {1 - alpha:.0%}, Actual: {cov:.0%})")
    ax.set_xlabel("Sample (sorted)")
    ax.set_ylabel("Value")

plt.suptitle("Prediction Intervals at Different Confidence Levels", y=1.02)
plt.tight_layout()
plt.show()

Practical Use Case: Interactive Confidence Selection

A common scenario is letting users choose their desired confidence level.

Code
def get_prediction_with_confidence(model, X_sample, confidence_level):
    """
    Get prediction interval at user-specified confidence level.

    Parameters
    ----------
    model : ConformalRegressor
        Calibrated conformal regressor.
    X_sample : array-like
        Sample to predict.
    confidence_level : float
        Desired confidence (e.g., 0.90 for 90% confidence).

    Returns
    -------
    dict
        Prediction, lower bound, upper bound, and confidence level.
    """
    alpha = 1 - confidence_level
    point_pred = model.predict(X_sample.reshape(1, -1))[0]
    interval = model.predict_interval(X_sample.reshape(1, -1), alpha=alpha)[0]

    return {
        "prediction": point_pred,
        "lower": interval[0],
        "upper": interval[1],
        "confidence": confidence_level,
    }


# Example: user wants different confidence levels
print("\nInteractive confidence selection example:")
print("-" * 50)

sample = X_test[0]
for conf in [0.80, 0.90, 0.95, 0.99]:
    result = get_prediction_with_confidence(cr, sample, conf)
    width = result["upper"] - result["lower"]
    print(
        f"  {conf:.0%} confidence: ${result['prediction'] * 100:.0f}k "
        f"[${result['lower'] * 100:.0f}k, ${result['upper'] * 100:.0f}k] "
        f"(width: ${width * 100:.0f}k)"
    )

Interactive confidence selection example:
--------------------------------------------------
  80% confidence: $116k [$62k, $170k] (width: $108k)
  90% confidence: $116k [$34k, $198k] (width: $163k)
  95% confidence: $116k [$7k, $225k] (width: $218k)
  99% confidence: $116k [$-81k, $313k] (width: $395k)

Summary

The runtime alpha feature enables:

  1. Calibrate once: Store nonconformity scores during calibration
  2. Predict at any alpha: Recompute qhat from stored scores
  3. Multiple alphas: Get predictions for many alphas in one call
  4. Interactive apps: Let users choose confidence without backend changes

This follows the same pattern as MAPIE’s predict(X, alpha=[...]) API.

Code
print("\n" + "=" * 50)
print("SUMMARY")
print("=" * 50)
print("Runtime alpha allows:")
print("  - Overriding init alpha at prediction time")
print("  - Predicting at multiple alphas simultaneously")
print("  - Building interactive confidence selectors")
print("  - Performing sensitivity analysis efficiently")
print("=" * 50)

==================================================
SUMMARY
==================================================
Runtime alpha allows:
  - Overriding init alpha at prediction time
  - Predicting at multiple alphas simultaneously
  - Building interactive confidence selectors
  - Performing sensitivity analysis efficiently
==================================================