A house-price model gives you an estimate, but a buyer comparing homes also needs some sense of how far the eventual sale price could fall from it. A prediction interval can express that uncertainty, provided you know how often it covers the true price. Conformal prediction builds such intervals from errors on held-out calibration data. Under the assumption that calibration and test examples are exchangeable, it guarantees at least your chosen coverage rate, averaged over calibration sets and new test examples, even when the underlying model describes its uncertainty poorly.
Repeated calibration splits test that average. California Housing reaches 90.019% average coverage over 200 splits for a requested 90%. We implement split conformal, normalised scores, conformalised quantile regression and adaptive prediction sets in Python, then test coverage within groups.
Those checks reveal gaps beneath the average. Synthetic intervals cover 100% of a low-noise region and 74.7% of a high-noise one. On the seven-class forest dataset, prediction sets cover 94.9% of the commonest class and 29.4% of the rarest.
Let's Build It
Open this in Google Colab and run it top to bottom. Everything here is CPU work measured in seconds.
The whole method is one function. Score every calibration point, take a quantile of those scores, and use it as a threshold.
import numpy as np
def conformal_quantile(scores, alpha):
"""The ceiling-adjusted (1 - alpha) quantile of the calibration scores."""
n = len(scores)
k = int(np.ceil((n + 1) * (1 - alpha)))
if k > n:
return np.inf
return float(np.sort(scores)[k - 1])
California housing, three disjoint splits: the model trains on the first, the conformal quantile is computed on the second, and every coverage number comes off the third. The score is the plainest one available, the absolute residual.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
ALPHA = 0.10
X, y = fetch_california_housing(return_X_y=True)
def split_conformal(seed, n_train=4000, n_cal=2000, n_test=4000):
rng = np.random.default_rng(seed)
idx = rng.permutation(len(y))[: n_train + n_cal + n_test]
tr, ca, te = idx[:n_train], idx[n_train : n_train + n_cal], idx[n_train + n_cal :]
model = RandomForestRegressor(n_estimators=60, random_state=seed, n_jobs=-1).fit(X[tr], y[tr])
qhat = conformal_quantile(np.abs(y[ca] - model.predict(X[ca])), ALPHA)
covered = np.abs(y[te] - model.predict(X[te])) <= qhat
return covered.mean(), 2 * qhat
coverage, width = zip(*[split_conformal(s) for s in range(200)])
print(f"mean coverage {np.mean(coverage):.5f} requested {1 - ALPHA:.5f}")
print(f"guaranteed band [{1 - ALPHA:.5f}, {1 - ALPHA + 1 / 2001:.5f}]")
mean coverage 0.90019 requested 0.90000
guaranteed band [0.90000, 0.90050]

Any one split lands anywhere between 87.0% and 92.1%, because 4,000 test rows carry their own sampling noise. Averaged over splits the coverage settles at 90.019%, and the theorem says it must land in , which for 2,000 calibration rows is a band 0.05 percentage points wide. No distributional assumption went into that. The random forest was never asked to be well specified, and the target is a capped, skewed, spatially clustered house price.
The requested rate is a dial, and the animation below turns it. Each frame recomputes one quantile on the same calibration set and reports what the held-out data gave back.

