Sub topic 5
Turning text into features with TF-IDF
This chapter assumes you can run Python with scikit-learn installed. It also assumes you know what a training set and a test set are, and that you have read the earlier chapters on framing the task and normalizing noisy text. A classifier cannot read sentences, so it needs numbers. TF-IDF is the standard way to produce those numbers for a first sentiment baseline.
From text to vectors: the bag-of-words idea
A bag-of-words representation turns each document into a vector with one position per vocabulary term. The vocabulary is every distinct token seen in the training texts. Word order is discarded, which is why it is called a "bag".
The simplest version stores raw counts. The review "great phone great battery" becomes a vector in which great has the value 2, phone has 1, battery has 1, and every other vocabulary term has 0. Real vocabularies hold tens of thousands of terms, so these vectors are mostly zeros. scikit-learn stores them as sparse matrices, which keep only the nonzero entries.
Raw counts have a weakness. Words such as the, phone, and it appear in almost every review, so they get large counts without telling you anything about polarity. TF-IDF corrects for this.
What TF-IDF computes
TF-IDF multiplies two quantities for each term in each document.
- Term frequency (TF) is how often the term appears in this document.
- Inverse document frequency (IDF) measures how rare the term is across the whole training corpus. Terms found in many documents get a low IDF. Terms found in few documents get a high IDF.
scikit-learn's default IDF is smoothed:
idf(t) = ln((1 + n) / (1 + df(t))) + 1
Here n is the number of training documents and df(t) is the number of those documents containing t. After multiplying TF by IDF, each document vector is scaled to unit length (L2 normalization). Long reviews then do not dominate short ones just because they contain more words.
A small worked example
Run this on three tiny reviews. You can check the numbers by hand.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"great phone great battery",
"terrible battery",
"great screen",
]
vec = TfidfVectorizer()
X = vec.fit_transform(docs)
print(X.shape) # (3 documents, 5 terms)
for term, idf in zip(vec.get_feature_names_out(), vec.idf_):
print(f"{term:10s} {idf:.3f}")
print(X.toarray().round(2))The vocabulary is battery, great, phone, screen, terrible, in alphabetical order. With n = 3:
greatandbatteryeach appear in 2 documents, so their IDF is ln(4/3) + 1 ≈ 1.288.phone,screen, andterribleeach appear in 1 document, so their IDF is ln(4/2) + 1 ≈ 1.693.
For the first review, the raw TF-IDF values are battery 1.288, great 2 × 1.288 = 2.575, and phone 1.693. After L2 normalization the first row is about [0.39, 0.77, 0.51, 0, 0]. The repeated word great carries the most weight. The rarer word phone outweighs battery, even though both appear once in this review.
Notice that TF-IDF knows nothing about sentiment. It weights words by how distinctive they are, not by whether they are positive. The classifier in the next chapter learns which weighted terms predict which label.
The tokenizer decides what the model can see
TfidfVectorizer first splits text into tokens. Its defaults were designed for general documents, and they cause several quiet problems with reviews and social posts.
| Default behavior | Effect on sentiment text |
|---|---|
| Token pattern `(?u)\b\w\w+\b` keeps only tokens of 2 or more word characters | `don't` becomes `don`, because `t` is dropped. Single-character tokens are lost. |
| Punctuation is ignored | `!!!` and `?` vanish, though they often signal intensity. |
| Emojis are not word characters | They are discarded entirely. |
| `lowercase=True` | `GREAT` and `great` merge, so shouting is lost. |
| No stop-word removal unless requested | Fine for sentiment, as explained below. |
The next example uses a custom token pattern that keeps contractions together and treats each punctuation mark or emoji as its own token. It also adds bigrams, which are pairs of adjacent words.
from sklearn.feature_extraction.text import TfidfVectorizer
train = [
"not good at all",
"good value",
"not bad",
"really bad!",
"don't buy this",
]
vec = TfidfVectorizer(
token_pattern=r"(?u)\b\w[\w']*\b|[^\w\s]",
ngram_range=(1, 2),
sublinear_tf=True,
)
vec.fit(train)
print(sorted(vec.vocabulary_)[:12])
new = vec.transform(["not good, honestly great"])
print(vec.inverse_transform(new)[0]) # only terms seen during fitThe bigram not good becomes its own feature, separate from good. A linear model can then give it a negative weight even though good alone is positive. This is the cheapest way to capture simple negation. The last line shows that honestly and great are silently dropped, because they were not in the training vocabulary.
Parameters that matter for sentiment
| Parameter | What it does | Guidance |
|---|---|---|
| `ngram_range=(1, 2)` | Adds bigrams | Usually a clear gain on sentiment. Trigrams add many rare features for little benefit. |
| `min_df` | Drops terms found in fewer than this many documents | Use 2 to 5 on real data to remove typos and one-off tokens. |
| `max_df` | Drops terms found in more than this share of documents | Rarely needed. IDF already down-weights common words. |
| `max_features` | Keeps only the most frequent terms | Caps memory use. Prefer `min_df` first. |
| `sublinear_tf=True` | Uses `1 + ln(tf)` instead of `tf` | Helps when a word repeated many times should not dominate. |
| `lowercase` | Lowercases text | Keep it on unless you have tested that casing helps. |
| `stop_words` | Removes a fixed word list | Avoid for sentiment, as explained below. |
Fit on training data only
The vectorizer learns two things during fit: the vocabulary and the IDF weights. If you fit it on the whole dataset before splitting, the test set influences those weights. That is data leakage, and it makes your evaluation look better than it should.
The safe pattern is to call fit_transform on the training texts and only transform on everything else. In a scikit-learn Pipeline, this happens automatically, including inside cross-validation. That is the main reason to put the vectorizer and classifier in one pipeline.
At prediction time, any word not seen in training is ignored. For social posts this matters, because slang, new hashtags, and misspellings appear constantly. A post made mostly of unseen words becomes a near-empty vector. The classifier then falls back on its bias term, which usually means it predicts the majority class. Watch for this when you test on a new domain.
Common errors
- Fitting on test data. Symptom: unusually good test scores that disappear on live data. Fix: fit only on training data, or use a pipeline.
- Forgetting that features are sparse. Calling
.toarray()on a matrix with 50,000 terms and 100,000 documents will exhaust memory. Keep the matrix sparse and pass it directly to scikit-learn estimators. - Cleaning too aggressively. Stripping all punctuation and emojis before vectorizing removes signal. The normalization chapter keeps them for this reason, so make sure your tokenizer can see them.
- Mixing normalization between training and serving. If you replace URLs with
<url>in training, apply the same step in production. Otherwise the model sees tokens it never learned. - Reading IDF as sentiment. A high-IDF word is rare, not negative or positive. Only the classifier's learned weights carry polarity.
Limits of TF-IDF
TF-IDF treats great and excellent as unrelated columns. It cannot tell that "the film was not what I expected" is mixed, and sarcasm is invisible to it unless a specific phrase happens to predict the label. Contextual models handle these cases better, which is why the pretrained transformer chapter comes later. TF-IDF remains valuable because it is fast, needs no GPU, and gives a baseline whose features you can inspect directly. If a more complex model cannot beat it, the extra complexity is not justified.
Exercise
A teammate fits TfidfVectorizer(stop_words="english") on product reviews and reports that the classifier often labels "not good" as positive. Give two reasons this can happen, and name one change to the vectorizer for each reason.
Show answer
Reason 1: the English stop-word list contains not, so the text becomes "good" and the negation is gone. Fix: remove stop_words, or pass a custom list that excludes negators. Reason 2: unigrams treat not and good as independent features, so a model cannot learn that the pair means something different from good alone. Fix: set ngram_range=(1, 2) so that not good becomes its own feature. A third possible issue is the default token pattern splitting don't into don, which can be fixed with a custom token_pattern that keeps apostrophes inside tokens.
Exercise
You have 4 training documents. The word refund appears in exactly one of them. With scikit-learn's default smoothed IDF, what is the IDF of refund, rounded to 3 decimals?
Show answer
idf = ln((1 + 4) / (1 + 1)) + 1 = ln(2.5) + 1 ≈ 0.916 + 1 = 1.916.