This example demonstrates how to validate the exchangeability assumption that underlies conformal prediction using martingale-based tests.
Key Takeaways:
- Conformal prediction assumes exchangeability between calibration and test data
- Martingale tests detect violations of this assumption online
- If the martingale exceeds threshold
c, the false alarm probability is at most 1/c
- Use
ExchangeabilityTest before deploying conformal predictors to new data
Reference: Vovk et al. (2003). “Testing Exchangeability On-Line.” ICML.
Setup
We create a regression problem and compare exchangeable (iid) data with data that has undergone distribution shift.
Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from conformalpy.diagnostics import (
ExchangeabilityTest,
PowerMartingale,
SimpleJumper,
compute_conformal_p_values,
)
from conformalpy.regressor import ConformalRegressor
np.random.seed(42)
# Generate data
X, y = make_regression(n_samples=2000, n_features=10, noise=15.0, random_state=42)
# Split data
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 model
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Calibrate conformal regressor
cr = ConformalRegressor(model=model, alpha=0.1)
cr.calibrate(X_calib, y_calib)
print(f"Train: {len(y_train)}, Calibration: {len(y_calib)}, Test: {len(y_test)}")
print(f"Test coverage: {cr.score(X_test, y_test):.1%}")
Train: 1200, Calibration: 400, Test: 400
Test coverage: 93.2%
Scenario 1: Exchangeable Data (Same Distribution)
When test data comes from the same distribution as calibration data, the martingale should stay near 1.
Code
# Compute nonconformity scores for test data
test_preds = model.predict(X_test)
test_scores = np.abs(y_test - test_preds)
# Compute conformal p-values
p_values_iid = compute_conformal_p_values(cr.calibration_scores_, test_scores, random_state=42)
print("\n=== Scenario 1: Same Distribution ===")
print(f"P-value mean: {np.mean(p_values_iid):.3f} (expected ~0.5)")
print(f"P-value std: {np.std(p_values_iid):.3f}")
=== Scenario 1: Same Distribution ===
P-value mean: 0.508 (expected ~0.5)
P-value std: 0.278
Scenario 2: Distribution Shift
When test data comes from a shifted distribution, the martingale should grow, indicating a violation of exchangeability.
Code
# Create shifted data
X_shifted = X_test + 5 # Moderate covariate shift
shifted_preds = model.predict(X_shifted)
shifted_scores = np.abs(y_test - shifted_preds)
p_values_shifted = compute_conformal_p_values(cr.calibration_scores_, shifted_scores, random_state=42)
print("\n=== Scenario 2: Distribution Shift ===")
print(f"P-value mean: {np.mean(p_values_shifted):.3f}")
print(f"P-value std: {np.std(p_values_shifted):.3f}")
=== Scenario 2: Distribution Shift ===
P-value mean: 0.012
P-value std: 0.073
Visualize P-Value Distributions
Code
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
ax = axes[0]
ax.hist(p_values_iid, bins=20, density=True, alpha=0.7, edgecolor="black", label="Observed")
ax.axhline(y=1.0, color="red", linestyle="--", linewidth=2, label="Uniform")
ax.set_xlabel("P-value")
ax.set_ylabel("Density")
ax.set_title("Same Distribution (Exchangeable)")
ax.legend()
ax = axes[1]
ax.hist(p_values_shifted, bins=20, density=True, alpha=0.7, edgecolor="black", color="coral", label="Observed")
ax.axhline(y=1.0, color="red", linestyle="--", linewidth=2, label="Uniform")
ax.set_xlabel("P-value")
ax.set_ylabel("Density")
ax.set_title("Shifted Distribution (Non-Exchangeable)")
ax.legend()
plt.tight_layout()
plt.suptitle("P-Value Distributions Under Exchangeability", fontsize=13, y=1.02)
plt.show()
Running Martingale Tests
Compare Power Martingale and Simple Jumper on both scenarios.
Code
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
def _safe_for_semilog(values):
arr = np.asarray(values, dtype=float)
finite_positive = arr[np.isfinite(arr) & (arr > 0)]
if finite_positive.size == 0:
finite_positive = np.array([1.0])
safe_upper = min(max(np.nanmax(finite_positive), 1.0), 1e12)
return np.clip(arr, 1e-12, safe_upper)
for col, (p_vals, title) in enumerate(
[
(p_values_iid, "Same Distribution"),
(p_values_shifted, "Shifted Distribution"),
]
):
# Power Martingale
pm = PowerMartingale(epsilon=0.92)
pm_values = _safe_for_semilog(pm.update(p_vals))
ax = axes[0, col]
ax.semilogy(range(1, len(pm_values) + 1), pm_values, linewidth=1.5)
ax.axhline(y=100, color="red", linestyle="--", linewidth=2, label="Threshold (c=100)")
ax.axhline(y=1, color="gray", linestyle=":", alpha=0.5)
ax.set_xlabel("Sample Index")
ax.set_ylabel("Martingale Value (log)")
ax.set_title(f"Power Martingale (epsilon=0.92): {title}")
ax.legend()
ax.grid(True, alpha=0.3)
# Simple Jumper
sj = SimpleJumper()
sj_values = _safe_for_semilog(sj.update(p_vals))
ax = axes[1, col]
ax.semilogy(range(1, len(sj_values) + 1), sj_values, linewidth=1.5, color="seagreen")
ax.axhline(y=100, color="red", linestyle="--", linewidth=2, label="Threshold (c=100)")
ax.axhline(y=1, color="gray", linestyle=":", alpha=0.5)
ax.set_xlabel("Sample Index")
ax.set_ylabel("Martingale Value (log)")
ax.set_title(f"Simple Jumper: {title}")
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.suptitle("Martingale-Based Exchangeability Tests", fontsize=14, y=1.02)
plt.show()
High-Level ExchangeabilityTest API
The simplest way to test exchangeability.
Code
print("\n=== ExchangeabilityTest Results ===\n")
for scenario, test_sc in [
("Same Distribution", test_scores),
("Shifted Distribution", shifted_scores),
]:
et = ExchangeabilityTest(method="simple_jumper", threshold=100)
result = et.test(cr.calibration_scores_, test_sc, random_state=42)
status = "REJECTED" if result["rejected"] else "NOT REJECTED"
print(f"{scenario}:")
print(f" Exchangeability: {status}")
print(f" Max martingale: {result['max_martingale']:.2f}")
print(f" Significance: {result['significance']:.2%}")
print()
=== ExchangeabilityTest Results ===
Same Distribution:
Exchangeability: NOT REJECTED
Max martingale: 4.00
Significance: 1.00%
Shifted Distribution:
Exchangeability: REJECTED
Max martingale: inf
Significance: 1.00%
Gradual Drift Detection
Martingales can detect when drift begins. Let’s create data where the first half is exchangeable and the second half is shifted.
Code
n_test = len(X_test)
n_half = n_test // 2
# First half: same distribution. Second half: shifted
X_gradual = np.vstack([X_test[:n_half], X_test[n_half:] + 3])
preds_gradual = model.predict(X_gradual)
y_gradual = np.concatenate([y_test[:n_half], y_test[n_half:]])
scores_gradual = np.abs(y_gradual - preds_gradual)
p_values_gradual = compute_conformal_p_values(cr.calibration_scores_, scores_gradual, random_state=42)
sj = SimpleJumper()
gradual_values = sj.update(p_values_gradual)
safe_values = _safe_for_semilog(gradual_values)
fig, ax = plt.subplots(figsize=(10, 5))
ax.semilogy(range(1, len(safe_values) + 1), safe_values, linewidth=1.5)
ax.axhline(y=100, color="red", linestyle="--", linewidth=2, label="Threshold (c=100)")
ax.axhline(y=1, color="gray", linestyle=":", alpha=0.5)
ax.axvline(x=n_half, color="orange", linestyle="-.", linewidth=2, label=f"Drift starts (n={n_half})")
ax.set_xlabel("Sample Index")
ax.set_ylabel("Martingale Value (log)")
ax.set_title("Detecting Gradual Distribution Drift")
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# Find when threshold was first exceeded
exceeded_idx = np.where(safe_values >= 100)[0]
if len(exceeded_idx) > 0:
print(f"Threshold exceeded at sample {exceeded_idx[0] + 1} (drift started at sample {n_half})")
print(f"Detection delay: {exceeded_idx[0] + 1 - n_half} samples after drift")
else:
print("Threshold not exceeded (drift not detected with this threshold)")
Threshold exceeded at sample 208 (drift started at sample 200)
Detection delay: 8 samples after drift
Summary
Exchangeability testing validates the core assumption of conformal prediction.
Key Properties:
- Under exchangeability,
P(M_n >= c) <= 1/c (Ville’s inequality)
- Common thresholds:
c=20 (~5%), c=100 (~1%), c=1000 (~0.1%)
- SimpleJumper adapts to the pattern of violations (recommended)
- PowerMartingale uses a fixed sensitivity parameter
When to Use:
- Before deploying conformal predictors to new data
- Monitoring production systems for data drift
- Validating calibration/test data compatibility
- Detecting covariate shift or concept drift
API:
from conformalpy.diagnostics import ExchangeabilityTest
et = ExchangeabilityTest(method='simple_jumper', threshold=100)
result = et.test(calibration_scores, test_scores)
if result['rejected']:
print("Warning: exchangeability violated!")