Algorithm Search⌘K

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
Properties
randomizedexactofflinerandomizediterative
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 qq, the ⌈(n2+1)(1−α)⌉\lceil (n_2 + 1)(1 - \alpha) \rceil-th smallest of the n2n_2 calibration residuals. If the data and the new point are exchangeable, the interval holds the new response with probability at least 1−α1 - \alpha, and at most 1−α+1/(n2+1)1 - \alpha + 1/(n_2 + 1) 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 Zi=(Xi,Yi)Z_i = (X_i, Y_i), i=1,…,ni = 1, \ldots, n, a new input Xn+1X_{n+1}, a learning algorithm that maps a data set to a predictor μ^\hat\mu, and a level α∈(0,1)\alpha \in (0, 1), find an interval C(Xn+1)C(X_{n+1}) with

P(Yn+1∈C(Xn+1))≥1−αP\bigl(Y_{n+1} \in C(X_{n+1})\bigr) \ge 1 - \alpha

whenever Z1,…,Zn+1Z_1, \ldots, Z_{n+1} are exchangeable, with no other assumption about their law or about μ^\hat\mu. 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 Xn+1X_{n+1}.

The algorithm

  1. SPLIT-CONFORMAL(z_1, ..., z_n, n_1, fit, α)
  2. 1split {1, ..., n} at random into I_1 of size n_1 and I_2 of size n_2 = n - n_1
  3. 2μ̂ ← fit({z_i : i ∈ I_1})
  4. 3R_i ← |y_i - μ̂(x_i)| for each i ∈ I_2
  5. 4k ← ⌈(n_2 + 1)(1 - α)⌉
  6. 5if k > n_2 then q ← ∞
  7. 6else q ← the k-th smallest of {R_i : i ∈ I_2}
  8. 7return 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 1/α−11/\alpha - 1 calibration points, no finite qq is guaranteed to work, and the honest answer is the whole line.

Example

Forty points with xx uniform on [0,10][0, 10] and y=1+0.5x+εy = 1 + 0.5x + \varepsilon, ε\varepsilon standard normal (random.Random(2026)), were split by random.Random(1) into n1=20n_1 = 20 training and n2=20n_2 = 20 calibration points. A least squares line was fitted on the training part.

  • For α=0.1\alpha = 0.1: k=⌈21⋅0.9⌉=⌈18.9⌉=19k = \lceil 21 \cdot 0.9 \rceil = \lceil 18.9 \rceil = 19, so qq is the 19th smallest of the 20 absolute calibration residuals, q=1.565q = 1.565. At x=5x = 5 the line predicts 3.333.33 and the interval is [1.76,4.90][1.76, 4.90]. For comparison, the ideal 90% half width for standard normal errors with a known line is 1.6451.645.
  • For α=0.2\alpha = 0.2: k=⌈21⋅0.8⌉=17k = \lceil 21 \cdot 0.8 \rceil = 17 and q=1.469q = 1.469.
  • With the same data and n2=10n_2 = 10: k=⌈11⋅0.9⌉=10k = \lceil 11 \cdot 0.9 \rceil = 10, and q=1.738q = 1.738 is the largest calibration residual.
  • With n2=4n_2 = 4: k=⌈5⋅0.9⌉=5>4k = \lceil 5 \cdot 0.9 \rceil = 5 > 4, so line L5 sets q=∞q = \infty.

Coverage, measured. The theorem gives the exact value k/(n2+1)k/(n_2 + 1) for continuous errors, so these runs only check the code. Each row has 4000 data sets with one new point each, α=0.1\alpha = 0.1 and a least squares line.

errors nn n2n_2 k/(n2+1)k/(n_2 + 1) measured coverage median width 2q2q seed
normal 40 20 19/21=0.90519/21 = 0.905 0.908 3.65 3
Cauchy 40 20 19/21=0.90519/21 = 0.905 0.906 19.6 4
normal 200 100 91/101=0.90191/101 = 0.901 0.909 3.37 5
normal 40 10 10/11=0.90910/11 = 0.909 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 0.00460.0046.

Correctness

The proof is in the correctness file. Fix the training part. Then μ^\hat\mu is fixed, and the n2n_2 calibration scores and the score Rn+1=∣Yn+1−μ^(Xn+1)∣R_{n+1} = \lvert Y_{n+1} - \hat\mu(X_{n+1}) \rvert of the new point are n2+1n_2 + 1 exchangeable numbers. The new point is covered exactly when Rn+1R_{n+1} is at most the kk-th smallest calibration score, and that happens when at most k−1k - 1 calibration scores are strictly smaller than Rn+1R_{n+1}. At least kk of the n2+1n_2 + 1 scores have this property, and exactly kk when they are distinct, so by exchangeability

