Reviews, emails, support messages and comments are all text, and a model needs numbers. TF-IDF is a simple, strong way to turn text into numbers. It gives a high weight to words that appear often in one document but rarely across the whole collection. Paired with logistic regression, it makes a fast text classifier that is easy to explain.
In this lesson you will learn
- What term frequency and inverse document frequency mean
- How
TfidfVectorizerbuilds a vocabulary and weights words - Removing common words with
stop_words - Building a sentiment classifier with a pipeline
- What word pairs (bigrams) can and cannot fix
You should know logistic regression and pipelines. The Naive Bayes lesson shows another way to classify text, using word counts.
How TF-IDF Weights Words
TF-IDF multiplies two parts:
- Term frequency (TF): how often the word appears in this document. “great” twice counts more than once.
- Inverse document frequency (IDF): how rare the word is across all documents. A word found in every document, like “the”, tells you little, so it gets a low IDF.
scikit-learn then scales each document’s row to length 1, so long reviews do not get bigger numbers just for being long.
from sklearn.feature_extraction.text import TfidfVectorizer
reviews = [
"the battery is great and the screen is great",
"the battery died fast",
"the screen cracked and the speaker is weak",
]
vec = TfidfVectorizer()
X = vec.fit_transform(reviews)
print("Vocabulary size:", len(vec.vocabulary_))
words = vec.get_feature_names_out()
for i, text in enumerate(reviews):
row = X[i].toarray().ravel()
top = row.argsort()[::-1][:3]
print(f"Review {i}:", [(words[j], round(float(row[j]), 2)) for j in top])
print("Weight of 'the' in review 0:", round(float(X[0, vec.vocabulary_["the"]]), 2))
vec2 = TfidfVectorizer(stop_words="english")
row = vec2.fit_transform(reviews)[2].toarray().ravel()
words2 = vec2.get_feature_names_out()
print("Review 2 without stop words:",
[(words2[j], round(float(row[j]), 2)) for j in row.argsort()[::-1][:3]])
Output
Vocabulary size: 11
Review 0: [('great', 0.65), ('is', 0.49), ('the', 0.38)]
Review 1: [('fast', 0.58), ('died', 0.58), ('battery', 0.44)]
Review 2: [('the', 0.48), ('weak', 0.4), ('speaker', 0.4)]
Weight of 'the' in review 0: 0.38
Review 2 without stop words: [('weak', 0.53), ('speaker', 0.53), ('cracked', 0.53)]
- The vectorizer found 11 distinct words. Each review becomes a row of 11 numbers, mostly zeros.
- In review 0, “great” scores highest. It appears twice and in no other review.
- In review 1, “fast” and “died” tie at 0.58. Each appears once and only in this review. “battery” is a bit lower because review 0 mentions it too.
- In review 2, “the” still comes first, because it appears twice there. IDF lowers the weight of common words but does not remove them.
- With
stop_words="english", words like “the”, “is” and “and” are dropped. Review 2 is now described by “weak”, “speaker” and “cracked”, which carry the meaning.
A Sentiment Classifier
The next example trains a classifier on 20 short product reviews, 10 positive and 10 negative, and tests it on four new phrases. Real projects need thousands of examples, but the steps are the same.
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
pos = ["good battery and fast charging", "the camera is good", "great value, works well",
"fast delivery and good packing", "screen is bright and good", "love it, works great",
"good sound for the price", "very happy, good phone", "works well and looks great",
"battery lasts long, good buy"]
neg = ["not good, battery drains fast", "the camera is not good", "stopped working in a week",
"screen is dim and not bright", "bad sound and weak speaker", "not worth the price",
"charging is slow, not happy", "arrived broken, very bad", "the phone is not good at all",
"poor battery, returned it"]
texts = pos + neg
labels = np.array([1] * len(pos) + [0] * len(neg)) # 1 = positive
tests = ["good camera", "not good camera", "battery is not bad", "works great"]
for ngrams in [(1, 1), (1, 2)]:
model = make_pipeline(TfidfVectorizer(ngram_range=ngrams), LogisticRegression(C=10))
model.fit(texts, labels)
probs = model.predict_proba(tests)[:, 1]
print(f"ngram_range={ngrams}")
for t, p in zip(tests, probs):
print(f" {t:20} P(positive)={p:.2f}")
vec, clf = model[0], model[1]
words = vec.get_feature_names_out()
order = clf.coef_[0].argsort()
print("Most negative terms:", list(words[order[:4]]))
print("Most positive terms:", list(words[order[-4:]]))
Output
ngram_range=(1, 1)
good camera P(positive)=0.80
not good camera P(positive)=0.28
battery is not bad P(positive)=0.04
works great P(positive)=0.89
ngram_range=(1, 2)
good camera P(positive)=0.72
not good camera P(positive)=0.20
battery is not bad P(positive)=0.09
works great P(positive)=0.84
Most negative terms: ['not', 'not good', 'is not', 'bad']
Most positive terms: ['is good', 'works', 'great', 'good']
- The pipeline puts the vectorizer and the model together, so the vocabulary is learned from training text only.
- “good camera” and “works great” are rated positive; “not good camera” is rated negative. “not” appears in many negative reviews, so the model learned it as a negative word.
- “battery is not bad” is a positive phrase, but both models call it negative. “not” and “bad” each count against it, and the training data never contains the pair “not bad”. Bigrams (
ngram_range=(1, 2)) add word pairs as extra features, but a pair the model never saw during training gets no weight at all. - The coefficients make the model explainable. The most negative terms include “not”, “not good” and “bad”; the most positive include “great”, “good” and “works”.
The lesson here: TF-IDF only knows the words and pairs in its training data. It does not understand meaning. Collect enough real examples, including tricky phrases like “not bad”, or use a language model when meaning matters.
Useful TfidfVectorizer Options
| Option | What it does |
|---|---|
ngram_range=(1, 2) | Adds word pairs such as “not good” |
stop_words="english" | Drops common English words |
min_df=2 | Ignores words found in fewer than 2 documents, which removes typos and rare noise |
max_df=0.9 | Ignores words found in more than 90% of documents |
max_features=20000 | Keeps only the most frequent terms |
sublinear_tf=True | Uses 1 + log(count), so a word repeated 10 times does not dominate |
Be careful with stop_words in sentiment tasks: the built-in English list includes “not”, which can flip the meaning of a review.
Common Mistakes
- Fitting the vectorizer on all the data before splitting. The test set’s words then leak into the vocabulary. Use a pipeline.
- Calling
fit_transformon new text. Usetransform, so new text uses the vocabulary learned in training. - Removing negation words with a stop word list in a sentiment task.
- Judging the model on a tiny test set. A handful of phrases cannot measure accuracy. Use cross-validation on real data.
Practice Exercises
Exercise 1. Add the reviews “not bad at all” and “battery is not bad” to the positive list and run txt2.py again. What happens to “battery is not bad” with bigrams?
Show answer
Both models now rate it positive: about 0.62 without bigrams and 0.76 with them. The bigram model learns “not bad” as one of its strongest positive terms. Also look at “not good camera”. The bigram model still calls it clearly negative (about 0.24), but the single-word model drifts to about 0.47, because “not” now appears in positive reviews too. Word pairs let the model tell “not good” and “not bad” apart.
Exercise 2. Print the five most important words for the positive class from a fitted pipeline called model.
Show answer
words = model[0].get_feature_names_out()
coefs = model[1].coef_[0]
print(words[coefs.argsort()[-5:][::-1]])
Frequently Asked Questions
TF-IDF or word counts?
Plain counts (CountVectorizer) suit Naive Bayes. TF-IDF usually works better with linear models such as logistic regression and linear SVMs, because it lowers the weight of common words.
Does TF-IDF work for Bangla or other languages?
Yes, as long as words can be split apart. The default tokenizer splits on word characters. For some scripts you may need a custom token_pattern or tokenizer, and you would supply your own stop word list.
Is TF-IDF still useful now that large language models exist?
Yes. It trains in seconds, runs on a laptop, and its weights are easy to explain. It is a strong baseline to beat before trying heavier models.
Summary
- TF-IDF weights a word by how often it appears in a document and how rare it is overall.
TfidfVectorizerplusLogisticRegressionin a pipeline is a strong text baseline.- Bigrams capture short phrases, but only ones seen in training.
- Coefficients show which words push toward each class.
