TFIDF.lean
Lean 4 source, lean/DataMiningAsObservation/TFIDF.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
TFIDF.lean. Equation 0.36, TF-IDF.
A term's weight in a document is its frequency in the document times the logarithm of the
number of documents over the number containing the term. A term in every document carries
no weight, the weight is nonnegative whenever the term appears in at most every document,
it falls as the term spreads to more documents, and the frequency lies in the unit interval
since a term's count cannot exceed the document's length.
-/
import Mathlib
namespace DMO.TFIDF
/-- The term frequency, the count over the length. -/
noncomputable def tf (count length : ℕ) : ℝ := (count : ℝ) / length
/-- **Equation 0.36.** The weight of a term with frequency `f` appearing in `df` of `N` documents. -/
noncomputable def weight (f : ℝ) (N df : ℕ) : ℝ := f * Real.log ((N : ℝ) / df)
/-- **A term in every document carries no weight.** -/
theorem weight_everywhere (f : ℝ) (N : ℕ) (hN : 0 < N) : weight f N N = 0 := by
unfold weight
rw [div_self (by exact_mod_cast hN.ne'), Real.log_one, mul_zero]
/-- **The weight is nonnegative** for a nonnegative frequency and a term in at most every
document. -/
theorem weight_nonneg (f : ℝ) (hf : 0 ≤ f) (N df : ℕ) (hdf : 0 < df) (hle : df ≤ N) :
0 ≤ weight f N df := by
unfold weight
apply mul_nonneg hf
apply Real.log_nonneg
rw [le_div_iff₀ (by exact_mod_cast hdf), one_mul]
exact_mod_cast hle
/-- **The weight falls as the term spreads.** -/
theorem weight_antitone (f : ℝ) (hf : 0 ≤ f) (N df df' : ℕ) (hdf : 0 < df) (hle : df ≤ df')
(hN : 0 < N) : weight f N df' ≤ weight f N df := by
unfold weight
apply mul_le_mul_of_nonneg_left _ hf
apply Real.log_le_log
· have : (0 : ℝ) < df' := by exact_mod_cast lt_of_lt_of_le hdf hle
positivity
· apply div_le_div_of_nonneg_left (by positivity) (by exact_mod_cast hdf)
exact_mod_cast hle
/-- **The frequency lies in the unit interval**, since a term's count cannot exceed the
document's length. -/
theorem tf_mem_unit (count length : ℕ) (hlen : 0 < length) (hle : count ≤ length) :
0 ≤ tf count length ∧ tf count length ≤ 1 := by
unfold tf
have : (0 : ℝ) < length := by exact_mod_cast hlen
refine ⟨by positivity, ?_⟩
rw [div_le_one this]
exact_mod_cast hle
end DMO.TFIDF