1−α≤kn2+1≤P(Yn+1∈C(Xn+1)),1 - \alpha \le \frac{k}{n_2 + 1} \le P\bigl(Y_{n+1} \in C(X_{n+1})\bigr),

with equality in the second step for distinct scores. Since k<(n2+1)(1−α)+1k < (n_2 + 1)(1 - \alpha) + 1, the coverage with continuous scores is then below 1−α+1/(n2+1)1 - \alpha + 1/(n_2 + 1). Lei et al. (2018, Theorem 2.2) state the upper bound as 1−α+2/(n+2)1 - \alpha + 2/(n + 2) for an even split, n2=n/2n_2 = n/2, which is the same number.

The tests check the exact coverage by exchangeability: for six calibration and test points they enumerate all 720720 orderings and get exactly k/6k/6 for each α\alpha when the scores are distinct, and at least 1−α1 - \alpha 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. Z1,…,Zn,Zn+1Z_1, \ldots, Z_n, Z_{n+1} with Zi=(Xi,Yi)Z_i = (X_i, Y_i) are the data and the new point. The split of line L1 is independent of the data. I1I_1 has n1n_1 indices and I2I_2 has n2=n−n1n_2 = n - n_1. Write k=⌈(n2+1)(1−α)⌉k = \lceil (n_2 + 1)(1 - \alpha) \rceil, Ri=∣Yi−μ^(Xi)∣R_i = \lvert Y_i - \hat\mu(X_i) \rvert for i∈I2∪{n+1}i \in I_2 \cup \{n + 1\}, and R(1)cal≤⋯≤R(n2)calR^{\mathrm{cal}}_{(1)} \le \cdots \le R^{\mathrm{cal}}_{(n_2)} 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 xx is proved; the page only measures those.

Claim 1 (the event of coverage). If k≤n2k \le n_2, then Yn+1∈[μ^(Xn+1)−q,μ^(Xn+1)+q]Y_{n+1} \in [\hat\mu(X_{n+1}) - q, \hat\mu(X_{n+1}) + q] if and only if S≤k−1S \le k - 1, where S=#{i∈I2:Ri<Rn+1}S = \#\{i \in I_2 : R_i < R_{n+1}\}. If k>n2k > n_2, the new point is always covered.

Proof. If k>n2k > n_2, line L5 sets q=∞q = \infty. Otherwise line L6 sets q=R(k)calq = R^{\mathrm{cal}}_{(k)}, and the new point is covered exactly when Rn+1≤R(k)calR_{n+1} \le R^{\mathrm{cal}}_{(k)}. If Rn+1≤R(k)calR_{n+1} \le R^{\mathrm{cal}}_{(k)}, every calibration score below Rn+1R_{n+1} is below R(k)calR^{\mathrm{cal}}_{(k)}, so it is one of R(1)cal,…,R(k−1)calR^{\mathrm{cal}}_{(1)}, \ldots, R^{\mathrm{cal}}_{(k-1)}, and S≤k−1S \le k - 1. If Rn+1>R(k)calR_{n+1} > R^{\mathrm{cal}}_{(k)}, then R(1)cal,…,R(k)calR^{\mathrm{cal}}_{(1)}, \ldots, R^{\mathrm{cal}}_{(k)} are all below Rn+1R_{n+1} and S≥kS \ge k. □\square

Claim 2 (the scores are exchangeable given the training part). Conditional on the split and on (Zi)i∈I1(Z_i)_{i \in I_1}, the n2+1n_2 + 1 scores (Ri)i∈I2∪{n+1}(R_i)_{i \in I_2 \cup \{n+1\}} are exchangeable.

Proof. The split does not depend on the data, so conditional on it, (Zi)i∈I1(Z_i)_{i \in I_1} followed by (Zi)i∈I2∪{n+1}(Z_i)_{i \in I_2 \cup \{n+1\}} is still an exchangeable sequence. Permuting the last n2+1n_2 + 1 points therefore does not change the joint law, and hence does not change their conditional law given the first block. Given the training block, μ^\hat\mu is a fixed function, and each score is the same fixed function z↦∣y−μ^(x)∣z \mapsto \lvert y - \hat\mu(x) \rvert of its own point. A fixed function applied to each member of an exchangeable vector gives an exchangeable vector. □\square

