Sub topic 4
Save the whole Pipeline, not just the estimator
This chapter assumes you can fit and predict with a scikit-learn estimator, and that you know what a Pipeline is. It also assumes you have seen joblib.dump and joblib.load.
The problem with saving only the classifier
A fitted classifier expects input that looks like its training data. If you scaled, encoded, or imputed the features before training, the classifier learned from the transformed values. At prediction time, new data must go through the same transformation, using the values learned from the training set.
Suppose you save only the classifier and keep the scaler in your notebook. A month later you load the classifier in a service. Raw measurements go in, and the model receives numbers on the wrong scale. Nothing raises an error. The predictions are simply wrong.
A Pipeline avoids this. It chains the preprocessing steps and the final estimator into one object. When you call fit, each step is fitted in order. When you call predict, each step's transform runs before the final estimator's predict. The fitted state of every step lives inside the one object, so you save and load one file.
What is stored
Each fitted step holds attributes ending in an underscore. These are the learned values.
| Step | Learned state kept in the file |
|---|---|
| `StandardScaler` | `mean_`, `scale_`, `var_` |
| `SimpleImputer` | `statistics_` |
| `OneHotEncoder` | `categories_` |
| `LogisticRegression` | `coef_`, `intercept_`, `classes_` |
The file also records the settings you chose, such as max_iter. It does not store your training data, apart from what an estimator needs internally, as KNeighborsClassifier does.
Saving a fitted pipeline
This example builds a pipeline with a scaler and a classifier, fits it, and writes it with joblib.
from joblib import dump, load
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(X, y)
dump(model, "iris_model.joblib")The fitted scaler and the classifier are stored together in iris_model.joblib. To use the model later, load it and call predict on raw feature values:
loaded = load("iris_model.joblib")
print(loaded.predict([[5.1, 3.5, 1.4, 0.2]]))You pass the unscaled measurements. The loaded pipeline scales them with the mean and standard deviation it learned during training.
Common errors
- Saving the estimator, not the pipeline. If you call
dump(model[-1], ...), or you keep a separateclfvariable and dump that, the scaler is lost. Dump the outerPipelineobject. - Fitting the preprocessing outside the pipeline. If you call
scaler.fit_transform(X)by hand and then fit the classifier on the result, the pipeline has no scaler to save. Put every transformation inside the pipeline before callingfit. - Refitting after loading. Calling
fiton a loaded pipeline discards what it learned and learns from the new data. Usepredictortransformon loaded objects. - Custom code that is missing at load time. If a step uses your own function or class, such as a
FunctionTransformerthat points at a function you wrote, the file stores a reference to it by name, not its code. The loading environment must be able to import that same function from the same module. Keep custom code in an installed module, not in a notebook cell or__main__.
Inspecting a loaded pipeline
You can look inside a loaded pipeline to confirm that each step arrived with its learned state.
from joblib import load
loaded = load("iris_model.joblib")
print(loaded.steps)
print(loaded.named_steps["standardscaler"].mean_)
print(loaded[-1].coef_.shape)named_steps gives access by step name, which make_pipeline builds from the lowercase class name. Indexing with loaded[-1] returns the final estimator. If mean_ prints an array of four numbers, the scaler was fitted and saved with the model.
The next chapter checks the saved model more formally, by comparing its predictions with those of the original.
Exercise
A colleague fits a StandardScaler by hand, transforms the training data, fits a LogisticRegression on the result, and saves only the classifier with joblib. What goes wrong when the file is used in production on raw features, and how do you fix it?
Show answer
The classifier was trained on scaled values but receives raw ones, so its predictions are wrong without any error being raised. The scaler's learned mean and scale were never saved. Fix it by building make_pipeline(StandardScaler(), LogisticRegression()), fitting the pipeline on the raw training data, and saving the whole pipeline.
Exercise
After loading a pipeline from disk, you want to read the mean the scaler learned. Which expressions give it, assuming the pipeline was built with make_pipeline(StandardScaler(), LogisticRegression())?
Show answer
loaded.namedsteps["standardscaler"].mean or loaded[0].mean. Both return the fitted scaler's mean attribute.