Ask for 50% and 49.7% comes back. Ask for 75% and 75.0% comes back. Ask for 99% and 99.1% comes back. Nothing about the model changed between those frames.
What Just Happened?
The quantile is the method
Take a calibration set the model has never seen, and score each row by how badly the model missed it. For regression with absolute residuals, . Sort those scores. Find the value that 90% of them fall below. Call it .
Now a new point arrives. Its score is exchangeable with the calibration scores, meaning its rank among them is uniform, so there is a 90% chance it lands below too. Score below means , which rearranges to the interval .
That is the entire argument. It never mentions the model, and it holds for any score function you like, as long as the function itself was fixed before the calibration set was scored.
The ceiling is not a rounding detail
k = int(np.ceil((n + 1) * (1 - alpha)))
np.quantile(scores, 0.9) would give a slightly smaller threshold, and coverage would come back at roughly rather than above . At that is half a percentage point, invisible against sampling noise. At it is a full point and the guarantee is gone. The counts the test point itself: the argument is about the rank of a new score among scores, not among .
The same arithmetic explains the np.inf guard. If , no finite threshold can promise that rate, and the method says so instead of pretending. Ninety-five per cent coverage needs at least 19 calibration points; 99% needs at least 99. Below that the honest interval is the whole real line.
Exchangeability, and what it is not
Independent and identically distributed data is exchangeable. So is a random permutation of any fixed set, and so are draws without replacement from a finite population. Exchangeability is weaker than independence, which is why conformal prediction survives situations that trip up standard theory.
What breaks it is any ordering that carries information. Time series break it, because tomorrow is not exchangeable with yesterday. A model trained on one hospital and calibrated on another breaks it. Any covariate shift between calibration and deployment breaks it, and the last section of this post measures exactly how much.
The Guarantee Is an Average
Marginal coverage means averaged over the joint distribution of and . It does not say the interval covers 90% of the time for tall people, or for cheap houses, or for the rare class. Split conformal has no mechanism that could deliver that, and on data with unequal noise the failure is not subtle.
Here is one feature, one target, and noise that grows twelvefold from left to right.
def heteroscedastic_1d(n, seed=1):
rng = np.random.default_rng(seed)
x = rng.uniform(0, 10, n)
mu = 2.0 * np.sin(1.1 * x) + 0.4 * x
sd = 0.15 + 0.165 * x
return x[:, None], mu + rng.normal(0, sd, n), mu, sd
X, y, mu, sd = heteroscedastic_1d(14000, seed=1) # X and y now refer to this data
perm = np.random.default_rng(7).permutation(len(y))
tr, ca, te = perm[:3000], perm[3000:6000], perm[6000:]
Fit a gradient booster on 3,000 rows, calibrate on 3,000 more, and split the 8,000 held-out rows into quintiles of . Every coverage figure below is the mean of 100 recalibrations, each drawing a fresh calibration and test split from the same pool. The marginal number is exactly what was ordered. The conditional numbers are not.
marginal 0-2 2-4 4-6 6-8 8-10
absolute residual 89.9% 100.0% 99.3% 93.6% 82.0% 74.7%

The quintile figures move by less than 1.5 points across those 100 recalibrations, so this is structural rather than a lucky split. At the left edge the band is 7.4 times wider than the true 90% interval; at the right edge it is 0.61 times as wide as the interval it should be. The two errors cancel in the average. A user reading the interval at was told 90% and is getting 74.7%.
Two Repairs
Both repairs work the same way. Keep the conformal machinery untouched, and change the score function so that a score of means something different at different .
Normalised residuals
Fit a second model to predict the size of the error, then divide by it.
from sklearn.ensemble import GradientBoostingRegressor
base = GradientBoostingRegressor(random_state=0).fit(X[tr], y[tr])
resid = np.abs(y[tr] - base.predict(X[tr]))
scale_model = GradientBoostingRegressor(random_state=0).fit(X[tr], np.log(resid + 1e-6))
scale = lambda Z: np.exp(scale_model.predict(Z)) + 1e-6
qhat = conformal_quantile(np.abs(y[ca] - base.predict(X[ca])) / scale(X[ca]), ALPHA)
lo, hi = base.predict(X[te]) - qhat * scale(X[te]), base.predict(X[te]) + qhat * scale(X[te])
The scale model is fitted on training data only, so the score function is fixed before calibration begins and the guarantee is untouched. Log-target regression keeps the predicted scale positive without a constraint.
Conformalised quantile regression
Skip the mean entirely. Fit the 5th and 95th conditional quantiles, then let conformal prediction correct whatever the quantile fits got wrong.
lo_model = GradientBoostingRegressor(loss="quantile", alpha=0.05, random_state=0).fit(X[tr], y[tr])
hi_model = GradientBoostingRegressor(loss="quantile", alpha=0.95, random_state=0).fit(X[tr], y[tr])
def cqr_score(y, lo, hi):
"""How far outside the quantile band y fell. Negative if comfortably inside."""
return np.maximum(lo - y, y - hi)
qhat = conformal_quantile(cqr_score(y[ca], lo_model.predict(X[ca]), hi_model.predict(X[ca])), ALPHA)
lo, hi = lo_model.predict(X[te]) - qhat, hi_model.predict(X[te]) + qhat
The score is signed. When the quantile regression is already too wide, the 90% quantile of the scores comes out negative and shrinks the band rather than growing it. Romano, Patterson and Candès designed the score that way in 2019 precisely so that a good quantile fit is not punished.

