Calibration.lean
Lean 4 source, lean/DataMiningAsObservation/Calibration.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
Calibration.lean. Equation 0.29, the expected calibration error.
The expected calibration error is the average over score bins, weighted by bin size, of the
absolute difference between the mean score and the fraction of positives in the bin. With
bin weights that are nonnegative and sum to one, and means and fractions in the unit
interval, it lies between zero and one, and it is zero exactly when every bin with positive
weight is calibrated. Calibration is a property of the score values, not of their ranking,
which is why the reliability weight of equation 0.38, a function of the ranking alone, is
reported beside it and not in place of it.
-/
import Mathlib
namespace DMO.Calibration
open Finset
variable {β : Type*}
/-- **Equation 0.29.** The expected calibration error over bins `B`, with weight `w b`, mean
score `sbar b`, and fraction of positives `ybar b`. -/
noncomputable def ece (B : Finset β) (w sbar ybar : β → ℝ) : ℝ :=
∑ b ∈ B, w b * |sbar b - ybar b|
/-- The error is nonnegative. -/
theorem ece_nonneg (B : Finset β) (w sbar ybar : β → ℝ) (hw : ∀ b ∈ B, 0 ≤ w b) :
0 ≤ ece B w sbar ybar :=
Finset.sum_nonneg fun b hb => mul_nonneg (hw b hb) (abs_nonneg _)
/-- The error is at most one when the weights sum to one and every mean and fraction lies in
the unit interval. -/
theorem ece_le_one (B : Finset β) (w sbar ybar : β → ℝ) (hw : ∀ b ∈ B, 0 ≤ w b)
(hsum : ∑ b ∈ B, w b = 1) (hs : ∀ b ∈ B, 0 ≤ sbar b ∧ sbar b ≤ 1)
(hy : ∀ b ∈ B, 0 ≤ ybar b ∧ ybar b ≤ 1) : ece B w sbar ybar ≤ 1 := by
unfold ece
calc ∑ b ∈ B, w b * |sbar b - ybar b| ≤ ∑ b ∈ B, w b * 1 := by
apply Finset.sum_le_sum
intro b hb
apply mul_le_mul_of_nonneg_left _ (hw b hb)
rw [abs_le]
constructor <;> linarith [hs b hb, hy b hb]
_ = 1 := by simp [hsum]
/-- **Zero error means every weighted bin is calibrated.** -/
theorem ece_eq_zero_iff (B : Finset β) (w sbar ybar : β → ℝ) (hw : ∀ b ∈ B, 0 ≤ w b) :
ece B w sbar ybar = 0 ↔ ∀ b ∈ B, 0 < w b → sbar b = ybar b := by
unfold ece
rw [Finset.sum_eq_zero_iff_of_nonneg fun b hb => mul_nonneg (hw b hb) (abs_nonneg _)]
constructor
· intro h b hb hpos
have := h b hb
rcases mul_eq_zero.1 this with h0 | h0
· exact absurd h0 hpos.ne'
· exact sub_eq_zero.1 (abs_eq_zero.1 h0)
· intro h b hb
rcases eq_or_lt_of_le (hw b hb) with h0 | h0
· rw [← h0, zero_mul]
· rw [h b hb h0, sub_self, abs_zero, mul_zero]
/-- A calibrated score has zero error. -/
theorem ece_of_calibrated (B : Finset β) (w sbar ybar : β → ℝ) (h : ∀ b ∈ B, sbar b = ybar b) :
ece B w sbar ybar = 0 := by
unfold ece
exact Finset.sum_eq_zero fun b hb => by rw [h b hb, sub_self, abs_zero, mul_zero]
end DMO.Calibration