Skip to content

MLDay 20 of 50Supervised and Unsupervised Learning

Turn Text into Features

Bag-of-Words and TF-IDF

9 min read

Logistic regression needs a table of numbers, but a spam filter receives "WINNER! Claim your prize now". Before any model can learn from a message, the text has to become a row of numbers.

The idea

Split each message into tokens: the words the computer keeps. The vocabulary is every distinct token in the training messages. Bag-of-words turns a message into one row, with a column per vocabulary word holding how often that word appears. That count is the term frequency (tf). Word order is thrown away: "call me now" and "now call me" get the same row.

Raw counts treat every word alike. But a word found in almost every message says little about any one of them. TF-IDF (term frequency × inverse document frequency) multiplies each count by a weight: large for words found in few messages, small for words found in many. A word's document frequency (df) is the number of messages that contain it.

A real vocabulary holds thousands of words, and one text uses about a dozen, so almost every cell is 0. A sparse matrix stores only the non-zero cells. A linear model such as logistic regression (Day 12) then learns one weight per word.

An n-gram is a run of n tokens in a row. Adding 2-grams (word pairs such as "call now") brings back a little order, so "not good" gets its own column, apart from "good".

A tiny example

Three messages. scikit-learn lowercases them and drops one-letter words, so "a" and "I" vanish.

Message call can free later me now prize win you
A: "WIN a free prize, call now" 1 0 1 0 0 1 1 1 0
B: "call me later" 1 0 0 1 1 0 0 0 0
C: "I can call you now" 1 1 0 0 0 1 0 0 1
df 3 1 1 1 1 2 1 1 1

"call" is in all three messages, so it can't tell them apart. "free" appears only in A, so it should count for more there.

The formula

The textbook weight multiplies the count by how rare the word is.

tfidf=tf⋅log⁡Ndf\text{tfidf} = \text{tf} \cdot \log\frac{N}{\text{df}}
Symbol Meaning
tf how many times the word appears in this message
NN the number of messages
df how many messages contain the word
log⁡\log a logarithm; base 10 here

Worked: a word appears twice in a message (tf = 2) and in 10 of N=100N = 100 messages. Its weight is 2⋅log⁡1010010=2⋅1=22 \cdot \log_{10}\frac{100}{10} = 2 \cdot 1 = 2. A word in all 100 messages gets 2⋅log⁡101=02 \cdot \log_{10} 1 = 0.

scikit-learn's TfidfVectorizer uses a smoothed idf (the rarity part), then rescales each row.

idf=ln⁡1+n1+df+1\text{idf} = \ln\frac{1 + n}{1 + \text{df}} + 1
Symbol Meaning
nn the number of training messages
df how many of them contain the word
ln⁡\ln the natural log

The 1s inside act like one extra message that holds every word, so nothing divides by zero. The +1 outside keeps a word that's everywhere at weight 1 instead of 0. Then each row is divided by its length (the square root of its sum of squares, the L2 norm). Without that step, a long message would score high just for having more words.

Worked, message A (n=3n = 3): "free" has idf ln⁡42+1=1.693\ln\frac{4}{2} + 1 = 1.693, "now" ln⁡43+1=1.288\ln\frac{4}{3} + 1 = 1.288 and "call" ln⁡44+1=1\ln\frac{4}{4} + 1 = 1. A's row is call 1, free 1.693, now 1.288, prize 1.693, win 1.693. Its length is 1+3⋅1.6932+1.2882=3.355\sqrt{1 + 3 \cdot 1.693^2 + 1.288^2} = 3.355, so "free" ends at 1.693/3.355=0.5051.693 / 3.355 = 0.505 and "call" at 0.2980.298.

Try it

Which words tell these texts apart?

Click any word. A word that appears in every document tells them apart badly, so it gets a low weight; a word in just one document gets a high one.

  1. D1 a ,
  2. D2
  3. D3I
  4. D4 !
  5. D5 I

word “call”df 4 of 5 documentsidf = ln((1 + 5) / (1 + 4)) + 1 = 1.182

tf, tf × idf and normalized tf-idf of "call" in each document
documenttf (count)tf × idftf-idf (row length 1)bar
D111.1820.312
D211.1820.37
D311.1820.327
D4000
D511.1820.309

Computed as scikit-learn's TfidfVectorizer does by default: words are lowercased, one-letter words (struck through) are dropped, tf is the raw count, idf = ln((1 + n) / (1 + df)) + 1, and each document's tf × idf values are scaled so the row has length 1 (L2 normalization).

It starts on "call", which is in 4 of the 5 messages, so its idf is only 1.182 and its weight stays between 0.31 and 0.37 in the four messages that have it. Click "free" (in 2 messages) and then "sorry" (in 1): the idf climbs to 1.693, then 2.099, and "sorry" ends at 0.549 in the last message.

In code

TfidfVectorizer does the counting, weighting and row scaling in one step. It matches the hand calculation.

# script_id: day_020_text_features_tfidf/tiny
from sklearn.feature_extraction.text import TfidfVectorizer

