Module 8 · Intermediate · Naive Bayes

Bag of words and TF-IDF explained

Bag of words and TF-IDF explained for beginners, with the TF-IDF sum worked by hand and CountVectorizer and TfidfVectorizer used on real SMS messages in Python.

By theprogrammers team · · 14 min read

Tip the words of a text message into a bag and shake it. You lose the order, but you can still count what's inside: two "free", one "prize", one "now". For spotting spam, those counts already say a lot. That's the bag of words: turning each piece of text into a row of word counts, so a model that only understands numbers can learn from it.

TF-IDF improves on plain counts by asking one more question: how unusual is each word? "The" in a message tells you nothing; "prize" tells you a lot. This lesson builds both by hand on four short messages, then uses them on 5,000 real ones.

What you need first: Naive Bayes classifier, where you first used CountVectorizer, and feature scaling.

Key terms

  • Document: one piece of text, here one message.
  • Vocabulary: every distinct word the vectoriser learnt from the training documents; each one becomes a column.
  • Bag of words: a table with one row per document and one column per vocabulary word, holding counts.
  • Document frequency: how many documents contain a word.
  • TF-IDF: a word's count in a document (term frequency) multiplied by a weight that is high for rare words (inverse document frequency).
  • N-gram: a run of n words in a row; "free prize" is a 2-gram, or bigram.

Bag of words by hand

Four tiny messages, two spam and two normal (called "ham"):

import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer

docs = [
    "win a free prize",
    "free entry win cash",
    "see you at lunch",
    "lunch at noon then see the film",
]
counter = CountVectorizer()
counts = counter.fit_transform(docs)
print(pd.DataFrame(counts.toarray(), columns=counter.get_feature_names_out()))
   at  cash  entry  film  free  lunch  noon  prize  see  the  then  win  you
0   0     0      0     0     1      0     0      1    0    0     0    1    0
1   0     1      1     0     1      0     0      0    0    0     0    1    0
2   1     0      0     0     0      1     0      0    1    0     0    0    1
3   1     0      0     1     0      1     1      0    1    1     1    0    0

This table is the one picture to keep: one row per message, one column per word, counts inside. fit_transform does two jobs: fit learns the vocabulary from the messages, and transform counts each word in each message. get_feature_names_out() lists the vocabulary in alphabetical order.

Notice what's missing: "a" has no column. By default CountVectorizer keeps only words of two or more letters, and it lowercases everything first. Notice also what's lost: "win a free prize" and "prize a free win" give the same row. Word order is gone.

Predict first: a new message arrives, "free lunch for the winner". Which of its words will be counted?

print(pd.DataFrame(counter.transform(["free lunch for the winner"]).toarray(),
                   columns=counter.get_feature_names_out()))
   at  cash  entry  film  free  lunch  noon  prize  see  the  then  win  you
0   0     0      0     0     1      1     0      0    0    1     0    0    0

Only "free", "lunch" and "the". "For" and "winner" weren't in the four training messages, so there's no column for them, and the vectoriser ignores them. "Winner" doesn't match "win" either: to a bag of words, they're unrelated strings. This is why transform, not fit_transform, is used on new text: the columns must stay the ones the model was trained on.

The problem with raw counts

In real messages, the most common words are "to", "you", "the" and "I". They appear in spam and ham alike, so they carry almost no signal, yet in a count table they're the biggest numbers. A model can learn to ignore them, but it helps to down-weight them from the start.

The idea of TF-IDF: a word matters in a message if it appears there often, and is rare across all the messages.

TF-IDF worked by hand

TF-IDF has two parts.

Term frequency (TF) is the count you already have: how many times the word appears in this message.

Inverse document frequency (IDF) is a weight per word, the same in every message. Scikit-learn's formula is:

$$\text{idf}(w) = \ln\frac{1 + n}{1 + \text{df}(w)} + 1$$

Read it as: "take the number of documents plus one, divide by the number of documents containing the word plus one, take the natural log, and add one". Here n is the number of documents and df(w) is how many contain the word w. The log keeps the weights from growing huge; the +1s inside stop a division by zero; the +1 at the end means even a word that's in every document keeps a small weight instead of zero.

With 4 messages: "free" is in 2 of them, so its weight is ln(5/3) + 1 ≈ 1.511. "Prize" is in 1, so ln(5/2) + 1 ≈ 1.916. The rarer word gets the bigger weight. Check with scikit-learn:

