Regression with Conformal Prediction

conformalpy also supports conformal prediction for regression tasks, producing prediction intervals with coverage guarantees.

The Coverage Guarantee (Regression)

For regression, the coverage guarantee ensures:

\[P(Y_{test} \in [\hat{y} - \hat{q}, \hat{y} + \hat{q}]) \geq 1 - \alpha\]

This means: if you set alpha=0.10, the prediction interval will contain the true value at least 90% of the time.

Basic Usage

from sklearn.ensemble import RandomForestRegressor
from conformalpy.regressor import ConformalRegressor

# Train base model
model = RandomForestRegressor().fit(X_train, y_train)

# Create conformal regressor
cr = ConformalRegressor(model=model, alpha=0.10)

# Calibrate on held-out data
cr.calibrate(X_calib, y_calib)

# Get prediction intervals
intervals = cr.predict_interval(X_test)
# intervals[:, 0] = lower bounds
# intervals[:, 1] = upper bounds

# Check coverage
print(f"Coverage: {cr.score(X_test, y_test):.1%}")

The Split Conformal Method

ConformalRegressor uses absolute residuals as nonconformity scores:

\[s_i = |y_i - \hat{y}_i|\]

The quantile threshold is computed to ensure finite-sample coverage:

\[\hat{q} = \text{Quantile}(s_1, ..., s_n; \lceil (n+1)(1-\alpha) \rceil / n)\]

Prediction intervals are then symmetric around the point prediction:

\[C(x) = [\hat{y}(x) - \hat{q}, \hat{y}(x) + \hat{q}]\]

Regression Evaluation Metrics

conformalpy provides metrics for evaluating prediction intervals:

from conformalpy.evaluation import (
    interval_coverage_score,  # Proportion of true values in intervals
    average_interval_width,   # Mean interval width
    winkler_score,            # Penalized interval score
    regression_summary,       # All metrics combined
)

# Evaluate intervals
coverage = interval_coverage_score(y_test, intervals)
width = average_interval_width(intervals)
winkler = winkler_score(y_test, intervals, alpha=0.1)

# Or get everything at once
summary = regression_summary(y_test, intervals, alpha=0.1)
print(f"Coverage: {summary['coverage']:.1%}")
print(f"Width: {summary['avg_width']:.2f}")

Winkler Score

The Winkler score penalizes both interval width and coverage failures:

  • When the true value is covered: score = interval width
  • When below the interval: score = width + (2/α) × distance below
  • When above the interval: score = width + (2/α) × distance above

Lower Winkler score is better.

Comparing Alpha Values

The choice of alpha affects the trade-off between coverage and interval width:

Alpha Target Coverage Interval Width Use Case
0.05 95% Wider High-stakes decisions
0.10 90% Medium Default choice
0.20 80% Narrower Exploratory analysis

Conformalized Quantile Regression (CQR)

For adaptive prediction intervals that are narrower where the model is confident, use CQR:

from sklearn.ensemble import GradientBoostingRegressor
from conformalpy.regressor import CQR

# Train quantile regression models (5th and 95th percentiles)
model_lo = GradientBoostingRegressor(loss='quantile', alpha=0.05)
model_hi = GradientBoostingRegressor(loss='quantile', alpha=0.95)
model_lo.fit(X_train, y_train)
model_hi.fit(X_train, y_train)

# Create and calibrate CQR
cqr = CQR(model_lower=model_lo, model_upper=model_hi, alpha=0.10)
cqr.calibrate(X_calib, y_calib)

# Get adaptive intervals
intervals = cqr.predict_interval(X_test)

CQR vs Split Conformal:

Method Interval Width Best For
Split Conformal Fixed (same for all samples) Simple, any base model
CQR Adaptive (varies by sample) Heteroscedastic data

CQR uses the nonconformity score:

\[E_i = \max(\hat{q}_{lo}(X_i) - Y_i, Y_i - \hat{q}_{hi}(X_i))\]

This captures how much the true value exceeds the predicted quantile interval.

See the regression methods comparison example for a comparison of Split Conformal, CQR, and Normalized CP.

Normalized Conformal Prediction

For adaptive intervals without quantile regression, use NormalizedConformalRegressor. It scales residuals by a learned uncertainty estimate (sigma):

import numpy as np
from sklearn.ensemble import RandomForestRegressor
from conformalpy.regressor import NormalizedConformalRegressor

# Train main model
model = RandomForestRegressor().fit(X_train, y_train)

# Train sigma model on absolute residuals
train_preds = model.predict(X_train)
abs_residuals = np.abs(y_train - train_preds)
sigma_model = RandomForestRegressor().fit(X_train, abs_residuals)

# Create and calibrate
ncr = NormalizedConformalRegressor(
    model=model, sigma_model=sigma_model, alpha=0.10
)
ncr.calibrate(X_calib, y_calib)

