Building a Pipeline

In order to make the vectorizer => transformer => classifier easier to work with, scikit-learn provides a Pipeline class that behaves like a compound classifier:

from sklearn.pipeline import Pipeline
text_clf = Pipeline([
   ('vect', CountVectorizer()),
   ('tfidf', TfidfTransformer()),
   ('clf', MultinomialNB()),
 ])

The names vect, tfidf and clf (classifier) are arbitrary. We will use them to perform grid search for suitable hyperparameters1 below. We can now train the entire three-step model with a single command:

text_clf.fit(reviews_train, labels_train)

When you call text_clf.fit(...), the pipeline automatically calls fit_transform on vect and tfidf, and then calls fit on clf. When you call text_clf.predict(...), it automatically calls only transform on vect and tfidf before calling predict on clf—preventing data leakage automatically.

Note: In scikit-learn 1.7 and later, when you display pipeline objects in Jupyter notebooks, you’ll see enhanced HTML representations with comprehensive parameter information and a copy button for easy configuration.

Estimators and hyperparameters used in the pipeline:

Each of the estimators in the text_clf pipeline has hyperparameters that have default values but can also be set to new values. In our example we are using the default values. Here is one key hyperparameter for each:


Creative Commons License AI Programming 1 Course Materials by Brian Bird, written in are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.


  1. Hyperparameter refers to a configuration setting that is external to the model and whose value can’t be estimated from the data. Instead, a hyperparameter’s value must be set by the developer. ↩