from sklearn.feature_extraction.text import TfidfVectorizer

tfidf = TfidfVectorizer()
weights = tfidf.fit_transform(docs)
print(pd.Series(tfidf.idf_, index=tfidf.get_feature_names_out()).round(3).to_string())
at       1.511
cash     1.916
entry    1.916
film     1.916
free     1.511
lunch    1.511
noon     1.916
prize    1.916
see      1.511
the      1.916
then     1.916
win      1.511
you      1.916

idf_ holds one weight per vocabulary word. to_string() prints the whole Series without the summary line.

Each word's TF-IDF score in a message is its count times its weight. Then one last step: each message's row is scaled so that its length, the square root of the sum of squares, is 1. That stops long messages from getting bigger numbers just for being long, the same idea as feature scaling, applied per row.

Work out the first message, "win a free prize", by hand: "free", "prize" and "win" each appear once, with weights 1.511, 1.916 and 1.511. The squares add up to 1.511² + 1.916² + 1.511² ≈ 8.24, whose square root is about 2.871. Divide each weight by 2.871: "free" and "win" become 0.526, "prize" 0.667 (0.668 with unrounded weights).

print(pd.DataFrame(weights.toarray(), columns=tfidf.get_feature_names_out()).round(3).to_string())
      at   cash  entry   film   free  lunch   noon  prize    see    the   then    win    you
0  0.000  0.000  0.000  0.000  0.526  0.000  0.000  0.668  0.000  0.000  0.000  0.526  0.000
1  0.000  0.555  0.555  0.000  0.438  0.000  0.000  0.000  0.000  0.000  0.000  0.438  0.000
2  0.466  0.000  0.000  0.000  0.000  0.466  0.000  0.000  0.466  0.000  0.000  0.000  0.591
3  0.326  0.000  0.000  0.413  0.000  0.326  0.413  0.000  0.326  0.413  0.413  0.000  0.000

to_string() prints every column instead of hiding the middle ones. The first row matches the hand calculation. In every row, the word that appears in only one message scores highest: "prize" in the first, "cash" and "entry" in the second, "you" in the third.

Settings that matter

Three settings change what the columns are:

  • ngram_range=(1, 2) adds every pair of neighbouring words as an extra column. "Not good" then exists as its own feature, which brings back a little word order.
  • min_df=2 drops words that appear in fewer than 2 documents. Rare typos and one-off words make thousands of columns that the model can't learn from.
  • stop_words="english" drops a built-in list of common English words. It's often unnecessary with TF-IDF, which already down-weights them, and it can remove useful words such as "not".

Now real data: the SMS Spam Collection, 5,574 text messages labelled spam or ham, the same data as the spam classifier project that follows.