texts = ["WIN a free prize, call now", "call me later", "I can call you now"]
vec = TfidfVectorizer()                        # lowercase, smoothed idf, L2-normalized rows
X = vec.fit_transform(texts)                   # a sparse matrix: 3 rows, one column per word

print("vocabulary:", list(vec.get_feature_names_out()))
print("idf:       ", vec.idf_.round(3))
print("message A: ", X.toarray()[0].round(3))
vocabulary: ['call', 'can', 'free', 'later', 'me', 'now', 'prize', 'win', 'you']
idf:        [1.    1.693 1.693 1.693 1.693 1.288 1.693 1.693 1.693]
message A:  [0.298 0.    0.505 0.    0.    0.384 0.505 0.505 0.   ]

Now the 5,574 real SMS messages. 403 of them repeat an earlier text exactly. Drop the copies before splitting: otherwise a message lands in training and its twin in the test set, which flatters the score. A Pipeline (Day 11) joins the vectorizer and the model, so the vocabulary and idf come from the training messages only.

# script_id: day_020_text_features_tfidf/sms
import os
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
sms = pd.read_csv(DATA_DIR / "sms_spam" / "SMSSpamCollection", sep="\t", header=None,
                  names=["label", "text"], quoting=3)
sms = sms.drop_duplicates("text")             # a copy on both sides of the split would leak
y = (sms["label"] == "spam").astype(int)
X_train, X_test, y_train, y_test = train_test_split(sms["text"], y, test_size=0.25, random_state=42)

model = make_pipeline(TfidfVectorizer(), LogisticRegression())   # C=1.0 by default
pred = model.fit(X_train, y_train).predict(X_test)
print(f"{len(sms)} unique messages, {len(X_test)} held out")
print(f"always 'ham' accuracy: {1 - y_test.mean():.3f}")
print(f"TF-IDF + logistic:     {accuracy_score(y_test, pred):.3f} "
      f"(spam precision {precision_score(y_test, pred):.2f}, recall {recall_score(y_test, pred):.2f})")

X = model[0].transform(X_train)               # step 0, the vectorizer: the matrix the model saw
print(f"matrix: {X.shape[0]} x {X.shape[1]}, {X.nnz / (X.shape[0] * X.shape[1]):.2%} of cells non-zero")
pairs = TfidfVectorizer(ngram_range=(1, 2)).fit(X_train)
print(f"columns with word pairs too: {len(pairs.vocabulary_)}")
5171 unique messages, 1293 held out
always 'ham' accuracy: 0.872
TF-IDF + logistic:     0.969 (spam precision 0.98, recall 0.78)
matrix: 3878 x 7326, 0.18% of cells non-zero
columns with word pairs too: 40275

The model gets 96.9% right, against 87.2% for always guessing "ham" (not spam). Almost every message it flags is spam, but it catches only about 4 spam texts in 5 (Day 13 covers that trade-off). The matrix has 28.4 million cells, yet only 0.18% of them are stored. ngram_range=(1, 2) adds word pairs and grows it to 40,275 columns.

Each word gets one weight from the model, model[-1]. Above 0 pushes towards spam; below 0, towards ham.

# script_id: day_020_text_features_tfidf/sms
words = model[0].get_feature_names_out()
w = model[-1].coef_[0]                        # one weight per word, in vocabulary order
order = np.argsort(w)
print("spam:", ", ".join(f"{words[i]} {w[i]:+.1f}" for i in order[::-1][:7]))
print("ham: ", ", ".join(f"{words[i]} {w[i]:+.1f}" for i in order[:7]))
has_code = sms["text"].str.contains("<#>")
print("labels of messages containing '<#>':", sms.loc[has_code, "label"].value_counts().to_dict())
spam: txt +4.1, call +4.1, free +3.2, text +3.1, reply +3.1, stop +3.0, claim +2.8
ham:  me -2.6, my -2.3, it -1.7, that -1.5, how -1.5, can -1.5, lt -1.5
labels of messages containing '<#>': {'ham': 197}

Spam words are calls to action: txt, call, free, reply, claim. Ham words are personal: me, my, how. And "lt" is a quirk of the data. It comes from &lt;#&gt;, the web-page code for <#>, which appears in 197 messages, all of them ham. The model learns whatever separates the classes, typos and quirks included.

Quick check

Quick check

1. A word appears in every training message. What idf does scikit-learn give it?

2. Bag-of-words turns "dog bites man" and "man bites dog" into…

3. Why drop duplicate messages before splitting into train and test?

Next

Day 21: Naive Bayes builds a spam filter from the same word counts with Bayes' rule, and puts it up against this one.

Data: SMS Spam Collection v.1 (UCI Machine Learning Repository, dataset 228), CC BY 4.0; cite Almeida, T. A., Gómez Hidalgo, J. M. and Yamakami, A. (2011), "Contributions to the Study of SMS Spam Filtering: New Collection and Results", Proceedings of the 2011 ACM Symposium on Document Engineering.

Next · Day 21 · 9 minNaive Bayes← Previous: Day 19 · Compress Features with PCA
Not tapped yet