Claim 3 (lower bound). P(Yn+1∈C(Xn+1))≥k/(n2+1)≥1−αP\bigl(Y_{n+1} \in C(X_{n+1})\bigr) \ge k/(n_2 + 1) \ge 1 - \alpha when k≤n2k \le n_2, and the coverage is 1 when k>n2k > n_2.

Proof. Work conditionally on the split and the training block, and index the n2+1n_2 + 1 scores by jj. Let SjS_j be the number of the other n2n_2 scores that are strictly smaller than RjR_j; then S=Sn+1S = S_{n+1}. Let T(1)≤⋯≤T(n2+1)T_{(1)} \le \cdots \le T_{(n_2 + 1)} be all n2+1n_2 + 1 scores sorted. If Sj≥kS_j \ge k, then at least kk scores are strictly below RjR_j, so Rj>T(k)R_j > T_{(k)}. At most n2+1−kn_2 + 1 - k indices have a score strictly above T(k)T_{(k)}. So at most n2+1−kn_2 + 1 - k indices have Sj≥kS_j \ge k, and at least kk have Sj≤k−1S_j \le k - 1. Permuting the scores permutes the SjS_j in the same way, and the scores are exchangeable (Claim 2), so the vector (Sj)(S_j) is exchangeable and P(Sj≤k−1)P(S_j \le k - 1) is the same for every jj. Hence

P(Sn+1≤k−1)=1n2+1E #{j:Sj≤k−1}≥kn2+1.P(S_{n+1} \le k - 1) = \frac{1}{n_2 + 1} E\,\#\{j : S_j \le k - 1\} \ge \frac{k}{n_2 + 1}.

By Claim 1 this is the conditional coverage, and averaging over the training block keeps the bound. Finally k≥(n2+1)(1−α)k \ge (n_2 + 1)(1 - \alpha) by the definition of the ceiling. The case k>n2k > n_2 is Claim 1. □\square

Claim 4 (upper bound for distinct scores). If the n2+1n_2 + 1 scores are almost surely distinct, for example when YY given XX has a continuous law, then for k≤n2k \le n_2

P(Yn+1∈C(Xn+1))=kn2+1<1−α+1n2+1.P\bigl(Y_{n+1} \in C(X_{n+1})\bigr) = \frac{k}{n_2 + 1} < 1 - \alpha + \frac{1}{n_2 + 1}.

Proof. With distinct scores, SjS_j is the rank of RjR_j minus one, the SjS_j are 0,1,…,n20, 1, \ldots, n_2 in some order, and exactly kk indices have Sj≤k−1S_j \le k - 1. The display in Claim 3 is then an equality. The ceiling gives k<(n2+1)(1−α)+1k < (n_2 + 1)(1 - \alpha) + 1; divide by n2+1n_2 + 1. □\square

With an even split, n2=n/2n_2 = n/2, the slack is 1/(n/2+1)=2/(n+2)1/(n/2 + 1) = 2/(n + 2), 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 RR of a new point has a continuous distribution function FF. Then the coverage conditional on the training and calibration blocks is F(q)F(q), and for k≤n2k \le n_2 it has the Beta law with parameters kk and n2+1−kn_2 + 1 - k.

Proof. Given both blocks, qq is fixed and the new point is independent of them, so the conditional coverage is P(Rn+1≤q)=F(q)P(R_{n+1} \le q) = F(q). The calibration scores are iid with the continuous distribution function FF, so Ui=F(Ri)U_i = F(R_i) are iid uniform on [0,1][0, 1], and FF is nondecreasing, so F(R(k)cal)=U(k)F(R^{\mathrm{cal}}_{(k)}) = U_{(k)}, the kk-th order statistic of n2n_2 uniforms, whose law is Beta(k,n2+1−k)(k, n_2 + 1 - k). Its mean is k/(n2+1)k/(n_2 + 1), which agrees with Claim 4. □\square

Claim 6 (cost). Lines L1 and L3 to L5 take O(n)O(n) time besides the n2n_2 predictions, line L2 is one fit, and line L6 takes O(n2log⁡n2)O(n_2 \log n_2) time by sorting or O(n2)O(n_2) by linear-time selection. The space is O(n)O(n) besides the model.

