Sub topic 15
Saving the Pipeline and Making Predictions
This chapter continues the house price project. It assumes that best_model and the split data (X, X_test) already exist from the earlier chapters, and that you know how to call fit and predict.
Why save the model
Training happens once, but predictions happen many times. If you keep the model only in memory, you have to rerun the whole notebook each time you need a price. Saving the fitted model to a file lets another script or session load it and predict right away.
The diagram shows the two sessions involved.
Saving and loading with joblib
scikit-learn models are Python objects. joblib stores them efficiently, including the large NumPy arrays inside them.
import joblib
joblib.dump(best_model, "house_price_model.joblib")
loaded = joblib.load("house_price_model.joblib")
print(loaded.predict(X_test.iloc[:3]))The loaded model should give the same predictions as best_model. Checking this on a few rows is a cheap test that the file round-trips correctly.
Save the whole pipeline
In this project the final model is a gradient boosting regressor, which needs no scaling. If your final model includes preprocessing, such as the StandardScaler and Ridge pipeline from earlier, save the whole pipeline object. A saved model without its scaler will accept raw numbers and silently give wrong answers, because it expects scaled input.
Predicting for a new house
New data must be a DataFrame with the same column names, in the same meaning and units, as the training data. The target is in units of $100,000, so convert the output when you report it.
import pandas as pd
import joblib
model = joblib.load("house_price_model.joblib")
new_houses = pd.DataFrame(
[
{
"MedInc": 5.0,
"HouseAge": 20.0,
"AveRooms": 6.0,
"AveBedrms": 1.0,
"Population": 1200.0,
"AveOccup": 3.0,
"Latitude": 34.0,
"Longitude": -118.3,
}
]
)
price = model.predict(new_houses)[0] * 100_000
print(f"Predicted price: ${price:,.0f}")MedInc is the median income of the block in tens of thousands of dollars, so 5.0 means $50,000. The other columns are block-level averages, not single-house values.
Common errors
- Version mismatch. A file saved with one scikit-learn version may fail to load, or behave differently, under another. Record the version when you save, and use the same version when you load.
- Wrong columns. Missing, renamed, or reordered columns cause errors or warnings. Build new inputs from the same column list you trained on, for example
new_houses[X.columns]. - Saving only part of the workflow. Save the fitted object you evaluated on the test set, not a freshly created, unfitted copy.
- Retraining on the fly. Loading a file does not refit anything. If the data changes, you must retrain and save again.
You can store the version next to the model:
import json
import sklearn
with open("house_price_model.json", "w") as f:
json.dump({"sklearn_version": sklearn.__version__}, f)Where the project ends
You framed the problem, explored and split the data, set a baseline, and compared Ridge with gradient boosting using cross-validation. You tuned the better model, scored it once on the test set, and checked which features it relies on. Saving the model is the last step, and it makes the result usable.
Exercise
You load a saved model in a new script and call predict on a DataFrame whose columns are in a different order than the training data. Why is this risky, and how do you reduce the risk?
Show answer
The model expects each feature in a fixed position, and wrong order or missing names can cause errors, warnings, or silently wrong predictions. Reduce the risk by selecting columns with the training column list, for example new_houses[X.columns], before calling predict.