Margin.lean
Lean 4 source, lean/DataMiningAsObservation/Margin.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
Margin.lean. Chapter 6 section 6.1 and chapter 9 section 9.3, the margin.
A row's margin is how far its score sits from the threshold. For a linear classifier, a
perturbation of the input whose length times the weight length is smaller than the margin
cannot move the score across the threshold, by Cauchy–Schwarz, so the decision survives
every such perturbation. A perturbation along the weights of exactly that size reaches the
boundary. The margin is therefore a certificate on the decision, and the certificate of
chapter 9 is the same idea with a noise model in place of a perturbation bound.
-/
import Mathlib
import DataMiningAsObservation.Classifier
import DataMiningAsObservation.DotProduct
namespace DMO.Margin
open DMO.Classifier DMO.DotProduct
variable {n : ℕ}
/-- The margin of a row, its score minus the threshold. -/
def margin (w : Fin n → ℝ) (b τ : ℝ) (x : Fin n → ℝ) : ℝ := score w b x - τ
/-- The score moves by the weights' dot product with the perturbation. -/
theorem score_add (w : Fin n → ℝ) (b : ℝ) (x δ : Fin n → ℝ) :
score w b (x + δ) = score w b x + w ⬝ᵥ δ := by
unfold score
rw [dotProduct_add]; ring
/-- **A perturbation smaller than the margin cannot change the decision.** If the squared
length of the perturbation times the squared length of the weights is below the squared
margin, the perturbed score stays on the same side of the threshold. -/
theorem decision_stable (w : Fin n → ℝ) (b τ : ℝ) (x δ : Fin n → ℝ)
(h : (δ ⬝ᵥ δ) * (w ⬝ᵥ w) < margin w b τ x ^ 2) :
(0 < margin w b τ x → 0 < margin w b τ (x + δ)) ∧
(margin w b τ x < 0 → margin w b τ (x + δ) < 0) := by
have hcs : (w ⬝ᵥ δ) ^ 2 ≤ (w ⬝ᵥ w) * (δ ⬝ᵥ δ) := dot_sq_le w δ
have hlt : (w ⬝ᵥ δ) ^ 2 < margin w b τ x ^ 2 := by nlinarith
have habs : |w ⬝ᵥ δ| < |margin w b τ x| := sq_lt_sq.1 hlt
have hm : margin w b τ (x + δ) = margin w b τ x + w ⬝ᵥ δ := by
unfold margin; rw [score_add]; ring
rw [hm]
constructor
· intro hpos
rw [abs_of_pos hpos] at habs
linarith [neg_abs_le (w ⬝ᵥ δ)]
· intro hneg
rw [abs_of_neg hneg] at habs
linarith [le_abs_self (w ⬝ᵥ δ)]
/-- **The margin is tight along the weights.** The step along the weights that lands on the
boundary has squared length equal to the squared margin over the squared weight length. -/
theorem tight_along_weights (w : Fin n → ℝ) (hw : w ⬝ᵥ w ≠ 0) (b τ : ℝ) (x : Fin n → ℝ) :
margin w b τ (x + (-(margin w b τ x) / (w ⬝ᵥ w)) • w) = 0 ∧
((-(margin w b τ x) / (w ⬝ᵥ w)) • w) ⬝ᵥ ((-(margin w b τ x) / (w ⬝ᵥ w)) • w)
= margin w b τ x ^ 2 / (w ⬝ᵥ w) := by
constructor
· have h := score_add w b x ((-(margin w b τ x) / (w ⬝ᵥ w)) • w)
unfold margin at h ⊢
rw [h, dotProduct_smul, smul_eq_mul]
field_simp
try ring
· rw [smul_dotProduct, dotProduct_smul, smul_eq_mul, smul_eq_mul]
field_simp
try ring
end DMO.Margin