This example demonstrates Jackknife+ conformal regression, which uses leave-one-out (LOO) cross-validation to compute prediction intervals without requiring a separate calibration set.
Key takeaways:
Jackknife+ uses all data for both training and calibration
No need to hold out a separate calibration set
CV mode is faster for large datasets
Setup and Data Generation
Generate a regression problem with limited samples.
Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from conformalpy.evaluation import average_interval_width, interval_coverage_score
from conformalpy.regressor import ConformalRegressor, JackknifePlusRegressor
# Generate regression data (limited samples)
np.random.seed(42 )
X, y = make_regression(
n_samples= 300 ,
n_features= 10 ,
n_informative= 5 ,
noise= 10 ,
random_state= 42 ,
)
# For split conformal: train/calibrate/test split
X_train_full, X_test, y_train_full, y_test = train_test_split(X, y, test_size= 0.3 , random_state= 42 )
X_train, X_calib, y_train, y_calib = train_test_split(X_train_full, y_train_full, test_size= 0.4 , random_state= 42 )
print ("Split Conformal data sizes:" )
print (f" Train: { len (y_train)} , Calibrate: { len (y_calib)} , Test: { len (y_test)} " )
print (" \n Jackknife+ data sizes:" )
print (f" Train+Calibrate: { len (y_train_full)} , Test: { len (y_test)} " )
Split Conformal data sizes:
Train: 126, Calibrate: 84, Test: 90
Jackknife+ data sizes:
Train+Calibrate: 210, Test: 90
Method 2: Jackknife+ (LOO)
Uses all data via leave-one-out cross-validation.
Code
jp_loo = JackknifePlusRegressor(
base_estimator= Ridge(alpha= 1.0 ),
alpha= 0.10 ,
cv= None , # None = leave-one-out
)
jp_loo.fit(X_train_full, y_train_full)
intervals_loo = jp_loo.predict_interval(X_test)
coverage_loo = interval_coverage_score(y_test, intervals_loo)
width_loo = average_interval_width(intervals_loo)
print (" \n === Jackknife+ (LOO) ===" )
print (f"Training + calibration samples: { len (y_train_full)} " )
print (f"Coverage: { coverage_loo:.1%} " )
print (f"Avg width: { width_loo:.2f} " )
=== Jackknife+ (LOO) ===
Training + calibration samples: 210
Coverage: 94.4%
Avg width: 36.21
Method 3: Jackknife+ (CV mode)
Faster alternative using K-fold CV instead of LOO.
Code
jp_cv = JackknifePlusRegressor(
base_estimator= Ridge(alpha= 1.0 ),
alpha= 0.10 ,
cv= 5 , # Use 5-fold CV
random_state= 42 ,
)
jp_cv.fit(X_train_full, y_train_full)
intervals_cv = jp_cv.predict_interval(X_test)
coverage_cv = interval_coverage_score(y_test, intervals_cv)
width_cv = average_interval_width(intervals_cv)
print (" \n === Jackknife+ (5-fold CV) ===" )
print (f"Training + calibration samples: { len (y_train_full)} " )
print (f"Coverage: { coverage_cv:.1%} " )
print (f"Avg width: { width_cv:.2f} " )
=== Jackknife+ (5-fold CV) ===
Training + calibration samples: 210
Coverage: 94.4%
Avg width: 36.18
Compare Results
Visualize the comparison between methods.
Code
fig, axes = plt.subplots(1 , 2 , figsize= (12 , 5 ))
methods = ["Split CP" , "J+ (LOO)" , "J+ (CV)" ]
coverages = [coverage_split, coverage_loo, coverage_cv]
widths = [width_split, width_loo, width_cv]
colors = ["steelblue" , "coral" , "mediumseagreen" ]
# Coverage comparison
ax = axes[0 ]
bars = ax.bar(methods, coverages, color= colors, edgecolor= "black" , alpha= 0.8 )
ax.axhline(y= 0.90 , color= "red" , linestyle= "--" , linewidth= 2 , label= "Target (90%)" )
ax.set_ylabel("Coverage" )
ax.set_title("Coverage Comparison" )
ax.set_ylim(0.8 , 1.0 )
ax.legend()
for bar, cov in zip (bars, coverages):
ax.annotate(
f" { cov:.1%} " ,
xy= (bar.get_x() + bar.get_width() / 2 , bar.get_height()),
xytext= (0 , 3 ),
textcoords= "offset points" ,
ha= "center" ,
va= "bottom" ,
fontsize= 11 ,
)
# Width comparison
ax2 = axes[1 ]
bars2 = ax2.bar(methods, widths, color= colors, edgecolor= "black" , alpha= 0.8 )
ax2.set_ylabel("Average Interval Width" )
ax2.set_title("Interval Width Comparison" )
for bar, w in zip (bars2, widths):
ax2.annotate(
f" { w:.1f} " ,
xy= (bar.get_x() + bar.get_width() / 2 , bar.get_height()),
xytext= (0 , 3 ),
textcoords= "offset points" ,
ha= "center" ,
va= "bottom" ,
fontsize= 11 ,
)
plt.tight_layout()
plt.suptitle("Jackknife+ vs Split Conformal" , fontsize= 14 , y= 1.02 )
plt.show()
Visualize Prediction Intervals
Show intervals for a subset of test samples.
Code
fig, axes = plt.subplots(3 , 1 , figsize= (12 , 10 ), sharex= True )
# Sort by true value for better visualization
n_show = 50
sort_idx = np.argsort(y_test)[:n_show]
methods_data = [
("Split Conformal" , intervals_split),
("Jackknife+ (LOO)" , intervals_loo),
("Jackknife+ (CV)" , intervals_cv),
]
colors = ["steelblue" , "coral" , "mediumseagreen" ]
for ax, (name, intervals), color in zip (axes, methods_data, colors):
y_sorted = y_test[sort_idx]
int_sorted = intervals[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= 20 , zorder= 5 , label= "Covered" )
ax.scatter(x_pos[~ covered], y_sorted[~ covered], color= "red" , s= 20 , zorder= 5 , label= "Not covered" )
ax.set_ylabel("Value" )
ax.set_title(f" { name} (Coverage: { np. mean(covered):.1%} )" )
if ax == axes[0 ]:
ax.legend(loc= "upper left" )
axes[- 1 ].set_xlabel("Sample (sorted by true value)" )
plt.tight_layout()
plt.show()
Summary
Key findings:
All methods achieve target coverage (~90%)
Jackknife+ uses all data, producing potentially tighter intervals
CV mode is much faster than LOO with similar results
When to use Jackknife+:
Limited data (can’t afford separate calibration set)
Single fit() call preferred
sklearn pipeline compatibility needed
Computational considerations:
LOO: O(n) model fits (slow for large n)
CV mode: O(K) model fits (use for n > 500)
Code
print (" \n " + "=" * 60 )
print ("SUMMARY" )
print ("=" * 60 )
print (f" { 'Method' :<25} { 'Coverage' :>12} { 'Avg Width' :>12} " )
print ("-" * 60 )
print (f" { 'Split Conformal' :<25} { coverage_split:>11.1%} { width_split:>12.2f} " )
print (f" { 'Jackknife+ (LOO)' :<25} { coverage_loo:>11.1%} { width_loo:>12.2f} " )
print (f" { 'Jackknife+ (5-fold CV)' :<25} { coverage_cv:>11.1%} { width_cv:>12.2f} " )
print ("=" * 60 )
============================================================
SUMMARY
============================================================
Method Coverage Avg Width
------------------------------------------------------------
Split Conformal 92.2% 35.20
Jackknife+ (LOO) 94.4% 36.21
Jackknife+ (5-fold CV) 94.4% 36.18
============================================================