Adaptive Conformal Inference (ACI)

This example demonstrates Adaptive Conformal Inference (ACI) for time series and streaming data with potential distribution shift.

Key concepts:

The ACI update rule:

\[\alpha_{t+1} = \alpha_t + \gamma \cdot (\text{error}_t - \alpha_{\text{target}})\]

where \(\text{error}_t = 1\) if true value not covered, 0 otherwise.

Reference: Gibbs, I., & Candes, E. (2021). “Adaptive Conformal Inference Under Distribution Shift.” NeurIPS.

Classification with ACI

First, we demonstrate ACI for classification tasks.

Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification, make_regression
from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor
from sklearn.model_selection import train_test_split

from conformalpy.nonconformity.classification import lac_nonconformity
from conformalpy.timeseries import (
    AdaptiveConformalClassifier,
    AdaptiveConformalRegressor,
)

np.random.seed(42)

# Generate data
X, y = make_classification(
    n_samples=1000,
    n_features=20,
    n_informative=10,
    n_classes=3,
    n_clusters_per_class=1,
    random_state=42,
)

# Split data
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.6, random_state=42, stratify=y)
X_calib, X_test, y_calib, 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_calib)}, Test: {len(X_test)}")
Train: 400, Calibration: 300, Test: 300

Train Base Model and Create ACI Classifier

Code
model = GradientBoostingClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

aci = AdaptiveConformalClassifier(
    model=model,
    nonconformity_function=lac_nonconformity,
    target_coverage=0.9,
    gamma=0.02,  # Learning rate
)

# Calibrate on initial data
aci.calibrate(X_calib, y_calib)

print(f"Initial alpha: {aci.alpha_:.4f}")
print(f"Initial qhat: {aci.qhat_:.4f}")
Initial alpha: 0.1000
Initial qhat: 0.4400

Simulate Online Learning

Process test samples one by one, updating alpha after each observation.

Code
# Store predictions before update for proper evaluation
predictions_before_update = []
true_labels = []

for i in range(len(X_test)):
    # Get prediction using current alpha
    pred_sets = aci.predict(X_test[i : i + 1])
    predictions_before_update.append(pred_sets[0])
    true_labels.append(y_test[i])

    # Update with true label (this would happen after observing ground truth)
    aci.update(X_test[i : i + 1], y_test[i : i + 1])

print(f"\nAfter {aci.n_updates_} updates:")
print(f"Final alpha: {aci.alpha_:.4f}")
print(f"Final coverage: {aci.current_coverage:.1%}")

After 300 updates:
Final alpha: 0.0010
Final coverage: 99.3%

Visualize Alpha Adaptation

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

# Alpha over time
ax = axes[0, 0]
ax.plot(aci.alpha_history_, color="#3498db", linewidth=1.5)
ax.axhline(0.1, color="red", linestyle="--", alpha=0.7, label="Target alpha (0.1)")
ax.set_xlabel("Time step")
ax.set_ylabel("Alpha")
ax.set_title("Alpha Adaptation Over Time")
ax.legend()
ax.grid(True, alpha=0.3)

# Coverage over time
ax = axes[0, 1]
ax.plot(aci.coverage_history_, color="#2ecc71", linewidth=1.5)
ax.axhline(0.9, color="red", linestyle="--", alpha=0.7, label="Target coverage (90%)")
ax.set_xlabel("Time step")
ax.set_ylabel("Cumulative Coverage")
ax.set_title("Coverage Tracking Over Time")
ax.legend()
ax.grid(True, alpha=0.3)

# Error history (smoothed)
ax = axes[1, 0]
window = 20
errors = np.array(aci.error_history_)
if len(errors) >= window:
    smoothed = np.convolve(errors, np.ones(window) / window, mode="valid")
    ax.plot(range(window - 1, len(errors)), smoothed, color="#e74c3c", linewidth=1.5)
    ax.axhline(0.1, color="red", linestyle="--", alpha=0.7, label="Target error rate (10%)")
else:
    ax.plot(errors, color="#e74c3c", linewidth=1.5)
ax.set_xlabel("Time step")
ax.set_ylabel(f"Error Rate (rolling {window}-step)")
ax.set_title("Rolling Error Rate")
ax.legend()
ax.grid(True, alpha=0.3)

# Alpha distribution
ax = axes[1, 1]
ax.hist(aci.alpha_history_, bins=30, color="#9b59b6", edgecolor="white", alpha=0.8)
ax.axvline(0.1, color="red", linestyle="--", alpha=0.7, label="Target alpha")
ax.axvline(
    np.mean(aci.alpha_history_),
    color="blue",
    linestyle="-",
    linewidth=2,
    label=f"Mean: {np.mean(aci.alpha_history_):.3f}",
)
ax.set_xlabel("Alpha")
ax.set_ylabel("Frequency")
ax.set_title("Alpha Distribution")
ax.legend()