Both repairs land within about a point of 90% in every quintile. Coverage figures are again means over 100 recalibrations; the widths come off a single split, because only changes between recalibrations and the widths barely move.
marginal 0-2 2-4 4-6 6-8 8-10 mean width
absolute residual 89.9% 100.0% 99.3% 93.6% 82.0% 74.7% 3.64
normalised residual 90.0% 88.5% 91.0% 89.7% 91.1% 89.6% 3.26
CQR 90.1% 90.6% 93.1% 88.1% 89.1% 89.5% 3.25
The average width fell as well, from 3.64 to about 3.25, so the constant band was not buying its extra safety anywhere. It was spending width in the quiet region where nobody needed it. Across the five quintiles the normalised band widens 1.09, 2.12, 3.17, 4.51, 5.40; CQR widens 1.10, 2.36, 3.21, 4.38, 5.21. The constant band is 3.64 in all five.
Neither method is guaranteed to give conditional coverage, and no distribution-free method can. Vovk proved in 2012 that exact conditional coverage forces infinite-length intervals under any non-atomic distribution. What these scores buy is approximate conditional coverage when the scale model or the quantile fit is decent, and the marginal guarantee unconditionally when it is not.
Prediction Sets
For classification the output is a set of labels rather than an interval, and the same quantile does the work. Forest cover type, seven classes, a random forest at 81.3% accuracy on 8,000 held-out rows. The simplest score is one minus the probability the model gave the true class.
q_lac = conformal_quantile(1 - P_cal[np.arange(len(y_cal)), y_cal], ALPHA)
sets = P_test >= 1 - q_lac
That is the least ambiguous set-valued classifier, LAC. It returns 90.01% coverage at a mean set size of 1.23 labels: 6,153 of the 8,000 test rows come back as an ordinary single-label prediction, 1,843 as a pair, and four as the empty set, which is what a fixed probability threshold does to a row where no class cleared it. Then look at coverage per class.
class n accuracy coverage set size
Lodgepole Pine 3,923 87.3% 94.9% 1.20
Ponderosa Pine 495 90.1% 93.7% 1.18
Spruce/Fir 2,894 79.0% 89.2% 1.26
Krummholz 286 71.0% 82.9% 1.30
Douglas-fir 220 45.9% 63.2% 1.36
Cottonwood/Willow 46 30.4% 41.3% 1.35
Aspen 136 21.3% 29.4% 1.24

