Sub topic 8
Putting it together in a Pipeline
This chapter assumes you can read basic scikit-learn code and understand the training/test split. It also assumes you know what a document-term matrix is, how TF-IDF weights terms, and what logistic regression does with a feature matrix. Earlier chapters covered each of those pieces. Here you combine them into one object, fit it correctly, and learn the errors that appear most often.
Why a Pipeline
A text classifier has two learned stages. The vectorizer learns a vocabulary and an IDF value for each term. The classifier learns one weight per term for each class. Both stages learn from data, so both must see only the training data.
A common mistake is to run the vectorizer on the full dataset and then split the result into train and test. This leaks information. The vocabulary and the IDF values then contain facts about the test documents. The test score looks better than it really is.
A Pipeline chains the stages into one estimator. Calling fit on a pipeline fits the vectorizer on the training text only. It then transforms that text and fits the classifier on the result. Calling predict on new text applies the already-fitted vectorizer with transform and passes the result to the classifier.
A first look at the vectorizer
Before building the pipeline, look at the vectorizer alone on three tiny documents.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"cats and dogs are pets",
]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(docs)
print(X.shape)
print(vectorizer.get_feature_names_out())
print(X.toarray().round(2))fit_transform does two things in one call. It builds the vocabulary from docs, then returns a sparse matrix with one row per document and one column per term. Each row is L2-normalized by default, so every document vector has length 1. This keeps long documents from dominating only because they have more words.
Note that cat and cats are separate columns. The default tokenizer does no stemming. Words such as the appear in two documents, so they receive a lower IDF than words that appear in one.
Building the full pipeline
The next example uses the 20 Newsgroups dataset. It trains on three categories and evaluates on the official test subset.
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.pipeline import make_pipeline
categories = ["sci.space", "rec.autos", "talk.politics.misc"]
remove = ("headers", "footers", "quotes")
train = fetch_20newsgroups(subset="train", categories=categories, remove=remove)
test = fetch_20newsgroups(subset="test", categories=categories, remove=remove)
model = make_pipeline(
TfidfVectorizer(sublinear_tf=True, ngram_range=(1, 2), min_df=2, stop_words="english"),
LogisticRegression(C=1.0, max_iter=1000),
)
model.fit(train.data, train.target)
pred = model.predict(test.data)
print(classification_report(test.target, pred, target_names=test.target_names))The first call downloads the dataset and caches it on disk, so it needs network access once.
What each choice does
remove=("headers", "footers", "quotes")strips metadata that identifies the newsgroup. Without it, the model can score highly by reading email addresses and signatures instead of the message content. The result would not transfer to other text.sublinear_tf=Truereplaces the raw term count with1 + log(count). A word that appears 20 times is not treated as 20 times more important than a word that appears once.ngram_range=(1, 2)adds two-word phrases to the vocabulary, such asspace shuttle.min_df=2drops terms that appear in fewer than two training documents. This removes typos and one-off tokens and shrinks the matrix.stop_words="english"removes a built-in list of common function words.C=1.0sets the inverse regularization strength. Smaller values mean stronger regularization.max_iter=1000gives the solver enough steps to converge on high-dimensional data. The default of 100 often triggers a convergence warning on text.
Why `make_pipeline`
make_pipeline names each step automatically from its lowercase class name. Here the names are tfidfvectorizer and logisticregression. You use these names to reach into the pipeline and to set parameters. If you prefer explicit names, use Pipeline([("tfidf", ...), ("clf", ...)]). Both forms behave the same.
What happens during fit and predict
The table shows which method each stage receives.
| Pipeline call | Vectorizer receives | Classifier receives |
|---|---|---|
| `fit(X, y)` | `fit_transform(X)` | `fit(matrix, y)` |
| `predict(X)` | `transform(X)` | `predict(matrix)` |
| `predict_proba(X)` | `transform(X)` | `predict_proba(matrix)` |
| `score(X, y)` | `transform(X)` | `score(matrix, y)` |
Only fit changes the vectorizer. Every other call uses the vocabulary and IDF values learned from the training text. Terms in new documents that are not in that vocabulary are ignored silently.
Inspecting a fitted pipeline
You can reach any step by name with named_steps.
import numpy as np
vectorizer = model.named_steps["tfidfvectorizer"]
classifier = model.named_steps["logisticregression"]
feature_names = vectorizer.get_feature_names_out()
print(len(feature_names))
print(classifier.coef_.shape)
for i, label in enumerate(train.target_names):
top = np.argsort(classifier.coef_[i])[-10:][::-1]
print(label, list(feature_names[top]))classifier.coef_ has one row per class and one column per vocabulary term. For three classes, the shape is (3, number_of_terms). Sorting a row shows the terms that push a document toward that class. The pipeline slice model[:-1] also gives you everything except the final classifier, which is useful when you want the transformed matrix for debugging.
Tuning the whole pipeline
Parameters of every step can be tuned together. A grid search refits the whole pipeline on each fold, so the vectorizer sees only that fold's training portion.
from sklearn.model_selection import GridSearchCV
param_grid = {
"tfidfvectorizer__ngram_range": [(1, 1), (1, 2)],
"logisticregression__C": [0.1, 1.0, 10.0],
}
search = GridSearchCV(model, param_grid, cv=5, scoring="f1_macro", n_jobs=-1)
search.fit(train.data, train.target)
print(search.best_params_)
print(round(search.best_score_, 3))The key format is stepname__parametername, with two underscores. This is how the grid reaches parameters inside the pipeline. This setup runs 6 combinations times 5 folds, which is 30 fits, plus one final refit on all training data with the best parameters. The details of cross-validation belong to a later chapter. The point here is that the pipeline makes the procedure leak-free without extra code.
Common errors
The failures below come up repeatedly when people first build text pipelines.
- Calling
fit_transformon test data. This refits the vectorizer on the test set, so the test matrix has a different vocabulary than the one the classifier was trained on. The column counts may not match, and even when they do, the columns mean different terms. Usetransformon test data, or callpredicton the pipeline, which does this for you. - Fitting the vectorizer outside the pipeline. This is the leakage described earlier. The error is silent. Nothing crashes, and the scores are simply too good.
- A
ConvergenceWarningfrom the solver. Raisemax_iter. If the warning persists, try a smallerC, since very weak regularization on sparse data can make the optimization hard. - Leaking label information through the text. Headers, footers, and quoted replies in newsgroup data reveal the source. The same happens with real data that includes ticket IDs, agent names, or templates that correlate with the label. Inspect the top coefficients; if they are names or addresses rather than content words, you have a leak.
- Passing a single string to
predict. The pipeline expects an iterable of documents. A bare string is treated as a sequence of characters. Wrap it in a list:model.predict(["The rocket reached orbit"]). - Changing the vectorizer settings and reusing an old fitted object. After changing a parameter, call
fitagain. A fitted vectorizer does not update itself.
Saving and reusing the pipeline
Because the pipeline contains the vectorizer and classifier together, you save one object and get consistent preprocessing at prediction time.
import joblib
joblib.dump(model, "newsgroups_model.joblib")
loaded = joblib.load("newsgroups_model.joblib")
print(loaded.predict(["The rocket reached orbit after a perfect launch."]))
print(loaded.predict_proba(["The rocket reached orbit after a perfect launch."]).round(3))Load a saved model only from sources you trust, and use the same scikit-learn version that saved it. The file format is pickle-based, and loading an untrusted file can run arbitrary code. Version changes can also break old files or change behavior.
Design choices to keep in mind
- Keep preprocessing inside the pipeline. If you add custom cleaning, such as lowercasing special tokens or replacing numbers, wrap it in the vectorizer's
preprocessorortokenizerargument, or write a transformer class. Cleaning done outside the pipeline must be repeated by hand in production, which invites mismatches. - Sparse in, sparse through. The vectorizer returns a sparse matrix and
LogisticRegressionaccepts it directly. Do not call.toarray()on a large matrix. A vocabulary of 100,000 terms across 50,000 documents would need tens of gigabytes as a dense array. - Set
random_statewhere it applies. Some solvers, such assagaandsag, shuffle the data. Settingrandom_statemakes results repeatable. - Cache expensive steps if needed.
Pipeline(..., memory="cache_dir")caches fitted transformers. It helps when a grid search varies only the classifier's parameters, because the vectorizer need not be refit for each setting.
Exercise
A colleague fits TfidfVectorizer on all 10,000 labeled documents, splits the resulting matrix 80/20, trains LogisticRegression on the 80%, and reports the score on the 20%. Name the problem, explain how it affects the score, and describe the fix.
Show answer
The vocabulary and IDF values were learned from all documents, including the 20% used for testing. Information about the test set influences the features, which is data leakage, and it tends to make the test score look better than it would on truly new text. The fix is to split the raw text first, then build a pipeline of the vectorizer and classifier and call fit on the training portion only. The pipeline then fits the vocabulary and IDF on the training text and applies them to the test text with transform.
Exercise
In a pipeline made with make_pipeline(TfidfVectorizer(), LogisticRegression()), write the keys you would use in a grid search to vary the minimum document frequency (values 1, 2, 5) and the solver (values "liblinear", "lbfgs").
Show answer
The keys are "tfidfvectorizer_mindf" with [1, 2, 5] and "logisticregression__solver" with ["liblinear", "lbfgs"]. The step name comes first, followed by two underscores and the parameter name.
Exercise
After fitting the pipeline, model.predict("rocket launch") returns an array with 13 entries instead of one. Why, and how do you fix it?
Show answer
The pipeline treats a string as an iterable of documents, so each character becomes its own one-character document, and the result has one prediction per character. Pass a list containing the string: model.predict(["rocket launch"]).