Pipeline
What it is
Pipeline([(name, step), ...]) composes any number of transformers and one final estimator into a single object. Calling fit fits each step in order, passing each one's output to the next; calling predict runs the same chain forward through the already-fitted steps.
Why it matters
It collapses a scattered sequence of notebook cells into one thing you can cross-validate, tune, pickle and deploy. Without it, 'the model' is a fitted estimator plus an oral history of what was done to the data first, and the oral history is what breaks.
In the real world: Bundling cleaning, encoding, scaling and the model into one object, so production runs exactly what was tested.
Visual example
sklearn PipelineOne object, one fit: raw columns go in the left end, a prediction comes out the right end.
Why this matters
The arrow in this picture is the artifact. Ship only the right-hand estimator and you have shipped a model that expects numbers it will never be sent.
Common misconception
Wrong idea: a pipeline is a convenience wrapper that saves a few lines of code.
Correct idea: it is the unit of reproducibility. The fitted imputation medians, scaling statistics and category vocabulary are state learnt from training data, and the pipeline is what keeps that state attached to the model that depends on it.
- 1imputeMissing
ageandincomefilled with the training median. - 2scaleNumeric columns centred and divided by the training standard deviation.
- 3encode
citybecomes one indicator column per category seen in training. - 4clfThe final step fits on the matrix the three transformers produced.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipe = Pipeline([
('scale', StandardScaler()),
('clf', LogisticRegression(max_iter=1000)),
])
pipe.fit(X_train, y_train) # fits the scaler, then the model on scaled data
pipe.predict(X_test) # scales with the TRAINING statistics, then predicts
pipe.named_steps['clf'].coef_ # the inner estimator is still reachableEvery step except the last must implement transform; the last one only needs fit/predict. Putting a classifier in the middle of a pipeline fails with an error about a missing transform, which reads as a bug in the classifier rather than as a step in the wrong slot.
Practise it: A Pipeline That Does Not Leak