Download the data: sms-spam.csv (487 KB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("sms-spam.csv").

import csv
import zipfile
import urllib.request
from pathlib import Path
from sklearn.model_selection import train_test_split

url = "https://archive.ics.uci.edu/static/public/228/sms+spam+collection.zip"
path = Path("sms_spam.zip")
if not path.exists():
    urllib.request.urlretrieve(url, path)
with zipfile.ZipFile(path) as z:
    sms = pd.read_csv(z.open("SMSSpamCollection"), sep="\t", header=None,
                      names=["label", "text"], quoting=csv.QUOTE_NONE)
sms = sms.drop_duplicates()

X_train, X_test, y_train, y_test = train_test_split(
    sms["text"], sms["label"] == "spam", test_size=0.2, stratify=sms["label"], random_state=42)

for settings in [{}, {"min_df": 2}, {"ngram_range": (1, 2)}, {"ngram_range": (1, 2), "min_df": 2}]:
    columns = TfidfVectorizer(**settings).fit_transform(X_train).shape[1]
    print(f"{str(settings):40}: {columns:6,} columns")
{}                                      :  7,669 columns
{'min_df': 2}                           :  3,310 columns
{'ngram_range': (1, 2)}                 : 42,608 columns
{'ngram_range': (1, 2), 'min_df': 2}    : 10,164 columns

The code downloads the zip file once and reuses it. drop_duplicates() removes repeated messages, so the same text can't land in both training and test sets. **settings passes the dictionary's entries as named arguments, so {"min_df": 2} becomes min_df=2.

Adding word pairs multiplies the columns by more than five; min_df=2 then removes three-quarters of them, because most word pairs appear only once.

Sparse matrices: why this doesn't fill your memory

With 42,608 columns and 4,136 rows, a full table would have about 176 million cells. But each message has only a few dozen words, so almost every cell is 0. The vectorisers return a sparse matrix, which stores only the non-zero cells:

matrix = TfidfVectorizer(ngram_range=(1, 2)).fit_transform(X_train)
cells = matrix.shape[0] * matrix.shape[1]
print(f"{matrix.shape}, non-zero cells: {matrix.nnz:,} of {cells:,} ({matrix.nnz / cells:.3%})")
(4136, 42608), non-zero cells: 109,212 of 176,226,688 (0.062%)

nnz is the number of non-zero values. That's why the earlier code calls .toarray() only on the four tiny messages: on real text, turning a sparse matrix into a full one can use gigabytes. Scikit-learn's linear models and Naive Bayes work on sparse matrices directly.

Counts or TF-IDF: which is better?

Experiment: train Naive Bayes and logistic regression on counts and on TF-IDF, scored with 5-fold cross-validation. Predict first: will TF-IDF beat counts for both models?

from sklearn.pipeline import make_pipeline
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, StratifiedKFold

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for vec_name, vectoriser in [("counts", CountVectorizer), ("TF-IDF", TfidfVectorizer)]:
    for model_name, model in [("Naive Bayes", MultinomialNB()),
                              ("Logistic regression", LogisticRegression(max_iter=1000))]:
        pipe = make_pipeline(vectoriser(), model)
        f1 = cross_val_score(pipe, X_train, y_train, cv=cv, scoring="f1").mean()
        print(f"{vec_name:7} + {model_name:20}: F1 {f1:.3f}")
counts  + Naive Bayes         : F1 0.931
counts  + Logistic regression : F1 0.909
TF-IDF  + Naive Bayes         : F1 0.751
TF-IDF  + Logistic regression : F1 0.845

The vectoriser goes inside the pipeline, so each fold learns its vocabulary and IDF weights from its own training messages only. Fitting it on all the messages first would leak test words into training, as in data leakage.

A surprise: with default settings, TF-IDF makes both models worse, and Naive Bayes much worse. The reason is scale. TF-IDF values are small fractions, while counts are whole numbers. Naive Bayes adds its smoothing alpha=1 to every word's total; against tiny TF-IDF totals, that smoothing swamps the evidence. Logistic regression's penalty C has the same problem: small inputs need bigger weights, and the default penalty holds them back. Give each model a setting that suits the new scale:

for name, model in [("Naive Bayes, alpha=0.1", MultinomialNB(alpha=0.1)),
                    ("Logistic regression, C=10", LogisticRegression(max_iter=1000, C=10))]:
    pipe = make_pipeline(TfidfVectorizer(), model)
    f1 = cross_val_score(pipe, X_train, y_train, cv=cv, scoring="f1").mean()
    print(f"TF-IDF + {name:26}: F1 {f1:.3f}")
TF-IDF + Naive Bayes, alpha=0.1    : F1 0.932
TF-IDF + Logistic regression, C=10 : F1 0.919

With settings that match its scale, TF-IDF catches up: 0.932 against 0.931 for Naive Bayes, and 0.919 against 0.909 for logistic regression. The lesson isn't "TF-IDF is better" or "counts are better": changing how text becomes numbers changes the scale of the numbers, so the model's settings need tuning again. On short messages like these, counts and TF-IDF end up close; TF-IDF tends to help more on long documents, where common words pile up.

What a bag of words can't do

  • Word order is lost. "Dog bites man" and "man bites dog" are the same bag. Bigrams recover a little.
  • Meaning is lost. "Cheap", "inexpensive" and "low-cost" are three unrelated columns, and so are "win" and "winner".
  • New words are ignored. A spammer who writes "fr33" instead of "free" walks past a vocabulary learnt from "free".

Word embeddings and language models, later in the course, fix these by turning words into numbers that capture meaning. Bag of words remains a fast, strong baseline for classifying text.

When to use bag of words or TF-IDF

SituationUse
Short texts, such as messages or titles, with Naive BayesCounts (CountVectorizer)
Longer documents, such as articles or reviewsTF-IDF, which stops common words piling up
Linear models such as logistic regression or a linear SVMEither; try TF-IDF, and tune the penalty
Phrases matter ("not good", "free entry")Add ngram_range=(1, 2)
Too many columns, or many one-off typosmin_df=2 or higher
Meaning and word order matter, such as questions and answersEmbeddings or a language model, not a bag of words

Practice

  1. Without running code, write the bag-of-words row for "free free cash" using the vocabulary from the four tiny messages.
Show the answer

"free" is 2, "cash" is 1, every other column 0.

print(pd.DataFrame(counter.transform(["free free cash"]).toarray(),
                   columns=counter.get_feature_names_out()))
   at  cash  entry  film  free  lunch  noon  prize  see  the  then  win  you
0   0     1      0     0     2      0     0      0    0    0     0    0    0
  1. With the four tiny messages, the word "at" appears in 2 documents and "the" in 1. Which has the bigger IDF weight, and why does that make sense?
Show the answer

"The" has the bigger weight here (1.916 against 1.511), because it appears in fewer of these documents. IDF only knows how rare a word is in the training documents, not in English generally. With four messages, "the" happens to be rare; with thousands, it would be in most of them and get a small weight.

  1. Why is fit_transform used on the training messages but only transform on the test messages?
Show the answer

fit learns the vocabulary and the IDF weights. These must come from the training messages only, and the test messages must be turned into the same columns with the same weights. Calling fit on the test messages would create different columns that the model was never trained on, and would leak information from the test set.

  1. Use CountVectorizer(ngram_range=(1, 2)) on the four tiny messages. How many columns are there now, and which bigrams appear?
Show the answer
bigrams = CountVectorizer(ngram_range=(1, 2)).fit(docs)
names = bigrams.get_feature_names_out()
print(len(names))
print([n for n in names if " " in n])
27
['at lunch', 'at noon', 'entry win', 'free entry', 'free prize', 'lunch at', 'noon then', 'see the', 'see you', 'the film', 'then see', 'win cash', 'win free', 'you at']

Every pair of neighbouring words in each message becomes a column. "A" is still dropped, so "win a free prize" gives "win free", not "win a".

  1. A colleague switches from counts to TF-IDF and the model gets worse. Before going back to counts, what should they try?
Show the answer

Retune the model's main setting for the new scale: a smaller alpha for Naive Bayes, a larger C for logistic regression or a linear SVM. TF-IDF values are small fractions, so settings chosen for counts are usually wrong for them.

Interview questions

What is TF-IDF?

A way to turn text into numbers where each word's score in a document is its frequency in that document times its inverse document frequency, a weight that is higher for words that appear in fewer documents. Common words get low scores and distinctive words get high ones. Scikit-learn also normalises each document's vector to length 1.

What are the limitations of a bag of words?

It ignores word order, treats similar words (synonyms, plurals) as unrelated, ignores words not seen in training, and produces very wide, sparse matrices. Embeddings and transformer models address these.

Why must a vectoriser be fitted inside cross-validation?

Its vocabulary and IDF weights are learnt from data. Fitting it on all the data lets words and frequencies from the validation folds influence training, which is data leakage and gives optimistic scores. Putting it in a pipeline fits it on each training fold only.

Key takeaways

  • A bag of words turns each document into a row of word counts, one column per vocabulary word; word order is lost.
  • TF-IDF multiplies each count by a weight that's high for rare words, then scales each row to length 1.
  • Fit the vectoriser on training text only, inside a pipeline; use transform for new text.
  • ngram_range adds phrases, min_df removes rare noise; the result is a sparse matrix.
  • Switching between counts and TF-IDF changes the scale of the features, so retune the model's settings.

Frequently asked questions

Is TF-IDF still used now that there are language models?

Yes. It's fast, needs no GPU, is easy to explain, and is a strong baseline for classification and search. Many search systems still combine a TF-IDF-style score with embeddings.

What's the difference between CountVectorizer and TfidfVectorizer?

CountVectorizer returns raw counts. TfidfVectorizer returns TF-IDF scores: the same counts multiplied by IDF weights and normalised per document. TfidfVectorizer is the same as CountVectorizer followed by TfidfTransformer.

Should I remove stop words?

Often not with TF-IDF, which already down-weights common words, and stop-word lists can remove meaningful words such as "not". Try both with cross-validation.

What to learn next

  1. Build a complete spam filter with TF-IDF and three classifiers in the spam classifier project, the next lesson.
  2. Revisit how Naive Bayes uses word counts in Naive Bayes from scratch.
  3. Tune alpha and C properly with hyperparameter tuning.