Log inStart free
LESSON 7.02 · 6 STAGES · 2 CONTROLS · 3 CHECKS

Bag of words and TF-IDF

Watch five sentences become word counts, then weights that favour rare words.


EXPLAINER · 7.02 · TEXT BAY
01
Stage 1 of 6 · Split into words
Each document splits into tokens at the spaces. The 9 distinct words, sorted, form the vocabulary.
Explain it simply

You see five short documents on the left. Each one is cut at the spaces into tokens, the words the computer will count. Every distinct word goes into the vocabulary at the top, in sorted order. A new word that is not in the vocabulary gets no column, so it is ignored later.

Five documents on the left, each split into token chips. The vocabulary of 9 sorted words runs along the top.

tokens, counts, dfidftf-idf, cosinezero
Toy: 5 short documents, 9 distinct words
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
smooth
How a document count becomes a word weight.
D1
The document to compare with the others.
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
V=sorted {distinct tokens}\sy{v}{data}{V} = \mathrm{sorted}\,\{\text{distinct tokens}\}
∣V∣=9|V| = 9

The vocabulary holds each distinct token once, in sorted order.

Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import math
from collections import Counter

docs = [
    "the cat sat on the mat",
    "the cat saw the mat",
    "the dog chased the cat",
    "the cat chased the dog",
    "the dog sat on a mat",
]
tokens = [d.split() for d in docs]
vocab = sorted({t for doc in tokens for t in doc})
print(vocab)  # ['a', 'cat', 'chased', 'dog', 'mat', 'on', 'sat', 'saw', 'the']

counts = [[Counter(doc)[w] for w in vocab] for doc in tokens]  # bag of words
print(counts[2] == counts[3])  # True: D3 and D4 get the same row

N = len(docs)
df = {w: sum(w in doc for doc in tokens) for w in vocab}
def idf(w):
    return math.log((1 + N) / (1 + df[w])) + 1   # smooth (scikit-learn's default)

print([round(idf(w), 2) for w in vocab])  # [2.1, 1.18, 1.69, 1.41, 1.41, 1.69, 1.69, 2.1, 1.0]
weights = [[c * idf(w) for c, w in zip(row, vocab)] for row in counts]

def cos(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / math.sqrt(sum(x * x for x in a) * sum(y * y for y in b))

q = 0  # the query: D1
print([round(cos(counts[q], row), 2) for row in counts])   # [1.0, 0.8, 0.67, 0.67, 0.72]
print([round(cos(weights[q], row), 2) for row in weights])  # [1.0, 0.59, 0.47, 0.47, 0.69]

Copy it into a file and run it.

Common mix-ups

MYTHA bag of words keeps the word order.

FIXIt keeps only counts. D3 and D4 hold the same words in another order, so their cosine is 1.00.

MYTHTF-IDF knows which words carry the meaning.

FIXIt only counts documents. "a" is in 1 of 5 documents, so it ties with "saw" for the largest idf, 2.10.

Predict, then reveal
0 / 3 REVEALED
Q01With the plain idf, what weight does "the" get in each document?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02With D1 as the query, does the TF-IDF cosine of D1 and D2 go up or down with plain idf?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03With D5 as the query, do counts and TF-IDF pick the same document?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. A bag of words counts each word and drops the word order.
  2. The idf gives words in fewer documents a larger weight.
  3. With TF-IDF, shared rare words count more than shared common words.