Sub topic 17
A TF-IDF text classification pipeline
This chapter assumes you know the following:
- Basic Python.
- The
fitandpredictpattern of scikit-learn classifiers. - How
TfidfVectorizerturns documents into a sparse, L2-normalized matrix. - How
min_df,max_dfandngram_rangechange the vocabulary.
Here you combine the vectorizer and a classifier into one object, and you learn which mistakes break it.
Why use a pipeline
A TF-IDF classifier has two learned parts:
- The vectorizer learns a vocabulary and one IDF value per term.
- The classifier learns one weight per term, or per term for each class.
Both parts must learn only from training texts. If IDF values are computed on the full dataset, the test documents influence the features, and your evaluation score becomes too optimistic. This is a form of data leakage.
A Pipeline runs the steps in order. fit calls fit_transform on the vectorizer and passes the result to the classifier. predict calls only transform on the vectorizer, so the vocabulary and IDF stay frozen.
A minimal pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
train_texts = [
"great movie, loved it",
"wonderful acting and a great story",
"terrible plot and bad acting",
"boring, bad and far too long",
]
train_labels = [1, 1, 0, 0]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
LogisticRegression(max_iter=1000),
)
model.fit(train_texts, train_labels)
print(model.predict(["loved the acting"]))The settings in this example:
ngram_range=(1, 2)adds two-word phrases such as "great story".sublinear_tf=Truereplaces a raw counttfwith1 + ln(tf). A word repeated ten times then counts for about 3.3 times a single occurrence, not ten times.max_iter=1000gives the solver enough iterations to converge.
Words in a new text that were not in the training vocabulary are silently ignored. If a text has no known words, its vector is all zeros and the classifier falls back to its intercept.
Why a linear model fits
TF-IDF matrices have thousands of columns, and most entries are zero. Linear models such as logistic regression and linear SVMs work well on this shape for these reasons:
- They train quickly on sparse input.
- With many more features than documents, they can often separate the classes.
- Each weight belongs to one term, so you can read the model.
L2 normalization from the previous chapter keeps long and short documents on the same scale, so document length does not dominate the weights.
Inspecting what the model learned
Pipeline steps are available by name. make_pipeline lowercases the class name to build the step name.
import numpy as np
vectorizer = model.named_steps["tfidfvectorizer"]
classifier = model.named_steps["logisticregression"]
terms = vectorizer.get_feature_names_out()
weights = classifier.coef_[0]
order = np.argsort(weights)
print("most negative:", terms[order[:5]])
print("most positive:", terms[order[-5:]])For a binary classifier, coef_[0] holds one weight per term. Positive weights push toward class 1 and negative weights toward class 0. Check this list for terms that should not matter, such as a name, a date or a formatting artifact. These often reveal a shortcut the model uses instead of the real signal.
Tuning the whole pipeline
Vectorizer settings are hyperparameters, so tune them together with the classifier. If you fit the vectorizer once on all the data and then cross-validate only the classifier, leakage returns. Put both in one pipeline and pass the pipeline to GridSearchCV. Each cross-validation fold then refits the vectorizer on that fold's training part only.
Parameter names use the pattern stepname__parameter.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
texts = [
"great movie, loved it",
"wonderful acting and a great story",
"a moving film with superb acting",
"loved the story and the music",
"terrible plot and bad acting",
"boring, bad and far too long",
"awful script and a dull story",
"hated the movie, a terrible waste",
]
labels = [1, 1, 1, 1, 0, 0, 0, 0]
pipe = Pipeline([
("tfidf", TfidfVectorizer()),
("clf", LogisticRegression(max_iter=1000)),
])
grid = {
"tfidf__ngram_range": [(1, 1), (1, 2)],
"tfidf__sublinear_tf": [False, True],
"clf__C": [0.1, 1.0, 10.0],
}
search = GridSearchCV(pipe, grid, cv=2, scoring="accuracy")
search.fit(texts, labels)
print(search.best_params_)
print(round(search.best_score_, 2))Eight documents are far too few for a trustworthy choice, so treat the printed result as a demonstration only. On real data, use a held-out test set that the search never sees. Then evaluate once with classification_report.
Choosing settings
| Setting | Effect | Typical choice |
|---|---|---|
| `ngram_range=(1, 2)` | Captures short phrases such as "not good", and grows the vocabulary quickly | Try it first, and combine with `min_df` |
| `min_df=2` to `5` | Drops terms that are too rare to generalize, and shrinks the matrix | Use on corpora with thousands of documents |
| `max_df=0.8` to `0.95` | Drops terms that appear in almost every document | Use as an alternative to a stop word list |
| `sublinear_tf=True` | Dampens repeated words | Often helps on longer documents |
| `C` in logistic regression | Controls regularization. Smaller values mean stronger regularization | Search on a log scale, such as 0.1, 1 and 10 |
| `class_weight="balanced"` | Reweights errors on rare classes | Use when classes are imbalanced |
Change one setting at a time when you can. Too many interacting options make it hard to explain why a score changed.
Common errors
- Fitting the vectorizer before the split. Calling
fit_transformon all texts and then splitting leaks IDF statistics into the test set. Put the vectorizer in the pipeline, or split first. - Calling
fit_transformon the test set. This builds a second vocabulary, so the columns no longer match the classifier's weights. Usepredicton the pipeline, ortransformon the vectorizer alone. - Pruning too hard. A large
min_dfon a small corpus can leave an empty vocabulary. Scikit-learn then raises "After pruning, no terms remain." - Using accuracy on imbalanced data. A model that always predicts the majority class can score high. Look at per-class precision and recall, or macro F1.
- Preprocessing mismatch. Lowercasing, stop words and tokenization must be identical at training and prediction time. Keep them inside the vectorizer so that they are.
- Saving only the classifier. Persist the whole pipeline with
joblib.dump. The classifier is meaningless without the vocabulary and IDF values that built its columns.
Limits to expect
A TF-IDF pipeline is a strong baseline that is fast to train and easy to debug. It does not see word order beyond the n-gram window. It also treats "excellent" and "superb" as unrelated columns, and any word absent from training contributes nothing. If a TF-IDF baseline plateaus, consider pretrained embeddings or a fine-tuned transformer. Keep the baseline as a point of comparison.
Exercise
A teammate fits a TfidfVectorizer on all 10,000 labeled reviews, then splits the matrix into train and test parts and reports test accuracy. Why is the score unreliable, and how do you fix it?
Show answer
The IDF values and the vocabulary were computed using the test documents, so information from the test set influenced the features (data leakage). Split the raw texts first, or put the vectorizer and classifier in one Pipeline and fit it on the training texts only. Then evaluate on the test texts with predict, which only calls transform.
Exercise
In a Pipeline built with Pipeline([("tfidf", TfidfVectorizer()), ("clf", LogisticRegression())]), what key would you use in a GridSearchCV grid to try min_df values of 1 and 2?
Show answer
"tfidf_mindf", with the value list [1, 2].