Proof. Line L1 is a shuffle of nn indices. Line L3 makes one prediction and one subtraction for each calibration point. Line L4 is arithmetic. Selection of the kk-th smallest of n2n_2 numbers takes linear time by the median of medians method, or the sort can be used. □\square

What the tests check. The test file fixes a training block and enumerates all 6!=7206! = 720 orderings of five calibration points and one new point. With distinct scores the coverage is exactly k/6k/6 for each α\alpha tested (Claims 3 and 4), and with tied scores it is at least 1−α1 - \alpha (Claim 3). It also checks the identity 1/(n/2+1)=2/(n+2)1/(n/2 + 1) = 2/(n + 2) and the inequalities 1−α≤k/(n2+1)<1−α+1/(n2+1)1 - \alpha \le k/(n_2 + 1) < 1 - \alpha + 1/(n_2 + 1) for all n2<60n_2 < 60.

Complexity

With ff the cost of the fit and of the n2n_2 predictions, the method takes Θ(f+nlog⁡n)\Theta(f + n \log n) time with sorting at line L6, or Θ(f+n)\Theta(f + n) with a linear-time selection, and Θ(n)\Theta(n) 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 nn, 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 xx, and no method can achieve coverage at each xx 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 F(q)F(q), where FF is the law of a new score. It has the Beta law with parameters kk and n2+1−kn_2 + 1 - k, with mean k/(n2+1)k/(n_2 + 1). For n2=20n_2 = 20 and α=0.1\alpha = 0.1 its standard deviation is 0.0630.063 and it is below 0.850.85 with probability 0.180.18; for n2=100n_2 = 100 the standard deviation is 0.0300.030; for n2=1000n_2 = 1000 it is 0.00950.0095.
  • Constant width. With the absolute residual score the interval has the same width 2q2q at every xx. 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 nn 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 q^lo\hat q_{\mathrm{lo}} and q^hi\hat q_{\mathrm{hi}} at levels α/2\alpha/2 and 1−α/21 - \alpha/2 on the training part. Use the score Ei=max⁡(q^lo(xi)−yi, yi−q^hi(xi))E_i = \max\bigl(\hat q_{\mathrm{lo}}(x_i) - y_i,\ y_i - \hat q_{\mathrm{hi}}(x_i)\bigr) and return [q^lo(x)−q,q^hi(x)+q][\hat q_{\mathrm{lo}}(x) - q, \hat q_{\mathrm{hi}}(x) + q]. The guarantee is the same, and the width now follows the spread of yy given xx. In the heteroscedastic example under Pitfalls, with 8-bin empirical quantiles as the quantile fit, the coverage was 0.9410.941 for ∣x∣<0.25\lvert x \rvert < 0.25 and 0.8870.887 for ∣x∣>0.75\lvert x \rvert > 0.75, against 1.0001.000 and 0.7600.760 for the absolute residual score.
  • Scaled residuals. Use ∣y−μ^(x)∣/σ^(x)\lvert y - \hat\mu(x) \rvert/\hat\sigma(x) with a fitted spread σ^\hat\sigma, and return μ^(x)±q σ^(x)\hat\mu(x) \pm q\,\hat\sigma(x).
  • Classification. Use a score such as one minus the fitted probability of the true label, and return all labels whose score is at most qq.
  • 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 1−2α1 - 2\alpha 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 xx 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 xx uniform on [−1,1][-1, 1], errors with standard deviation 0.1+∣x∣0.1 + \lvert x \rvert, n=400n = 400 split 200/200200/200, α=0.1\alpha = 0.1 and 3000 data sets (seed 7), the overall coverage was 0.9050.905, but 1.0001.000 for ∣x∣<0.25\lvert x \rvert < 0.25 and 0.7600.760 for ∣x∣>0.75\lvert x \rvert > 0.75.
  • Wrong rank. Taking the ⌈n2(1−α)⌉\lceil n_2(1 - \alpha) \rceil-th score, the plain empirical quantile, gives coverage ⌈n2(1−α)⌉/(n2+1)\lceil n_2(1 - \alpha)\rceil/(n_2 + 1), which can be below 1−α1 - \alpha: for n2=20n_2 = 20 and α=0.1\alpha = 0.1 it is 18/21=0.85718/21 = 0.857. The +1+1 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 α\alpha 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.

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

  1. 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)
  2. 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)
  3. 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
  4. 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
  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 (coverage conditional on x is not possible without assumptions)
  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 (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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example