Sub topic 1
Why Save a Trained Model
A fitted scikit-learn estimator is an object in memory. When your Python process ends, it is gone. This chapter explains what a fitted model holds, why you save it, and what could go wrong. Later chapters cover the how in detail.
Prerequisites
This chapter assumes you have:
- Basic Python, including reading and writing files and using imports.
- Experience calling
fitandpredicton a scikit-learn estimator. - Some familiarity with scikit-learn pipelines. This is helpful but not required.
What a fitted model contains
Before fit, an estimator holds only its hyperparameters, such as C or max_iter. After fit, it also holds the state it learned from the data. scikit-learn names these attributes with a trailing underscore.
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)
print(hasattr(model, "coef_"))
model.fit(X, y)
print(hasattr(model, "coef_"))
print(model.coef_.shape)
print(model.classes_)The first print shows False and the second shows True. After fitting, coef_ has shape (3, 4): one row of weights per class and one column per feature. classes_ lists the labels the model can predict.
Saving a model means writing this learned state, together with the hyperparameters, to disk. The data you trained on is usually not stored, though some estimators keep a copy. A k-nearest neighbors model, for example, must keep its training samples to make predictions.
Why persist a model
Training and prediction often happen at different times and in different places. Saving the model lets you separate them.
- Avoid retraining. Training can take minutes or hours. Loading a saved file takes seconds.
- Get repeatable results. Retraining on the same data can give slightly different models if randomness is involved. A saved file gives you the exact model you evaluated.
- Deploy to another process. A web service or a scheduled job can load the model without having the training data or training code.
- Share and audit. A colleague can load the same model you tested, and you can keep a record of what was in production on a given date.
What you must save
The model alone is often not enough. If you scaled or encoded features before training, new data needs the same transformations with the same fitted values. A scaler fitted on your training set stores a mean and a standard deviation. Fitting a new scaler on new data would give different numbers, and the model would receive inputs on a different scale than the one it learned from.
The safe pattern is to save the whole preprocessing and model chain as one object, which is what a Pipeline provides. A later chapter shows this in full.
What can go wrong
Saving is easy, but loading a file safely requires care. Two risks matter most.
- Security. The standard formats are based on Python's
pickle, which can run arbitrary code when a file is loaded. A file from an untrusted source can harm your system. - Version mismatch. A file saved with one scikit-learn version may fail to load in another. Worse, it may load and give wrong results without any error.
You can reduce both risks by recording library versions next to the model and by considering safer formats. Both topics have their own chapters.
The plan for the next chapters
The following chapters build up in order:
- Saving with
pickle, the standard library tool. - Saving with
joblib, which handles large NumPy arrays well. - Saving a full
Pipeline. - Checking that a loaded model matches the original.
- Compression, security, versions, metadata, and alternative formats such as skops and ONNX.
- Loading a model once and reusing it for many predictions.
Exercise
You fit a StandardScaler on your training features, then train a classifier on the scaled output. You save only the classifier. Why will predictions on new raw data be unreliable, and what should you save instead?
Show answer
The classifier learned from scaled inputs, but the fitted scaler (its mean and standard deviation) was not saved. New raw data would reach the classifier on a different scale, or you would have to fit a new scaler on different data, which gives different values. Save the whole Pipeline, containing both the fitted scaler and the classifier, as one object.
Exercise
Name two reasons to save a trained model and one risk of loading a saved model file.
Show answer
Reasons: avoid retraining, which saves time; deploy the exact evaluated model to another process; share or audit the model. Risks: loading a pickle-based file from an untrusted source can run arbitrary code, and a file saved with a different scikit-learn version may fail or give wrong results.