Algorithm Search⌘K

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 yy of the new response it adds (xn+1,y)(x_{n+1}, y) to the data, computes a nonconformity score for every point, and keeps yy if the new score is not among the largest fraction α\alpha of the n+1n + 1 scores. If the n+1n + 1 points are exchangeable, the set contains the true response with probability at least 1−α1 - \alpha, for every sample size, every distribution and every model. The guarantee is marginal, averaged over the new xx; it is not a guarantee for each xx.

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 Zi=(Xi,Yi)Z_i = (X_i, Y_i), i=1,…,ni = 1, \ldots, n, and the new point Zn+1Z_{n+1} 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 AA that maps a bag of n+1n + 1 points to n+1n + 1 numbers, RiR_i for point ii, 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 n+1n + 1 points and set Ri=∣yi−μ^(xi)∣R_i = \lvert y_i - \hat\mu(x_i) \rvert.
  • You can afford one model fit for each candidate yy, 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 AA, the candidate values Y\mathcal Y and the level α\alpha.

  1. FULL-CONFORMAL(z_1, ..., z_n, x, Y, A, α)
  2. 1C ← ∅
  3. 2for each candidate y ∈ Y do
  4. 3z_(n+1) ← (x, y)
  5. 4(R_1, ..., R_(n+1)) ← A(z_1, ..., z_(n+1)) ▷ refit on all n + 1 points
  6. 5π(y) ← #{i ≤ n + 1 : R_i ≥ R_(n+1)} / (n + 1)
  7. 6if π(y) > α then C ← C ∪ {y}
  8. 7return C

The number π(y)\pi(y) is the conformal p-value of yy. It is the p-value of a permutation test of the hypothesis that (x,y)(x, y) is exchangeable with the data, with the score as test statistic. The set CC is the set of yy that this test does not reject at level α\alpha, so the coverage statement is the level of the test, turned around.

Coverage theorem. Let Z1,…,Zn+1Z_1, \ldots, Z_{n+1} be exchangeable and let AA treat the points symmetrically. Then

P(Yn+1∈C)≥1−⌊α(n+1)⌋n+1≥1−α,P\bigl(Y_{n+1} \in C\bigr) \ge 1 - \frac{\lfloor \alpha(n+1) \rfloor}{n+1} \ge 1 - \alpha,

and if the scores are almost surely distinct, P(Yn+1∈C)=⌈(1−α)(n+1)⌉/(n+1)<1−α+1/(n+1)P(Y_{n+1} \in C) = \lceil (1 - \alpha)(n + 1) \rceil/(n + 1) < 1 - \alpha + 1/(n + 1) (Vovk, Gammerman and Shafer, Chapter 2; Lei et al. 2018, Theorem 2.1).

Proof. Take y=Yn+1y = Y_{n+1}. Then the bag is the true data, and by symmetry of AA and exchangeability, the vector (R1,…,Rn+1)(R_1, \ldots, R_{n+1}) is exchangeable. Let Kj=#{i:Ri≥Rj}K_j = \#\{i : R_i \ge R_j\} and k=⌊α(n+1)⌋k = \lfloor \alpha(n+1) \rfloor, so that π(Yn+1)≤α\pi(Y_{n+1}) \le \alpha exactly when Kn+1≤kK_{n+1} \le k. If Kj≤kK_j \le k, then RjR_j is strictly larger than the (k+1)(k+1)-th largest score, because otherwise the k+1k + 1 largest scores are all at least RjR_j. At most kk indices have a score strictly larger than the (k+1)(k+1)-th largest, and exactly kk when the scores are distinct. So #{j:Kj≤k}≤k\#\{j : K_j \le k\} \le k, with equality for distinct scores. By exchangeability, P(Kj≤k)P(K_j \le k) is the same for every jj, so P(Kn+1≤k)=E #{j:Kj≤k}/(n+1)P(K_{n+1} \le k) = E\,\#\{j : K_j \le k\}/(n + 1), which is at most k/(n+1)k/(n + 1), with equality for distinct scores. Finally 1−k/(n+1)=⌈(1−α)(n+1)⌉/(n+1)1 - k/(n + 1) = \lceil (1 - \alpha)(n + 1) \rceil/(n + 1). □\square

The proof uses nothing about the model, so a bad model only makes the set larger. If α<1/(n+1)\alpha < 1/(n + 1), then k=0k = 0 and CC is the whole space: nn points cannot support a smaller error rate.

Least squares in closed form. For the score ∣yi−a^−b^xi∣\lvert y_i - \hat a - \hat b x_i \rvert of a least squares line fitted on the bag, every residual is an affine function ai+biya_i + b_i y of the candidate, with aa and bb given by the hat matrix of the n+1n + 1 design points. The p-value changes only where ∣ai+biy∣=∣an+1+bn+1y∣\lvert a_i + b_i y \rvert = \lvert a_{n+1} + b_{n+1} y \rvert, at most 2n2n values. Evaluating π\pi 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 O(n2)O(n^2) time, and the tests check it against lines L1 to L7 on a dense grid of candidates.

Worked example. Ten points (xi,yi)(x_i, y_i) with xi=1,…,10x_i = 1, \ldots, 10 and yy = 2.9, 5.5, 4.6, 5.1, 5.1, 5.4, 6.2, 6.0, 5.8, 6.1 have least squares line 3.887+0.2515x3.887 + 0.2515x. For a new point at x=5.5x = 5.5, where the line predicts 5.275.27:

