Weighted Conformal Prediction for Covariate Shift

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:

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 plt
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression

np.random.seed(42)

# Create data with different distributions for calibration and test
n_train = 500
n_cal = 200
n_test = 300

# Training data: X ~ N(0, 1)
X_train = np.random.randn(n_train, 5)
# Binary classification based on first two features
y_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.5
X_test = np.random.randn(n_test, 5) + shift
y_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

Visualize the Distribution Shift

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

# Feature distribution
ax = axes[0]
ax.hist(X_cal[:, 0], bins=30, alpha=0.5, label="Calibration", density=True)
ax.hist(X_test[:, 0], bins=30, alpha=0.5, label="Test", density=True)
ax.set_xlabel("Feature 0")
ax.set_ylabel("Density")
ax.set_title("Distribution Shift in Feature Space")
ax.legend()

# 2D view
ax = axes[1]
ax.scatter(X_cal[:, 0], X_cal[:, 1], alpha=0.3, label="Calibration", s=20)
ax.scatter(X_test[:, 0], X_test[:, 1], alpha=0.3, label="Test", s=20)
ax.set_xlabel("Feature 0")
ax.set_ylabel("Feature 1")
ax.set_title("Calibration vs Test Data (2D)")
ax.legend()

plt.tight_layout()
plt.show()

Train the Model

Code
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, WeightedConformalClassifier
from conformalpy.nonconformity import lac_nonconformity

alpha = 0.1

# Standard conformal prediction
std_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:

  1. Kernel Density Estimation
  2. Logistic regression (classify cal vs test)
  3. 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 weights


weights = 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

Compare Results

Code
print("\n=== Comparison ===")
print(f"{'Method':<25} {'Coverage':>12} {'Avg Set Size':>15} {'Coverage Gap':>15}")
print("-" * 70)
print(f"{'Standard CP':<25} {std_coverage:>11.1%} {std_avg_size:>15.2f} {std_coverage - (1 - alpha):>+14.1%}")
print(
    f"{'Weighted CP':<25} {weighted_coverage:>11.1%} {weighted_avg_size:>15.2f} "
    f"{weighted_coverage - (1 - alpha):>+14.1%}"
)

=== Comparison ===
Method                        Coverage    Avg Set Size    Coverage Gap
----------------------------------------------------------------------
Standard CP                     83.3%            0.87          -6.7%
Weighted CP                     80.0%            0.82         -10.0%

Visualize Weight Distribution

Code
fig, axes = plt.subplots(1, 3, figsize=(14, 4))

# Weight histogram
ax = axes[0]
ax.hist(weights, bins=30, edgecolor="black", alpha=0.7)
ax.axvline(1.0, color="red", linestyle="--", label="Uniform weight")
ax.set_xlabel("Importance Weight")
ax.set_ylabel("Count")
ax.set_title("Distribution of Importance Weights")
ax.legend()

# Weights vs feature value
ax = axes[1]
ax.scatter(X_cal[:, 0], weights, alpha=0.5, s=20)
ax.set_xlabel("Feature 0 (shifted feature)")
ax.set_ylabel("Importance Weight")
ax.set_title("Weight vs Feature Value")

# Coverage comparison
ax = axes[2]
methods = ["Standard CP", "Weighted CP"]
coverages = [std_coverage, weighted_coverage]
colors = ["steelblue", "seagreen"]
bars = ax.bar(methods, coverages, color=colors, edgecolor="black")
ax.axhline(1 - alpha, color="red", linestyle="--", label=f"Target ({1 - alpha:.0%})")
ax.set_ylabel("Coverage")
ax.set_title("Coverage Comparison")
ax.set_ylim(0.5, 1.0)
ax.legend()

# Add value labels on bars
for bar, cov in zip(bars, coverages):
    ax.annotate(
        f"{cov:.1%}", xy=(bar.get_x() + bar.get_width() / 2, bar.get_height()), ha="center", va="bottom", fontsize=10
    )

plt.tight_layout()
plt.suptitle("Weighted Conformal Prediction: Handling Covariate Shift", y=1.02, fontsize=13)
plt.show()

Coverage Across Different Shift Magnitudes

Let’s see how coverage varies as the distribution shift increases.

Code
shifts = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
results = []

for s in shifts:
    # Generate shifted test data
    X_test_s = np.random.randn(n_test, 5) + s
    y_test_s = ((X_test_s[:, 0] + 0.5 * X_test_s[:, 1] + 0.2 * np.random.randn(n_test)) > 0).astype(int)

    # Standard CP
    std_cov = std_cp.score(X_test_s, y_test_s)

    # Weighted CP (re-estimate weights for this shift)
    w = estimate_importance_weights(X_cal, X_test_s)
    wcp = WeightedConformalClassifier(
        model=model,
        alpha=alpha,
        nonconformity_function=lac_nonconformity,
    )
    wcp.calibrate(X_cal, y_cal, weights=w)
    weighted_cov = wcp.score(X_test_s, y_test_s)

    results.append(
        {
            "shift": s,
            "std_coverage": std_cov,
            "weighted_coverage": weighted_cov,
        }
    )

Plot Coverage vs Shift Magnitude

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

shifts_plot = [r["shift"] for r in results]
std_coverages = [r["std_coverage"] for r in results]
weighted_coverages = [r["weighted_coverage"] for r in results]

ax.plot(shifts_plot, std_coverages, "o-", markersize=8, linewidth=2, label="Standard CP", color="steelblue")
ax.plot(shifts_plot, weighted_coverages, "s--", markersize=8, linewidth=2, label="Weighted CP", color="seagreen")
ax.axhline(1 - alpha, color="red", linestyle=":", linewidth=2, label=f"Target ({1 - alpha:.0%})")

ax.set_xlabel("Distribution Shift Magnitude", fontsize=11)
ax.set_ylabel("Coverage", fontsize=11)
ax.set_title("Coverage vs Covariate Shift Magnitude", fontsize=12)
ax.legend(fontsize=10)
ax.set_ylim(0.5, 1.05)
ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

print("\n=== Summary Table ===")
print(f"{'Shift':<10} {'Std CP Coverage':>18} {'Weighted CP Coverage':>22}")
print("-" * 52)
for r in results:
    print(f"{r['shift']:<10.1f} {r['std_coverage']:>17.1%} {r['weighted_coverage']:>21.1%}")


=== Summary Table ===
Shift         Std CP Coverage   Weighted CP Coverage
----------------------------------------------------
0.0                    88.0%                 88.0%
0.5                    88.3%                 85.3%
1.0                    90.7%                 77.7%
1.5                    97.0%                 63.0%
2.0                    92.7%                 37.7%
2.5                    85.0%                 58.0%
3.0                    56.3%                 32.0%

Summary

When to use Weighted Conformal Prediction:

  • 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:

  1. 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.

  2. Distribution overlap: If calibration and test distributions barely overlap, even perfect weights won’t help much.

  3. Weight variance: Extreme weights (very large or very small) can lead to high variance and unstable predictions.

  4. 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