Outlier.lean

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

/-
Outlier.lean. Chapter 0 section 0.16 and chapter 10 section 10.1, the outlier.

The statistical detector scores a row by its distance from the mean in units of spread,
the z-score. The score is zero at the mean, unchanged when the data are rescaled and
shifted together, and a row passes a threshold `t` exactly when its distance from the mean
exceeds `t` spreads. Chebyshev's bound says the weight of rows beyond `t` is at most the
mean squared score over `t²`, so the detector's positives are few by arithmetic.
-/
import Mathlib

namespace DMO.Outlier

open Finset

/-- The z-score. -/
noncomputable def zscore (x μ σ : ℝ) : ℝ := (x - μ) / σ

/-- **The mean scores zero.** -/
theorem zscore_mean (μ σ : ℝ) : zscore μ μ σ = 0 := by
  simp [zscore]

/-- **Rescaling and shifting the data, mean, and spread together changes no score.** -/
theorem zscore_affine (a b x μ σ : ℝ) (ha : 0 < a) :
    zscore (a * x + b) (a * μ + b) (a * σ) = zscore x μ σ := by
  unfold zscore
  rw [show a * x + b - (a * μ + b) = a * (x - μ) by ring, mul_div_mul_left _ _ ha.ne']

/-- **A row is an outlier at `t` exactly when it lies more than `t` spreads from the mean.** -/
theorem outlier_iff (x μ σ t : ℝ) (hσ : 0 < σ) : t < |zscore x μ σ| ↔ t * σ < |x - μ| := by
  unfold zscore
  rw [abs_div, abs_of_pos hσ, lt_div_iff₀ hσ]

/-- **The score is odd about the mean.** -/
theorem zscore_reflect (x μ σ : ℝ) : zscore (2 * μ - x) μ σ = -zscore x μ σ := by
  unfold zscore
  ring

open Classical in
/-- **Chebyshev.** The weight of rows whose score exceeds `t` is at most the weighted mean
squared score over `t²`. -/
theorem chebyshev {Ω : Type*} [Fintype Ω] (w z : Ω → ℝ) (hw : ∀ ω, 0 ≤ w ω) (t : ℝ)
    (ht : 0 < t) :
    ∑ ω ∈ univ.filter (fun ω => t < |z ω|), w ω ≤ (∑ ω, w ω * z ω ^ 2) / t ^ 2 := by
  rw [le_div_iff₀ (by positivity)]
  calc (∑ ω ∈ univ.filter (fun ω => t < |z ω|), w ω) * t ^ 2
      = ∑ ω ∈ univ.filter (fun ω => t < |z ω|), w ω * t ^ 2 := by rw [Finset.sum_mul]
    _ ≤ ∑ ω ∈ univ.filter (fun ω => t < |z ω|), w ω * z ω ^ 2 := by
        refine Finset.sum_le_sum fun ω hω => ?_
        rw [Finset.mem_filter] at hω
        apply mul_le_mul_of_nonneg_left _ (hw ω)
        rw [← sq_abs (z ω)]
        exact pow_le_pow_left₀ ht.le hω.2.le 2
    _ ≤ ∑ ω, w ω * z ω ^ 2 :=
        Finset.sum_le_sum_of_subset_of_nonneg (Finset.filter_subset _ _)
          fun ω _ _ => mul_nonneg (hw ω) (sq_nonneg _)

end DMO.Outlier