Sub topic 1
Why Save a Trained Model
Prerequisites
This chapter assumes you can:
- Read and write basic Python, including imports and opening files.
- Train a scikit-learn estimator with
fitand get results withpredict. - Recognize a scikit-learn
Pipeline. Experience with one is helpful but not required.
You do not need to know how serialization works. The later chapters cover that. This chapter explains why saving a model is worth doing and what a saved model contains.
The problem: training is not prediction
A typical scikit-learn script loads data, fits an estimator, and prints a score. When the script ends, the Python process exits and the fitted model disappears from memory. To use the model again, you would have to run the whole script again, including fit.
That is acceptable for a small experiment. It becomes a problem when training is expensive or when the program that trains the model is not the program that uses it. Persistence means writing an object to disk so it outlives the process that created it. For a model, persistence separates two jobs:
- Training. Done once, or on a schedule, with the full training data.
- Prediction. Done many times, often in another process, on another machine, or weeks later.
Without persistence, every prediction process must also train. With persistence, training writes a file and prediction reads it.
What a fitted model contains
A scikit-learn estimator is an ordinary Python object. Before you call fit, it holds only the hyperparameters you chose, such as C or max_iter. After fit, it also holds what it learned from the data. By convention, scikit-learn names these learned values with a trailing underscore, such as coef_ or classes_.
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("fitted before fit:", hasattr(model, "coef_"))
model.fit(X, y)
print("fitted after fit:", hasattr(model, "coef_"))
learned = sorted(
name for name in vars(model) if name.endswith("_") and not name.startswith("_")
)
print("learned attributes:", learned)
print("coef_ shape:", model.coef_.shape)
print("hyperparameter C:", model.get_params()["C"])Running this shows that coef_ does not exist until fit runs. After fitting, the object holds coef_, intercept_, classes_, n_features_in_, and n_iter_. The coef_ array has shape (3, 4): one row of weights per class, one column per input feature.
The learned attributes are the trained model. The hyperparameters tell you how it was trained, but the learned attributes decide what it predicts. Saving a model means saving both, so the loaded object behaves like the original.
The size of the learned state varies
How much a model stores depends on the algorithm:
| Estimator type | What it stores after `fit` | Typical size |
|---|---|---|
| Linear models | One weight per feature per class, plus intercepts | Kilobytes |
| Random forest, gradient boosting | Every tree, with split points and leaf values | Megabytes to gigabytes |
| k-nearest neighbors | A copy of the training data, or an index built from it | As large as the training set |
| Scalers and encoders | Means, scales, category lists | Kilobytes |
The k-nearest neighbors row surprises many people. That model does not compress the data into weights. Its learned state is the training data, so a saved file contains training rows. Keep this in mind when the data is private. A model file can carry more of your data than you expect.
Why save a model
Training cost
Fitting can take seconds or hours. The next example fits a random forest on a synthetic data set and compares the cost of fit with the cost of predict.
import time
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
X, y = make_classification(
n_samples=50_000, n_features=40, n_informative=15, random_state=0
)
model = RandomForestClassifier(n_estimators=300, n_jobs=-1, random_state=0)
start = time.perf_counter()
model.fit(X, y)
fit_seconds = time.perf_counter() - start
start = time.perf_counter()
model.predict(X[:100])
predict_seconds = time.perf_counter() - start
print(f"fit: {fit_seconds:.2f} s")
print(f"predict: {predict_seconds:.4f} s for 100 rows")The exact numbers depend on your hardware. Fitting is typically several orders of magnitude slower than predicting a small batch. If a web service retrained at startup, every restart would pay the fit cost before answering a single request.
Reproducibility of a specific result
Training involves randomness: random initialization, shuffled data, bootstrap samples. Even with a fixed random_state, results can change when the data, library version, or number of threads changes. If a report says "the model had 91% accuracy", you need the model that produced that number. A saved file is the exact object that was evaluated. A saved training script is only a recipe for something similar.
Separating teams and environments
A common arrangement is that a data scientist trains in a notebook, and an engineer serves predictions in an application. The two can share a file, which is easier than sharing a notebook and a copy of the training data. The engineer does not need the training data at all, except for model types like k-nearest neighbors that embed it.
Retraining is not always possible
Sometimes the training data changes or is gone. Rows are deleted for privacy reasons, a database table is overwritten, or the original data was a one-time export. Retraining then produces a different model, or none. The saved model may be the only remaining artifact from that training run.
Auditing and rollback
If a new model performs worse in production, you want to return to the previous one. That is easy if each trained model is a file with a version label, such as churn-2026-11-01. It is hard if the old model exists only as a code revision plus a data snapshot that may no longer be available.
Why the preprocessing must be saved too
A model rarely receives raw data. Features are usually scaled, encoded, or imputed first, and those steps are also fitted. A StandardScaler learns a mean and a standard deviation from the training data. Predictions are only correct if new data is scaled with those same numbers.
import numpy as np
from sklearn.preprocessing import StandardScaler
train = np.array([[1.0], [2.0], [3.0], [4.0]])
scaler = StandardScaler().fit(train)
new_row = np.array([[3.0]])
print("scaled with training statistics:", scaler.transform(new_row))
print("scaled by refitting on the row: ", StandardScaler().fit_transform(new_row))The first line prints about 0.447, because the training mean is 2.5 and the training standard deviation is about 1.118. The second line prints 0.0, because a scaler fitted on a single row sees a mean equal to that value and a standard deviation of zero. The same input gives different features, so the model would receive different data than it was trained on.
This failure is silent. No exception is raised, and the predictions are simply wrong. The practical rule is to save everything that was fitted: the scaler, the encoder, the imputer, and the final estimator. The cleanest way is to put all the steps in a single Pipeline and save that one object. A later chapter covers this in detail.
The persistence workflow
The next diagram shows where saving fits. Training happens in one place and prediction in another, and the file is the only thing that travels between them.
Two steps carry the risk: saving and loading. Saving captures the learned state. Loading must rebuild the object in an environment that understands it. The rest of this tutorial covers how to do each step safely.
Options you will meet
You will use several formats over the next chapters. This table is only a map, and each format gets its own treatment later.
| Format | Where it comes from | Main strength | Main limitation |
|---|---|---|---|
| pickle | Python standard library | Works on almost any Python object | Loading can run arbitrary code; tied to Python and library versions |
| joblib | Library used by scikit-learn | Efficient for objects holding large NumPy arrays | Same security and version limits as pickle |
| skops | scikit-learn community project | Lets you inspect file contents before trusting them | Supports fewer object types than pickle |
| ONNX | Open model exchange format | Runs outside Python, in a separate runtime | Needs a conversion step; not every estimator converts |
The first two options use pickle serialization underneath. That is why they share the same two limits: a file is only safe to load if you trust its source, and it only loads reliably in a compatible environment.
What saving a model does not do
A saved model file is a snapshot of one object. It does not capture several things you may assume it does:
- The code around the model. If your pipeline uses a custom function or class, the file refers to it by name. The loading environment must be able to import that same code.
- The training data. Most models do not include it, so you cannot reproduce training from the file alone.
- The library versions. The file does not guarantee that a different scikit-learn version will interpret it correctly. Versions are a main source of problems later.
- A guarantee of quality. A model that loads without errors may still have drifted away from the real world. Saving does not replace monitoring.
Common mistakes
- Saving only the final estimator. The preprocessing steps are lost, and the application has to recreate them. Prefer saving a full
Pipeline. - Retraining on every start. This is slow and can give different results from run to run. Load a saved model instead.
- Keeping a model only in a notebook. Notebook state disappears when the kernel restarts. Write the file as an explicit step.
- Overwriting the previous file. Without a version label you cannot roll back. Use a name that includes a date or a version number.
- Treating model files as harmless data. A pickle-based file can execute code when loaded. Handle it like a program from the same source.
Summary of the idea
A fitted estimator is an object whose learned attributes make up its value. Training is usually the expensive, random, and data-dependent part, while prediction is cheap and repeated. Saving the fitted object lets you pay the training cost once, reproduce a specific result, share it between environments, and roll back to earlier versions. Everything that was fitted must be saved together, including the preprocessing, or the predictions will be wrong without any warning. The cost of persistence is that files depend on the environment that made them and can be unsafe to load, which the rest of the tutorial addresses.
Exercise
You train a LogisticRegression on features scaled by a StandardScaler. You save only the LogisticRegression. A colleague loads it in a service and passes in raw, unscaled feature values. Predictions run without errors but look wrong. What went wrong, and what should you have saved?
Show answer
The scaler's learned mean and standard deviation were not saved, so the service fed the classifier raw values on a different scale than it was trained on. No error is raised because the shapes still match. You should have saved the whole Pipeline (scaler plus classifier) as one object, so the same fitted scaler is applied before every prediction.
Exercise
A k-nearest neighbors classifier is trained on a table of customer records. Why might its saved file be a privacy concern, when a saved logistic regression trained on the same table usually is not?
Show answer
A k-nearest neighbors model's learned state is the training data itself (or an index built from it), so the file contains customer rows. A logistic regression stores only weights and intercepts, which are summaries of the data and not the rows.
Exercise
List two learned attributes of a fitted LogisticRegression, and explain how the trailing underscore helps you tell them apart from hyperparameters.
Show answer
Examples are coef, intercept, classes, and nfeaturesin. By scikit-learn convention, attributes learned during fit end with an underscore, while hyperparameters such as C and maxiter have no underscore and exist before fit is called. So hasattr(model, "coef") is False before fit and True after.