Correlation.lean
Lean 4 source, lean/DataMiningAsObservation/Correlation.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
Correlation.lean. Chapter 0 section 0.6 and chapter 3 section 3.1, the correlation.
Pearson's correlation is the cosine of the two centred columns. It therefore lies between
minus one and one, is one for a column against itself, is symmetric, and is unchanged by
shifting or positively rescaling either column, which is the sense in which correlation
distance lives on the quotient that discards shift and scale.
-/
import Mathlib
import DataMiningAsObservation.Cosine
namespace DMO.Correlation
open Finset DMO.Cosine
variable {n : ℕ}
/-- The mean of a column. -/
noncomputable def mean (x : Fin n → ℝ) : ℝ := (∑ i, x i) / n
/-- The centred column. -/
def center (x : Fin n → ℝ) (μ : ℝ) : Fin n → ℝ := fun i => x i - μ
/-- Pearson's correlation, the cosine of the centred columns. -/
noncomputable def corr (x y : Fin n → ℝ) : ℝ := cosine (center x (mean x)) (center y (mean y))
/-- **The correlation lies between minus one and one.** -/
theorem abs_corr_le_one (x y : Fin n → ℝ) (hx : center x (mean x) ⬝ᵥ center x (mean x) ≠ 0)
(hy : center y (mean y) ⬝ᵥ center y (mean y) ≠ 0) : |corr x y| ≤ 1 :=
abs_le.mpr ⟨neg_one_le_cosine _ _ hx hy, cosine_le_one _ _ hx hy⟩
/-- **A column has correlation one with itself.** -/
theorem corr_self (x : Fin n → ℝ) (hx : center x (mean x) ⬝ᵥ center x (mean x) ≠ 0) :
corr x x = 1 :=
cosine_self _ hx
/-- **The cosine is symmetric.** -/
theorem cosine_comm (u v : Fin n → ℝ) : cosine u v = cosine v u := by
unfold cosine
rw [dotProduct_comm, mul_comm]
/-- **The correlation is symmetric.** -/
theorem corr_comm (x y : Fin n → ℝ) : corr x y = corr y x :=
cosine_comm _ _
/-- **Shifting a column does not change its centred form.** -/
theorem center_shift (x : Fin n → ℝ) (c : ℝ) (hn : 0 < n) :
center (fun i => x i + c) (mean fun i => x i + c) = center x (mean x) := by
have hn' : (n : ℝ) ≠ 0 := by positivity
funext i
simp only [center, mean, Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ,
Fintype.card_fin, nsmul_eq_mul]
field_simp
ring
/-- **Rescaling a column rescales its centred form.** -/
theorem center_smul (x : Fin n → ℝ) (c : ℝ) :
center (fun i => c * x i) (mean fun i => c * x i) = c • center x (mean x) := by
funext i
simp only [center, mean, Pi.smul_apply, smul_eq_mul, ← Finset.mul_sum]
ring
/-- **Shifting a column does not change the correlation.** -/
theorem corr_shift (x y : Fin n → ℝ) (c : ℝ) (hn : 0 < n) :
corr (fun i => x i + c) y = corr x y := by
unfold corr
rw [center_shift x c hn]
/-- **Positively rescaling a column does not change the correlation.** -/
theorem corr_smul (x y : Fin n → ℝ) (c : ℝ) (hc : 0 < c) :
corr (fun i => c * x i) y = corr x y := by
unfold corr
rw [center_smul, cosine_smul c hc]
end DMO.Correlation