PCA.lean

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

/-
PCA.lean. Chapter 4 section 4.1 and chapter 0 section 0.4, principal component analysis.

In the basis of the covariance's eigenvectors the variance along a unit direction is the
eigenvalue-weighted sum of its squared coordinates. It lies between the smallest and the
largest eigenvalue, a basis direction attains its own eigenvalue, and the error of keeping
the first `k` components, the total variance less what is kept, is the sum of the dropped
eigenvalues. That is the identity reader's distortion, and chapter 4 asks whose it is.
-/
import Mathlib
import DataMiningAsObservation.ExplainedVariance

namespace DMO.PCA

open Finset DMO.ExplainedVariance

variable {n : ℕ}

/-- Variance along direction `u` when the covariance is diagonal with entries `lam`. -/
def varAlong (lam u : Fin n → ℝ) : ℝ := ∑ i, lam i * u i ^ 2

/-- **A basis direction attains its own eigenvalue.** -/
theorem varAlong_basis (lam : Fin n → ℝ) (j : Fin n) :
    varAlong lam (fun i => if i = j then 1 else 0) = lam j := by
  simp only [varAlong]
  rw [Finset.sum_eq_single j]
  · simp
  · intro b _ hb
    simp [hb]
  · intro h
    exact absurd (Finset.mem_univ j) h

/-- **The variance along a unit direction is at most the largest eigenvalue.** -/
theorem varAlong_le (lam u : Fin n → ℝ) (M : ℝ) (hM : ∀ i, lam i ≤ M) (hu : ∑ i, u i ^ 2 = 1) :
    varAlong lam u ≤ M := by
  calc varAlong lam u = ∑ i, lam i * u i ^ 2 := rfl
    _ ≤ ∑ i, M * u i ^ 2 :=
        Finset.sum_le_sum fun i _ => mul_le_mul_of_nonneg_right (hM i) (sq_nonneg _)
    _ = M * ∑ i, u i ^ 2 := by rw [Finset.mul_sum]
    _ = M := by rw [hu, mul_one]

/-- **The variance along a unit direction is at least the smallest eigenvalue.** -/
theorem varAlong_ge (lam u : Fin n → ℝ) (m : ℝ) (hm : ∀ i, m ≤ lam i) (hu : ∑ i, u i ^ 2 = 1) :
    m ≤ varAlong lam u := by
  calc m = m * ∑ i, u i ^ 2 := by rw [hu, mul_one]
    _ = ∑ i, m * u i ^ 2 := by rw [Finset.mul_sum]
    _ ≤ ∑ i, lam i * u i ^ 2 :=
        Finset.sum_le_sum fun i _ => mul_le_mul_of_nonneg_right (hm i) (sq_nonneg _)
    _ = varAlong lam u := rfl

/-- **The error of keeping `k` components is the sum of the dropped eigenvalues.** -/
theorem dropped_eq (lam : Fin n → ℝ) (k : ℕ) :
    (∑ i, lam i) - kept n lam k = ∑ i, if k ≤ i.val then lam i else 0 := by
  simp only [kept]
  rw [← Finset.sum_sub_distrib]
  refine Finset.sum_congr rfl fun i _ => ?_
  split_ifs <;> first | omega | ring

/-- **The dropped variance is nonnegative when the eigenvalues are.** -/
theorem dropped_nonneg (lam : Fin n → ℝ) (hn : ∀ i, 0 ≤ lam i) (k : ℕ) :
    0 ≤ (∑ i, lam i) - kept n lam k := by
  rw [dropped_eq]
  refine Finset.sum_nonneg fun i _ => ?_
  split_ifs
  · exact hn i
  · exact le_rfl

end DMO.PCA