KMeans.lean

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

/-
KMeans.lean. Chapter 9 section 9.1 and equation 9.1, k-means.

K-means minimizes the sum of squared errors to the cluster centres. The error about any
centre is the error about the mean plus the row count times the squared gap between them,
so the mean minimizes a cluster's error, and assigning each row to its nearest centre
never raises the total. That is the identity reader's clustering.
-/
import Mathlib

namespace DMO.KMeans

open Finset

variable {n : ℕ}

/-- The mean of `n` values. -/
noncomputable def mean (x : Fin n → ℝ) : ℝ := (∑ i, x i) / n

/-- The sum of squared errors about a centre `c`. -/
def sse (x : Fin n → ℝ) (c : ℝ) : ℝ := ∑ i, (x i - c) ^ 2

/-- **The error about any centre decomposes as the error about the mean plus the gap.** -/
theorem sse_decomposition (x : Fin n → ℝ) (c : ℝ) (hn : 0 < n) :
    sse x c = sse x (mean x) + n * (mean x - c) ^ 2 := by
  unfold sse mean
  have hn' : (n : ℝ) ≠ 0 := by positivity
  have hsum : ∑ i, (x i - (∑ j, x j) / n) = 0 := by
    rw [Finset.sum_sub_distrib, Finset.sum_const, Finset.card_univ, Fintype.card_fin,
      nsmul_eq_mul, mul_div_cancel₀ _ hn', sub_self]
  have hexp : ∀ i, (x i - c) ^ 2 = (x i - (∑ j, x j) / n) ^ 2
      + 2 * ((∑ j, x j) / n - c) * (x i - (∑ j, x j) / n) + ((∑ j, x j) / n - c) ^ 2 :=
    fun i => by ring
  simp only [hexp, Finset.sum_add_distrib, ← Finset.mul_sum, hsum, mul_zero, add_zero,
    Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul]

/-- **The mean minimizes the sum of squared errors.** -/
theorem mean_minimizes (x : Fin n → ℝ) (c : ℝ) (hn : 0 < n) : sse x (mean x) ≤ sse x c := by
  rw [sse_decomposition x c hn]
  linarith [mul_nonneg (Nat.cast_nonneg n : (0 : ℝ) ≤ n) (sq_nonneg (mean x - c))]

/-- **Assigning each row to its nearest centre never raises the total.** -/
theorem assign_nearest {K : ℕ} [NeZero K] (d : Fin n → Fin K → ℝ) (a : Fin n → Fin K) :
    ∑ i, univ.inf' Finset.univ_nonempty (d i) ≤ ∑ i, d i (a i) :=
  Finset.sum_le_sum fun _ _ => Finset.inf'_le _ (Finset.mem_univ _)

end DMO.KMeans