Sub topic 1
Saving and Loading a Trained scikit-learn Model
Prerequisites
This chapter assumes basic Python, file handling, and scikit-learn knowledge. You should know how fit trains an estimator and how predict uses it.
Why save a trained model
Training can take time and may require data that is unavailable in a production application. Saving a fitted model, called persistence, lets you reuse its learned state without training again.
A saved estimator contains values learned during fit. For example, a linear model stores coefficients, while a decision tree stores its learned tree structure. The file does not usually contain the original training data.
A typical workflow is:
Persistence separates training from prediction. You can train during deployment preparation, save the result, and load it when a service starts.
Saving with pickle
pickle is Python’s built-in object serialization module. Serialization converts an object into bytes that can be written to a file.
import pickle
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
model = LogisticRegression(max_iter=200).fit(X, y)
with open("model.pkl", "wb") as file:
pickle.dump(model, file)
with open("model.pkl", "rb") as file:
loaded_model = pickle.load(file)
print(loaded_model.predict(X[:3]))The modes "wb" and "rb" mean write-binary and read-binary. The loaded object is a fitted LogisticRegression instance.
Saving and loading with joblib
joblib provides a convenient persistence API that often handles models containing large NumPy arrays efficiently.
from joblib import dump, load
dump(model, "model.joblib")
loaded_model = load("model.joblib")
print(loaded_model.predict(X[:3]))Use joblib when your model is Python-specific and you want convenient handling of typical scikit-learn objects. For production use, also record the Python and library versions used to create the file. Compatibility problems can occur when those versions differ.
Exercise
Why must you save a fitted estimator instead of an unfitted estimator?
Show answer
Only the fitted estimator contains the learned parameters needed to make predictions.