Sub topic 4
Save the whole Pipeline, not just the estimator
This chapter assumes you can fit and call predict on a scikit-learn estimator, and that you have saved a model with joblib.dump and joblib.load. You should know what a Pipeline is. The chapter explains why the saved object should be the whole pipeline, what the file contains, and which parts of a pipeline do not survive a save and load.
The problem: a model is more than its classifier
A classifier only works on data that looks like the data it was trained on. In real projects, the raw data goes through preprocessing first. Examples are scaling numbers, encoding categories, filling missing values, and selecting columns. Each of these steps learns something during fit:
StandardScalerlearns a mean and a standard deviation per column.OneHotEncoderlearns the list of categories it saw.SimpleImputerlearns the fill value for each column.- A feature selector learns which columns to keep.
These learned values are the fitted state of the step. They are stored as attributes that end in an underscore, such as mean_, scale_, and categories_. If you save only the final classifier, you lose all of that state. The classifier then expects inputs transformed in a way you can no longer reproduce exactly.
The usual failure looks like this:
from joblib import dump, load
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
scaler = StandardScaler().fit(X)
clf = LogisticRegression(max_iter=200).fit(scaler.transform(X), y)
# Only the classifier is saved. The scaler is lost.
dump(clf, "clf_only.joblib")
loaded_clf = load("clf_only.joblib")
raw_predictions = loaded_clf.predict(X)
scaled_predictions = loaded_clf.predict(scaler.transform(X))
print("agree on raw input:", (raw_predictions == scaled_predictions).mean())The script runs without error. That is the danger. The loaded classifier accepts raw measurements and returns labels, but it was trained on standardized values. Feeding it raw values gives predictions that differ from the correct ones for some rows. Nothing warns you, because the shapes match.
You could also refit a new StandardScaler on the data you are about to predict. That is worse. The scaler would learn the mean and spread of the new batch, not the training set. A batch of one row would have zero spread.
Persist a Pipeline as one object
A Pipeline chains preprocessing steps and a final estimator into one estimator. Calling fit fits every step in order. Calling predict runs the data through every fitted step and then the final model. Saving the pipeline saves every step together with its fitted state.
from joblib import dump
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")One file now holds the fitted scaler and the fitted classifier. The code that loads it needs no knowledge of how the data was prepared:
from joblib import load
from sklearn.datasets import load_iris
X, _ = load_iris(return_X_y=True)
loaded = load("iris_model.joblib")
print(loaded.predict(X[:3]))The loader passes raw measurements to predict, and the pipeline applies the saved scaling itself.
A realistic example with mixed column types
Real tables mix numeric and categorical columns. A ColumnTransformer applies different preprocessing to different columns, and you can put it inside a pipeline. The next example trains on a small pandas table and saves the whole pipeline.
import pandas as pd
from joblib import dump, load
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame(
{
"age": [22, 35, 58, 44, 29, 61, 38, 50],
"plan": ["basic", "pro", "pro", "basic", "basic", "pro", "basic", "pro"],
"churned": [1, 0, 0, 1, 1, 0, 1, 0],
}
)
X = df[["age", "plan"]]
y = df["churned"]
preprocess = ColumnTransformer(
[
("num", StandardScaler(), ["age"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
]
)
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression())])
model.fit(X, y)
dump(model, "churn_pipeline.joblib")
loaded = load("churn_pipeline.joblib")
new_rows = pd.DataFrame({"age": [30, 55], "plan": ["basic", "enterprise"]})
print(loaded.predict(new_rows))
print(loaded.predict_proba(new_rows))Three details matter here.
- The input is a DataFrame with named columns. The
ColumnTransformerselects columns by name, so the code that callspredictmust supply a DataFrame with the same column names. A bare NumPy array would fail, because the string names"age"and"plan"cannot be matched to positions. handle_unknown="ignore"matters for serving. The category"enterprise"never appeared in training. With the default setting, the encoder raises an error. With"ignore", the unknown category becomes a row of zeros. You choose this when you build the pipeline, and it travels with the saved file.- The loader needs no preprocessing code. It does not import
StandardScalerorOneHotEncoderby name. Pickle imports them for you from the saved references.
You can inspect the learned state of a step inside the loaded pipeline. This is a good way to confirm what was saved:
prep = loaded.named_steps["prep"]
scaler = prep.named_transformers_["num"]
encoder = prep.named_transformers_["cat"]
print("age mean:", scaler.mean_)
print("plan categories:", encoder.categories_)The values are the ones computed from the training table, not from new_rows.
What a pipeline file contains, and what it does not
A pipeline file stores the structure of the pipeline, every step's hyperparameters, and every step's fitted attributes. It does not store your training data, your training script, or the Python code of any function you wrote yourself.
| Item | Saved in the file? | Notes |
|---|---|---|
| Step order and names | Yes | Same `named_steps` after loading |
| Hyperparameters | Yes | For example `max_iter`, `handle_unknown` |
| Fitted attributes (`mean_`, `coef_`, `categories_`) | Yes | This is the learned state |
| Training data | No | Except for estimators that keep it, such as k-nearest neighbors |
| Source code of scikit-learn classes | No | The same version must be installed when loading |
| Source code of your own functions | No | Only a reference by module and name is stored |
| Input column names and order | Partly | Recorded as `feature_names_in_` when fitted on a DataFrame |
The last row is useful. When you fit on a DataFrame, scikit-learn records the column names in feature_names_in_. If someone later passes a DataFrame with different names, scikit-learn raises an error. That check protects you from reordered columns.
Some estimators do store training data. A k-nearest neighbors model keeps the whole training set, so its file grows with the data and may contain sensitive records. Check the file size and content before you share it.
Custom code inside a pipeline
Pipelines can include your own steps, for example a FunctionTransformer that wraps a function. Pickle does not store the function body. It stores the function's module and name, and looks it up again on load.
This has two consequences:
- A
lambdaor a function defined inside another function cannot be pickled by reference. Saving fails with an error. - A function defined in a regular module must be importable when you load the file. If the module is renamed, moved, or missing, loading fails.
Define the function in a module that is part of your package. Here is a small module and a script that uses it:
# features.py
import numpy as np
def log_income(values):
return np.log1p(values)# train.py
import numpy as np
from joblib import dump
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
from features import log_income
X = np.array([[10.0], [100.0], [1000.0], [10000.0]])
y = np.array([1.0, 2.0, 3.0, 4.0])
model = make_pipeline(FunctionTransformer(log_income), LinearRegression())
model.fit(X, y)
dump(model, "income_model.joblib")Any script that calls load("income_model.joblib") must be able to run import features. Put features.py in the same package you deploy with the model. If you edit log_income later, old saved models use the new behavior, because only the name was saved. Treat such edits as a change to the model, and retrain and re-save.
Check what you saved
After saving, load the file in a fresh Python process, not in the same session. A fresh process shows missing imports and missing modules that your running session hides. Then compare predictions with the original model. The next chapter covers that check in detail, so here is the short form:
import numpy as np
from joblib import load
loaded = load("iris_model.joblib")
assert np.array_equal(loaded.predict(X), model.predict(X))
assert np.allclose(loaded.predict_proba(X), model.predict_proba(X))Run it from a separate script. If the original model is not available there, save a small set of reference inputs and their expected predictions when you train, and compare against those.
Common errors
- Saving the estimator, then scaling by hand in the serving code. The scaler in the serving code is almost always refit or rebuilt, and drifts from training. Save the pipeline instead.
- Fitting preprocessing outside the pipeline on all the data. If you scale the full dataset before cross-validation, information from the test folds leaks into training. Putting the scaler inside the pipeline fixes both leakage and persistence at once.
- Loading with a different column order or names. A pipeline fitted on a DataFrame checks names. A pipeline fitted on a NumPy array checks only the number of columns, so reordered columns pass silently. Prefer DataFrames for tabular data you will serve.
- Saving a pipeline that was never fitted.
dumpaccepts it without complaint.predictthen fails after loading with aNotFittedError. Fit first. - Lambdas and local functions in
FunctionTransformer. These cannot be pickled by reference. Use named functions in an importable module.
Summary
- Fitted preprocessing steps hold learned state. Losing it breaks the match between training and serving.
- Put preprocessing and the model in one
Pipeline, fit it once, and save that single object. - A
ColumnTransformerinside the pipeline lets the saved model accept raw DataFrame columns. - The file stores structure, hyperparameters, and fitted attributes. It stores references to your own functions, not their code.
- Test the file by loading it in a new process and comparing predictions.
Exercise
You trained a model by running StandardScaler().fit_transform(X_train) and then fitting a RandomForestClassifier on the result. You saved only the classifier with joblib.dump. A colleague loads it and calls predict on raw feature values. Name the problem, and describe how to restructure the code so that the saved file works on raw values.
Show answer
The classifier was trained on standardized values, but the scaler and its learned mean and standard deviation were not saved. The classifier receives raw values on a different scale, so it returns unreliable predictions with no error. Build make_pipeline(StandardScaler(), RandomForestClassifier()), call fit(X_train, y_train) on the pipeline, and save the pipeline with joblib.dump. The loaded pipeline then scales raw input with the training mean and standard deviation before predicting.
Exercise
A pipeline contains FunctionTransformer(lambda x: x * 2). What happens when you call joblib.dump on it, and what change makes it saveable?
Show answer
Saving fails, because pickle stores functions by module and name and a lambda has no importable name. Define the function with def in a module that is part of the deployed package, pass it to FunctionTransformer, and make sure that module can be imported wherever the file is loaded.
Exercise
A pipeline was fitted on a DataFrame with columns age and plan. At serving time a request is converted to a DataFrame with the columns in the order plan, age. What do you expect, and why is this safer than fitting on a NumPy array?
Show answer
Because the pipeline recorded feature_names_in_ when it was fitted on a DataFrame, and a ColumnTransformer selects columns by name, the columns are matched by name and the prediction is correct (or scikit-learn raises an error if names are missing or different). A pipeline fitted on a plain array checks only the column count, so swapped columns would be used in the wrong positions without any error.