# Get adaptive intervals
intervals = ncr.predict_interval(X_test)

Comparison of Regression Methods:

Method Intervals Requirements Use Case
ConformalRegressor Fixed width Any regressor Simple, homoscedastic
CQR Adaptive Quantile regression Best efficiency
NormalizedConformalRegressor Adaptive Sigma model No quantile regression
JackknifePlusRegressor Fixed width Any regressor Limited data (no calibration set)
ConformalPredictiveDistribution Full CDF Any regressor Complete uncertainty quantification

Conformal Predictive Distributions

Unlike standard conformal regression which outputs prediction intervals, Conformal Predictive Distributions (CPD) provide a full probability distribution for each prediction. This enables:

  • Computing P(Y <= threshold) for any threshold
  • Extracting any quantile (not just symmetric intervals)
  • Asymmetric prediction intervals
  • Complete uncertainty characterization
from sklearn.ensemble import RandomForestRegressor
from conformalpy.regressor import ConformalPredictiveDistribution

# Train base model
model = RandomForestRegressor().fit(X_train, y_train)

# Create CPD
cpd = ConformalPredictiveDistribution(model=model, alpha=0.1)
cpd.calibrate(X_calib, y_calib)

# Get predictive distribution for a test sample
distributions = cpd.predict_distribution(X_test[0:1])
dist = distributions[0]

# Evaluate CDF: What's P(Y <= 100)?
prob = dist.cdf(100.0)

# Get any quantile
median = dist.quantile(0.5)
q95 = dist.quantile(0.95)

# Get prediction interval
lower, upper = dist.interval(alpha=0.1)

Batch operations:

# Evaluate CDF at multiple thresholds
thresholds = np.array([50, 100, 150])
cdf_matrix = cpd.predict_cdf(X_test, thresholds)  # (n_samples, 3)

# Get multiple quantiles
quantiles = cpd.predict_quantile(X_test, [0.25, 0.5, 0.75])  # (n_samples, 3)

# Standard prediction intervals
intervals = cpd.predict_interval(X_test, alpha=0.1)  # (n_samples, 2)

When to use CPD:

  • Need complete uncertainty quantification
  • Decision-making based on probability thresholds
  • Want asymmetric prediction intervals
  • Need to communicate uncertainty to stakeholders

Reference:

Vovk, V., Shen, J., Manokhin, V., & Xie, M. (2017). “Nonparametric Predictive Distributions Based on Conformal Prediction.” Machine Learning.

See the conformal predictive distributions example for a complete CPD workflow.

Jackknife+ (LOO/CV+)

Jackknife+ (Barber et al. 2021) is a true cross-conformal procedure, not split conformal with cross-validated residuals. Concretely:

  1. The data is partitioned into \(K\) folds (with \(K = n\) for the leave-one-out variant). For each fold \(i\), a model \(\hat{\mu}_{-i}\) is trained on the other folds and the out-of-fold residual \(R_i = \lvert y_i - \hat{\mu}_{-i}(x_i) \rvert\) is recorded.
  2. At test time the per-fold predictors are kept and used. For a new \(x_{n+1}\) the prediction interval is built from the \(\lceil \alpha (n+1) \rceil\)-th and \(\lceil (1 - \alpha) (n+1) \rceil\)-th order statistics of \(\{ \hat{\mu}_{-i}(x_{n+1}) \pm R_i : i = 1, \dots, n \}\), not from a single quantile applied to a refit full-data model.

This is what gives jackknife+ its \(1 - 2\alpha\) coverage guarantee without ever holding out a calibration set:

from sklearn.ensemble import RandomForestRegressor
from conformalpy.regressor import JackknifePlusRegressor

# No separate calibration set needed!
jp = JackknifePlusRegressor(
    base_estimator=RandomForestRegressor(n_estimators=100),
    alpha=0.10,
)

jp.fit(X_train, y_train)  # Uses LOO internally
intervals = jp.predict_interval(X_test)

For large datasets, use K-fold CV mode for faster computation:

# Use 5-fold CV instead of LOO (faster for large datasets)
jp = JackknifePlusRegressor(
    base_estimator=RandomForestRegressor(n_estimators=100),
    alpha=0.10,
    cv=5,  # Use K-fold instead of LOO
)

See the Jackknife+ example for a complete Jackknife+ workflow.

Regression Nonconformity Functions

conformalpy provides several nonconformity score functions for regression:

from conformalpy.nonconformity.regression import (
    absolute_residual,      # |y - y_pred| (standard)
    signed_residual,        # y - y_pred (asymmetric)
    normalized_residual,    # |y - y_pred| / sigma
    gamma_residual,         # |y - y_pred| / |y_pred| (proportional)
    compute_conformal_quantile,  # Quantile with finite-sample correction
)

