This example demonstrates the JackknifePlusClassifier which uses leave-one-out (LOO) or K-fold cross-validation to compute nonconformity scores, eliminating the need for a separate calibration set.
Key advantages of Jackknife+:
Uses all data for both training and calibration
No need to hold out a separate calibration set
Provides finite-sample coverage guarantees
Trade-offs:
More computationally expensive (O(n) or O(K) model fits)
For large datasets, use cv=K for faster K-fold approximation
Generate Classification Data
We create a 5-class classification problem.
Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from conformalpy.classifier import (
ConformalClassifier,
CVPlusClassifier,
JackknifePlusClassifier,
)
from conformalpy.evaluation import average_set_size, coverage_score
from conformalpy.nonconformity.classification import lac_nonconformity
X, y = make_classification(
n_samples= 1000 ,
n_features= 20 ,
n_informative= 10 ,
n_classes= 5 ,
n_clusters_per_class= 1 ,
random_state= 42 ,
)
# For split conformal: train/calibration/test split
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size= 0.4 , random_state= 42 , stratify= y)
X_cal, X_test, y_cal, y_test = train_test_split(X_temp, y_temp, test_size= 0.5 , random_state= 42 , stratify= y_temp)
# For Jackknife+/CV+: use train+cal combined, test separately
X_train_full = np.vstack([X_train, X_cal])
y_train_full = np.hstack([y_train, y_cal])
print (f"Split Conformal - Train: { len (X_train)} , Cal: { len (X_cal)} , Test: { len (X_test)} " )
print (f"Jackknife+/CV+ - Train: { len (X_train_full)} , Test: { len (X_test)} " )
Split Conformal - Train: 600, Cal: 200, Test: 200
Jackknife+/CV+ - Train: 800, Test: 200
Compare Three Methods
Split Conformal (ConformalClassifier)
CV+ (CVPlusClassifier)
Jackknife+ (JackknifePlusClassifier)
Code
alpha = 0.10
# Method 1: Split Conformal
model_split = LogisticRegression(max_iter= 1000 , random_state= 42 )
model_split.fit(X_train, y_train)
split_clf = ConformalClassifier(
model= model_split,
alpha= alpha,
nonconformity_function= lac_nonconformity,
)
split_clf.calibrate(X_cal, y_cal)
pred_sets_split = split_clf.predict(X_test)
# Method 2: CV+
cvplus_clf = CVPlusClassifier(
base_estimator= LogisticRegression(max_iter= 1000 , random_state= 42 ),
alpha= alpha,
n_splits= 5 ,
nonconformity_function= lac_nonconformity,
random_state= 42 ,
)
cvplus_clf.fit(X_train_full, y_train_full)
pred_sets_cvplus = cvplus_clf.predict(X_test)
# Method 3: Jackknife+ with K-fold CV
jp_clf = JackknifePlusClassifier(
base_estimator= LogisticRegression(max_iter= 1000 , random_state= 42 ),
alpha= alpha,
nonconformity_function= lac_nonconformity,
cv= 5 , # K-fold mode for speed
random_state= 42 ,
)
jp_clf.fit(X_train_full, y_train_full)
pred_sets_jp = jp_clf.predict(X_test)
Compare Coverage and Set Size
Code
results = {
"Split Conformal" : {
"coverage" : coverage_score(pred_sets_split, y_test),
"avg_size" : average_set_size(pred_sets_split),
"train_samples" : len (X_train),
},
"CV+ (5-fold)" : {
"coverage" : coverage_score(pred_sets_cvplus, y_test),
"avg_size" : average_set_size(pred_sets_cvplus),
"train_samples" : len (X_train_full),
},
"Jackknife+ (5-fold)" : {
"coverage" : coverage_score(pred_sets_jp, y_test),
"avg_size" : average_set_size(pred_sets_jp),
"train_samples" : len (X_train_full),
},
}
print (" \n Results (Target coverage: 90%)" )
print ("-" * 55 )
print (f" { 'Method' :<22} { 'Coverage' :>10} { 'Avg Size' :>10} { 'Train N' :>10} " )
print ("-" * 55 )
for method, res in results.items():
print (f" { method:<22} { res['coverage' ]:>10.1%} { res['avg_size' ]:>10.2f} { res['train_samples' ]:>10} " )
Results (Target coverage: 90%)
-------------------------------------------------------
Method Coverage Avg Size Train N
-------------------------------------------------------
Split Conformal 89.5% 1.56 600
CV+ (5-fold) 91.5% 1.66 800
Jackknife+ (5-fold) 91.5% 1.66 800
Visualize Comparison
Code
fig, axes = plt.subplots(1 , 2 , figsize= (12 , 5 ))
methods = list (results.keys())
colors = ["#3498db" , "#2ecc71" , "#9b59b6" ]
# Coverage comparison
ax = axes[0 ]
coverages = [results[m]["coverage" ] for m in methods]
bars = ax.bar(methods, coverages, color= colors)
ax.axhline(0.90 , color= "red" , linestyle= "--" , alpha= 0.7 , 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.text(
bar.get_x() + bar.get_width() / 2 ,
bar.get_height() + 0.005 ,
f" { cov:.1%} " ,
ha= "center" ,
fontsize= 10 ,
)
# Set size comparison
ax = axes[1 ]
avg_sizes = [results[m]["avg_size" ] for m in methods]
bars = ax.bar(methods, avg_sizes, color= colors)
ax.set_ylabel("Average Set Size" )
ax.set_title("Efficiency Comparison" )
for bar, size in zip (bars, avg_sizes):
ax.text(
bar.get_x() + bar.get_width() / 2 ,
bar.get_height() + 0.02 ,
f" { size:.2f} " ,
ha= "center" ,
fontsize= 10 ,
)
plt.tight_layout()
plt.show()
Runtime Alpha with Jackknife+
Like other conformal classifiers, Jackknife+ supports runtime alpha.
Code
alphas = [0.05 , 0.10 , 0.15 , 0.20 ]
jp_coverages = []
jp_sizes = []
for a in alphas:
pred_sets = jp_clf.predict(X_test, alpha= a)
jp_coverages.append(coverage_score(pred_sets, y_test))
jp_sizes.append(average_set_size(pred_sets))
fig, axes = plt.subplots(1 , 2 , figsize= (12 , 5 ))
# Coverage vs alpha
ax = axes[0 ]
ax.plot(alphas, jp_coverages, "o-" , color= "#9b59b6" , linewidth= 2 , markersize= 8 )
ax.plot(alphas, [1 - a for a in alphas], "--" , color= "red" , alpha= 0.7 , label= "Target (1-α)" )
ax.set_xlabel("Alpha (α)" )
ax.set_ylabel("Coverage" )
ax.set_title("Jackknife+ Coverage vs Alpha" )
ax.legend()
ax.grid(True , alpha= 0.3 )
# Set size vs alpha
ax = axes[1 ]
ax.plot(alphas, jp_sizes, "o-" , color= "#9b59b6" , linewidth= 2 , markersize= 8 )
ax.set_xlabel("Alpha (α)" )
ax.set_ylabel("Average Set Size" )
ax.set_title("Jackknife+ Set Size vs Alpha" )
ax.grid(True , alpha= 0.3 )
plt.tight_layout()
plt.show()
When to Use Each Method
Split Conformal (ConformalClassifier):
Fastest (single model fit)
Requires separate calibration set
Best when data is abundant
CV+ (CVPlusClassifier):
Moderate speed (K model fits)
Uses all data for training and calibration
Good balance of efficiency and coverage
Jackknife+ (JackknifePlusClassifier):
True LOO mode (cv=None): O(n) fits, most accurate
K-fold mode (cv=K): O(K) fits, good approximation
Best when data is limited and you need all samples
For most practical purposes, Jackknife+ with cv=5 or cv=10 provides similar results to CV+ with better theoretical guarantees.