This example demonstrates Weighted Conformal Prediction, which provides valid coverage guarantees when the test distribution differs from the calibration distribution (covariate shift).
Key insight: When test data comes from a different distribution than the calibration data, standard conformal prediction may undercover. Weighted CP uses importance weights to correct for this distribution shift.
Key Takeaways:
Standard CP assumes exchangeability (same distribution)
Weighted CP handles covariate shift using importance weights
Valid coverage under the target (test) distribution
Reference: Tibshirani et al. (2019). “Conformal Prediction Under Covariate Shift.” NeurIPS.
Setup: Simulating Covariate Shift
We create a scenario where the test distribution is shifted from the calibration distribution. This mimics real-world scenarios like:
Deploying to a different population
Temporal distribution drift
Domain adaptation
Code
import matplotlib.pyplot as pltimport numpy as npfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.linear_model import LogisticRegressionnp.random.seed(42)# Create data with different distributions for calibration and testn_train =500n_cal =200n_test =300# Training data: X ~ N(0, 1)X_train = np.random.randn(n_train, 5)# Binary classification based on first two featuresy_train = ((X_train[:, 0] +0.5* X_train[:, 1] +0.2* np.random.randn(n_train)) >0).astype(int)# Calibration data: X ~ N(0, 1) (same as training)X_cal = np.random.randn(n_cal, 5)y_cal = ((X_cal[:, 0] +0.5* X_cal[:, 1] +0.2* np.random.randn(n_cal)) >0).astype(int)# Test data: X ~ N(0.5, 1) - SHIFTED distribution (moderate shift)shift =0.5X_test = np.random.randn(n_test, 5) + shifty_test = ((X_test[:, 0] +0.5* X_test[:, 1] +0.2* np.random.randn(n_test)) >0).astype(int)print("Data Summary:")print(f" Train mean X[:,0]: {X_train[:, 0].mean():.2f}")print(f" Calib mean X[:,0]: {X_cal[:, 0].mean():.2f}")print(f" Test mean X[:,0]: {X_test[:, 0].mean():.2f} (shifted by {shift})")print(f" Test class distribution: {np.mean(y_test):.1%} class 1")
Data Summary:
Train mean X[:,0]: 0.05
Calib mean X[:,0]: -0.03
Test mean X[:,0]: 0.47 (shifted by 0.5)
Test class distribution: 72.7% class 1
model = RandomForestClassifier(n_estimators=100, random_state=42)model.fit(X_train, y_train)print(f"Model accuracy on test: {model.score(X_test, y_test):.1%}")
Model accuracy on test: 91.7%
Compare Standard vs Weighted Conformal Prediction
First, let’s see how standard CP performs under covariate shift.
Code
from conformalpy.classifier import ConformalClassifier, WeightedConformalClassifierfrom conformalpy.nonconformity import lac_nonconformityalpha =0.1# Standard conformal predictionstd_cp = ConformalClassifier( model=model, alpha=alpha, nonconformity_function=lac_nonconformity,)std_cp.calibrate(X_cal, y_cal)std_coverage = std_cp.score(X_test, y_test)std_pred_sets = std_cp.predict(X_test)std_avg_size = np.mean([len(s) for s in std_pred_sets])print("\n=== Standard Conformal Prediction ===")print(f"Target coverage: {1- alpha:.0%}")print(f"Actual coverage: {std_coverage:.1%}")print(f"Average set size: {std_avg_size:.2f}")
=== Standard Conformal Prediction ===
Target coverage: 90%
Actual coverage: 83.3%
Average set size: 0.87
Estimate Importance Weights
The key to weighted CP is estimating the density ratio:
\[w(x) = \frac{P_{test}(x)}{P_{cal}(x)}\]
Common approaches:
Kernel Density Estimation
Logistic regression (classify cal vs test)
Domain adaptation techniques
Here we use logistic regression to estimate weights.
Code
def estimate_importance_weights(X_cal, X_test):""" Estimate importance weights using logistic regression. Train a classifier to distinguish calibration from test samples, then use predicted probabilities to estimate density ratios. """# Create labels: 0 for calibration, 1 for test n_cal =len(X_cal) n_test =len(X_test) X_combined = np.vstack([X_cal, X_test]) y_combined = np.concatenate([np.zeros(n_cal), np.ones(n_test)])# Train classifier to distinguish cal from test clf = LogisticRegression(random_state=42, max_iter=1000) clf.fit(X_combined, y_combined)# Get probability of being from test distribution p_test = clf.predict_proba(X_cal)[:, 1]# Density ratio: P(test|x) / P(cal|x) = p / (1-p)# Clip to avoid extreme weights p_test = np.clip(p_test, 0.01, 0.99) weights = p_test / (1- p_test)# Normalize to account for different sample sizes weights = weights * (n_cal / n_test)return weightsweights = estimate_importance_weights(X_cal, X_test)print("\n=== Importance Weights ===")print(f"Mean weight: {np.mean(weights):.2f}")print(f"Std weight: {np.std(weights):.2f}")print(f"Min weight: {np.min(weights):.2f}")print(f"Max weight: {np.max(weights):.2f}")
=== Importance Weights ===
Mean weight: 1.07
Std weight: 1.62
Min weight: 0.02
Max weight: 10.97
Weighted Conformal Prediction
Code
weighted_cp = WeightedConformalClassifier( model=model, alpha=alpha, nonconformity_function=lac_nonconformity,)weighted_cp.calibrate(X_cal, y_cal, weights=weights)weighted_coverage = weighted_cp.score(X_test, y_test)weighted_pred_sets = weighted_cp.predict(X_test)weighted_avg_size = np.mean([len(s) for s in weighted_pred_sets])print("\n=== Weighted Conformal Prediction ===")print(f"Target coverage: {1- alpha:.0%}")print(f"Actual coverage: {weighted_coverage:.1%}")print(f"Average set size: {weighted_avg_size:.2f}")
=== Weighted Conformal Prediction ===
Target coverage: 90%
Actual coverage: 80.0%
Average set size: 0.82
Test data from different distribution than calibration
Domain adaptation scenarios
Temporal drift in data
Population shift between development and deployment
Important caveats:
The effectiveness of weighted CP depends critically on:
Quality of weight estimation: Poorly estimated weights can make coverage worse than standard CP. The logistic regression approach used here is a simple baseline - more sophisticated methods may help.
Distribution overlap: If calibration and test distributions barely overlap, even perfect weights won’t help much.
Weight variance: Extreme weights (very large or very small) can lead to high variance and unstable predictions.
Effective sample size: With importance weighting, the effective sample size may be much smaller than n, reducing precision.
Practical tips:
Clip extreme weights to avoid instability (e.g., max weight of 10)
Use robust density ratio estimation (KLIEP, LSIF, etc.)
Monitor coverage in production - recalibrate when needed
Consider Adaptive Conformal Inference for online settings
When distributions are too different, collect new calibration data