Sub topic 8
Putting It Together in a Pipeline
Prerequisites
This chapter assumes that you know basic Python, training and test splits, NumPy-style arrays, and the purpose of supervised learning. You should also know that text must be converted into numeric features before a machine-learning model can use it.
A scikit-learn Pipeline connects several processing steps into one estimator. For text classification, the usual steps are:
TfidfVectorizerlearns a vocabulary and converts documents into sparse TF-IDF vectors.LogisticRegressionlearns class boundaries from those vectors.- The pipeline applies the same transformations automatically when you call
predict.
The pipeline keeps preprocessing and model training together. This reduces mistakes and makes cross-validation safer.
How the pipeline works
During fit, the pipeline performs these operations:
- It fits the vectorizer on the training documents.
- It transforms the training documents into TF-IDF features.
- It fits logistic regression on those features.
During predict, it does not learn anything new. It uses the vocabulary and IDF values already learned during training, transforms the new documents, and passes the resulting vectors to the classifier.
The test set must not influence the vocabulary, document frequencies, or IDF weights. If you vectorize all documents before splitting them, information from the test set leaks into training. A pipeline helps prevent this when it is fitted only on the training data.
Building and evaluating a complete pipeline
The following example uses three small classes: space, cars, and politics. The split is stratified, so each class appears in both subsets.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
texts = [
"rocket launch reached orbit",
"astronaut studied moon rocks",
"space telescope found a galaxy",
"mission control tracked satellite",
"brake pads need replacement",
"engine oil protects the car",
"tire pressure improves driving",
"mechanic repaired the vehicle",
"election debate discussed taxes",
"parliament passed a new bill",
"voters chose a mayor",
"government announced a policy",
]
labels = [
"space", "space", "space", "space",
"cars", "cars", "cars", "cars",
"politics", "politics", "politics", "politics",
]
classes = sorted(set(labels))
X_train, X_test, y_train, y_test = train_test_split(
texts,
labels,
test_size=0.25,
random_state=7,
stratify=labels,
)
model = make_pipeline(
TfidfVectorizer(
sublinear_tf=True,
ngram_range=(1, 2),
min_df=1,
),
LogisticRegression(
C=1.0,
max_iter=1000,
),
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(classification_report(y_test, predictions, labels=classes))
print(confusion_matrix(y_test, predictions, labels=classes))
print(model.predict(["the satellite entered orbit"]))ngram_range=(1, 2) includes single words and two-word sequences. sublinear_tf=True reduces the effect of repeatedly occurring words. C controls regularization: smaller values constrain the model more strongly, while larger values allow it to fit the training data more closely.
The fitted vectorizer and classifier are available through named pipeline steps. For a pipeline created with make_pipeline, scikit-learn generates names from the class names:
vectorizer = model.named_steps["tfidfvectorizer"]
classifier = model.named_steps["logisticregression"]
print(len(vectorizer.get_feature_names_out()))
print(classifier.classes_)These objects are useful for inspection, coefficient analysis, and saving a trained model. In production, save the whole pipeline rather than saving only the classifier. The classifier expects the exact feature ordering created by the vectorizer.
Pipelines and cross-validation
A pipeline is especially important during hyperparameter tuning. GridSearchCV can clone and refit the complete pipeline for every fold and parameter combination. This means each fold learns its own vocabulary from only that fold's training portion.
For example, a search can tune both feature extraction and classification:
from sklearn.model_selection import GridSearchCV
search = GridSearchCV(
model,
{
"tfidfvectorizer__ngram_range": [(1, 1), (1, 2)],
"logisticregression__C": [0.1, 1.0, 10.0],
},
cv=3,
scoring="f1_macro",
)
search.fit(X_train, y_train)
print(search.best_params_)The double underscore separates the pipeline step name from its parameter name.
Exercise
Why should TfidfVectorizer and LogisticRegression be placed in the same pipeline when using cross-validation?
Show answer
The pipeline refits the vectorizer inside each training fold, preventing validation documents from influencing the vocabulary or IDF weights.