Sub topic 16
Fitting the vectorizer on training data only
This chapter assumes you can use TfidfVectorizer and CountVectorizer, know what a train/test split is, and have seen a scikit-learn fit and predict call. You will learn what a vectorizer learns during fit, why it must learn that only from training text, and how a pipeline enforces the rule for you.
What a vectorizer learns
A vectorizer is an estimator, like a classifier. Calling fit stores state computed from the texts you pass in:
- The vocabulary. This is the mapping from each token to a column index. It is stored in
vocabulary_. - The IDF values.
TfidfVectorizercomputes one inverse document frequency per vocabulary term. They are stored inidf_. These depend on how many documents contain each term.
Calling transform applies that stored state to new text. It does not change the vocabulary or the IDF values. fit_transform is a shortcut for fit followed by transform on the same data.
The rule is that fit sees only training documents. Validation and test documents go through transform only.
from sklearn.feature_extraction.text import TfidfVectorizer
train_docs = ["the cat sat on the mat", "the dog sat on the log"]
test_docs = ["the cat chased the bird"]
vec = TfidfVectorizer()
X_train = vec.fit_transform(train_docs)
X_test = vec.transform(test_docs)
print(vec.get_feature_names_out())
print(X_train.shape, X_test.shape)
print("bird" in vec.vocabulary_)
print(vec.transform(["bird flew away"]).nnz)The test document has the same number of columns as the training matrix (7). The words "chased" and "bird" never appeared in training, so they have no column and are silently dropped. A document made only of unseen words becomes a row of zeros, and nnz (the count of stored nonzero values) is 0.
Two ways to get it wrong
Fitting on the test set separately
Calling fit_transform on the test texts builds a second vocabulary from the test documents. Its columns no longer line up with the training columns.
from sklearn.feature_extraction.text import TfidfVectorizer
train_docs = ["the cat sat on the mat", "the dog sat on the log"]
test_docs = ["the cat chased the bird"]
wrong = TfidfVectorizer()
wrong.fit(train_docs)
X_test_wrong = TfidfVectorizer().fit_transform(test_docs)
print(wrong.transform(test_docs).shape)
print(X_test_wrong.shape)The first shape is (1, 7) and the second is (1, 4). A classifier trained on 7 columns raises an error on 4. The worse case is a test vocabulary that happens to have the same size. Then no error is raised, and column 3 in the test matrix means a different word than column 3 in the training matrix. The predictions are meaningless but look normal.
Fitting on all the data before splitting
A common shortcut is to vectorize the whole corpus and then split the rows. This is data leakage: information from the test set influences the features used for training.
- The vocabulary includes words that occur only in test documents.
- The IDF values count test documents. A word that is rare in training but common in the test set gets a lower weight than training data alone would give it.
The vectorizer is unsupervised and never sees labels, so the leak is usually small. It is still wrong, for two reasons. Your evaluation no longer simulates deployment, where future text is not available at fit time. The effect also grows with small datasets, rare terms, and options such as max_features, min_df and max_df, which select the vocabulary using document counts.
| Step | Correct | Leaky |
|---|---|---|
| Learn vocabulary and IDF | Training texts only | Training and test texts together |
| Handle test texts | `transform` | `fit_transform`, or fitted on everything |
| Unseen test words | Ignored | Given a column and an IDF value |
| What the score estimates | Performance on new text | An optimistic figure |
Let a pipeline enforce the rule
A Pipeline bundles the vectorizer and classifier into one estimator. Calling fit on the pipeline fits the vectorizer on the texts it receives, then trains the classifier on the result. Calling predict only transforms. You cannot forget the rule, because there is no separate step to get wrong.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
texts = [
"great movie, loved it",
"wonderful acting and a great story",
"a joyful, moving film",
"brilliant script and lovely music",
"loved the characters",
"great fun from start to end",
"terrible plot and bad acting",
"boring, bad and far too long",
"a dull, lifeless film",
"awful script and poor music",
"hated the characters",
"bad pacing from start to end",
]
labels = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
X_train, X_test, y_train, y_test = train_test_split(
texts, labels, test_size=0.25, stratify=labels, random_state=0
)
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
LogisticRegression(max_iter=1000),
)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
print(model.predict(["loved the acting"]))The pipeline takes raw strings, not matrices. Pass lists of text to fit, predict and score.
Cross-validation needs the pipeline
Cross-validation makes the leakage problem harder to see. If you vectorize first and pass the matrix to cross_val_score, every fold's validation rows were included when the IDF values were computed. Passing the pipeline and the raw texts fixes this, because scikit-learn clones the pipeline and refits it inside each fold.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
texts = [
"great movie, loved it",
"wonderful acting and a great story",
"a joyful, moving film",
"brilliant script and lovely music",
"loved the characters",
"great fun from start to end",
"terrible plot and bad acting",
"boring, bad and far too long",
"a dull, lifeless film",
"awful script and poor music",
"hated the characters",
"bad pacing from start to end",
]
labels = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
model = make_pipeline(
TfidfVectorizer(sublinear_tf=True),
LogisticRegression(max_iter=1000),
)
scores = cross_val_score(model, texts, labels, cv=3)
print(scores.round(2))
print(scores.mean().round(2))Each fold builds its own vocabulary and IDF values from its training portion. The same applies to hyperparameter search: pass the pipeline to GridSearchCV and name parameters with the step prefix, for example tfidfvectorizer__min_df.
Edge cases to expect
- Unseen words are dropped. If most validation words are out of vocabulary, rows become sparse or empty, and predictions fall back on the classifier's intercept. Check how many validation documents have
nnz == 0when scores look strangely low. - Small training sets shrink the vocabulary. Terms that appear only in the test set cannot help, and that is the honest signal of how the model will behave on new text.
- Fitted state must travel with the model. When you save a model for deployment, save the whole pipeline. A classifier saved without its vectorizer cannot be used, because the column meanings are lost.
- Refit before production use. After you finish evaluating, you may refit the pipeline on all labeled data. That final model is no longer evaluated by that data, so keep the earlier scores as your estimate.
Exercise
A colleague runs vec.fit_transform(all_texts), splits the rows of the resulting matrix into train and test, and reports a test accuracy of 0.91. Name two things in the features that came from the test documents, and say what you would change.
Show answer
The vocabulary contains words that appear only in test documents, and the IDF values were computed using the test documents in the document counts. Both make the features reflect text the model would not have at deployment time. Split the raw texts first, then put TfidfVectorizer and the classifier in a Pipeline, fit it on the training texts only, and score it on the held-out texts. Use the pipeline inside cross_val_score or GridSearchCV if you cross-validate.
Exercise
You call vec.fit(train_docs) and then vec.transform(["zebra quartz"]), where neither word appeared in training. What does the result look like, and why does no error occur?
Show answer
The result is a 1-row sparse matrix with the same number of columns as the training matrix, and every value is zero (nnz is 0). The words are not in vocabulary_, so they are ignored, and an empty row stays empty after L2 normalization. No error occurs because dropping unseen tokens is the defined behavior of transform.