The marginal 90.01% is real and the theorem delivered it. It was paid for by the two classes holding 89% of the rows. Aspen, which the model gets right one time in five, receives sets that contain the truth 29.4% of the time, and those sets are no larger than anyone else's. LAC has a fixed probability threshold, so a class the model is uniformly unsure about simply falls below it and disappears from the set.
Adaptive prediction sets
Adaptive prediction sets score by cumulative probability mass instead. Sort the classes by probability, walk down the list, and record how much mass you had to accumulate before reaching the true label.
def aps_scores(probs, labels, u):
order = np.argsort(-probs, axis=1)
srt = np.take_along_axis(probs, order, axis=1)
cum = np.cumsum(srt, axis=1)
rank = np.argmax(order == labels[:, None], axis=1)
rows = np.arange(len(labels))
return cum[rows, rank] - u * srt[rows, rank]
The uniform draw u removes a random slice of the true label's own mass. Without it the sets round upward at every step and coverage overshoots. The prediction set is then built by peeling labels off in descending order until the cumulative mass passes , which makes the set grow on exactly the rows where the model spread its mass thin.
Coverage on the two hardest classes rises from 29.4% to 53.7% and from 41.3% to 63.0%, and the sets that carry that improvement are the ones that grew: 1.82 for Aspen and 1.98 for Cottonwood/Willow, against 1.36 and 1.37 for the two classes holding most of the rows. The mean set size across the whole test set went from 1.23 to 1.41. That is the trade, and it is not a free repair. Aspen at 53.7% is closer to 90% than it was, and it is still not 90%; only class-conditional calibration, computing a separate per class, delivers that, and it needs enough rows per class to compute a quantile with.
Set size as a difficulty score
The set size is a per-row signal worth reading on its own. Splitting the test set by the size of its APS set:
set size rows top-1 accuracy
1 4,929 88.5%
2 2,883 70.7%
3 178 57.3%
4 10 40.0%
The model's own maximum probability carries some of this information, but only after calibration and only on a scale nobody can interpret. Set size arrives as a count, on a scale set by the coverage level you chose, and it needs no calibration step of its own. Routing every row with a set larger than one to a human is a triage rule you can state in a sentence and audit in a table.
Breaking Exchangeability
Exchangeability is the one assumption, so the honest thing to do is break it and measure the damage. California housing splits cleanly at latitude 36: the northern half holds the Bay Area and the Central Valley, the southern half holds Los Angeles and San Diego. Train the model and compute on the north, then deploy on the south.
housing = fetch_california_housing()
X, y = housing.data, housing.target # back to the housing data
north = X[:, housing.feature_names.index("Latitude")] >= 36
# train and calibrate inside `north`, then predict on the rest
held out, same region 89.8%
deployed, southern half 37.2%

Same state, same model, same interval width of 1.35 in units of $100,000. Coverage falls from 89.8% to 37.2%, and mixing the two populations moves it along a straight line between those endpoints. Nothing in the method notices. There is no warning, no widening interval, no diagnostic that fires. The output looks exactly as it did when it was correct.
Tibshirani, Barber, Candès and Ramdas extended the theory to this case in 2019 by weighting each calibration point by its likelihood ratio between the two distributions, which restores the guarantee when the covariate shift is known or estimable and the conditional distribution of given is unchanged. Both conditions are real constraints. In deployment the usual answer is duller and more reliable: recalibrate on data from where the model is running, and monitor coverage as an operational metric rather than trusting a number computed once.
Going Deeper
Three philosophies, one dataset
The Bayesian interval, the bootstrap interval and the conformal interval answer three different questions, and only one of them is about where the next observation will fall.