plt.tight_layout()
plt.show()

Regression with ACI

ACI also works for regression tasks with prediction intervals.

Code
# Generate regression data
X_reg, y_reg = make_regression(
    n_samples=1000,
    n_features=10,
    n_informative=5,
    noise=20,
    random_state=42,
)

# Split
X_train_r, X_temp_r, y_train_r, y_temp_r = train_test_split(X_reg, y_reg, test_size=0.6, random_state=42)
X_calib_r, X_test_r, y_calib_r, y_test_r = train_test_split(X_temp_r, y_temp_r, test_size=0.5, random_state=42)

# Train regressor
reg_model = GradientBoostingRegressor(n_estimators=100, random_state=42)
reg_model.fit(X_train_r, y_train_r)

# Create ACI regressor
acr = AdaptiveConformalRegressor(
    model=reg_model,
    target_coverage=0.9,
    gamma=0.02,
)
acr.calibrate(X_calib_r, y_calib_r)

print(f"Regression - Initial alpha: {acr.alpha_:.4f}")
Regression - Initial alpha: 0.1000

Simulate Online Prediction for Regression

Code
for i in range(len(X_test_r)):
    # Get interval
    intervals = acr.predict_interval(X_test_r[i : i + 1])

    # Update with true value
    acr.update(X_test_r[i : i + 1], y_test_r[i : i + 1])

print(f"\nAfter {acr.n_updates_} updates:")
print(f"Final alpha: {acr.alpha_:.4f}")
print(f"Final coverage: {acr.current_coverage:.1%}")

After 300 updates:
Final alpha: 0.5000
Final coverage: 75.3%

Visualize Regression ACI

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

# Alpha over time
ax = axes[0]
ax.plot(acr.alpha_history_, color="#3498db", linewidth=1.5)
ax.axhline(0.1, color="red", linestyle="--", alpha=0.7, label="Target alpha (0.1)")
ax.set_xlabel("Time step")
ax.set_ylabel("Alpha")
ax.set_title("Regression: Alpha Adaptation")
ax.legend()
ax.grid(True, alpha=0.3)

# Coverage over time
ax = axes[1]
ax.plot(acr.coverage_history_, color="#2ecc71", linewidth=1.5)
ax.axhline(0.9, color="red", linestyle="--", alpha=0.7, label="Target coverage (90%)")
ax.set_xlabel("Time step")
ax.set_ylabel("Cumulative Coverage")
ax.set_title("Regression: Coverage Tracking")
ax.legend()
ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Effect of Gamma (Learning Rate)

The learning rate gamma controls how quickly alpha adapts. Larger gamma = faster adaptation but more oscillation. Smaller gamma = smoother adaptation but slower response to shift.

Code
gammas = [0.005, 0.02, 0.05, 0.1]
colors = ["#3498db", "#2ecc71", "#e74c3c", "#9b59b6"]

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

for gamma, color in zip(gammas, colors):
    # Reset and run with this gamma
    aci_temp = AdaptiveConformalClassifier(
        model=model,
        nonconformity_function=lac_nonconformity,
        target_coverage=0.9,
        gamma=gamma,
    )
    aci_temp.calibrate(X_calib, y_calib)

    for i in range(len(X_test)):
        aci_temp.update(X_test[i : i + 1], y_test[i : i + 1])

    # Plot alpha
    axes[0].plot(aci_temp.alpha_history_, color=color, linewidth=1.5, label=f"gamma={gamma}", alpha=0.8)

    # Plot coverage
    axes[1].plot(aci_temp.coverage_history_, color=color, linewidth=1.5, label=f"gamma={gamma}", alpha=0.8)

axes[0].axhline(0.1, color="black", linestyle="--", alpha=0.5)
axes[0].set_xlabel("Time step")
axes[0].set_ylabel("Alpha")
axes[0].set_title("Alpha Adaptation: Effect of Gamma")
axes[0].legend()
axes[0].grid(True, alpha=0.3)

axes[1].axhline(0.9, color="black", linestyle="--", alpha=0.5)
axes[1].set_xlabel("Time step")
axes[1].set_ylabel("Coverage")
axes[1].set_title("Coverage: Effect of Gamma")
axes[1].legend()
axes[1].grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

When to Use ACI

Use ACI when:

  • Data is non-exchangeable (time series, streaming)
  • Distribution shift is expected over time
  • You need online/adaptive prediction
  • Coverage guarantee is important despite non-exchangeability

Use standard conformal (split/CV+) when:

  • Data is exchangeable (i.i.d.)
  • No distribution shift expected
  • Batch prediction is sufficient
  • Computational efficiency is critical

Choosing gamma:

  • Start with gamma=0.01-0.02 for most applications
  • Use larger gamma (0.05-0.1) for rapid distribution shift
  • Use smaller gamma (<0.01) for stable distributions