Algorithmresearch
Split conformal prediction
Also called inductive conformal prediction.
Fit the model on one part of the data, compute residual scores on the other, and widen predictions by their quantile. It gives finite-sample marginal coverage cheaply.
- Time
- Θ(f + n log n) worstΘ(f + n) best
- Space
- Θ(n) extra
- Where
- f = the time to fit the model on the training part and predict at the calibration points; n = the number of data points
- Model
- Real RAM
- Properties
- randomizedexactofflinerandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Harris Papadopoulos, Kostas Proedrou, Vladimir Vovk, Alex Gammerman, 2002
Split conformal prediction builds a prediction interval around any fitted model with a coverage guarantee that holds for every sample size and every distribution. It fits the model once on a training part of the data, computes the absolute residuals on the other part, the calibration set, and widens each prediction by , the -th smallest of the calibration residuals. If the data and the new point are exchangeable, the interval holds the new response with probability at least , and at most when the residuals have no ties. It costs one fit, where full conformal prediction needs one fit for each candidate response.
In plain words
Split your data in two piles. Train any model you like on the first pile. Then use the model on the second pile, where you know the answers, and write down how far off each prediction was.
Sort those errors. For a 90% interval, take an error size that about 90% of the errors do not exceed; the exact rank is fixed by a small formula. For a new input, predict with the model and add and subtract that error size.
The new case is just like one more member of the second pile. Its error is equally likely to land anywhere in the sorted list, so it is bigger than the chosen error only about 10% of the time. That holds whatever the model is, and however good or bad it is. A bad model only makes the interval wider.
The problem
Given data , , a new input , a learning algorithm that maps a data set to a predictor , and a level , find an interval with
whenever are exchangeable, with no other assumption about their law or about . The probability is over the data, the new point and the random split. This is a prediction interval for a new response, not a confidence interval for a parameter, and its coverage is marginal: averaged over .
The algorithm
SPLIT-CONFORMAL(z_1, ..., z_n, n_1, fit, α)- 1
split {1, ..., n} at random into I_1 of size n_1 and I_2 of size n_2 = n - n_1 - 2
μ̂ ← fit({z_i : i ∈ I_1}) - 3
R_i ← |y_i - μ̂(x_i)| for each i ∈ I_2 - 4
k ← ⌈(n_2 + 1)(1 - α)⌉ - 5
if k > n_2 then q ← ∞ - 6
else q ← the k-th smallest of {R_i : i ∈ I_2} - 7
return x ↦ [μ̂(x) - q, μ̂(x) + q]
Line L1 is a random shuffle and a cut; any split that does not look at the data works, and so does a fixed split of data in random order. The fit of line L2 can be any procedure at all, as long as it sees only the training part. Line L6 is a selection of one order statistic. Line L5 is needed: with fewer than calibration points, no finite is guaranteed to work, and the honest answer is the whole line.
Example
Forty points with uniform on and , standard normal (random.Random(2026)), were split by random.Random(1) into training and calibration points. A least squares line was fitted on the training part.
- For : , so is the 19th smallest of the 20 absolute calibration residuals, . At the line predicts and the interval is . For comparison, the ideal 90% half width for standard normal errors with a known line is .
- For : and .
- With the same data and : , and is the largest calibration residual.
- With : , so line L5 sets .
Coverage, measured. The theorem gives the exact value for continuous errors, so these runs only check the code. Each row has 4000 data sets with one new point each, and a least squares line.
| errors | measured coverage | median width | seed | |||
|---|---|---|---|---|---|---|
| normal | 40 | 20 | 0.908 | 3.65 | 3 | |
| Cauchy | 40 | 20 | 0.906 | 19.6 | 4 | |
| normal | 200 | 100 | 0.909 | 3.37 | 5 | |
| normal | 40 | 10 | 0.920 | 3.80 | 6 |
The coverage stays at its level even with Cauchy errors, where least squares is a poor fit; the intervals are then wide. With 4000 data sets the standard error of each measured value is about .
Correctness
The proof is in the correctness file. Fix the training part. Then is fixed, and the calibration scores and the score of the new point are exchangeable numbers. The new point is covered exactly when is at most the -th smallest calibration score, and that happens when at most calibration scores are strictly smaller than . At least of the scores have this property, and exactly when they are distinct, so by exchangeability
with equality in the second step for distinct scores. Since , the coverage with continuous scores is then below . Lei et al. (2018, Theorem 2.2) state the upper bound as for an even split, , which is the same number.
The tests check the exact coverage by exchangeability: for six calibration and test points they enumerate all orderings and get exactly for each when the scores are distinct, and at least with tied scores.
Proof: Split conformal intervals have coverage between 1 - alpha and 1 - alpha + 1/(n_2 + 1)full
We use the pseudocode of the page. with are the data and the new point. The split of line L1 is independent of the data. has indices and has . Write , for , and for the sorted calibration scores.
This file proves the coverage bounds for every law and every fitting procedure, under exchangeability. Nothing about the width of the interval or about coverage at a fixed is proved; the page only measures those.
Claim 1 (the event of coverage). If , then if and only if , where . If , the new point is always covered.
Proof. If , line L5 sets . Otherwise line L6 sets , and the new point is covered exactly when . If , every calibration score below is below , so it is one of , and . If , then are all below and .
Claim 2 (the scores are exchangeable given the training part). Conditional on the split and on , the scores are exchangeable.
Proof. The split does not depend on the data, so conditional on it, followed by is still an exchangeable sequence. Permuting the last points therefore does not change the joint law, and hence does not change their conditional law given the first block. Given the training block, is a fixed function, and each score is the same fixed function of its own point. A fixed function applied to each member of an exchangeable vector gives an exchangeable vector.
Claim 3 (lower bound). when , and the coverage is 1 when .
Proof. Work conditionally on the split and the training block, and index the scores by . Let be the number of the other scores that are strictly smaller than ; then . Let be all scores sorted. If , then at least scores are strictly below , so . At most indices have a score strictly above . So at most indices have , and at least have . Permuting the scores permutes the in the same way, and the scores are exchangeable (Claim 2), so the vector is exchangeable and is the same for every . Hence
By Claim 1 this is the conditional coverage, and averaging over the training block keeps the bound. Finally by the definition of the ceiling. The case is Claim 1.
Claim 4 (upper bound for distinct scores). If the scores are almost surely distinct, for example when given has a continuous law, then for
Proof. With distinct scores, is the rank of minus one, the are in some order, and exactly indices have . The display in Claim 3 is then an equality. The ceiling gives ; divide by .
With an even split, , the slack is , the bound of Lei et al. (2018, Theorem 2.2). If ties have positive probability, the upper bound can fail; with constant scores the coverage is 1.
Claim 5 (coverage given the calibration set). Suppose the points are iid and, given the training block, the score of a new point has a continuous distribution function . Then the coverage conditional on the training and calibration blocks is , and for it has the Beta law with parameters and .
Proof. Given both blocks, is fixed and the new point is independent of them, so the conditional coverage is . The calibration scores are iid with the continuous distribution function , so are iid uniform on , and is nondecreasing, so , the -th order statistic of uniforms, whose law is Beta. Its mean is , which agrees with Claim 4.
Claim 6 (cost). Lines L1 and L3 to L5 take time besides the predictions, line L2 is one fit, and line L6 takes time by sorting or by linear-time selection. The space is besides the model.
Proof. Line L1 is a shuffle of indices. Line L3 makes one prediction and one subtraction for each calibration point. Line L4 is arithmetic. Selection of the -th smallest of numbers takes linear time by the median of medians method, or the sort can be used.
What the tests check. The test file fixes a training block and enumerates all orderings of five calibration points and one new point. With distinct scores the coverage is exactly for each tested (Claims 3 and 4), and with tied scores it is at least (Claim 3). It also checks the identity and the inequalities for all .
Complexity
With the cost of the fit and of the predictions, the method takes time with sorting at line L6, or with a linear-time selection, and extra space. After that, each new point costs one prediction. Full conformal prediction needs a refit for every candidate response and every new point.
Properties
- Finite-sample, distribution-free. The coverage bounds hold for every , every law of the data and every model, under exchangeability only.
- Marginal only. The probability is over the training data, the calibration data and the new point. It does not hold for each , and no method can achieve coverage at each for every law with intervals of finite expected length (Barber et al. 2021).
- Random given the calibration set. For continuous scores, the coverage conditional on the training and calibration data is , where is the law of a new score. It has the Beta law with parameters and , with mean . For and its standard deviation is and it is below with probability ; for the standard deviation is ; for it is .
- Constant width. With the absolute residual score the interval has the same width at every . Other scores change this; see the variants.
- Uses only part of the data to fit. The fitted model is worse than one fitted on all points, so the intervals are usually a little wider than those of full conformal prediction.
Variants and improvements
- Conformalized quantile regression (Romano, Patterson and Candès 2019). Fit lower and upper quantile regressions and at levels and on the training part. Use the score and return . The guarantee is the same, and the width now follows the spread of given . In the heteroscedastic example under Pitfalls, with 8-bin empirical quantiles as the quantile fit, the coverage was for and for , against and for the absolute residual score.
- Scaled residuals. Use with a fitted spread , and return .
- Classification. Use a score such as one minus the fitted probability of the true label, and return all labels whose score is at most .
- Cross-conformal, jackknife+ and CV+. Use every point for both fitting and calibration through K folds or leave-one-out fits, as in cross-validation. They give narrower intervals with a weaker worst-case guarantee, at least for the jackknife+ and CV+.
- Label-conditional (Mondrian) calibration. Calibrate separately within each class or group, which gives coverage within each group if each group has enough calibration points.
- Full conformal prediction. Conformal prediction refits on each candidate. It uses all the data for fitting at a much higher cost.
When to use it
Use split conformal prediction when you have a model you trust for point prediction, enough data to set aside a calibration set of a few hundred points, and a need for intervals whose coverage does not rest on model assumptions. It is the usual choice for large models, where a refit for each candidate is not possible. With very little data, prefer the jackknife+ or full conformal prediction, which use all points for fitting. If you need coverage for each or for each subgroup, the plain method does not give it; use group-wise calibration or an adaptive score and check the coverage in each group.
Pitfalls
- Marginal coverage only. With uniform on , errors with standard deviation , split , and 3000 data sets (seed 7), the overall coverage was , but for and for .
- Wrong rank. Taking the -th score, the plain empirical quantile, gives coverage , which can be below : for and it is . The counts the new point.
- Reusing the training data. Residuals on the training part are too small, because the model was fitted to them. Calibrating on them gives intervals that are too short.
- Choosing the split, the model or after looking at the calibration set. Any choice that depends on the calibration scores breaks exchangeability.
- Small calibration sets. The guarantee holds on average over calibration sets, and for a single small calibration set the actual coverage varies a lot (see Properties). Use at least a few hundred calibration points when a single deployed interval matters.
- Exchangeability fails. Drift over time and covariate shift between training and use break the argument.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/split-conformal-prediction/. The authors are listed in prov/6A6QRB.jsonl.
import math
import random
from fractions import Fraction
from typing import Callable, List, NamedTuple, Optional, Sequence, Tuple
Point = Tuple[float, float] # (x, y)
INF = float("inf")
def level(alpha) -> Fraction:
"""alpha as an exact fraction; a float is read as the decimal it prints as (0.1 is 1/10)."""
a = Fraction(str(alpha)) if isinstance(alpha, float) else Fraction(alpha)
if not 0 < a < 1:
raise ValueError("alpha must be in (0, 1)")
return a
def calibration_rank(n2: int, alpha) -> int:
"""k = ceil((n2 + 1)(1 - alpha)), the rank of the calibration score used as q."""
return math.ceil((n2 + 1) * (1 - level(alpha)))
def conformal_quantile(scores: Sequence, alpha):
"""The k-th smallest score with k = ceil((n2 + 1)(1 - alpha)), or infinity if k > n2."""
k = calibration_rank(len(scores), alpha)
if k > len(scores):
return INF
return sorted(scores)[k - 1]
class SplitConformal(NamedTuple):
mu: Callable # the fitted predictor
q: object # the half width
k: int # the rank of q among the calibration scores
n2: int # the number of calibration points
def interval(self, x) -> Tuple[object, object]:
m = self.mu(x)
return m - self.q, m + self.q
def split_conformal(
points: Sequence[Point],
n1: int,
fit: Callable[[List[Point]], Callable],
alpha,
rng: Optional[random.Random] = None,
) -> SplitConformal:
"""Fit on n1 points, calibrate on the other n2 = n - n1. With rng None the split is the
given order: the first n1 points train and the rest calibrate."""
n = len(points)
if not 1 <= n1 < n:
raise ValueError("need 1 <= n1 < n")
order = list(range(n))
if rng is not None:
rng.shuffle(order)
train = [points[i] for i in order[:n1]] # @line L1
calib = [points[i] for i in order[n1:]]
mu = fit(train) # @line L2
scores = [abs(y - mu(x)) for x, y in calib] # @line L3
n2 = len(calib)
k = calibration_rank(n2, alpha) # @line L4
if k > n2: # @line L5
q = INF
else: # @line L6
q = sorted(scores)[k - 1]
return SplitConformal(mu, q, k, n2) # @line L7
def fit_line(points: Sequence[Point]) -> Callable:
"""The least squares line through the points, as a function."""
n = len(points)
mx = sum(x for x, _ in points) / n
my = sum(y for _, y in points) / n
sxx = sum((x - mx) ** 2 for x, _ in points)
slope = sum((x - mx) * (y - my) for x, y in points) / sxx if sxx else 0
intercept = my - slope * mx
return lambda x: intercept + slope * x
# Conformalized quantile regression (Romano, Patterson and Candes 2019): the same split,
# with lower and upper quantile fits and the score max(lo(x) - y, y - hi(x)).
def conformalized_quantile_regression(
points: Sequence[Point],
n1: int,
fit_quantile: Callable[[List[Point], float], Callable],
alpha,
rng: Optional[random.Random] = None,
) -> Callable:
n = len(points)
if not 1 <= n1 < n:
raise ValueError("need 1 <= n1 < n")
order = list(range(n))
if rng is not None:
rng.shuffle(order)
train = [points[i] for i in order[:n1]]
calib = [points[i] for i in order[n1:]]
a = float(level(alpha))
lo = fit_quantile(train, a / 2)
hi = fit_quantile(train, 1 - a / 2)
scores = [max(lo(x) - y, y - hi(x)) for x, y in calib]
q = conformal_quantile(scores, alpha)
return lambda x: (lo(x) - q, hi(x) + q)
def fit_binned_quantile(points: Sequence[Point], tau: float, bins: int = 8) -> Callable:
"""A simple quantile regression: the empirical tau-quantile of y in equal-width bins of x."""
xs = [x for x, _ in points]
lo, hi = min(xs), max(xs)
width = (hi - lo) / bins or 1.0
def which(x):
return min(max(int((x - lo) / width), 0), bins - 1)
groups = [[] for _ in range(bins)]
for x, y in points:
groups[which(x)].append(y)
every = sorted(y for _, y in points)
def quantile(ys):
ys = sorted(ys) if ys else every
return ys[min(len(ys) - 1, max(0, math.ceil(tau * len(ys)) - 1))]
values = [quantile(g) for g in groups]
return lambda x: values[which(x)]
test_split_conformal_prediction.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/split-conformal-prediction/. The authors are listed in prov/6A6QRB.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from split_conformal_prediction import (
INF,
calibration_rank,
conformal_quantile,
conformalized_quantile_regression,
fit_binned_quantile,
fit_line,
split_conformal,
)
ALPHAS = (Fraction(1, 20), Fraction(1, 10), Fraction(1, 6), Fraction(1, 5), Fraction(1, 3), Fraction(1, 2))
TRAIN = [(Fraction(0), Fraction(1)), (Fraction(2), Fraction(2)), (Fraction(4), Fraction(4)), (Fraction(6), Fraction(4))]
def exact_coverage(train, rest, alpha):
"""P(Y_new in the interval) when the n2 calibration points and the new point are in a
uniformly random order: enumerate every ordering of them, with the training part fixed."""
hits = total = 0
for perm in itertools.permutations(rest):
calib, (x_new, y_new) = list(perm[:-1]), perm[-1]
res = split_conformal(train + calib, len(train), fit_line, alpha)
lo, hi = res.interval(x_new)
hits += lo <= y_new <= hi
total += 1
return Fraction(hits, total)
def test_exact_coverage_by_exchangeability():
rest = [(Fraction(1), Fraction(3)), (Fraction(3), Fraction(1)), (Fraction(5), Fraction(7)),
(Fraction(7), Fraction(2)), (Fraction(2), Fraction(5, 2)), (Fraction(8), Fraction(9))]
mu = fit_line(TRAIN)
scores = [abs(y - mu(x)) for x, y in rest]
assert len(set(scores)) == len(scores)
n2 = len(rest) - 1
for alpha in ALPHAS:
k = calibration_rank(n2, alpha)
cov = exact_coverage(TRAIN, rest, alpha)
assert cov == (Fraction(k, n2 + 1) if k <= n2 else 1)
# Lei et al. bounds: 1 - alpha <= coverage <= 1 - alpha + 1/(n2 + 1)
assert 1 - alpha <= cov <= 1 - alpha + Fraction(1, n2 + 1)
def test_ties_keep_the_lower_bound():
# residuals +-1, +-1, 2, -2 give tied scores: coverage can only go up
mu = fit_line(TRAIN)
rest = [(Fraction(x), mu(Fraction(x)) + s) for x, s in ((1, 1), (3, -1), (5, 1), (7, 2), (2, -2), (8, 1))]
scores = [abs(y - mu(x)) for x, y in rest]
assert len(set(scores)) == 2
n2 = len(rest) - 1
raised = False
for alpha in ALPHAS:
k = calibration_rank(n2, alpha)
cov = exact_coverage(TRAIN, rest, alpha)
assert cov >= 1 - alpha
raised |= cov > Fraction(min(k, n2 + 1), n2 + 1)
assert raised
def test_rank_and_bounds_arithmetic():
for n2 in range(1, 60):
for alpha in ALPHAS + (Fraction(1, 100), Fraction(9, 10)):
k = calibration_rank(n2, alpha)
if k <= n2:
assert 1 - alpha <= Fraction(k, n2 + 1) < 1 - alpha + Fraction(1, n2 + 1)
else:
assert alpha < Fraction(1, n2 + 1)
# with n/2 calibration points the upper slack 1/(n2 + 1) is Lei et al.'s 2/(n + 2)
for n in range(2, 200, 2):
assert Fraction(1, n // 2 + 1) == Fraction(2, n + 2)
assert calibration_rank(19, 0.1) == 18 and calibration_rank(20, 0.1) == 19
assert conformal_quantile([5, 1, 4, 2, 3], 0.1) == INF
assert conformal_quantile([5, 1, 4, 2, 3], 0.5) == 3
def test_q_is_the_kth_smallest_score_and_infinite_when_k_exceeds_n2():
rng = random.Random(1)
pts = [(x, 2 * x + rng.gauss(0, 1)) for x in (rng.uniform(0, 5) for _ in range(30))]
res = split_conformal(pts, 20, fit_line, 0.2, random.Random(4))
assert res.n2 == 10 and res.k == 9
order = list(range(30))
random.Random(4).shuffle(order)
mu = fit_line([pts[i] for i in order[:20]])
scores = sorted(abs(pts[i][1] - mu(pts[i][0])) for i in order[20:])
assert res.q == scores[8]
assert split_conformal(pts, 26, fit_line, 0.1, random.Random(4)).q == INF
with pytest.raises(ValueError):
split_conformal(pts, 30, fit_line, 0.1)
with pytest.raises(ValueError):
split_conformal(pts, 10, fit_line, 0.0)
def gen(rng, n, noise):
out = []
for _ in range(n):
x = rng.uniform(0, 10)
out.append((x, 1 + 0.5 * x + noise(rng)))
return out
def test_marginal_coverage_is_measured():
def cauchy(rng):
return math.tan(math.pi * (rng.random() - 0.5))
rng = random.Random(4)
trials, hits = 3000, 0
for _ in range(trials):
pts = gen(rng, 41, cauchy)
lo, hi = split_conformal(pts[:40], 20, fit_line, 0.1, rng).interval(pts[-1][0])
hits += lo <= pts[-1][1] <= hi
expected = 19 / 21 # k/(n2 + 1) with n2 = 20
assert abs(hits / trials - expected) < 4 * math.sqrt(expected * (1 - expected) / trials)
def test_cqr_adapts_to_the_spread_measured():
rng = random.Random(7)
split_outer = cqr_outer = outer = 0
split_all = cqr_all = 0
trials = 1200
for _ in range(trials):
pts = []
for _ in range(401):
x = rng.uniform(-1, 1)
pts.append((x, x + rng.gauss(0, 0.1 + abs(x))))
data, (xn, yn) = pts[:400], pts[-1]
lo, hi = split_conformal(data, 200, fit_line, 0.1, rng).interval(xn)
a, b = conformalized_quantile_regression(data, 200, fit_binned_quantile, 0.1, rng)(xn)
s, c = lo <= yn <= hi, a <= yn <= b
split_all += s
cqr_all += c
if abs(xn) > 0.75:
outer += 1
split_outer += s
cqr_outer += c
assert abs(split_all / trials - 0.9) < 0.04 and abs(cqr_all / trials - 0.9) < 0.04
assert split_outer / outer < 0.82 < cqr_outer / outer
History
Vladimir Vovk, Alex Gammerman and Glenn Shafer developed conformal prediction in the late 1990s and early 2000s. Its main cost was one refit for each candidate. In 2002 Harris Papadopoulos, Kostas Proedrou, Vovk and Gammerman proposed the inductive version, which fits once on a training set and calibrates on the rest, and applied it to ridge regression. Vovk, Gammerman and Shafer treated inductive conformal predictors in their 2005 book. Jing Lei, Max G'Sell, Alessandro Rinaldo, Ryan Tibshirani and Larry Wasserman (2018) studied the method for regression under the name split conformal, proved the upper bound on its coverage and compared it with full conformal prediction. Romano, Patterson and Candès (2019) combined it with quantile regression. Because it needs only one fit, it is the form of conformal prediction that is used with large models.
References
- Harris Papadopoulos, Kostas Proedrou, Volodya Vovk and Alex Gammerman, Inductive confidence machines for regression, Machine Learning, ECML 2002, Lecture Notes in Computer Science 2430, Springer, 2002, pp. 345 to 356 (the inductive, or split, procedure for regression with a ridge regression model)
- Jing Lei, Max G'Sell, Alessandro Rinaldo, Ryan J. Tibshirani and Larry Wasserman, Distribution-free predictive inference for regression, Journal of the American Statistical Association 113(523), 2018, Section 2.2 and Theorem 2.2 (split conformal coverage, between 1 - alpha and 1 - alpha + 2/(n + 2) with n/2 calibration points and continuous residuals)
- Vladimir Vovk, Alex Gammerman and Glenn Shafer, Algorithmic Learning in a Random World, Springer, 2005, Chapter 4 (modifications of conformal predictors, including inductive conformal predictors), general locator
- Yaniv Romano, Evan Patterson and Emmanuel J. Candès, Conformalized quantile regression, 2019, the CQR score max(lo(x) - y, y - hi(x)) and its coverage guarantee
- Rina Foygel Barber, Emmanuel J. Candès, Aaditya Ramdas and Ryan J. Tibshirani, The limits of distribution-free conditional predictive inference, Information and Inference 10(2), 2021, pp. 455 to 482 (coverage conditional on x is not possible without assumptions)
- Anastasios N. Angelopoulos and Stephen Bates, Conformal prediction, a gentle introduction, Foundations and Trends in Machine Learning 16(4), 2023, pp. 494 to 591 (split conformal with many scores, and the Beta law of the coverage given the calibration set)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6A6QRB Edit this page History Report an error Markdown