This example compares the three conformal regression methods available in conformalpy:
- ConformalRegressor: Fixed-width intervals (split conformal)
- CQR: Adaptive intervals using quantile regression
- NormalizedConformalRegressor: Adaptive intervals using sigma model
All methods provide the same coverage guarantee, but differ in interval efficiency (width) and requirements.
Key Takeaways:
- All methods achieve the target coverage (90%)
- CQR and Normalized CP produce adaptive (varying width) intervals
- CQR typically has best efficiency but requires quantile regression
- Normalized CP is a good alternative when quantile regression isn’t available
Setup and Data Generation
Generate heteroscedastic data where noise varies with X.
Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.model_selection import train_test_split
from conformalpy.evaluation import regression_summary
from conformalpy.regressor import CQR, ConformalRegressor, NormalizedConformalRegressor
# Generate heteroscedastic data
np.random.seed(42)
n_samples = 2000
X = np.random.randn(n_samples, 5)
# Noise increases with X[:, 0] - this is heteroscedasticity
noise_scale = 0.5 + 1.5 * np.abs(X[:, 0])
y = 2 * X[:, 0] + X[:, 1] - X[:, 2] + noise_scale * np.random.randn(n_samples)
# 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"Train: {len(y_train)}, Calibration: {len(y_calib)}, Test: {len(y_test)}")
Train: 1200, Calibration: 400, Test: 400
Method 2: CQR (Quantile Regression)
Conformalized Quantile Regression with adaptive intervals.
Code
# Train quantile models
model_lo = GradientBoostingRegressor(loss="quantile", alpha=0.05, n_estimators=100, random_state=42)
model_hi = GradientBoostingRegressor(loss="quantile", alpha=0.95, n_estimators=100, random_state=42)
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)
intervals_cqr = cqr.predict_interval(X_test)
summary_cqr = regression_summary(y_test, intervals_cqr, alpha=0.10)
print("\n=== CQR ===")
print(f"Coverage: {summary_cqr['coverage']:.1%}")
print(f"Avg Width: {summary_cqr['avg_width']:.3f}")
print(f"Width Std: {np.std(intervals_cqr[:, 1] - intervals_cqr[:, 0]):.3f}")
=== CQR ===
Coverage: 91.8%
Avg Width: 6.367
Width Std: 2.031
Compare Interval Width Distributions
Visualize how interval widths differ between methods.
Code
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
widths_split = intervals_split[:, 1] - intervals_split[:, 0]
widths_cqr = intervals_cqr[:, 1] - intervals_cqr[:, 0]
widths_norm = intervals_norm[:, 1] - intervals_norm[:, 0]
def plot_width_hist(ax, widths, color, title, coverage):
"""Plot histogram handling zero-variance case (fixed-width intervals)."""
mean_width = np.mean(widths)
if np.std(widths) < 1e-10:
# Fixed-width intervals: use a bar chart instead
ax.bar([mean_width], [len(widths)], width=mean_width * 0.1, edgecolor="black", alpha=0.7, color=color)
ax.set_xlim(mean_width * 0.8, mean_width * 1.2)
ax.annotate(
f"Fixed width\n{mean_width:.2f}", xy=(mean_width, len(widths)), ha="center", va="bottom", fontsize=10
)
else:
ax.hist(widths, bins=30, edgecolor="black", alpha=0.7, color=color)
ax.axvline(mean_width, color="red", linestyle="--", label=f"Mean: {mean_width:.2f}")
ax.legend()
ax.set_title(f"{title}\n(Coverage: {coverage:.1%})")
ax.set_xlabel("Interval Width")
plot_width_hist(axes[0], widths_split, "blue", "Split Conformal", summary_split["coverage"])
plot_width_hist(axes[1], widths_cqr, "green", "CQR", summary_cqr["coverage"])
plot_width_hist(axes[2], widths_norm, "orange", "Normalized CP", summary_norm["coverage"])
plt.suptitle("Interval Width Distributions by Method", fontsize=14)
plt.tight_layout()
plt.show()
Visualize Intervals for Each Method
Show prediction intervals sorted by true value.
Code
fig, axes = plt.subplots(3, 1, figsize=(12, 10))
# Subsample for cleaner visualization
n_show = 100
idx = np.random.choice(len(y_test), n_show, replace=False)
sort_idx = np.argsort(y_test[idx])
for ax, intervals, name, color in zip(
axes,
[intervals_split, intervals_cqr, intervals_norm],
["Split Conformal", "CQR", "Normalized CP"],
["blue", "green", "orange"],
):
y_sorted = y_test[idx][sort_idx]
int_sorted = intervals[idx][sort_idx]
covered = (y_sorted >= int_sorted[:, 0]) & (y_sorted <= int_sorted[:, 1])
x_pos = np.arange(n_show)
ax.fill_between(x_pos, int_sorted[:, 0], int_sorted[:, 1], alpha=0.3, color=color)
ax.scatter(x_pos[covered], y_sorted[covered], color="green", s=15, zorder=5)
ax.scatter(x_pos[~covered], y_sorted[~covered], color="red", s=15, zorder=5)
ax.set_ylabel("Value")
ax.set_title(f"{name} (Coverage: {np.mean(covered):.1%})")
axes[-1].set_xlabel("Sample (sorted by true value)")
plt.tight_layout()
plt.show()
Summary Comparison
Compare all methods side by side.
Code
print("\n" + "=" * 60)
print("SUMMARY COMPARISON")
print("=" * 60)
print(f"{'Method':<25} {'Coverage':>12} {'Avg Width':>12} {'Width Std':>12}")
print("-" * 60)
print(
f"{'Split Conformal':<25} {summary_split['coverage']:>11.1%} {summary_split['avg_width']:>12.3f} {np.std(widths_split):>12.4f}"
)
print(f"{'CQR':<25} {summary_cqr['coverage']:>11.1%} {summary_cqr['avg_width']:>12.3f} {np.std(widths_cqr):>12.3f}")
print(
f"{'Normalized CP':<25} {summary_norm['coverage']:>11.1%} {summary_norm['avg_width']:>12.3f} {np.std(widths_norm):>12.3f}"
)
print("=" * 60)
============================================================
SUMMARY COMPARISON
============================================================
Method Coverage Avg Width Width Std
------------------------------------------------------------
Split Conformal 91.8% 7.456 0.0000
CQR 91.8% 6.367 2.031
Normalized CP 92.5% 6.697 3.679
============================================================
Key Observations
Coverage: All methods achieve >=90% coverage (target)
Split Conformal: Nearly constant width (std ≈ 0)
- Simplest to implement
- Works with any base model
- Inefficient for heteroscedastic data
CQR: Varying widths that adapt to local uncertainty
- Best efficiency (often smallest avg width)
- Requires quantile regression models
Normalized CP: Also adaptive, using sigma model
- Good alternative to CQR
- Works with any base regressor
- Requires training an additional sigma model
Recommendation: Use CQR when quantile regression is available, Normalized CP otherwise, and Split Conformal for simplicity.