NaiveBayes.lean
Lean 4 source, lean/DataMiningAsObservation/NaiveBayes.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
NaiveBayes.lean. Chapter 6 section 6.1, naive Bayes.
Naive Bayes multiplies one-dimensional likelihoods and adds their logs. The log of the
product is the sum of the logs, the log odds add across features, and one feature's
contribution to the score is the same whatever the other features are, so the score has
no interaction terms and its Hessian is diagonal.
-/
import Mathlib
namespace DMO.NaiveBayes
open Finset
variable {ι : Type*} [Fintype ι]
/-- **The log likelihood is a sum.** -/
theorem log_likelihood_sum (p : ι → ℝ) (hp : ∀ i, 0 < p i) :
Real.log (∏ i, p i) = ∑ i, Real.log (p i) :=
Real.log_prod fun i _ => (hp i).ne'
/-- **The log odds add across features.** -/
theorem log_odds_sum (p q : ι → ℝ) (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
Real.log ((∏ i, p i) / ∏ i, q i) = ∑ i, (Real.log (p i) - Real.log (q i)) := by
rw [Real.log_div (Finset.prod_ne_zero_iff.mpr fun i _ => (hp i).ne')
(Finset.prod_ne_zero_iff.mpr fun i _ => (hq i).ne'),
log_likelihood_sum p hp, log_likelihood_sum q hq, Finset.sum_sub_distrib]
/-- **One feature's contribution does not depend on the others.** Changing feature `j`
alone changes the score by that feature's log-ratio change. -/
theorem contribution_independent (p p' q : ι → ℝ) (j : ι) (h : ∀ i, i ≠ j → p i = p' i) :
(∑ i, (Real.log (p i) - Real.log (q i))) - ∑ i, (Real.log (p' i) - Real.log (q i))
= Real.log (p j) - Real.log (p' j) := by
rw [← Finset.sum_sub_distrib, Finset.sum_eq_single j]
· ring
· intro b _ hb
rw [h b hb]
ring
· intro hj
exact absurd (Finset.mem_univ j) hj
end DMO.NaiveBayes