Conformal prediction under covariate shift: quantiles, scores, (weighted) exchangeability and conformal bands
DefinitionConformalCovariateShift_BasicObjects of Sections 1-3 of Tibshirani, Barber, Candès and Ramdas (2019).
- Quantiles (Section 1.1). For a distribution on the augmented real line , . A discrete distribution is . For values , is the quantile of , and is the quantile of . For weights , the distribution is used in (8), (16) and Lemma 3.
- Scores (Section 1.2, eq. 4). Data points are . A score function takes a point and a multiset of points. For points , the nonconformity scores are , where is the multiset of the other points. For training points and a candidate , the scores of (4) are those of the points .
- Exchangeability. Random variables are exchangeable if has the same law as for every permutation .
- Conformal band (eq. 5). .
- Covariate shift (eqs. 7-8). For a weight function on , for and . The band (8) is .
- Weighted exchangeability (Definition 1). Random variables with values in a measurable space are weighted exchangeable with measurable, nonnegative weight functions if their joint law has a density with respect to a measure on that is invariant under permutations of the coordinates, and with invariant under permutations of its arguments.
- Weighted band (eqs. 15-16). , the sums over permutations of . The band (16) is .
Formalization Note The augmented real line is EReal with ; quantiles take values there, and the infimum of an empty set is . Weights enter a discrete distribution through ENNReal.ofReal, which is the identity on the nonnegative weights used here. When a denominator in (7) or (15) is , Lean's division returns , all weights vanish and the quantile is ; this happens only on a null event in every statement. The paper allows an arbitrary base measure in Definition 1; the definition requires it to be permutation invariant, because with an arbitrary base measure Lemma 3 is false (see the report).
import Mathlib
/-!
Tibshirani, Barber, Candès and Ramdas, *Conformal Prediction Under Covariate Shift*,
arXiv:1904.06019v3 (2019): quantiles of discrete distributions on the augmented real line
(Section 1.1), nonconformity scores and the conformal band (Section 1.2, eqs. (4)-(5)), the
covariate-shift weights and band (Section 2.1, eqs. (7)-(8)), and weighted exchangeability with
the weights (15) and the weighted conformal band (16) (Sections 3.2-3.4).
-/
open MeasureTheory
noncomputable section
namespace ConformalCovariateShift
/-- Section 1.1, p. 2: `Quantile(β; F) = inf {z : P{Z ≤ z} ≥ β}` for `Z ∼ F`, where `F` is a
distribution on the augmented real line `ℝ ∪ {∞}`, here encoded in `EReal` (with `∞ = ⊤`). -/
def quantile (β : ℝ) (F : Measure EReal) : EReal :=
sInf {z : EReal | ENNReal.ofReal β ≤ F (Set.Iic z)}
/-- Section 1.1, p. 2: the discrete distribution `∑_i p_i δ_{v_i}` on `ℝ ∪ {∞}`. With
`p_i = 1/m` for all `i` it is the empirical distribution of the multiset `v_{1:m}`. -/
def discreteDist {ι : Type*} [Fintype ι] (p : ι → ℝ) (v : ι → EReal) : Measure EReal :=
∑ i, ENNReal.ofReal (p i) • Measure.dirac (v i)
/-- Eqs. (8), (16) and Lemma 3: `∑_{i=1}^n p_i δ_{v_i} + p_{n+1} δ_∞`, the distribution of
the first `n` values with weights `p_1, …, p_n` plus a point mass `p_{n+1}` at `∞` (the
`(n+1)`-st value is not used). -/
def augDist {n : ℕ} (p : Fin (n + 1) → ℝ) (v : Fin (n + 1) → ℝ) : Measure EReal :=
discreteDist p (fun i => if i = Fin.last n then (⊤ : EReal) else (v i : EReal))
/-- Lemma 1 and eq. (5): `Quantile(β; v_{1:n} ∪ {∞})`, the level-`β` quantile of the empirical
distribution of the `n + 1` values `v_1, …, v_n, ∞` (the `(n+1)`-st value is not used). -/
def quantileWithInf {n : ℕ} (β : ℝ) (v : Fin (n + 1) → ℝ) : EReal :=
quantile β (augDist (fun _ => 1 / ((n : ℝ) + 1)) v)
/-- Eq. (2): `Quantile(β; v_{1:(n+1)})`, the level-`β` quantile of the empirical distribution
of the `n + 1` real values `v_1, …, v_{n+1}`. -/
def empQuantile {n : ℕ} (β : ℝ) (v : Fin (n + 1) → ℝ) : EReal :=
quantile β (discreteDist (fun _ => 1 / ((n : ℝ) + 1)) (fun i => (v i : EReal)))
/-- Section 1.2, p. 2: a data point `(x, y) ∈ ℝ^d × ℝ`. -/
abbrev DataPt (d : ℕ) : Type := (Fin d → ℝ) × ℝ
/-- Section 1.2, p. 2 and footnote 1: a score function `S((x, y), Z)` of a point and a multiset
`Z` of points (the points of `Z` are unordered). -/
abbrev ScoreFn (E : Type*) : Type _ := E → Multiset E → ℝ
/-- Eq. (4) and Lemma 3: the nonconformity scores `V_i = S(z_i, z_{1:m} \ {z_i})` of the points
`z_1, …, z_m`, where `z_{1:m} \ {z_i}` is the multiset of the other `m - 1` points. -/
def scores {E : Type*} {m : ℕ} (S : ScoreFn E) (z : Fin m → E) (i : Fin m) : ℝ :=
S (z i) ((Finset.univ.erase i).val.map z)
/-- Section 1.2, p. 2: the `n + 1` points `Z_1, …, Z_n, (x, y)` formed by the `n` training points
and a candidate test point `(x, y)`; the scores of eq. (4) are `scores S (withTest Z (x, y))`. -/
def withTest {E : Type*} {n : ℕ} (data : Fin n → E) (p : E) : Fin (n + 1) → E :=
Fin.snoc (α := fun _ => E) data p
/-- Section 1.1 and the proof of Theorem 1, p. 3: the random variables `V_1, …, V_m` (measurable
maps on a probability space) are exchangeable, i.e. `(V_{σ(1)}, …, V_{σ(m)})` and
`(V_1, …, V_m)` have the same joint law for every permutation `σ`. -/
def IsExchangeable {Omega E : Type*} [MeasurableSpace Omega] [MeasurableSpace E] {m : ℕ}
(P : Measure Omega) (V : Fin m → Omega → E) : Prop :=
(∀ i, Measurable (V i)) ∧
∀ σ : Equiv.Perm (Fin m),
Measure.map (fun ω i => V (σ i) ω) P = Measure.map (fun ω i => V i ω) P
/-- Eq. (5), Theorem 1: the conformal band at `x` built from the training points
`Z_1, …, Z_n`: the set of `y ∈ ℝ` with `V_{n+1}^{(x,y)} ≤ Quantile(1 - α; V_{1:n}^{(x,y)} ∪ {∞})`. -/
def conformalBand {d n : ℕ} (S : ScoreFn (DataPt d)) (α : ℝ) (data : Fin n → DataPt d)
(x : Fin d → ℝ) : Set ℝ :=
{y | (scores S (withTest data (x, y)) (Fin.last n) : EReal) ≤
quantileWithInf (1 - α) (scores S (withTest data (x, y)))}
/-- Eq. (7), Section 2.1, p. 4: the covariate-shift weights
`p_i^w(x) = w(X_i) / (∑_{j=1}^n w(X_j) + w(x))` for `i ≤ n` and
`p_{n+1}^w(x) = w(x) / (∑_{j=1}^n w(X_j) + w(x))`. -/
def covShiftWeights {d n : ℕ} (w : (Fin d → ℝ) → ℝ) (X : Fin n → (Fin d → ℝ))
(x : Fin d → ℝ) : Fin (n + 1) → ℝ :=
fun i => w (withTest X x i) / (∑ j, w (X j) + w x)
/-- Eq. (8), Corollary 1: the weighted conformal band under covariate shift: the set of `y ∈ ℝ`
with `V_{n+1}^{(x,y)} ≤ Quantile(1 - α; ∑_{i=1}^n p_i^w(x) δ_{V_i^{(x,y)}} + p_{n+1}^w(x) δ_∞)`. -/
def covShiftBand {d n : ℕ} (S : ScoreFn (DataPt d)) (α : ℝ) (w : (Fin d → ℝ) → ℝ)
(data : Fin n → DataPt d) (x : Fin d → ℝ) : Set ℝ :=
{y | (scores S (withTest data (x, y)) (Fin.last n) : EReal) ≤
quantile (1 - α) (augDist (covShiftWeights w (fun i => (data i).1) x)
(scores S (withTest data (x, y))))}
/-- Definition 1, Section 3.2, p. 12: the random variables `Z_1, …, Z_m` are weighted
exchangeable with weight functions `w_1, …, w_m` if their joint law has a density `f` with respect
to a base measure `ν` on `E^m` and `f(z_1, …, z_m) = ∏_i w_i(z_i) · g(z_1, …, z_m)` with `g`
invariant under permutations of its arguments. The `Z_i` are measurable, the weight functions are
measurable and nonnegative, and the base measure `ν` is required to be invariant under
permutations of the coordinates (the paper says "arbitrary base measure"; see the mission's
report for why invariance is needed). -/
def IsWeightedExchangeable {Omega E : Type*} [MeasurableSpace Omega] [MeasurableSpace E] {m : ℕ}
(P : Measure Omega) (Z : Fin m → Omega → E) (w : Fin m → E → ℝ) : Prop :=
(∀ i, Measurable (Z i)) ∧ (∀ i, Measurable (w i)) ∧ (∀ i z, 0 ≤ w i z) ∧
∃ (ν : Measure (Fin m → E)) (f g : (Fin m → E) → ENNReal),
(∀ σ : Equiv.Perm (Fin m), Measure.map (fun z => z ∘ σ) ν = ν) ∧
Measurable f ∧
Measure.map (fun ω i => Z i ω) P = ν.withDensity f ∧
(∀ z, f z = (∏ i, ENNReal.ofReal (w i (z i))) * g z) ∧
(∀ (σ : Equiv.Perm (Fin m)) (z : Fin m → E), g (z ∘ σ) = g z)
/-- Eq. (15), Lemma 3, p. 12: `p_i^w(z_1, …, z_{n+1}) =
(∑_{σ : σ(n+1) = i} ∏_{j=1}^{n+1} w_j(z_{σ(j)})) / (∑_σ ∏_{j=1}^{n+1} w_j(z_{σ(j)}))`, the sums
running over permutations `σ` of `1, …, n+1`. -/
def permWeight {E : Type*} {n : ℕ} (w : Fin (n + 1) → E → ℝ) (z : Fin (n + 1) → E)
(i : Fin (n + 1)) : ℝ :=
(∑ σ ∈ Finset.univ.filter (fun σ : Equiv.Perm (Fin (n + 1)) => σ (Fin.last n) = i),
∏ j, w j (z (σ j))) /
∑ σ : Equiv.Perm (Fin (n + 1)), ∏ j, w j (z (σ j))
/-- Eq. (16), Theorem 2, p. 13: the weighted conformal band: the set of `y ∈ ℝ` with
`V_{n+1}^{(x,y)} ≤ Quantile(1 - α; ∑_{i=1}^n p_i^w(Z_1, …, Z_n, (x, y)) δ_{V_i^{(x,y)}}
+ p_{n+1}^w(Z_1, …, Z_n, (x, y)) δ_∞)`. -/
def weightedConformalBand {d n : ℕ} (S : ScoreFn (DataPt d)) (α : ℝ)
(w : Fin (n + 1) → DataPt d → ℝ) (data : Fin n → DataPt d) (x : Fin d → ℝ) : Set ℝ :=
{y | (scores S (withTest data (x, y)) (Fin.last n) : EReal) ≤
quantile (1 - α) (augDist (permWeight w (withTest data (x, y)))
(scores S (withTest data (x, y))))}
end ConformalCovariateShift
Read-back
What the Lean code literally says, in plain math · claude-opus-5-5
quantile. For a real number and an arbitrary measure on the extended real line , which may be infinite and need not be a probability measure,
where the infimum is taken in . Here is the set of all extended reals , including . The level enters only through .
- If , every qualifies and the quantile is .
- If no qualifies, for example when exceeds the total mass , the infimum of the empty set is .
discreteDist. Let be any finite index set, possibly empty. Given real weights and points in , this is the measure
on .
- Negative weights are replaced by .
- The weights are not normalized, so the total mass is . That total may differ from , and it is when is empty.
augDist. For a natural number , real weights and real values , this is the measure
on .
- The value is ignored. Its slot is replaced by the point .
- Negative weights are truncated to , and there is no normalization.
- When , the measure is just .
quantileWithInf. For , a real level and real values , this is (as defined above) of the probability measure
The value is not used.
- If , the result is .
- If , the defining set is empty and the result is .
- When , all mass sits at , so the result is for every .
empQuantile. For , a real level and real values , this is of the empirical probability measure
on .
- If , the result is .
- If , the result is .
DataPt. For a natural number (possibly ), a data point is a pair with and .
ScoreFn. For any type , a score function is an arbitrary map
No measurability, symmetry or other regularity is required.
scores. Given a score function on , a number , points and an index , the score of point is
Here the second argument is the multiset of the other points, with repetitions kept. When , there are no indices.
withTest. Given points and a further point , this is the -tuple
with placed in the last position .
IsExchangeable. Let be any measure on a measurable space ; it is not required to be a probability measure, nor even finite. Let be maps into a measurable space , with . The statement " are exchangeable under " means both of the following:
- Each is measurable.
- For every permutation of , the image measure of under equals the image measure of under . Both are measures on with the product -algebra.
When , condition 2 is automatic.
conformalBand. The inputs are:
- dimensions ;
- an arbitrary score function on data points in ;
- a real number , which is not restricted to ;
- training points ;
- a point .
For each , let be the scores of the points . That is, for ,
The band is the set of with
with the comparison made in .
- If , the quantile is and the band is empty.
- If , the quantile is and the band is all of .
- If but , the quantile is and the band is all of . This includes every when .
covShiftWeights. The inputs are:
- an arbitrary real-valued function on , which may be negative and need not be measurable;
- covariates ;
- a point .
Write . The real weights are
- If , division by zero is defined to give , so all weights equal .
- If takes negative values, and the individual weights can be negative.
covShiftBand. The inputs are as in conformalBand, together with an arbitrary real function on . Let be the scores defined in conformalBand. Let be the weights of covShiftWeights, computed from the covariates (the first components of the ) and ; these weights do not depend on . The band is the set of with
Because negative weights are truncated, the measure's total mass need not be .
- If , the band is empty.
- If , the measure is zero. The quantile is then whenever , so the band is all of .
IsWeightedExchangeable. Let be any measure on , not required to be a probability measure. Let be maps, and functions. The statement "the are weighted exchangeable with weights " means all of the following:
- Each is measurable.
- Each is measurable and satisfies everywhere.
- There exist a measure on (product -algebra) and functions such that:
- is invariant under every coordinate permutation: the image of under is ;
- is measurable;
- the image of under equals the measure with density with respect to ;
- for every (pointwise, not almost everywhere), , using the convention ;
- for every permutation and every , .
is not required to be measurable. Some degenerate cases:
- If is the zero measure, the conditions are satisfied with , provided the measurability and nonnegativity conditions on the and hold.
- If some is identically , then , so the joint law must be the zero measure.
permWeight. Let be any type, , and let be arbitrary real functions, which may be negative. For points and an index ,
Both sums run over permutations of . If the denominator is , the value is for every .
weightedConformalBand. The inputs are as in conformalBand, together with arbitrary real functions on . For each :
- let be the scores defined in
conformalBand; - let be the weights of
permWeight; these weights depend on .
The band is the set of with
Negative weights are truncated to , and the total mass need not be .
- If , the band is empty.
- If the permutation sum in the denominator vanishes at some and , the measure there is zero and its quantile is , so that belongs to the band.
Confirmed by the mission captain (proposal self-audit).
Confirmed by the moderator at approval.