TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
Plain word counts treat every word the same. TF-IDF multiplies each count by how rare the word is, then scales each row to length 1. Worked by hand on four restaurant reviews, then on 2,000 movie reviews.
What you will learn
- Explain term frequency (TF) and inverse document frequency (IDF)
- Compute one review's TF-IDF by hand and match scikit-learn
- Read the idf_ values and the row-length scaling of TfidfVectorizer
- Compare the top words by counts and by TF-IDF on real reviews
Before you start
- Bag of Words with CountVectorizer
- Basic pandas
Imagine a pile of restaurant reviews on your desk:
- Review 0: The food was great
- Review 1: The food was cold
- Review 2: Great food, friendly staff
- Review 3: The food was mouldy
Every single review says food. When you read that word, you learn nothing new. But only one review says mouldy. That word is rare, and it tells you a lot. You'd remember that restaurant, and you'd probably never go back.
A word that is everywhere should whisper, and a rare word should shout. That's the whole idea of TF-IDF.
Plain counts treat every word the same
In Bag of Words with CountVectorizer we turned text into word counts. Let's do that for the four reviews:
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
reviews = ["The food was great", "The food was cold",
"Great food, friendly staff",
"The food was mouldy"]
cv = CountVectorizer()
counts = cv.fit_transform(reviews)
terms = cv.get_feature_names_out()
pd.DataFrame(counts.toarray(), columns=terms)
cold food friendly great mouldy staff the was
0 0 1 0 1 0 0 1 1
1 1 1 0 0 0 0 1 1
2 0 1 1 1 0 1 0 0
3 0 1 0 0 1 0 1 1
This count has a name: TF, the term frequency, how often a word appears in this review. Look at the food column: a 1 in every row. And mouldy is also just a 1. The counts can't tell us which word matters.
IDF: the rarer the word, the bigger the number
So we need a second number, the IDF, the inverse document frequency. For every word we check how many reviews hold it. scikit-learn uses this formula (the default, smoothed version):
idf = ln( (1 + n) / (1 + df) ) + 1
Here n is the number of reviews (4) and df is how many of them contain the word. A TfidfVectorizer counts the words and also learns the idf of each one, in its idf_ attribute:
tfidf = TfidfVectorizer()
X = tfidf.fit_transform(reviews)
terms = tfidf.get_feature_names_out()
for word, value in zip(terms, tfidf.idf_):
print(word, f"{value:.3f}")
cold 1.916
food 1.000
friendly 1.916
great 1.511
mouldy 1.916
staff 1.916
the 1.223
was 1.223
food is in all four reviews, so it gets the smallest value, 1.000. the and was are in three reviews and get 1.223. great is in two and gets 1.511. mouldy, cold, friendly and staff are each in just one review, so they get the biggest value, 1.916.
Review 3 by hand: TF x IDF, then scale
Let's see what happens inside for review 3, "The food was mouldy". Each of its four words appears once, so the TF is 1 for all of them. First, multiply TF by IDF. Then measure the length of the row: the square root of the sum of squares.
raw = counts[3].toarray()[0] * tfidf.idf_
for word, value in zip(terms, raw):
if value > 0:
print(word, f"{value:.3f}")
print("length", f"{np.linalg.norm(raw):.2f}")
food 1.000
mouldy 1.916
the 1.223
was 1.223
length 2.77
The length is 2.77. Last, divide every value by it, so the whole row ends up with length 1:
TfidfVectorizer does it all in one go
The X we got from fit_transform already holds these scaled values for every review:
pd.DataFrame(X.toarray(), columns=terms).round(2)
cold food friendly great mouldy staff the was
0 0.00 0.40 0.00 0.60 0.00 0.00 0.49 0.49
1 0.69 0.36 0.00 0.00 0.00 0.00 0.44 0.44
2 0.00 0.31 0.59 0.46 0.00 0.59 0.00 0.00
3 0.00 0.36 0.00 0.00 0.69 0.00 0.44 0.44
Row 3 matches our hand calculation: mouldy 0.69, food 0.36. In row 1 the rare word cold wins with 0.69. And every row has length 1, so long and short reviews can be compared fairly.
The same idea on 2,000 movie reviews
Now the real data. We glue the sentences back into reviews and fit a CountVectorizer and a TfidfVectorizer, both with English stop words:
sents = pd.read_csv("movie_review.csv")
grouped = sents.groupby(["cv_tag", "tag"])["text"]
movies = grouped.apply(" ".join).reset_index()
cv = CountVectorizer(stop_words="english")
tv = TfidfVectorizer(stop_words="english")
C = cv.fit_transform(movies["text"])
T = tv.fit_transform(movies["text"])
print(C.shape, T.shape)
(2000, 39354) (2000, 39354)
Same vocabulary, same shape: 2,000 rows and 39,354 columns. Only the numbers inside differ. Let's compare the top five words of review 0 under each:
def top5(s):
s = s.sort_values(ascending=False)
return list(s.index[:5])
words = cv.get_feature_names_out()
counts0 = pd.Series(C[0].toarray()[0], index=words)
weights0 = pd.Series(T[0].toarray()[0], index=words)
print("counts:", *top5(counts0))
print("tf-idf:", *top5(weights0))
counts: 10 film movie make pretty
tf-idf: 10 teen sagemiller memento strangeness
film and movie fill every movie review, so they tell us very little about this one. teen, sagemiller, memento and strangeness tell us what this review is really about. Common words fade, and rare words speak. That's why TF-IDF is a strong, fast first try for search, spam filters and review classifiers.
Here the vectorizers are fitted on all 2,000 reviews only to look at the words. The idf values are learned from the data, so when you train a model, fit the vectorizer on the training reviews only. A Pipeline does that for you, as shown in Build a Text Classifier with TF-IDF and a Pipeline.
Common mistakes
- Expecting a different vocabulary. TF-IDF changes the numbers, not the columns. With the same settings,
CountVectorizerandTfidfVectorizergive the same shape. - Forgetting the row scaling. TF x IDF alone gives 1.916 for mouldy; the table shows 0.69 because each row is divided by its length.
- Fitting on the test text. idf counts how many documents hold each word, so test reviews would leak into it. Fit on train, transform the test.
Recap
| Piece | Meaning | Review 3 example |
|---|---|---|
| TF | How often the word appears in this review | 1 for every word |
| IDF | How rare the word is across all the reviews | food 1.000, mouldy 1.916 |
| TF x IDF | Multiply the two | mouldy 1.916 |
| Scale | Divide the row by its length so it has length 1 | 1.916 / 2.77 = 0.69 |
TfidfVectorizer | All of the above in one line | row 3: mouldy 0.69, food 0.36 |
Try it yourself
Add a fifth review, "The food was mouldy and cold", to reviews and fit the TfidfVectorizer again. Which word gets the biggest TF-IDF in it? The notebook and the dataset are in the community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Bag of Words with CountVectorizer: Turn Text into Word Counts
Next →Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Bag of Words with CountVectorizer: Turn Text into Word Counts
A model only does maths, so text has to become numbers first. Clean a review, count its words with CountVectorizer, read the document-term matrix, see why it is sparse, and add word pairs with n-grams. Shown on 2,000 movie reviews.
Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
Train a movie-review sentiment classifier: split first, put TF-IDF and the model in one Pipeline, compare MultinomialNB (F1 0.801) with LinearSVC (F1 0.857), read the confusion matrix and predict new reviews from raw text.