Residual.lean

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

/-
Residual.lean. Chapter 8 section 8.6 and chapter 12 section 12.5, residualization.

Residualizing a column on another removes the least-squares multiple of the second from
the first. The residual is orthogonal to the column removed, its squared length is the
original squared length less the squared dot product over the removed column's squared
length, a column orthogonal to the removed one is unchanged, and a column residualized on
itself vanishes. Whether named categories survive residualization is chapter 12's test.
-/
import Mathlib

namespace DMO.Residual

variable {n : ℕ}

/-- The least-squares slope of `y` on `x`. -/
noncomputable def slope (x y : Fin n → ℝ) : ℝ := (x ⬝ᵥ y) / (x ⬝ᵥ x)

/-- The residual of `y` after removing `x`. -/
noncomputable def residual (x y : Fin n → ℝ) : Fin n → ℝ := y - slope x y • x

/-- **The residual is orthogonal to the column removed.** -/
theorem residual_orth (x y : Fin n → ℝ) (hx : x ⬝ᵥ x ≠ 0) : x ⬝ᵥ residual x y = 0 := by
  unfold residual slope
  rw [dotProduct_sub, dotProduct_smul, smul_eq_mul, div_mul_cancel₀ _ hx, sub_self]

/-- **The residual's squared length.** -/
theorem residual_sq (x y : Fin n → ℝ) (hx : x ⬝ᵥ x ≠ 0) :
    residual x y ⬝ᵥ residual x y = y ⬝ᵥ y - (x ⬝ᵥ y) ^ 2 / (x ⬝ᵥ x) := by
  unfold residual slope
  simp only [sub_dotProduct, dotProduct_sub, dotProduct_smul, smul_dotProduct, smul_eq_mul,
    dotProduct_comm y x]
  field_simp
  ring

/-- **A column orthogonal to the removed one is unchanged.** -/
theorem residual_of_orth (x y : Fin n → ℝ) (h : x ⬝ᵥ y = 0) : residual x y = y := by
  unfold residual slope
  rw [h, zero_div, zero_smul, sub_zero]

/-- **A column residualized on itself vanishes.** -/
theorem residual_self (x : Fin n → ℝ) (hx : x ⬝ᵥ x ≠ 0) : residual x x = 0 := by
  unfold residual slope
  rw [div_self hx, one_smul, sub_self]

end DMO.Residual