Spearman.lean
Lean 4 source, lean/DataMiningAsObservation/Spearman.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
Spearman.lean. Equation 0.14, the Spearman correlation.
The Spearman correlation of two rankings is one minus six times the sum of squared rank
differences over n(n² − 1). It is at most one, it is exactly one when the two rankings
agree, and for three items ranked in opposite orders it is minus one. Since it is computed
from ranks alone, a strictly increasing transform of either score leaves the ranks and so
the correlation unchanged, which is the same fact the Kendall file checks for its statistic.
-/
import Mathlib
namespace DMO.Spearman
open Finset
/-- **Equation 0.14.** The Spearman correlation from the rank differences `d` over `n` items. -/
noncomputable def rho (n : ℕ) (d : Fin n → ℝ) : ℝ := 1 - 6 * (∑ i, d i ^ 2) / (n * (n ^ 2 - 1))
/-- **The correlation is at most one** whenever there are at least two items. -/
theorem rho_le_one (n : ℕ) (hn : 2 ≤ n) (d : Fin n → ℝ) : rho n d ≤ 1 := by
unfold rho
have hn' : (2 : ℝ) ≤ n := by exact_mod_cast hn
have hden : 0 < (n : ℝ) * (n ^ 2 - 1) := by nlinarith
have : 0 ≤ 6 * (∑ i, d i ^ 2) / (n * (n ^ 2 - 1)) := by
apply div_nonneg _ hden.le
exact mul_nonneg (by norm_num) (Finset.sum_nonneg fun i _ => sq_nonneg _)
linarith
/-- **Identical rankings correlate at one.** -/
theorem rho_identical (n : ℕ) : rho n (fun _ => 0) = 1 := by
simp [rho]
/-- **Three items in opposite orders correlate at minus one.** Ranks 1, 2, 3 against 3, 2, 1
give differences −2, 0, 2. -/
theorem rho_reversed_three : rho 3 (![-2, 0, 2]) = -1 := by
unfold rho
simp [Fin.sum_univ_three]
norm_num
/-- The rank of an item, the number of items scoring strictly below it. -/
noncomputable def rank {ι : Type*} [Fintype ι] (s : ι → ℝ) (i : ι) : ℕ := (Finset.univ.filter fun j => s j < s i).card
/-- **Ranks depend on the ordering alone.** A strictly increasing transform of a score leaves
every rank, and so the correlation, unchanged. -/
theorem rank_comp {ι : Type*} [Fintype ι] {g : ℝ → ℝ} (hg : StrictMono g) (s : ι → ℝ) (i : ι) :
rank (g ∘ s) i = rank s i := by
unfold rank
congr 1
exact Finset.filter_congr fun j _ => by simp [hg.lt_iff_lt]
end DMO.Spearman