Sub topic 16
Fitting the Vectorizer on Training Data Only
Assume you know basic Python, NumPy vectors, and the fit and predict steps of machine learning. This chapter focuses on a common error: allowing information from evaluation data to influence text features.
What `fit` and `transform` mean
A vectorizer learns a mapping from text to numbers.
fitlearns this mapping. ForTfidfVectorizer, it builds the vocabulary and calculates inverse document frequency values.transformapplies an already learned mapping to text.fit_transformperforms both operations on the same data.
Split your documents before fitting the vectorizer. Fit it only on the training documents. Then transform both the training and test documents with that fitted vectorizer.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
texts = [
"great movie and wonderful acting",
"excellent story and great music",
"boring plot and terrible acting",
"bad movie with a slow story",
"wonderful cast and excellent direction",
"terrible film with boring dialogue",
]
labels = [1, 1, 0, 0, 1, 0]
train_texts, test_texts, train_labels, test_labels = train_test_split(
texts,
labels,
test_size=0.33,
random_state=42,
stratify=labels,
)
vectorizer = TfidfVectorizer(ngram_range=(1, 2))
X_train = vectorizer.fit_transform(train_texts)
X_test = vectorizer.transform(test_texts)
model = LogisticRegression(max_iter=1000)
model.fit(X_train, train_labels)
print(model.score(X_test, test_labels))The test documents can contain words that were absent from the training set. The vectorizer ignores those unknown words because they have no learned columns. This is correct: the model must be evaluated using only information available during training.
Why fitting on all data leaks information
Suppose you call fit_transform on the complete collection before splitting it. The vectorizer then sees test documents while it learns:
- which terms belong in the vocabulary,
- how frequently each term appears across documents,
- which terms receive high or low IDF values.
The labels are not used, but the test texts still influence the features. This is called data leakage. It can make evaluation scores look better than performance on genuinely new data.
| Operation | Training data | Test data |
|---|---|---|
| Learn vocabulary and IDF | `fit` | Never |
| Create feature matrix | `transform` | `transform` |
| Train classifier | Yes | Never |
| Measure final score | Never | Yes |
Use a pipeline for cross-validation
A pipeline keeps vectorization and classification together. During cross-validation, each fold fits the vectorizer only on that fold's training portion.
from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), min_df=1),
LogisticRegression(max_iter=1000),
)
pipeline.fit(train_texts, train_labels)
print(pipeline.score(test_texts, test_labels))This also prevents accidental use of the wrong vocabulary when you save or reuse a model.
Exercise
Why should X_test be created with vectorizer.transform(test_texts) instead of fit_transform(test_texts)?
Show answer
transform reuses vocabulary and IDF values learned from training data. Fitting on test text leaks information into the evaluation.