DecisionTree.lean
Lean 4 source, lean/DataMiningAsObservation/DecisionTree.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
DecisionTree.lean. Chapter 6 section 6.1, the decision tree.
A decision tree scores by axis-aligned splits and is flat within a leaf, so its finite
difference is zero at every row that does not straddle a split, a split on one coordinate
reads nothing of the others, and the Gini impurity it splits on is at most one half for
two classes and zero exactly for a pure leaf.
-/
import Mathlib
namespace DMO.DecisionTree
/-- A stump, one split at `t` with leaf values `a` and `b`. -/
noncomputable def stump (t a b x : ℝ) : ℝ := if x < t then a else b
/-- **The score is flat left of the split.** -/
theorem stump_flat_left (t a b x h : ℝ) (hx : x < t) (hxh : x + h < t) :
stump t a b (x + h) - stump t a b x = 0 := by
simp [stump, hx, hxh]
/-- **The score is flat right of the split.** -/
theorem stump_flat_right (t a b x h : ℝ) (hx : ¬ x < t) (hxh : ¬ x + h < t) :
stump t a b (x + h) - stump t a b x = 0 := by
simp [stump, hx, hxh]
/-- **A split on one coordinate reads nothing of the others.** -/
theorem split_reads_one_axis (t a b : ℝ) (v w : Fin 2 → ℝ) (hw : w 0 = 0) :
stump t a b ((v + w) 0) = stump t a b (v 0) := by
simp [hw]
/-- The two-class Gini impurity at positive fraction `p`. -/
def gini (p : ℝ) : ℝ := 2 * p * (1 - p)
/-- **Gini impurity is at most one half.** -/
theorem gini_le_half (p : ℝ) : gini p ≤ 1 / 2 := by
unfold gini
nlinarith [sq_nonneg (p - 1 / 2)]
/-- **A pure leaf has zero impurity, and only a pure leaf does.** -/
theorem gini_eq_zero_iff (p : ℝ) : gini p = 0 ↔ p = 0 ∨ p = 1 := by
unfold gini
constructor
· intro h
have : p * (1 - p) = 0 := by linarith
rcases mul_eq_zero.mp this with h0 | h1
· exact Or.inl h0
· exact Or.inr (by linarith)
· rintro (h | h) <;> simp [h]
end DMO.DecisionTree