Sub topic 15
Saving the Pipeline and Making Predictions
A trained model is only useful if you can use it again. This chapter closes the project. You save the fitted model to disk, load it in a fresh process, and predict on houses it has never seen. It assumes you finished the earlier chapters: you have a fitted best_model, the train/test split, and a working knowledge of pandas DataFrames. You also need to know why the test set is used once.
Why save a model at all
Training happens in your notebook. Predictions usually happen somewhere else: a web service, a scheduled job, or a colleague's laptop next week. Retraining on every start is slow and can give a slightly different model. It also needs the full training data on hand.
Saving separates the two jobs. You train once, write the fitted object to a file, and load that file wherever you need predictions.
Saving with joblib
scikit-learn models are ordinary Python objects. joblib serializes them to a file. It is the usual choice for scikit-learn because it handles the large NumPy arrays inside fitted models efficiently.
The script below is self-contained. It rebuilds the data and split, then fits a model with the same settings as the grid search candidates. In your project, use search.best_estimator_ instead.
import json
import joblib
import numpy as np
import sklearn
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Stand-in for search.best_estimator_ from the grid search chapter.
best_model = HistGradientBoostingRegressor(
learning_rate=0.1, max_leaf_nodes=31, random_state=42
).fit(X_train, y_train)
joblib.dump(best_model, "house_price_model.joblib")
# Record what the file needs in order to be used correctly later.
metadata = {
"sklearn_version": sklearn.__version__,
"features": list(X.columns),
"target": "MedHouseVal (units of $100,000)",
"test_mae": float(mean_absolute_error(y_test, best_model.predict(X_test))),
}
with open("house_price_model.json", "w") as f:
json.dump(metadata, f, indent=2)
print(metadata)Two files now exist. The .joblib file holds the model. The .json file is a small label that says which library version produced it, which columns it expects, and how well it did on the test set.
Loading and checking the round trip
Load the file and confirm that it behaves exactly like the original object. Do this once whenever you change how you save.
import joblib
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
_, X_test, _, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
loaded = joblib.load("house_price_model.joblib")
print(loaded.predict(X_test.iloc[:3]))
print("Expected feature names:", list(loaded.feature_names_in_))The model is deterministic at prediction time, so predictions from the loaded model should match the original exactly. Compare them with np.allclose(original.predict(X_test), loaded.predict(X_test)) if both objects are in the same session. A mismatch means something went wrong in saving or loading.
The attribute feature_names_in_ is useful. scikit-learn records the column names it saw during fit when you pass it a DataFrame. A loaded model can therefore tell you what input it expects.
Predicting on a new house
A new house must arrive in the same shape as the training features. That means the same eight columns with the same meaning and units. The MedInc column is in tens of thousands of dollars, and AveRooms is rooms per household, not a total.
import joblib
import pandas as pd
model = joblib.load("house_price_model.joblib")
new_house = pd.DataFrame(
[
{
"MedInc": 5.0,
"HouseAge": 20.0,
"AveRooms": 6.0,
"AveBedrms": 1.0,
"Population": 1200.0,
"AveOccup": 3.0,
"Latitude": 37.8,
"Longitude": -122.3,
}
]
)
prediction = model.predict(new_house)[0]
print(f"Predicted median value: {prediction:.3f} (units of $100,000)")
print(f"That is about ${prediction * 100_000:,.0f}")The prediction is in the target's units. The target MedHouseVal is measured in hundreds of thousands of dollars, so a prediction of 3.0 means about $300,000. Multiply by 100,000 when you show the result to someone else.
Remember also what the number means. The target is the median house value for a census block group, not the price of one specific house. A prediction for a single home is an estimate of its neighborhood's median. The test MAE you reported in the final evaluation chapter tells you the typical size of the error.
Wrong inputs fail in different ways
A loaded model does not guard you against bad inputs on its own. What happens depends on how the input is wrong.
| Input problem | What scikit-learn does | What you should do |
|---|---|---|
| Column renamed or misspelled | Raises `ValueError` about feature names | Fix the column names |
| Wrong number of columns | Raises `ValueError` about feature count | Supply all features |
| Columns in a different order, same names | Recent versions check names and raise an error | Reorder with `new_data[model.feature_names_in_]` |
| A plain NumPy array | Predicts with a warning that names are missing | Wrap it in a DataFrame with the right columns |
| Values in the wrong units | No error, wrong predictions | Validate ranges yourself |
The last row is the dangerous one. If someone enters MedInc in dollars (50000) instead of tens of thousands (5.0), the model returns a number without complaint. It extrapolates far outside the training range. In a real service, check ranges against the training data summary from df.describe() before you call predict.
Saving the whole pipeline, not only the final model
In this project the final model is a HistGradientBoostingRegressor, which needs no scaling. The model file therefore contains everything that happens between raw features and a prediction.
That changes if you save the Ridge model. Ridge needs scaled inputs, so you must save the entire pipeline, scaler included. If you saved only the Ridge step, the scaler's learned means and standard deviations would be lost. Anyone who loaded the file would have to rebuild the scaling by hand, and a small mismatch would silently degrade predictions.
import joblib
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
housing = fetch_california_housing(as_frame=True)
X = housing.frame.drop(columns="MedHouseVal")
y = housing.frame["MedHouseVal"]
ridge = make_pipeline(StandardScaler(), Ridge(alpha=1.0)).fit(X, y)
joblib.dump(ridge, "ridge_pipeline.joblib")
restored = joblib.load("ridge_pipeline.joblib")
print(restored.named_steps["standardscaler"].mean_)
print(restored.predict(X.iloc[:2]))The restored pipeline carries the scaler's mean_ values with it. Raw rows go in, and the scaler and model apply the same learned transformation as in training. The rule is simple: save the object you would call predict on, never a piece of it.
This example fits on all the data for brevity. In the project itself, you fit on X_train only, as in the earlier chapters.
Version and environment gotchas
A saved model is tied to the code that created it. These are the common failures:
- scikit-learn version change. Loading a file saved with a different scikit-learn version may emit an
InconsistentVersionWarning. It may also fail, or worse, load and behave subtly differently. Pin the same version in the environment that loads the file, and record it, as the metadata file above does. - Python and NumPy changes. Major jumps can also break loading. Keep the training and serving environments aligned, for example with a
requirements.txtthat lists exact versions. - Custom code. If your pipeline uses a function or class you defined yourself, the loading process must be able to import it from the same module path. Built-in scikit-learn components avoid this problem.
- Stale models. House prices drift over time. A model saved today and loaded in two years will still run, but its accuracy may have degraded. Store the training date and the test MAE with the file, and plan to retrain.
A checklist before you ship
- Save the object that accepts raw features and returns predictions.
- Write down the scikit-learn version, feature names, target units, and test score.
- Reload the file in a new Python process and compare its predictions to the original's.
- Check input ranges before predicting.
- Only load files you trust.
You have now gone from a question to a saved, reusable model. You framed the problem, explored the data, split it, set a baseline, built pipelines, compared models with cross-validation, tuned, evaluated once, and stored the result. The same order of steps applies to your next project.
Exercise
You save only the fitted Ridge regressor, taken out of a pipeline with the StandardScaler, and a teammate loads it to predict on raw California housing rows. Predictions look plausible but are quite inaccurate. What went wrong, and how do you fix it?
Show answer
The Ridge coefficients were learned on standardized features, but the teammate passed raw values, so the scale of every input is wrong. The model returns numbers without error but with the wrong meaning. Fix it by saving the whole pipeline (make_pipeline(StandardScaler(), Ridge())) with joblib.dump, so the scaler's learned means and standard deviations travel with the model. Then call predict on raw rows.
Exercise
A loaded model's feature_names_in_ is ['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude']. A new DataFrame has the same columns in a different order. Write one line that makes it safe to pass to predict, and name one input error that line will not catch.
Show answer
new_data = new_data[model.feature_names_in_] reorders the columns to match training. It does not catch wrong units or out-of-range values, such as MedInc given in dollars instead of tens of thousands of dollars. The model would predict without error. Check ranges against the training data yourself.