Variance.lean

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

/-
Variance.lean. Chapter 0 section 0.3, the variance.

The weighted variance of a column is the weighted mean of the squared deviation from the
weighted mean. It is nonnegative, it equals the mean square less the squared mean, it is
zero for a constant column, it scales with the square of a rescaling, and when every
weight is positive it is zero only for a constant column.
-/
import Mathlib

namespace DMO.Variance

open Finset

variable {Ω : Type*} [Fintype Ω]

/-- The weighted mean. -/
def mean (w x : Ω → ℝ) : ℝ := ∑ ω, w ω * x ω

/-- The weighted variance. -/
def variance (w x : Ω → ℝ) : ℝ := ∑ ω, w ω * (x ω - mean w x) ^ 2

/-- **The variance is nonnegative.** -/
theorem variance_nonneg (w x : Ω → ℝ) (hw : ∀ ω, 0 ≤ w ω) : 0 ≤ variance w x :=
  Finset.sum_nonneg fun ω _ => mul_nonneg (hw ω) (sq_nonneg _)

/-- **The variance is the mean square less the squared mean.** -/
theorem variance_eq (w x : Ω → ℝ) (hw1 : ∑ ω, w ω = 1) :
    variance w x = (∑ ω, w ω * x ω ^ 2) - mean w x ^ 2 := by
  unfold variance
  have h1 : ∑ ω, w ω * (x ω - mean w x) ^ 2
      = ∑ ω, (w ω * x ω ^ 2 - 2 * mean w x * (w ω * x ω) + mean w x ^ 2 * w ω) :=
    Finset.sum_congr rfl fun ω _ => by ring
  rw [h1, Finset.sum_add_distrib, Finset.sum_sub_distrib, ← Finset.mul_sum, ← Finset.mul_sum, hw1]
  unfold mean
  ring

/-- **A constant column has variance zero.** -/
theorem variance_const (w : Ω → ℝ) (hw1 : ∑ ω, w ω = 1) (c : ℝ) :
    variance w (fun _ => c) = 0 := by
  unfold variance mean
  simp [← Finset.sum_mul, hw1]

/-- **Rescaling a column scales its variance by the square.** -/
theorem variance_smul (w x : Ω → ℝ) (c : ℝ) :
    variance w (fun ω => c * x ω) = c ^ 2 * variance w x := by
  have hm : mean w (fun ω => c * x ω) = c * mean w x := by
    unfold mean
    rw [Finset.mul_sum]
    exact Finset.sum_congr rfl fun ω _ => by ring
  unfold variance
  rw [hm, Finset.mul_sum]
  exact Finset.sum_congr rfl fun ω _ => by ring

/-- **With positive weights, zero variance means a constant column.** -/
theorem eq_mean_of_variance_eq_zero (w x : Ω → ℝ) (hw : ∀ ω, 0 < w ω) (h : variance w x = 0)
    (ω : Ω) : x ω = mean w x := by
  unfold variance at h
  have := (Finset.sum_eq_zero_iff_of_nonneg fun ω _ => mul_nonneg (hw ω).le (sq_nonneg _)).mp h ω
    (Finset.mem_univ ω)
  rcases mul_eq_zero.mp this with h0 | h0
  · exact absurd h0 (hw ω).ne'
  · exact sub_eq_zero.mp ((pow_eq_zero_iff two_ne_zero).mp h0)

end DMO.Variance