When to use each:

  • absolute_residual: Default choice, symmetric intervals
  • signed_residual: When errors are asymmetric (e.g., always positive)
  • normalized_residual: For adaptive intervals with NormalizedConformalRegressor
  • gamma_residual: When relative error matters (e.g., prices, counts)

Regression Visualization

Visualize prediction intervals and coverage:

from conformalpy.plots import (
    plot_prediction_intervals,  # Intervals with true values
    plot_interval_widths,       # Width distribution histogram
    plot_coverage_by_alpha,     # Coverage vs alpha trade-off
    plot_residuals_vs_intervals,  # Residuals vs interval bounds
)

# Plot intervals sorted by true value
fig, ax = plot_prediction_intervals(y_test, intervals, sort_by='y_true')

# Coverage vs alpha sensitivity analysis
fig, ax = plot_coverage_by_alpha(
    alphas=[0.05, 0.10, 0.15, 0.20],
    coverages=[0.96, 0.91, 0.87, 0.82],
    widths=[2.5, 2.0, 1.7, 1.4],  # Optional: show width on secondary axis
)

See the basic regression example for a complete regression workflow with the California Housing dataset.

Multi-Output Conformal Regression

When predicting multiple targets simultaneously, MultiOutputConformalRegressor provides prediction intervals with joint or marginal coverage guarantees.

from conformalpy.regressor import MultiOutputConformalRegressor

cr = MultiOutputConformalRegressor(
    model=multi_output_model,  # sklearn-compatible multi-output model
    alpha=0.1,
    strategy='bonferroni',  # 'marginal', 'bonferroni', or 'max_residual'
)
cr.calibrate(X_calib, y_calib)  # y_calib shape: (n_samples, n_targets)

# Prediction intervals: shape (n_samples, 2, n_targets)
intervals = cr.predict_interval(X_test)

# Joint coverage (all targets simultaneously)
joint_cov = cr.score(X_test, y_test)

# Per-target marginal coverage
marginal_covs = cr.marginal_coverage(X_test, y_test)

Coverage Strategies:

Strategy Coverage Guarantee Interval Width Best For
marginal Per-target only Narrowest Independent targets
bonferroni Joint (conservative) Medium Few targets, simple
max_residual Joint (exact) Tightest joint Different scales

The max_residual strategy normalizes each target’s residuals by the median of its absolute residuals (a robust scale estimator — not the median absolute deviation about the median), making the joint score scale-invariant and suitable for targets with very different magnitudes.

See multi-output regression example for a complete multi-output regression example.

References

Barber, Rina Foygel, Emmanuel J. Candès, Aaditya Ramdas, and Ryan J. Tibshirani. 2021. “Predictive Inference with the Jackknife+.” The Annals of Statistics 49 (1): 486–507. https://doi.org/10.1214/20-AOS1965.
Lei, Jing, Max G’Sell, Alessandro Rinaldo, Ryan J. Tibshirani, and Larry Wasserman. 2018. “Distribution-Free Predictive Inference for Regression.” Journal of the American Statistical Association 113 (523): 1094–111. https://doi.org/10.1080/01621459.2017.1307116.
Lei, Jing, and Larry Wasserman. 2014. “Distribution-Free Prediction Bands for Non-Parametric Regression.” Journal of the Royal Statistical Society: Series B 76 (1): 71–96. https://doi.org/10.1111/rssb.12021.
Messoudi, Soundouss, Sébastien Destercke, and Sylvain Rousseau. 2021. “Copula-Based Conformal Prediction for Multi-Target Regression.” Pattern Recognition 120: 108101. https://doi.org/10.1016/j.patcog.2021.108101.
Papadopoulos, Harris, and Haris Haralambous. 2011. “Reliable Prediction Intervals with Regression Neural Networks.” Neural Networks 24 (8): 842–51. https://doi.org/10.1016/j.neunet.2011.05.008.
Romano, Yaniv, Evan Patterson, and Emmanuel Candès. 2019. “Conformalized Quantile Regression.” Advances in Neural Information Processing Systems 32.
Vovk, Vladimir. 2015. “Cross-Conformal Predictors.” Annals of Mathematics and Artificial Intelligence 74 (1–2): 9–28. https://doi.org/10.1007/s10472-013-9368-4.
Vovk, Vladimir, Alexander Gammerman, and Glenn Shafer. 2005. Algorithmic Learning in a Random World. Springer. https://doi.org/10.1007/b106715.
Vovk, Vladimir, Jieli Shen, Valery Manokhin, and Min-ge Xie. 2018. “Nonparametric Predictive Distributions Based on Conformal Prediction.” Machine Learning 108 (3): 445–74. https://doi.org/10.1007/s10994-018-5755-8.
Winkler, Robert L. 1972. “A Decision-Theoretic Approach to Interval Estimation.” Journal of the American Statistical Association 67 (337): 187–91. https://doi.org/10.1080/01621459.1972.10481224.