Conformal prediction: distribution-free coverage guarantees
Build split conformal prediction from the rank lemma, study realized coverage, and design regression and classification scores. Compare full conformal, jackknife+, and CV+.
After this lesson you can
- Prove the split-conformal marginal coverage guarantee and upper bound without ties.
- Calculate the finite-sample corrected quantile and Beta distribution of coverage conditional on calibration.
- Implement residual, normalized, and CQR intervals plus LAC, APS, and RAPS sets from scratch.
- Evaluate sets by coverage, mean size, and adaptivity across difficulty strata.
- Compare split, full conformal, jackknife+, and CV+ in guarantee, cost, and data use.
Before you start
A guarantee with a condition
Conformal prediction can wrap an already trained model with a set containing the future answer at a controlled marginal probability, without assuming a parametric distribution or a correct model. A central condition remains: calibration examples and the future example must be exchangeable, conditional on the model and decisions made before calibration. Temporal shift or selecting the model using those same calibration scores can invalidate the guarantee. It does not guarantee coverage for every person or subgroup.
If are exchangeable and almost surely distinct, every rank of the last among is equally likely. For ties, an appropriate random rule restores uniformity; an inclusive inequality gives a conservative lower guarantee.
Split conformal and the +1
In split conformal, separate training and calibration. Fit the model only on training; compute on the held-out examples, with higher scores indicating worse fit. Define
The nonconformity score induces . With distinct scores and , the event is equivalent to the future score’s rank not exceeding . By uniformity,
If , the full set covers with probability one. With ties and an inclusive threshold the lower bound remains, but overcoverage is possible and the upper bound generally fails without tie-breaking. The guarantee averages over calibration and the future example. Angelopoulos y Bates develop the argument and its limits.
Coverage for a particular calibration
There is another question: once a calibration sample is fixed, what coverage will its threshold have on future examples? If scores are continuous iid, conditional on the independently trained model, realized coverage follows for . Its mean is and its variance . Exchangeability alone without independence does not imply this Beta law. For coverage is one and the distribution degenerates.
If conditional coverage must exceed a target with high probability, choose and using a Beta tail under those assumptions; do not confuse that requirement with the usual marginal guarantee. Nor does it give a conditional guarantee for each value of without further assumptions.
Designing scores
In regression, absolute residual gives constant-width bands. Dividing by positive scale fitted without calibration allows variable bands; a poor scale still yields marginal coverage if assumptions hold, though it may be inefficient. Conformalized quantile regression (CQR) starts from estimated quantiles and uses ; the threshold can be negative and narrow a conservative band. Romano and colleagues present the method.
In classification, LAC uses . For adaptive sets, order classes by probability and use the sum before plus , with . APS applies that score to each candidate label; RAPS adds to penalize large ranks. The same random variable per example keeps sets nested in this design. Randomization can produce empty sets; omitting it or including a boundary label uses another convention and changes size and coverage. Romano, Sesia, and Candès y Angelopoulos and colleagues study APS and RAPS.
Overall coverage near target does not require every group to achieve it: here the hard group is defined by maximum confidence below 0.8. Stratifying and calibrating by group can provide another marginal guarantee per group if the partition and assumptions are fixed correctly and enough data are available.
Beyond one split
Full conformal, jackknife+, and CV+ trade off cost and data use. Full conformal incorporates each test candidate and refits symmetrically, with marginal coverage at least under exchangeability. Jackknife+ uses leave-one-out fits and their predictions at the new point; under the conditions of Barber and colleagues it guarantees at least . CV+ uses fits, but its general finite bound includes an additional term: for example, at least , not exactly for every . Stability can improve guarantees under additional assumptions. MAPIE and crepes offer implementations; compare conventions, randomization, and splits before expecting identical sets.
Lab: implementations from scratch
First fix the models without touching calibration. In regression the normalized scale is known because the generator is synthetic; in a real application estimate it only from training. Repeat 1000 splits of a held-out set and observe coverage and width. For digits, a fixed classifier is trained on 800 images and the remainder split 1000 times into calibration and test. Splits overlap across repetitions: averages summarize this study, not 1000 independent datasets. To check the Beta law, 1000 fresh iid calibrations of continuous uniform scores are generated separately.
"""Conformal split, CQR y conjuntos LAC/APS/RAPS."""
import numpy as np
from scipy.stats import norm,beta
def qhat(scores,alpha):
scores=np.asarray(scores);n=len(scores);k=int(np.ceil((n+1)*(1-alpha)))
if not 0<alpha<1:raise ValueError('alpha debe estar en (0,1)')
return np.inf if k>n else float(np.partition(scores,k-1)[k-1])
def class_scores(probs,u,method='aps',lam=0.,kreg=0):
"""Una U por fila, compartida entre clases: conjuntos anidados."""
probs=np.asarray(probs);u=np.asarray(u);order=np.argsort(-probs,axis=1,kind='stable')
ordered=np.take_along_axis(probs,order,axis=1);previous=np.cumsum(ordered,axis=1)-ordered
rank=np.arange(1,probs.shape[1]+1)[None,:]
if method=='lac':score=1-ordered
elif method in ('aps','raps'):
score=previous+u[:,None]*ordered+(lam*np.maximum(rank-kreg,0) if method=='raps' else 0)
else:raise ValueError('método desconocido')
result=np.empty_like(score);np.put_along_axis(result,order,score,axis=1);return result
def prediction_sets(probs,cal_probs,cal_y,alpha,rng,method='aps',lam=0.,kreg=0,randomized=True):
uc=rng.random(len(cal_y)) if randomized else np.zeros(len(cal_y))
ut=rng.random(len(probs)) if randomized else np.zeros(len(probs))
sc=class_scores(cal_probs,uc,method,lam,kreg);threshold=qhat(sc[np.arange(len(cal_y)),cal_y],alpha)
return class_scores(probs,ut,method,lam,kreg)<=threshold,threshold
def summarize(sets,labels,probs):
covered=sets[np.arange(len(labels)),labels];sizes=sets.sum(1);difficulty=probs.max(1)<.8
for name,mask in [('total',np.ones(len(labels),bool)),('difícil',difficulty),('fácil',~difficulty)]:
if mask.any():print(name,'n',mask.sum(),'cobertura',covered[mask].mean(),'tamaño',sizes[mask].mean())"""Ejecutar tras definir qhat: datos y modelos, 1000 particiones."""
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
rng=np.random.default_rng(30)
def sigma(x):return .15+.40/(1+np.exp(-2*x))
x=rng.uniform(-3,3,2500);y=np.sin(x)+sigma(x)*rng.normal(size=len(x));tr=np.arange(500);pool=np.arange(500,2500)mean_model=GradientBoostingRegressor(n_estimators=80,max_depth=2,random_state=30).fit(x[tr,None],y[tr])lower_model=GradientBoostingRegressor(loss='quantile',alpha=.05,n_estimators=80,max_depth=2,random_state=30).fit(x[tr,None],y[tr])upper_model=GradientBoostingRegressor(loss='quantile',alpha=.95,n_estimators=80,max_depth=2,random_state=30).fit(x[tr,None],y[tr])xx=x[pool];yy=y[pool];m=mean_model.predict(xx[:,None]);lo=lower_model.predict(xx[:,None]);hi=upper_model.predict(xx[:,None]);sc=sigma(xx)
S={'residuo':abs(yy-m),'normalizado':abs(yy-m)/sc,'cqr':np.maximum(lo-yy,yy-hi)}
coverage={name:[] for name in S};width={name:[] for name in S};rg=np.random.default_rng(32)
for _ in range(1000):
order=rg.permutation(len(xx));cal=order[:400];test=order[400:]
for name in S:
q=qhat(S[name][cal],.1)
if name=='residuo':a,b=m[test]-q,m[test]+q
elif name=='normalizado':a,b=m[test]-q*sc[test],m[test]+q*sc[test]
else:a,b=lo[test]-q,hi[test]+q
coverage[name].append(np.mean((yy[test]>=a)&(yy[test]<=b)));width[name].append(np.mean(b-a))
for name in S:print(name,'cobertura media',np.mean(coverage[name]),'anchura media',np.mean(width[name]))"""Cobertura condicionada exacta para scores Uniforme(0,1) iid."""
from scipy.stats import beta
rg=np.random.default_rng(30);n=100;alpha=.1;k=int(np.ceil((n+1)*(1-alpha)))
scores=rg.random((1000,n));conditional=np.partition(scores,k-1,axis=1)[:,k-1]
print('n',n,'k',k,'media simulada',conditional.mean(),'sd simulada',conditional.std(),'media Beta',beta.mean(k,n+1-k),'sd Beta',beta.std(k,n+1-k))"""Dígitos reales, modelo fijo y 1000 particiones de calibración/test."""
from sklearn.datasets import load_digits
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
digits=load_digits();D=digits.data;labels=digits.target
train,pool=train_test_split(np.arange(len(labels)),train_size=800,random_state=30,stratify=labels)
classifier=make_pipeline(StandardScaler(),LogisticRegression(max_iter=400)).fit(D[train],labels[train]);probs=classifier.predict_proba(D[pool]);target=labels[pool]rg=np.random.default_rng(30);u=rg.random(len(pool));score_all={name:class_scores(probs,u,name,.02,3) for name in ('lac','aps','raps')}
cov={name:[] for name in score_all};sizes={name:[] for name in score_all};difficult={name:[] for name in score_all}
for _ in range(1000):
ix=rg.permutation(len(pool));cal=ix[:400];test=ix[400:]
for name,S in score_all.items():
q=qhat(S[cal,target[cal]],.1);sets=S[test]<=q;covered=sets[np.arange(len(test)),target[test]]
cov[name].append(covered.mean());sizes[name].append(sets.sum(1).mean());hard=probs[test].max(1)<.8
if hard.any():difficult[name].append(covered[hard].mean())
for name in score_all:print(name,'cobertura',np.mean(cov[name]),'tamaño',np.mean(sizes[name]),'cobertura difícil',np.mean(difficult[name]))Local lab: CIFAR-100 and MAPIE
Train your own residual network with cifar100_train.py and then run cifar100_conformal.py in the same directory. It requires PyTorch, torchvision, NumPy, SciPy, scikit-learn, MAPIE 1.6.0, and crepes 0.9.1. The first cell downloads CIFAR-100 if absent from ORYON_CIFAR100_ROOT or ./data. Use 20 000 images for training, 1000 separate images for temperature, 3000 for calibration, and 5000 official test images. Temperature fitting precedes conformalization. The model trained for ten epochs on GPU; its limited accuracy affects set sizes. Crepes receives exactly the same custom scores and randomizations without smoothing p-values. MAPIE uses its own RAPS parameter selection and boundary convention, so coverage and size are compared without assuming equal sets. Per-class coverage is reported descriptively with a few dozen cases per class.
"""Entrena ResNet pequeño y guarda logits separados para calibración conformal."""
import os
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.datasets import CIFAR100
torch.set_num_threads(2);torch.manual_seed(30);device='cuda' if torch.cuda.is_available() else 'cpu'
root=os.environ.get('ORYON_CIFAR100_ROOT','./data')
train=CIFAR100(root,train=True,download=True);test=CIFAR100(root,train=False,download=True)
rng=np.random.default_rng(30);ids=rng.permutation(len(train));tr,cal,val=ids[:20000],ids[20000:23000],ids[23000:24000];te=rng.choice(len(test),5000,replace=False)
def tensor(data,ids):return torch.tensor(data[ids].transpose(0,3,1,2),dtype=torch.float32)/255
X=tensor(train.data,tr);y=torch.tensor(np.asarray(train.targets)[tr]);Xcal=tensor(train.data,cal);ycal=np.asarray(train.targets)[cal];Xval=tensor(train.data,val);yval=np.asarray(train.targets)[val];Xtest=tensor(test.data,te);ytest=np.asarray(test.targets)[te]
class Block(nn.Module):
def __init__(self,cin,cout,stride):
super().__init__();self.a=nn.Conv2d(cin,cout,3,stride,1,bias=False);self.b=nn.Conv2d(cout,cout,3,1,1,bias=False);self.n1=nn.BatchNorm2d(cout);self.n2=nn.BatchNorm2d(cout)
self.skip=nn.Identity() if stride==1 and cin==cout else nn.Sequential(nn.AvgPool2d(stride),nn.Conv2d(cin,cout,1,bias=False))
def forward(self,x):return F.relu(self.n2(self.b(F.relu(self.n1(self.a(x)))))+self.skip(x))
class ResNet(nn.Module):
def __init__(self):
super().__init__();self.conv=nn.Conv2d(3,32,3,1,1,bias=False);self.bn=nn.BatchNorm2d(32)
self.blocks=nn.Sequential(Block(32,32,1),Block(32,64,2),Block(64,128,2));self.out=nn.Linear(128,100)
def forward(self,x):return self.out(self.blocks(F.relu(self.bn(self.conv((x-.5)/.5)))).mean((2,3)))
model=ResNet().to(device);opt=torch.optim.Adam(model.parameters(),lr=.001,weight_decay=.0001);gen=torch.Generator().manual_seed(30)
for epoch in range(10):
model.train();order=torch.randperm(len(X),generator=gen)
for ids in order.split(128):
opt.zero_grad();logits=model(X[ids].to(device));loss=F.cross_entropy(logits,y[ids].to(device));loss.backward();opt.step()
print('época',epoch+1,'pérdida último lote',float(loss.detach()),flush=True)
model.eval()
def logits(images):
with torch.no_grad():return torch.cat([model(xx.to(device)).cpu() for xx in images.split(256)]).numpy()
zc=logits(Xcal);zv=logits(Xval);zt=logits(Xtest)
np.savez('cifar100_logits.npz',cal=zc,ycal=ycal,val=zv,yval=yval,test=zt,ytest=ytest)
torch.save(model.state_dict(),'resnet-cifar100.pt')
print('dispositivo',device,'entrenamiento/calibración/temperatura/test',len(tr),len(cal),len(val),len(te),'exactitud test',float(np.mean(zt.argmax(1)==ytest)))npm run lab and open the connection link."""RAPS propio y MAPIE sobre logits de cifar100_train.py."""
import numpy as np
from scipy.optimize import minimize_scalar
from scipy.special import softmax,logsumexp
from sklearn.base import BaseEstimator,ClassifierMixin
from mapie.classification import SplitConformalClassifier
from crepes import ConformalClassifier
import mapie,crepes
d=np.load('cifar100_logits.npz');zc=d['cal'];yc=d['ycal'];zv=d['val'];yv=d['yval'];zt=d['test'];yt=d['ytest']
def loss(logT):
z=zv/np.exp(logT);return float(np.mean(logsumexp(z,axis=1)-z[np.arange(len(yv)),yv]))
T=float(np.exp(minimize_scalar(loss,bounds=(-2,3),method='bounded').x))
def score(p,u,lam=.02,kreg=5):
order=np.argsort(-p,axis=1,kind='stable');sp=np.take_along_axis(p,order,axis=1);prev=np.cumsum(sp,axis=1)-sp
ranked=prev+u[:,None]*sp+lam*np.maximum(np.arange(1,p.shape[1]+1)[None,:]-kreg,0)
out=np.empty_like(ranked);np.put_along_axis(out,order,ranked,axis=1);return out
def own(cal,y,test):
rng=np.random.default_rng(30);sc=score(cal,rng.random(len(y)));k=int(np.ceil((len(y)+1)*.9));q=np.partition(sc[np.arange(len(y)),y],k-1)[k-1]
st=score(test,rng.random(len(test)));own_sets=st<=q
crepes_model=ConformalClassifier().fit(sc[np.arange(len(y)),y])
crepes_sets=crepes_model.predict_set(st,confidence=.9,smoothing=False).astype(bool)
return own_sets,crepes_sets
class FrozenProbs(ClassifierMixin,BaseEstimator):
def __init__(self):self.classes_=np.arange(100);self.n_features_in_=100
def fit(self,X,y):return self
def predict_proba(self,X):return np.asarray(X)
def predict(self,X):return np.asarray(X).argmax(1)
def report(name,sets):
hit=sets[np.arange(len(yt)),yt];n=np.bincount(yt,minlength=100);coverage=np.bincount(yt,weights=hit,minlength=100)/np.maximum(n,1)
print(name,'cobertura',hit.mean(),'tamaño medio',sets.sum(1).mean(),'por clase',np.round(coverage,3),'n por clase',n)
print('mapie',mapie.__version__,'crepes',crepes.__version__,'temperatura',T)
for name,temp in [('sin temperatura',1.),('con temperatura',T)]:
cal=softmax(zc/temp,axis=1);test=softmax(zt/temp,axis=1)
own_sets,crepes_sets=own(cal,yc,test);report(name+' RAPS propio',own_sets);report(name+' RAPS crepes',crepes_sets)
print('fracción de decisiones distintas propio/crepes',np.mean(own_sets!=crepes_sets))
# MAPIE selecciona parámetros RAPS en su propia subdivisión.
cp=SplitConformalClassifier(FrozenProbs(),confidence_level=.9,conformity_score='raps',prefit=True,random_state=30)
cp.conformalize(cal,yc);_,sets=cp.predict_set(test,conformity_score_params={'include_last_label':True})
report(name+' RAPS MAPIE',sets[:,:,0])npm run lab and open the connection link.Exercises
Step 1 of 3. Without ties, what distribution does the future score rank follow?
aps_sets(probs, qhat, rng) for an N×C matrix. For each row generate one shared uniform U, order classes by decreasing probability, and calculate previous sum + U·p for each label. Include classes whose score is ≤ qhat and return an N×C Boolean matrix. Do not force nonempty sets.def aps_sets(probs, qhat, rng):
passSummary
- The +1 and correct order avoid a fictitious nominal guarantee; ties require explicit treatment.
- Coverage conditional on one calibration varies; the Beta law requires continuous iid scores.
- Residual, CQR, APS, and RAPS change shape and efficiency; marginal coverage does not guarantee every subgroup.