Mahalanobis.lean

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

/-
Mahalanobis.lean. Equations 0.33 and 10.1, the Mahalanobis distance.

In the covariance's eigenbasis the squared Mahalanobis distance of a row from the mean is
the sum of its squared centred coordinates over the eigenvalues. It is nonnegative, zero at
the mean, unchanged when the data and the covariance are rescaled together, and equal to the
squared Euclidean length after whitening, which is why chapter 10 calls the statistical
detector the identity reader on whitened data.
-/
import Mathlib
import DataMiningAsObservation.Whitening

namespace DMO.Mahalanobis

open Finset

variable {n : ℕ}

/-- **Equation 10.1.** The squared Mahalanobis distance of the centred row `y` under the
eigenvalues `lam`. -/
noncomputable def dM2 (lam y : Fin n → ℝ) : ℝ := ∑ i, y i ^ 2 / lam i

/-- The distance is nonnegative for positive eigenvalues. -/
theorem dM2_nonneg (lam y : Fin n → ℝ) (hpos : ∀ i, 0 < lam i) : 0 ≤ dM2 lam y :=
  Finset.sum_nonneg fun i _ => div_nonneg (sq_nonneg _) (hpos i).le

/-- **The mean is at distance zero.** -/
theorem dM2_mean (lam : Fin n → ℝ) : dM2 lam (fun _ => 0) = 0 := by
  simp [dM2]

/-- **Scale invariance.** Rescaling the data by `c` rescales the eigenvalues by `c²` and
leaves the distance unchanged. -/
theorem dM2_scale (lam y : Fin n → ℝ) (c : ℝ) (hc : c ≠ 0) (hpos : ∀ i, 0 < lam i) :
    dM2 (fun i => c ^ 2 * lam i) (fun i => c * y i) = dM2 lam y := by
  unfold dM2
  refine Finset.sum_congr rfl fun i _ => ?_
  have := (hpos i).ne'
  field_simp

/-- **The identity reader on whitened data.** The squared Mahalanobis distance is the squared
Euclidean length after whitening. -/
theorem dM2_eq_whitened (lam y : Fin n → ℝ) (hpos : ∀ i, 0 < lam i) :
    dM2 lam y = ∑ i, DMO.Whitening.whiten lam y i ^ 2 := by
  unfold dM2
  rw [DMO.Whitening.whiten_sq_sum lam y hpos]

/-- **A large eigenvalue hides a large deviation.** The same centred coordinate counts for
less along a direction of larger variance. -/
theorem dM2_antitone_in_variance (lam lam' y : Fin n → ℝ) (hpos : ∀ i, 0 < lam i)
    (hle : ∀ i, lam i ≤ lam' i) : dM2 lam' y ≤ dM2 lam y := by
  unfold dM2
  apply Finset.sum_le_sum
  intro i _
  exact div_le_div_of_nonneg_left (sq_nonneg _) (hpos i) (hle i)

end DMO.Mahalanobis