BagOfWords.lean
Lean 4 source, lean/DataMiningAsObservation/BagOfWords.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
BagOfWords.lean. Chapter 12 section 12.1, the bag of words.
A bag of words represents a document as the vector of its term counts. Two documents that
are rearrangements of each other have the same bag, so the bag is a quotient that declares
word order irrelevant. The counts are nonnegative and sum to the document's length. As a
null model the bag reads only counts, which is why an encoder must beat it to be validated.
-/
import Mathlib
namespace DMO.BagOfWords
variable {α : Type*} [DecidableEq α]
/-- The bag of words of a document, its count of each term. -/
def bag (doc : List α) (t : α) : ℕ := doc.count t
/-- **Word order is unread.** Two documents that are rearrangements of each other have the
same bag. -/
theorem bag_perm (d₁ d₂ : List α) (h : d₁.Perm d₂) : bag d₁ = bag d₂ := by
funext t
exact h.count_eq t
/-- **A concrete rearrangement.** The bag of `[a, b, a]` equals the bag of `[a, a, b]`. -/
theorem bag_example (a b : α) : bag [a, b, a] = bag [a, a, b] :=
bag_perm _ _ ((List.Perm.swap a b []).cons a)
/-- **The counts sum to the length** over the document's own vocabulary. -/
theorem bag_sum (doc : List α) : ∑ t ∈ doc.toFinset, bag doc t = doc.length := by
unfold bag
exact List.sum_toFinset_count_eq_length doc
/-- A term absent from the document has count zero. -/
theorem bag_absent (doc : List α) (t : α) (h : t ∉ doc) : bag doc t = 0 :=
List.count_eq_zero.2 h
end DMO.BagOfWords