Whitening.lean
Lean 4 source, lean/DataMiningAsObservation/Whitening.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
Whitening.lean. Equation 0.6, whitening.
In the covariance's own eigenbasis, whitening divides each coordinate by the square root of
its eigenvalue. Each whitened coordinate then has unit variance, so the whitened covariance
is the identity, and the squared length of a whitened row is the sum of the squared
coordinates over the eigenvalues, which is the Mahalanobis distance of equation 0.33. The
file works in the eigenbasis, where the covariance is diagonal, which is the form
equation 0.6 states.
-/
import Mathlib
namespace DMO.Whitening
open Finset
variable {Ω : Type*} [Fintype Ω] {n : ℕ}
/-- **Equation 0.6** in the eigenbasis. The whitened coordinates of a centred row `y` under
the eigenvalues `lam`. -/
noncomputable def whiten (lam y : Fin n → ℝ) (i : Fin n) : ℝ := y i / Real.sqrt (lam i)
/-- The weighted second moment of coordinate `i` over the rows. -/
def moment (w : Ω → ℝ) (y : Ω → Fin n → ℝ) (i : Fin n) : ℝ := ∑ ω, w ω * y ω i ^ 2
/-- **Whitening gives unit variance.** If coordinate `i` has second moment `lam i` over the
rows, the whitened coordinate has second moment one. -/
theorem whiten_unit_variance (w : Ω → ℝ) (y : Ω → Fin n → ℝ) (lam : Fin n → ℝ) (i : Fin n)
(hpos : 0 < lam i) (hmom : moment w y i = lam i) :
moment w (fun ω => whiten lam (y ω)) i = 1 := by
unfold moment whiten at *
have hs : Real.sqrt (lam i) ^ 2 = lam i := Real.sq_sqrt hpos.le
have hs0 : Real.sqrt (lam i) ≠ 0 := (Real.sqrt_pos.2 hpos).ne'
calc ∑ ω, w ω * (y ω i / Real.sqrt (lam i)) ^ 2
= (∑ ω, w ω * y ω i ^ 2) / lam i := by
rw [Finset.sum_div]
refine Finset.sum_congr rfl fun ω _ => ?_
rw [div_pow, hs]; ring
_ = 1 := by rw [hmom, div_self hpos.ne']
/-- **Whitened length is the Mahalanobis form.** The squared length of a whitened row is the
sum of its squared coordinates over the eigenvalues. -/
theorem whiten_sq_sum (lam y : Fin n → ℝ) (hpos : ∀ i, 0 < lam i) :
∑ i, whiten lam y i ^ 2 = ∑ i, y i ^ 2 / lam i := by
unfold whiten
refine Finset.sum_congr rfl fun i _ => ?_
rw [div_pow, Real.sq_sqrt (hpos i).le]
end DMO.Whitening