A Gaussian process with an RBF kernel and a single white-noise term reached 89.6% marginal coverage here, which looks like a success until you split it by quintile: 100.0% at the left edge, 75.0% at the right. Its noise term is one number, so it produced the same constant-width failure as the absolute-residual score, with one difference. Conformal's marginal 90% was guaranteed by a theorem; the Gaussian process landed near 90% because this dataset happened to suit it. Change the noise model and the marginal number moves too.
The bootstrap did much worse, and for an instructive reason. Resampling the training set 100 times and taking the 5th and 95th percentiles of the predictions returned 19.9% coverage at a mean width of 0.50. That interval is correct for what it measures, which is uncertainty about the conditional mean, and it is not a prediction interval. As the training set grows the bootstrap band shrinks towards zero while the observations stay exactly as scattered as they were. Turning it into a prediction interval means adding a residual distribution back on, at which point it inherits every assumption conformal prediction avoids.
Split conformal is not the only conformal
Splitting the data costs you twice: the model trains on less, and the quantile is computed from a finite calibration set, which adds variance of order to the achieved coverage. That is the spread visible in the histogram at the top of this post.
Full conformal prediction avoids the split by refitting the model once per candidate label, which restores statistical efficiency and multiplies compute by the size of the candidate grid. The jackknife-plus of Barber, Candès, Ramdas and Tibshirani sits between the two, using leave-one-out residuals to reach a guarantee at model fits, with holding in practice. Cross-conformal and CV+ trade the same axis with folds. Split conformal is the default here because one extra model fit is a price anyone will pay and the guarantee is unconditional; the others are worth reaching for when data is scarce enough that giving up 2,000 rows hurts.
Calibration set size
The coverage of a single split is Beta distributed, so the standard deviation of achieved coverage is roughly . At 90% and 1,000 calibration rows that is 0.9 percentage points, so a single split lands within about two points of target. At 100 rows it is 3 points and the quantile itself becomes coarse. A thousand rows is a reasonable floor for a 90% interval, and 99% coverage needs proportionally more because the quantile sits further into the tail where the calibration scores are sparse.
For prediction sets the constraint is per class, not per dataset. Aspen contributed 136 rows to the test set here and a comparable number to calibration, which is why a class-conditional for it would be noisy even if you computed one.
Limits of the method
Conformal prediction does not improve a model. If the intervals come back too wide to act on, the method is reporting the truth about your predictor and the fix is a better predictor, not a different wrapper. It also gives you nothing when the loss is not about coverage: an expected-value calculation wants a calibrated probability, and recalibrating the model is the right tool for that. The two compose well, because calibration improves the probabilities that APS then sorts and accumulates.
The harder limit is the one measured under Breaking Exchangeability above. Time series, spatial extrapolation, any deployment that has drifted away from where the calibration data came from: exchangeability fails, and the guarantee fails silently with it.
Where This Comes From
Vovk, Gammerman and Shafer set out the framework in Algorithmic Learning in a Random World (2005), assembling a decade of work at Royal Holloway. Their formulation is transductive: to test whether a label belongs in the prediction set, add to the training data, refit, and measure how strange the augmented set looks. Split conformal, introduced by Papadopoulos, Proedrou, Vovk and Gammerman in "Inductive Confidence Machines for Regression" (2002), replaces the refit with a held-out set and turns an interesting theory into something anyone can run.
Lei, G'Sell, Rinaldo, Tibshirani and Wasserman gave the modern regression treatment in "Distribution-Free Predictive Inference for Regression" (2018), including the finite-sample statement of the split conformal guarantee and the upper bound verified numerically at the top of this post. They are also explicit about the gap between marginal and conditional coverage, and they propose the locally weighted score used here as the normalised residual.
Romano, Patterson and Candès introduced conformalised quantile regression in "Conformalized Quantile Regression" (2019). Their contribution is the signed score, which lets the conformal correction shrink an over-wide quantile band as well as grow an over-narrow one, so a well fitted quantile regression keeps its adaptivity instead of being padded to a common width.
Tibshirani, Barber, Candès and Ramdas handled the failure case in "Conformal Prediction Under Covariate Shift" (2019), showing that weighting calibration points by the likelihood ratio between training and test covariate distributions restores the guarantee, provided is unchanged and the ratio can be estimated.
Angelopoulos and Bates wrote the tutorial that brought the method into general machine-learning practice, "A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantification" (2021), which is where the adaptive prediction sets and the randomised score used above come from. Their companion work on regularised adaptive sets addresses the size problem this post ran into, by adding a penalty that discourages the long tail of low-probability labels.
Vovk's "Conditional Validity of Inductive Conformal Predictors" (2012) is the negative result behind the whole middle of this post: distribution-free conditional coverage is impossible at finite interval length, which is why every method above targets an approximation of it rather than the thing itself.
Interactive Tools
- Classification Metrics Calculator: accuracy, precision and recall all summarise a single-label prediction, and none of them has a way to describe a set-valued one.
- Distribution Explorer: the Beta distribution that governs the achieved coverage of a single calibration split, and the quantiles the method takes.
- Regression Playground: fit a model and watch the residual pattern that decides whether a constant-width interval will hold up.
Related Posts
- Model Calibration in Python: The Metric Decides the Method: the prerequisite, and the method that fixes the probabilities APS sorts and accumulates.
- Gaussian Process Regression: The Bayesian Approach to Curve Fitting: the credible band measured against conformal on the same data above, and why its noise term decides everything.
- Bayesian Neural Networks: Laplace and Evidence Framework: the other route to uncertainty from a network, with a prior instead of a guarantee.
- From MLE to Bayesian Inference: Why Your Estimate Needs a Prior: where the assumptions conformal prediction avoids come from in the first place.
- Gradient Boosting: Fitting the Residuals, From Scratch to XGBoost: the base model and the quantile loss behind conformalised quantile regression.
- Tabular Foundation Models: How TabPFN Predicts Without Training: another predictor whose outputs conformal prediction will wrap without modification.






