TF-IDF and Bag of Words: Text Representation & Search › Worked Example
TF-IDF and Bag of Words: Text Representation & Search › Worked ExampleOne section · Sections in this article4 / 8 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let's work through a concrete example with three short documents:
- Document 1: "the cat sat on the mat"
- Document 2: "the dog sat on the log"
- Document 3: "the cat and dog sat"
First, we build our vocabulary by collecting all unique words: . That's 8 words, so our vectors will have 8 dimensions.
Bag of Words vectors:
- Document 1: (2×"the", 1×"cat", 1×"sat", 1×"on", 1×"mat")
- Document 2: (2×"the", 1×"sat", 1×"on", 1×"dog", 1×"log")
- Document 3: (1×"the", 1×"cat", 1×"sat", 1×"dog", 1×"and")
Notice that "the" appears in all three documents, "sat" appears in all three, but "mat", "log", and "and" appear in only one document each.
Calculating IDF:
- "the": appears in 3/3 documents →
- "sat": appears in 3/3 documents →
- "cat": appears in 2/3 documents →
- "dog": appears in 2/3 documents →
- "mat": appears in 1/3 documents →
- "log": appears in 1/3 documents →
- "and": appears in 1/3 documents →
Calculating TF-IDF for Document 1:
Using raw counts for TF:
- "the": , →
- "cat": , →
- "mat": , →
The word "mat" gets the highest TF-IDF score in Document 1 because it's unique to that document. "The" gets zero weight because it appears everywhere. This is exactly the behavior we want: distinctive words are emphasized, common words are suppressed.