Covariance.lean

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

/-
Covariance.lean. Equations 0.3 and 0.4, the covariance matrix.

The covariance matrix of a weighted set of rows is the weighted average of the centred rows'
outer products, the same construction as the read operator with the centred row in place of
the sensitivity. Its quadratic form along a unit direction is the variance of the
projection onto that direction, equation 0.4, its trace is the total variance, and it is
positive semidefinite. The file reuses the read operator's algebra, which is the point
chapter 4 makes when it pairs the two matrices in one basis.
-/
import Mathlib
import DataMiningAsObservation.ReadOperator

namespace DMO.Covariance

open Finset Matrix DMO.ReadOperator

variable {Ω : Type*} [Fintype Ω] {n : ℕ}

/-- **Equation 0.3.** The covariance matrix of the rows `x` with weights `w` about the mean `μ`. -/
def cov (w : Ω → ℝ) (x : Ω → Fin n → ℝ) (μ : Fin n → ℝ) : Matrix (Fin n) (Fin n) ℝ :=
  readOp w (fun ω => x ω - μ)

/-- **Equation 0.4.** The quadratic form along `u` is the weighted variance of the projection
onto `u`. -/
theorem var_eq_quad (w : Ω → ℝ) (x : Ω → Fin n → ℝ) (μ : Fin n → ℝ) (u : Fin n → ℝ) :
    u ⬝ᵥ (cov w x μ *ᵥ u) = ∑ ω, w ω * ((x ω - μ) ⬝ᵥ u) ^ 2 := by
  unfold cov
  exact quad_readOp w _ u

/-- **The trace is the total variance.** -/
theorem trace_eq_total (w : Ω → ℝ) (x : Ω → Fin n → ℝ) (μ : Fin n → ℝ) :
    (cov w x μ).trace = ∑ ω, w ω * ((x ω - μ) ⬝ᵥ (x ω - μ)) := by
  unfold cov Matrix.trace
  simp only [Matrix.diag_apply, readOp_diag]
  rw [Finset.sum_comm]
  refine Finset.sum_congr rfl fun ω _ => ?_
  rw [← Finset.mul_sum]
  congr 1
  simp [dotProduct, sq]

/-- **Positive semidefinite** for nonnegative weights. -/
theorem quad_nonneg (w : Ω → ℝ) (hw : ∀ ω, 0 ≤ w ω) (x : Ω → Fin n → ℝ) (μ : Fin n → ℝ)
    (u : Fin n → ℝ) : 0 ≤ u ⬝ᵥ (cov w x μ *ᵥ u) := by
  unfold cov
  exact quad_readOp_nonneg w hw _ u

/-- The covariance is symmetric. -/
theorem cov_symm (w : Ω → ℝ) (x : Ω → Fin n → ℝ) (μ : Fin n → ℝ) (i j : Fin n) :
    cov w x μ i j = cov w x μ j i := by
  unfold cov
  exact readOp_symm w _ i j

end DMO.Covariance