Bootstrap.lean

Lean 4 source, lean/DataMiningAsObservation/Bootstrap.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.

/-
Bootstrap.lean. Chapter 0 section 0.9, the paired bootstrap.

A paired bootstrap resamples the same rows for two methods at once so that shared sampling
variation cancels. The algebra behind that sentence is the variance of a difference, which
is the sum of the two variances minus twice their covariance, so pairing narrows the
interval exactly when the two methods' scores covary positively across rows. The file
checks the identity and the equivalence on finite samples.
-/
import Mathlib

namespace DMO.Bootstrap

open Finset

variable {n : ℕ}

/-- The sample mean. -/
noncomputable def mean (a : Fin n → ℝ) : ℝ := (∑ i, a i) / n

/-- The sample covariance of two lists. -/
noncomputable def cov (a b : Fin n → ℝ) : ℝ := (∑ i, (a i - mean a) * (b i - mean b)) / n

/-- The sample variance. -/
noncomputable def var (a : Fin n → ℝ) : ℝ := cov a a

/-- The mean of a difference is the difference of the means. -/
theorem mean_sub (a b : Fin n → ℝ) : mean (fun i => a i - b i) = mean a - mean b := by
  unfold mean
  rw [Finset.sum_sub_distrib, sub_div]

/-- **The variance of a difference** is the sum of the variances minus twice the covariance. -/
theorem var_sub (a b : Fin n → ℝ) : var (fun i => a i - b i) = var a + var b - 2 * cov a b := by
  unfold var cov
  rw [mean_sub]
  have e : ∀ x y z : ℝ, (x + y) / n - 2 * (z / n) = (x + y - 2 * z) / n := by
    intro x y z; ring
  rw [← add_div, e]
  congr 1
  rw [Finset.mul_sum, ← Finset.sum_add_distrib, ← Finset.sum_sub_distrib]
  refine Finset.sum_congr rfl fun i _ => ?_
  dsimp only
  ring

/-- **Pairing narrows the interval exactly when the scores covary positively.** -/
theorem paired_lt_iff (a b : Fin n → ℝ) : var (fun i => a i - b i) < var a + var b ↔ 0 < cov a b := by
  rw [var_sub]
  constructor <;> intro h <;> linarith

/-- The covariance is symmetric, so which method is subtracted does not matter. -/
theorem cov_comm (a b : Fin n → ℝ) : cov a b = cov b a := by
  unfold cov
  congr 1
  exact Finset.sum_congr rfl fun i _ => by ring

end DMO.Bootstrap