Bag of words and TF-IDF
Watch five sentences become word counts, then weights that favour rare words.
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.
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.
Takeaways
- A bag of words counts each word and drops the word order.
- The idf gives words in fewer documents a larger weight.
- With TF-IDF, shared rare words count more than shared common words.