Sub topic 17
A TF-IDF text classification pipeline
Assume you know basic Python, NumPy vectors, logarithms, and the fit and predict pattern used by classifiers. This chapter combines a text vectorizer with a classifier while keeping training and evaluation data separate.
Why use a pipeline?
A classifier cannot directly use text. A TF-IDF vectorizer converts each document into a numeric vector:
- It tokenizes the text.
- It builds a vocabulary from the training documents.
- It calculates term frequency and inverse document frequency.
- It transforms each document into a TF-IDF vector.
- A classifier learns from those vectors.
A pipeline keeps these steps together. During prediction, the vectorizer reuses the vocabulary and IDF values learned during training.
Preventing fit leakage
fit means learning parameters from data. transform means applying already learned parameters. fit_transform does both.
Fit the vectorizer only on training text. If you fit it on test text too, information from the test set can influence the vocabulary, document frequencies, or IDF values. This is called data leakage. It can make evaluation look better than performance on genuinely unseen data.
A Pipeline applies the correct sequence automatically.
Building the classifier
This example classifies short reviews as positive (1) or negative (0).
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 vectorizer uses unigrams and bigrams because ngram_range=(1, 2) includes individual words and two-word phrases. With sublinear_tf=True, a term occurring many times receives a logarithmically adjusted term-frequency value. This prevents repeated words from dominating the document vector.
Choosing vectorizer settings
| Setting | Effect | Common reason to use it |
|---|---|---|
| `ngram_range=(1, 2)` | Includes words and two-word phrases | Preserve short expressions |
| `stop_words="english"` | Removes common English words | Reduce uninformative features |
| `min_df=2` | Removes very rare terms | Reduce noise and vocabulary size |
| `max_df=0.9` | Removes terms in most documents | Remove collection-wide common terms |
| `max_features=10000` | Keeps at most 10,000 features | Limit memory and training time |
Tune these settings using validation data or cross-validation. The best choice depends on the language, dataset size, and task.
Exercise
Why should a TF-IDF vectorizer be fitted on training documents rather than on all documents?
Show answer
Fitting on all documents leaks information from the test set into the features, producing an overly optimistic evaluation.