This example demonstrates Conformal Predictive Distributions (CPD), which provide full probability distributions instead of just prediction intervals.
Key insight : CPD outputs a complete CDF P(Y <= y) for each test point, enabling richer uncertainty quantification than point intervals.
Key Takeaways:
CPD provides a full predictive distribution for each sample
Can extract any quantile, not just symmetric intervals
CDF allows computing P(Y <= threshold) for any threshold
More informative than standard prediction intervals
Reference: Vovk et al. (2017). “Nonparametric Predictive Distributions Based on Conformal Prediction.” Machine Learning.
Setup: Generate Regression Data
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
np.random.seed(42 )
# Generate data
X, y = make_regression(
n_samples= 800 ,
n_features= 10 ,
noise= 20.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 )
print (f"Training samples: { len (y_train)} " )
print (f"Calibration samples: { len (y_calib)} " )
print (f"Test samples: { len (y_test)} " )
# Train model
model = RandomForestRegressor(n_estimators= 100 , random_state= 42 )
model.fit(X_train, y_train)
print (f"Model R² on test: { model. score(X_test, y_test):.3f} " )
Training samples: 480
Calibration samples: 160
Test samples: 160
Model R² on test: 0.720
Examine a Single Predictive Distribution
Get the full predictive distribution for one test point.
Code
# Get distribution for first test sample
distributions = cpd.predict_distribution(X_test[0 :1 ])
dist = distributions[0 ]
print (" \n === Predictive Distribution for Sample 0 ===" )
print (f"Point prediction: { dist. point_prediction:.2f} " )
print (f"True value: { y_test[0 ]:.2f} " )
print (f"Distribution mean: { dist. mean():.2f} " )
print (f"Distribution std: { dist. std():.2f} " )
# Compute various quantiles
print (" \n Quantiles:" )
for tau in [0.05 , 0.25 , 0.5 , 0.75 , 0.95 ]:
q = dist.quantile(tau)
print (f" Q { int (tau * 100 ):02d} : { q:.2f} " )
# Compute 90% prediction interval
lower, upper = dist.interval(alpha= 0.1 )
print (f" \n 90% Prediction Interval: [ { lower:.2f} , { upper:.2f} ]" )
print (f"True value in interval: { lower <= y_test[0 ] <= upper} " )
=== Predictive Distribution for Sample 0 ===
Point prediction: -62.80
True value: 21.62
Distribution mean: -56.47
Distribution std: 103.95
Quantiles:
Q05: -228.61
Q25: -126.63
Q50: -63.84
Q75: 20.46
Q95: 120.36
90% Prediction Interval: [-228.61, 120.36]
True value in interval: True
Visualize the Predictive Distribution CDF
Code
fig, axes = plt.subplots(1 , 2 , figsize= (12 , 4 ))
# CDF plot
ax = axes[0 ]
y_range = np.linspace(dist.point_prediction - 3 * dist.std(), dist.point_prediction + 3 * dist.std(), 200 )
cdf_values = dist.cdf(y_range)
ax.plot(y_range, cdf_values, "b-" , linewidth= 2 , label= "CDF" )
ax.axvline(y_test[0 ], color= "red" , linestyle= "--" , label= "True value" )
ax.axvline(dist.point_prediction, color= "green" , linestyle= ":" , label= "Prediction" )
ax.axhline(0.5 , color= "gray" , linestyle= ":" , alpha= 0.5 )
ax.set_xlabel("y" )
ax.set_ylabel("P(Y ≤ y)" )
ax.set_title("Conformal Predictive Distribution CDF" )
ax.legend()
ax.grid(True , alpha= 0.3 )
# Approximate PDF plot
ax = axes[1 ]
pdf_values = dist.pdf_approx(y_range)
ax.plot(y_range, pdf_values, "b-" , linewidth= 2 , label= "Approximate PDF" )
ax.axvline(y_test[0 ], color= "red" , linestyle= "--" , label= "True value" )
ax.axvline(dist.point_prediction, color= "green" , linestyle= ":" , label= "Prediction" )
ax.fill_between(y_range, pdf_values, alpha= 0.3 )
ax.set_xlabel("y" )
ax.set_ylabel("Density" )
ax.set_title("Approximate Predictive Density (KDE smoothed)" )
ax.legend()
ax.grid(True , alpha= 0.3 )
plt.tight_layout()
plt.show()
Asymmetric Intervals from CPD
CPD can produce asymmetric intervals by using different quantile levels.
Code
fig, ax = plt.subplots(figsize= (10 , 5 ))
# Get predictions and true values
n_plot = 15
predictions = cpd.predict(X_test[:n_plot])
# Standard symmetric interval
intervals_sym = cpd.predict_interval(X_test[:n_plot], alpha= 0.1 )
# Asymmetric intervals (different tail probabilities)
lower_asym = cpd.predict_quantile(X_test[:n_plot], 0.02 ) # 2nd percentile
upper_asym = cpd.predict_quantile(X_test[:n_plot], 0.92 ) # 92nd percentile
x_pos = np.arange(n_plot)
# Plot symmetric intervals
ax.errorbar(
x_pos - 0.15 ,
predictions,
yerr= [predictions - intervals_sym[:, 0 ], intervals_sym[:, 1 ] - predictions],
fmt= "o" ,
capsize= 3 ,
capthick= 1 ,
label= "Symmetric 90%" ,
alpha= 0.7 ,
)
# Plot asymmetric intervals
ax.errorbar(
x_pos + 0.15 ,
predictions,
yerr= [predictions - lower_asym, upper_asym - predictions],
fmt= "s" ,
capsize= 3 ,
capthick= 1 ,
label= "Asymmetric (2%, 92%)" ,
alpha= 0.7 ,
)
# Plot true values
ax.scatter(x_pos, y_test[:n_plot], color= "red" , marker= "x" , s= 80 , zorder= 5 , label= "True values" )
ax.set_xlabel("Test Sample Index" )
ax.set_ylabel("Value" )
ax.set_title("Symmetric vs Asymmetric Prediction Intervals from CPD" )
ax.legend()
ax.grid(True , alpha= 0.3 )
plt.tight_layout()
plt.show()
Batch CDF Evaluation
Evaluate CDF at multiple points for decision-making.
Code
# Example: What's the probability that output is below a threshold?
threshold = 50.0
# Get P(Y <= threshold) for all test samples
cdf_at_threshold = cpd.predict_cdf(X_test, np.array([threshold]))[:, 0 ]
print (f" \n === Decision Support: P(Y ≤ { threshold} ) ===" )
print (f"Samples with P(Y ≤ { threshold} ) > 0.9: { np. sum (cdf_at_threshold > 0.9 )} " )
print (f"Samples with P(Y ≤ { threshold} ) < 0.1: { np. sum (cdf_at_threshold < 0.1 )} " )
print (f"Samples with moderate uncertainty: { np. sum ((cdf_at_threshold >= 0.3 ) & (cdf_at_threshold <= 0.7 ))} " )
=== Decision Support: P(Y ≤ 50.0) ===
Samples with P(Y ≤ 50.0) > 0.9: 43
Samples with P(Y ≤ 50.0) < 0.1: 16
Samples with moderate uncertainty: 48
Visualize Multiple Predictive Distributions
Code
fig, axes = plt.subplots(2 , 2 , figsize= (12 , 10 ))
# Select 4 test samples with different prediction characteristics
sample_indices = [0 , 10 , 20 , 30 ]
for ax, idx in zip (axes.flat, sample_indices):
dist = cpd.predict_distribution(X_test[idx : idx + 1 ])[0 ]
y_range = np.linspace(dist.point_prediction - 3 * dist.std(), dist.point_prediction + 3 * dist.std(), 200 )
cdf_values = dist.cdf(y_range)
ax.plot(y_range, cdf_values, "b-" , linewidth= 2 )
ax.axvline(y_test[idx], color= "red" , linestyle= "--" , linewidth= 2 , label= "True" )
ax.axvline(dist.point_prediction, color= "green" , linestyle= ":" , linewidth= 2 , label= "Pred" )
# Mark 90% interval
lower, upper = dist.interval(0.1 )
ax.axvspan(lower, upper, alpha= 0.2 , color= "blue" , label= "90% CI" )
ax.set_xlabel("y" )
ax.set_ylabel("P(Y ≤ y)" )
ax.set_title(f"Sample { idx} : pred= { dist. point_prediction:.1f} , true= { y_test[idx]:.1f} " )
if idx == 0 :
ax.legend(loc= "lower right" , fontsize= 9 )
ax.grid(True , alpha= 0.3 )
plt.suptitle("Conformal Predictive Distributions for Different Test Samples" , y= 1.02 )
plt.tight_layout()
plt.show()
Coverage Analysis
Code
# Test coverage at different alpha levels
alphas = [0.05 , 0.10 , 0.15 , 0.20 , 0.25 ]
coverages = []
widths = []
for alpha in alphas:
intervals = cpd.predict_interval(X_test, alpha= alpha)
covered = (y_test >= intervals[:, 0 ]) & (y_test <= intervals[:, 1 ])
coverages.append(np.mean(covered))
widths.append(np.mean(intervals[:, 1 ] - intervals[:, 0 ]))
print (" \n === Coverage Analysis ===" )
print (f" { 'Alpha' :<10} { 'Target' :>10} { 'Actual' :>10} { 'Width' :>10} " )
print ("-" * 45 )
for a, c, w in zip (alphas, coverages, widths):
print (f" { a:<10.2f} { 1 - a:>10.0%} { c:>10.1%} { w:>10.2f} " )
=== Coverage Analysis ===
Alpha Target Actual Width
---------------------------------------------
0.05 95% 93.1% 373.71
0.10 90% 89.4% 348.96
0.15 85% 84.4% 291.82
0.20 80% 76.2% 248.76
0.25 75% 74.4% 234.94
Summary
Conformal Predictive Distributions provide:
Full CDF: P(Y <= y) for any y
Arbitrary quantiles: Q(tau) for any tau in [0, 1]
Asymmetric intervals: Different tail probabilities
Decision support: Compute probabilities for thresholds
When to use CPD:
Need complete uncertainty quantification
Decision-making based on probability thresholds
Want asymmetric prediction intervals
Need to communicate uncertainty to stakeholders
Key methods:
predict_distribution(X): Get PredictiveDistribution objects
predict_cdf(X, y_values): Batch CDF evaluation
predict_quantile(X, tau): Batch quantile computation
predict_interval(X, alpha): Standard intervals (compatibility)