α\alpha xx rank rule: keep yy if #{Ri≥R11}≥\#\{R_i \ge R_{11}\} \ge exact conformal set
0.2 5.5 3 [4.03,6.38][4.03, 6.38]
0.1 5.5 2 [3.91,6.78][3.91, 6.78]
0.1 20 2 [−5.70,19.01][-5.70, 19.01]

The candidate loop on the grid 0,0.01,…,120, 0.01, \ldots, 12 at α=0.2\alpha = 0.2 keeps the 235 values from 4.044.04 to 6.386.38, which agrees with the exact set. With n+1=11n + 1 = 11, the guaranteed coverage is ⌈0.8⋅11⌉/11=9/11=0.818\lceil 0.8 \cdot 11\rceil/11 = 9/11 = 0.818 for α=0.2\alpha = 0.2 and 10/11=0.90910/11 = 0.909 for α=0.1\alpha = 0.1. At x=20x = 20, far outside the data, the set is wide and not centred on the prediction 8.928.92. The new point has high leverage: a candidate yy pulls the fitted line toward itself, so its own residual stays small for a large range of yy.

Coverage, measured. The theorem is exact, so a simulation only checks the code. With Cauchy errors, for which least squares is a poor fit, y=1+0.5x+εy = 1 + 0.5x + \varepsilon, xx uniform on [0,10][0, 10], α=0.1\alpha = 0.1 and 4000 data sets each, the coverage was 0.90050.9005 for n=19n = 19 (theory 18/20=0.90018/20 = 0.900, seed 5) and 0.9110.911 for n=10n = 10 (theory 10/11=0.90910/11 = 0.909, seed 6).

Classic examples

  • Regression with a fitted model. Score ∣yi−μ^(xi)∣\lvert y_i - \hat\mu(x_i) \rvert with μ^\hat\mu 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 xx and the score Ri=yiR_i = y_i, the conformal set is (−∞,y(n+1−k)](-\infty, y_{(n+1-k)}] with k=⌊α(n+1)⌋≥1k = \lfloor \alpha(n+1) \rfloor \ge 1, 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 P(π≤t)≤tP(\pi \le t) \le t for every tt, with π\pi uniform on {1/(n+1),…,1}\{1/(n+1), \ldots, 1\} 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 (#{Ri>Rn+1}+U #{Ri=Rn+1})/(n+1)\bigl(\#\{R_i > R_{n+1}\} + U\,\#\{R_i = R_{n+1}\}\bigr)/(n + 1), where UU is uniform on [0,1][0, 1]. The coverage is then exactly 1−α1 - \alpha, 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 nn 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 1−2α1 - 2\alpha in the worst case (Barber et al. 2021) and usually close to 1−α1 - \alpha 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 ∣y−μ^(x)∣/σ^(x)\lvert y - \hat\mu(x) \rvert/\hat\sigma(x) and quantile regression scores give sets whose width changes with xx. Coverage is the same; only the shape of the sets changes.

Pitfalls

  • Marginal, not conditional, coverage. The guarantee is an average over the new xx. With errors whose spread grows with ∣x∣\lvert x \rvert (xx uniform on [−1,1][-1, 1], standard deviation 0.1+∣x∣0.1 + \lvert x \rvert, n=39n = 39, α=0.1\alpha = 0.1, 8000 data sets, seed 9), the least squares sets covered 0.9970.997 of the new points with ∣x∣<0.25\lvert x \rvert < 0.25 but only 0.7630.763 of those with ∣x∣>0.75\lvert x \rvert > 0.75, while the overall coverage was 0.90.9. No method can give coverage at each xx 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 nn 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 n+1n + 1 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 1−α1 - \alpha.
  • 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 α\alpha. If α<1/(n+1)\alpha < 1/(n + 1) the set is everything. This is correct, not a bug: with nn 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.

conformal_prediction.pyI0RawGitHub
# 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

  1. Show that π(Yn+1)\pi(Y_{n+1}) is uniform on {1/(n+1),2/(n+1),…,1}\{1/(n+1), 2/(n+1), \ldots, 1\} when the scores are almost surely distinct, and deduce the exact coverage ⌈(1−α)(n+1)⌉/(n+1)\lceil (1 - \alpha)(n + 1)\rceil/(n + 1).
  2. Show that the smoothed p-value is exactly uniform on [0,1][0, 1] under exchangeability, also when the scores have ties.
  3. For the least squares score, write aa and bb in terms of the hat matrix HH of the n+1n + 1 design points, and show that bn+1=1−Hn+1,n+1>0b_{n+1} = 1 - H_{n+1, n+1} > 0 when at least two of the first nn design points differ.
  4. With no xx and the score Ri=∣yi−yˉ∣R_i = \lvert y_i - \bar y \rvert, where yˉ\bar y is the mean of the bag, show that the conformal set is an interval and find its ends for n=4n = 4 and α=0.2\alpha = 0.2.
  5. 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

  1. 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)
  2. Vladimir Vovk, Alex Gammerman and Glenn Shafer, Algorithmic Learning in a Random World, second edition, Springer, 2022, Chapter 2 (conformal prediction), general locator
  3. 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)
  4. 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)
  5. 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)
  6. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises