Techniqueadvanced
Conformal prediction
Also called conformal inference.
Turns any predictor into prediction sets with coverage at least 1 - alpha, assuming only exchangeable data, by ranking a nonconformity score of a new point among those of the data.
Conformal prediction turns any predictive model into prediction sets with a coverage guarantee that needs no model assumptions. For each candidate value of the new response it adds to the data, computes a nonconformity score for every point, and keeps if the new score is not among the largest fraction of the scores. If the points are exchangeable, the set contains the true response with probability at least , for every sample size, every distribution and every model. The guarantee is marginal, averaged over the new ; it is not a guarantee for each .
In plain words
You have past examples of inputs and answers, and a new input whose answer you want to bound. Try a possible answer. Put it into the data as if it were true, fit your model to all the points, and measure how badly each point fits. If the trial answer fits worse than nearly all the old points, it is implausible, so reject it. Keep every trial answer that is not rejected. The kept answers form the prediction set.
Why does this work? If the new point comes from the same source as the old ones, and the order of the points carries no information, then the true answer is equally likely to have any rank among the misfit values. So it falls in the worst few ranks only rarely, and the set holds it as often as you asked. A wrong model gives a wide set that still holds.
When it applies
- The data , , and the new point are exchangeable: their joint law does not change when they are permuted. Independent and identically distributed points are exchangeable. Time series, data with a shift between training and use, and data chosen after looking at the new point are not.
- You can compute a nonconformity score that maps a bag of points to numbers, for point , and that treats the points symmetrically: permuting the bag permutes the scores in the same way. The usual way is to fit a model on all points and set .
- You can afford one model fit for each candidate , or the score has a structure that gives the set in closed form, as for least squares below. If not, use split conformal prediction, which fits once.
The template
The holes are the score , the candidate values and the level .
FULL-CONFORMAL(z_1, ..., z_n, x, Y, A, α)- 1
C ← ∅ - 2
for each candidate y ∈ Y do - 3
z_(n+1) ← (x, y) - 4
(R_1, ..., R_(n+1)) ← A(z_1, ..., z_(n+1)) ▷ refit on all n + 1 points - 5
π(y) ← #{i ≤ n + 1 : R_i ≥ R_(n+1)} / (n + 1) - 6
if π(y) > α then C ← C ∪ {y} - 7
return C
The number is the conformal p-value of . It is the p-value of a permutation test of the hypothesis that is exchangeable with the data, with the score as test statistic. The set is the set of that this test does not reject at level , so the coverage statement is the level of the test, turned around.
Coverage theorem. Let be exchangeable and let treat the points symmetrically. Then
and if the scores are almost surely distinct, (Vovk, Gammerman and Shafer, Chapter 2; Lei et al. 2018, Theorem 2.1).
Proof. Take . Then the bag is the true data, and by symmetry of and exchangeability, the vector is exchangeable. Let and , so that exactly when . If , then is strictly larger than the -th largest score, because otherwise the largest scores are all at least . At most indices have a score strictly larger than the -th largest, and exactly when the scores are distinct. So , with equality for distinct scores. By exchangeability, is the same for every , so , which is at most , with equality for distinct scores. Finally .
The proof uses nothing about the model, so a bad model only makes the set larger. If , then and is the whole space: points cannot support a smaller error rate.
Least squares in closed form. For the score of a least squares line fitted on the bag, every residual is an affine function of the candidate, with and given by the hat matrix of the design points. The p-value changes only where , at most values. Evaluating at these roots and once between each pair gives the exact set as a finite union of closed intervals. This is the ridge regression confidence machine of Vovk, Gammerman and Shafer with the ridge penalty set to zero. The implementation does this in time, and the tests check it against lines L1 to L7 on a dense grid of candidates.
Worked example. Ten points with and = 2.9, 5.5, 4.6, 5.1, 5.1, 5.4, 6.2, 6.0, 5.8, 6.1 have least squares line . For a new point at , where the line predicts :
| rank rule: keep if | exact conformal set | ||
|---|---|---|---|
| 0.2 | 5.5 | 3 | |
| 0.1 | 5.5 | 2 | |
| 0.1 | 20 | 2 |
The candidate loop on the grid at keeps the 235 values from to , which agrees with the exact set. With , the guaranteed coverage is for and for . At , far outside the data, the set is wide and not centred on the prediction . The new point has high leverage: a candidate pulls the fitted line toward itself, so its own residual stays small for a large range of .
Coverage, measured. The theorem is exact, so a simulation only checks the code. With Cauchy errors, for which least squares is a poor fit, , uniform on , and 4000 data sets each, the coverage was for (theory , seed 5) and for (theory , seed 6).
Classic examples
- Regression with a fitted model. Score with fitted on the bag: least squares, ridge regression, a nearest-neighbour average or any other learner. For linear smoothers the set has closed form as above; for other learners use a grid of candidates.
- Classification. The candidates are the finitely many labels, so lines L1 to L7 are exact with no grid. The nearest-neighbour score of Vovk, Gammerman and Shafer is the distance to the nearest point with the same label over the distance to the nearest point with another label. The set can hold one label, several labels when the case is ambiguous, or none.
- The distribution-free prediction bound. With no and the score , the conformal set is with , a bound at an order statistic of the sample. This is the one-sided case of the order-statistic prediction interval.
- Outlier detection. The conformal p-value of a new point measures how unusual it is among reference data. Under exchangeability for every , with uniform on when the scores are distinct, so it is a valid p-value for a test of each new point.
Variations
- Smoothed conformal prediction. Replace line L5 with , where is uniform on . The coverage is then exactly , also with ties. The tests check this exactly, for scores with ties, by enumerating all orderings of six points.
- Split conformal prediction. Fit the model once on part of the data and rank the scores of the other part. It needs one fit instead of one for each candidate, and its guarantee is the same with replaced by the number of calibration points.
- Jackknife+ and CV+. Use leave-one-out or K-fold fits, as in cross-validation, instead of a fit for each candidate. The coverage is at least in the worst case (Barber et al. 2021) and usually close to in practice. It uses all the data for fitting, unlike split conformal.
- Label-conditional, or Mondrian, conformal prediction. Rank the score of a candidate label only against points with the same label. The coverage then holds within each class, which helps when one class is rare.
- Other scores. Scaled residuals and quantile regression scores give sets whose width changes with . Coverage is the same; only the shape of the sets changes.
Pitfalls
- Marginal, not conditional, coverage. The guarantee is an average over the new . With errors whose spread grows with ( uniform on , standard deviation , , , 8000 data sets, seed 9), the least squares sets covered of the new points with but only of those with , while the overall coverage was . No method can give coverage at each for every distribution with sets of finite expected length (Barber et al. 2021, Information and Inference).
- A score that is not symmetric. If the model is fitted on the data points only and the new point is scored against that fit, the old scores are in-sample residuals and the new one is out-of-sample. They are not exchangeable, and the sets are too short. Either refit on all points, as in line L4, or use split conformal.
- Exchangeability fails. Time series, drift, and a test point chosen in a different way from the training points all break the argument. The coverage can then be far from .
- A grid of candidates. The set need not be an interval, and a coarse grid can miss small pieces of it or cut its ends. Use the closed form when there is one, and report the grid step otherwise.
- Very small . If the set is everything. This is correct, not a bug: with points no method can promise a smaller error rate without assumptions.
- Cost. One fit for each candidate and each new point. For a large model or many new points, split conformal or the jackknife+ is the practical choice.
Code
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/conformal-prediction/. The authors are listed in prov/83RAAM.jsonl.
from fractions import Fraction
from typing import Callable, Iterable, List, Optional, Sequence, Tuple
Point = Tuple[object, object] # (x, y)
Scores = Callable[[List[Point]], List[object]]
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 conformal_p_value(r: Sequence) -> Fraction:
"""#{i : R_i >= R_last} / len(R), the conformal p-value of the last score."""
return Fraction(sum(1 for v in r if v >= r[-1]), len(r))
def smoothed_p_value(r: Sequence, u) -> object:
"""(#{R_i > R_last} + u #{R_i = R_last}) / len(R), with u uniform on [0, 1]."""
greater = sum(1 for v in r if v > r[-1])
equal = sum(1 for v in r if v == r[-1])
return (greater + u * equal) / len(r)
def full_conformal_set(
data: Sequence[Point],
x_new: object,
candidates: Iterable,
scores: Scores,
alpha,
) -> list:
"""The candidates y whose conformal p-value at (x_new, y) is larger than alpha."""
alpha = level(alpha)
accepted = [] # @line L1
for y in candidates: # @line L2
bag = list(data) + [(x_new, y)] # @line L3
r = scores(bag) # @line L4
p = conformal_p_value(r) # @line L5
if p > alpha: # @line L6
accepted.append(y)
return accepted # @line L7
# Nonconformity scores. Each one is a symmetric function of the bag: it refits on all
# n + 1 points, so permuting the bag permutes the scores in the same way.
def mean_scores(bag: List[Point]) -> list:
"""|y_i - mean of the y in the bag|; x is ignored."""
ys = _numbers([y for _, y in bag])
m = sum(ys) / len(ys)
return [abs(y - m) for y in ys]
def least_squares_line(points: Sequence[Point]) -> Tuple[object, object]:
"""Intercept and slope of the least squares line through the points."""
n = len(points)
vals = _numbers([x for x, _ in points] + [y for _, y in points])
xs, ys = vals[:n], vals[n:]
mx = sum(xs) / n
my = sum(ys) / n
sxx = sum((x - mx) ** 2 for x in xs)
sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
slope = sxy / sxx
return my - slope * mx, slope
def least_squares_scores(bag: List[Point]) -> list:
"""|residual| of each point from the least squares line fitted on the whole bag."""
a, b = least_squares_line(bag)
pts = _numbers([v for p in bag for v in p])
return [abs(pts[2 * i + 1] - a - b * pts[2 * i]) for i in range(len(bag))]
def nearest_neighbour_scores(bag: List[Point]) -> list:
"""Distance to the nearest point with the same label over the distance to the nearest
point with another label (Vovk, Gammerman and Shafer). x is a number, labels are hashable.
A point with no other point of its label gets an infinite score."""
inf = float("inf")
out = []
for i, (x, y) in enumerate(bag):
same = min((abs(x - u) for j, (u, v) in enumerate(bag) if j != i and v == y), default=inf)
other = min((abs(x - u) for u, v in bag if v != y), default=inf)
if same == inf or other == 0:
out.append(inf if same > 0 else 0)
elif other == inf:
out.append(0)
else:
out.append(Fraction(same) / Fraction(other))
return out
# Exact full conformal set for the least squares score. The residuals of the bag are
# affine in the candidate y: r_i(y) = a_i + b_i y, so the p-value only changes where
# |r_i(y)| = |r_last(y)|. Evaluating it at those roots and between them gives the set.
def _numbers(values: Sequence) -> list:
"""Fractions if every value is exact, floats otherwise."""
if all(isinstance(v, (int, Fraction)) for v in values):
return [Fraction(v) for v in values]
return [float(v) for v in values]
def least_squares_affine_residuals(data: Sequence[Point], x_new) -> Tuple[list, list]:
"""a, b with r_i(y) = a_i + b_i y the residual of point i (the new point last) from the
least squares line fitted on the data and (x_new, y)."""
m = len(data) + 1
vals = _numbers([x for x, _ in data] + [x_new] + [y for _, y in data] + [0])
xs, ys = vals[:m], vals[m:]
mx = sum(xs) / m
sxx = sum((x - mx) ** 2 for x in xs)
if sxx == 0:
raise ValueError("the x values must not all be equal")
def h(i, j): # the hat matrix of the least squares line
return (1 + m * (xs[i] - mx) * (xs[j] - mx) / sxx) / m
a = [ys[i] - sum(h(i, j) * ys[j] for j in range(m)) for i in range(m)]
b = [(1 if i == m - 1 else 0) - h(i, m - 1) for i in range(m)]
return a, b
def _count(a, b, y) -> int:
last = abs(a[-1] + b[-1] * y)
return sum(1 for ai, bi in zip(a, b) if abs(ai + bi * y) >= last)
def full_conformal_least_squares(
data: Sequence[Point], x_new, alpha
) -> List[Tuple[Optional[object], Optional[object]]]:
"""The exact full conformal set for least_squares_scores, as closed intervals [lo, hi].
None stands for an infinite end. The set is a union of these intervals."""
alpha = level(alpha)
a, b = least_squares_affine_residuals(data, x_new)
m = len(a)
roots = set()
for ai, bi in zip(a[:-1], b[:-1]):
for da, db in ((ai - a[-1], bi - b[-1]), (ai + a[-1], bi + b[-1])):
if db != 0:
roots.add(-da / db)
roots = sorted(roots)
def ok(y) -> bool:
return _count(a, b, y) > alpha * m
# pieces in order: gap, root, gap, root, ..., root, gap
if not roots:
return [(None, None)] if ok(0) else []
pieces = [("gap", None, roots[0], ok(roots[0] - 1))]
for k, r in enumerate(roots):
pieces.append(("pt", r, r, ok(r)))
hi = roots[k + 1] if k + 1 < len(roots) else None
mid = (r + hi) / 2 if hi is not None else r + 1
pieces.append(("gap", r, hi, ok(mid)))
out = []
current = None
for _, lo, hi, good in pieces:
if good:
if current is None:
current = [lo, hi]
else:
current[1] = hi
elif current is not None:
out.append(tuple(current))
current = None
if current is not None:
out.append(tuple(current))
return out
def in_set(intervals, y) -> bool:
return any((lo is None or lo <= y) and (hi is None or y <= hi) for lo, hi in intervals)
test_conformal_prediction.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conformal-prediction/. The authors are listed in prov/83RAAM.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from conformal_prediction import (
conformal_p_value,
full_conformal_least_squares,
full_conformal_set,
in_set,
least_squares_affine_residuals,
least_squares_scores,
level,
mean_scores,
nearest_neighbour_scores,
smoothed_p_value,
)
ALPHAS = (Fraction(1, 20), Fraction(1, 10), Fraction(1, 5), Fraction(1, 4), Fraction(1, 2), Fraction(5, 6))
def exact_coverage(bag, scores, alpha):
"""P(Y_new is in the set) when the order of the bag is uniformly random: enumerate every
ordering, use the first n points as data and the last one as the new point."""
hits = total = 0
for perm in itertools.permutations(bag):
data, (x_new, y_new) = list(perm[:-1]), perm[-1]
hits += bool(full_conformal_set(data, x_new, [y_new], scores, alpha))
total += 1
return Fraction(hits, total)
def exact_smoothed_coverage(bag, scores, alpha):
"""The same, for the smoothed p-value, averaged exactly over u uniform on [0, 1]."""
total = Fraction(0)
perms = list(itertools.permutations(bag))
for perm in perms:
r = scores(list(perm))
greater = sum(1 for v in r if v > r[-1])
equal = sum(1 for v in r if v == r[-1])
# P(greater + u equal > alpha m) for u uniform on [0, 1]
threshold = (alpha * len(r) - greater) / equal
total += min(max(1 - threshold, Fraction(0)), Fraction(1))
return total / len(perms)
BAG = [(Fraction(1), Fraction(3)), (Fraction(2), Fraction(7, 2)), (Fraction(3), Fraction(6)),
(Fraction(4), Fraction(5)), (Fraction(5), Fraction(9)), (Fraction(6), Fraction(8))]
def test_exact_coverage_with_distinct_scores():
r = least_squares_scores(BAG)
assert len(set(r)) == len(r)
m = len(BAG)
for alpha in ALPHAS:
# with distinct scores the coverage is exactly ceil((1 - alpha)(n + 1))/(n + 1)
expected = Fraction(math.ceil((1 - alpha) * m), m)
assert exact_coverage(BAG, least_squares_scores, alpha) == expected
assert 1 - alpha <= expected < 1 - alpha + Fraction(1, m)
def test_ties_give_at_least_one_minus_alpha_and_smoothing_gives_exactly():
# y values symmetric about their mean: the scores |y - mean| come in tied pairs
bag = [(0, Fraction(v)) for v in (-3, -1, 1, 3, 0, 0)]
m = len(bag)
for alpha in ALPHAS:
cov = exact_coverage(bag, mean_scores, alpha)
assert cov >= 1 - alpha
assert exact_smoothed_coverage(bag, mean_scores, alpha) == 1 - alpha
assert exact_coverage(bag, mean_scores, Fraction(1, 2)) > Fraction(math.ceil(Fraction(1, 2) * m), m)
def test_classification_with_nearest_neighbour_scores():
bag = [(Fraction(0), "a"), (Fraction(1), "a"), (Fraction(3), "a"),
(Fraction(6), "b"), (Fraction(7), "b"), (Fraction(9), "b")]
for alpha in ALPHAS:
assert exact_coverage(bag, nearest_neighbour_scores, alpha) >= 1 - alpha
assert exact_smoothed_coverage(bag, nearest_neighbour_scores, alpha) == 1 - alpha
data = bag[:5]
assert full_conformal_set(data, Fraction(1, 2), ["a", "b"], nearest_neighbour_scores, 0.2) == ["a"]
assert full_conformal_set(data, Fraction(8), ["a", "b"], nearest_neighbour_scores, 0.2) == ["b"]
def test_exact_least_squares_set_against_the_candidate_loop():
rng = random.Random(3)
for trial in range(12):
n = rng.randint(4, 7)
data = [(Fraction(rng.randint(0, 20), 2), Fraction(rng.randint(-40, 40), 4)) for _ in range(n)]
if len({x for x, _ in data}) < 2:
continue
x_new = Fraction(rng.randint(-10, 30), 2)
alpha = rng.choice(ALPHAS)
sets = full_conformal_least_squares(data, x_new, alpha)
a, b = least_squares_affine_residuals(data, x_new)
# the affine form gives the same residuals as a refit
for y in (Fraction(-7), Fraction(0), Fraction(13, 3)):
direct = least_squares_scores(list(data) + [(x_new, y)])
assert direct == [abs(ai + bi * y) for ai, bi in zip(a, b)]
# brute force: a dense grid, every finite end, and points just inside and outside each end
cands = [Fraction(k, 8) for k in range(-200, 201)]
for lo, hi in sets:
for e in (lo, hi):
if e is not None:
cands += [e, e - Fraction(1, 10**6), e + Fraction(1, 10**6)]
accepted = set(full_conformal_set(data, x_new, cands, least_squares_scores, alpha))
for y in cands:
assert (y in accepted) == in_set(sets, y), (trial, y)
def test_worked_example():
data = [(1, "2.9"), (2, "5.5"), (3, "4.6"), (4, "5.1"), (5, "5.1"),
(6, "5.4"), (7, "6.2"), (8, "6.0"), (9, "5.8"), (10, "6.1")]
data = [(Fraction(x), Fraction(y)) for x, y in data]
[(lo, hi)] = full_conformal_least_squares(data, Fraction(11, 2), 0.2)
assert round(float(lo), 3) == 4.032 and round(float(hi), 3) == 6.380
[(lo, hi)] = full_conformal_least_squares(data, Fraction(11, 2), 0.1)
assert round(float(lo), 3) == 3.913 and round(float(hi), 3) == 6.783
[(lo, hi)] = full_conformal_least_squares(data, Fraction(20), 0.1)
assert round(float(lo), 3) == -5.698 and round(float(hi), 3) == 19.011
def simulate(n, alpha, trials, seed, make_point):
rng = random.Random(seed)
out = []
for _ in range(trials):
bag = [make_point(rng) for _ in range(n + 1)]
out.append((bag[-1][0], conformal_p_value(least_squares_scores(bag)) > level(alpha)))
return out
def test_marginal_coverage_with_heavy_tails_is_measured():
def cauchy_point(rng):
x = rng.uniform(0, 10)
return x, 1 + 0.5 * x + math.tan(math.pi * (rng.random() - 0.5))
trials = 3000
hits = sum(ok for _, ok in simulate(19, 0.1, trials, 5, cauchy_point))
assert abs(hits / trials - 0.9) < 4 * math.sqrt(0.09 / trials)
def test_coverage_is_not_conditional_on_x():
def spread_point(rng):
x = rng.uniform(-1, 1)
return x, x + rng.gauss(0, 0.1 + abs(x))
res = simulate(39, 0.1, 4000, 9, spread_point)
inner = [ok for x, ok in res if abs(x) < 0.25]
outer = [ok for x, ok in res if abs(x) > 0.75]
assert sum(inner) / len(inner) > 0.97
assert sum(outer) / len(outer) < 0.82
assert abs(sum(ok for _, ok in res) / len(res) - 0.9) < 0.02
def test_p_values_and_errors():
assert conformal_p_value([3, 1, 2, 2]) == Fraction(3, 4)
assert smoothed_p_value([3, 1, 2, 2], Fraction(1, 2)) == Fraction(1, 2)
with pytest.raises(ValueError):
full_conformal_set([(0, 1)], 0, [1], mean_scores, 1.0)
with pytest.raises(ValueError):
full_conformal_least_squares([(1, 1), (1, 2)], 1, 0.1)
Exercises
- Show that is uniform on when the scores are almost surely distinct, and deduce the exact coverage .
- Show that the smoothed p-value is exactly uniform on under exchangeability, also when the scores have ties.
- For the least squares score, write and in terms of the hat matrix of the design points, and show that when at least two of the first design points differ.
- With no and the score , where is the mean of the bag, show that the conformal set is an interval and find its ends for and .
- Give an example of exchangeable but not independent points for which conformal prediction is still valid, and an example of independent points that are not exchangeable.
References
- Vladimir Vovk, Alex Gammerman and Glenn Shafer, Algorithmic Learning in a Random World, Springer, 2005, Chapter 2 (conformal predictors, nonconformity measures, validity under exchangeability, smoothed conformal predictors, the nearest neighbour and ridge regression examples)
- Vladimir Vovk, Alex Gammerman and Glenn Shafer, Algorithmic Learning in a Random World, second edition, Springer, 2022, Chapter 2 (conformal prediction), general locator
- 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.1 and Theorem 2.1 (full conformal coverage, at least 1 - alpha and at most 1 - alpha + 1/(n + 1) for continuous scores)
- Rina Foygel Barber, Emmanuel J. Candès, Aaditya Ramdas and Ryan J. Tibshirani, Predictive inference with the jackknife+, The Annals of Statistics 49(1), 2021, pp. 486 to 507 (the jackknife+ and CV+, coverage at least 1 - 2 alpha)
- 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 (distribution-free coverage conditional on x is not possible with sets of finite expected length)
- Anastasios N. Angelopoulos and Stephen Bates, Conformal prediction, a gentle introduction, Foundations and Trends in Machine Learning 16(4), 2023, pp. 494 to 591 (a survey with scores for classification and regression)
Where this leads
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 83RAAM Edit this page History Report an error Markdown