Sub topic 2
Saving and Loading the Model
This chapter covers how a trained model becomes a file, and how a separate process loads it back. It assumes you can train a scikit-learn model and run Python scripts from a terminal. You don't need any web code yet. The only goal here is a reliable model.joblib file that the service can load later.
Why the model must become a file
Training and serving run in different processes, often on different machines and at different times. The training script ends and its memory is freed. The service starts later and needs the same fitted model.
The link between them is an artifact. An artifact is a file that holds everything the service needs to reproduce the model's predictions. For a scikit-learn model, this means the learned parameters (tree splits, coefficients, class labels) plus the object structure around them.
Training stays out of the service for three reasons:
- Training is slow and CPU heavy. Serving needs to answer in milliseconds.
- Training needs the full dataset. Serving only needs the finished model.
- Training results must be the same every time the service restarts. Retraining on startup would change predictions between restarts.
Training and saving
The training script below fits a random forest on the iris dataset and writes it to disk.
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import joblib
X, y = load_iris(return_X_y=True)
model = RandomForestClassifier(n_estimators=100, random_state=0)
model.fit(X, y)
joblib.dump(model, "model.joblib")Run it once:
python train.py
ls -lh model.joblibTwo details matter here:
random_state=0makes the forest reproducible. Retraining with the same data and library versions gives the same file behavior.joblib.dumpwrites the whole fitted estimator, not only the numbers. Loading it gives you back aRandomForestClassifierobject withpredictready to call.
Loading in a separate process
To confirm the artifact works on its own, load it in a fresh Python process that never imports the training code.
import joblib
model = joblib.load("model.joblib")
print(type(model).__name__)
print(model.predict([[5.1, 3.5, 1.4, 0.2]]))The first line printed is RandomForestClassifier. The prediction for this row is [0], the first iris class. Note the input shape: a list of rows, each row a list of four numbers. predict always takes a 2D input, even for one sample. The service will have to build that nested list from the request, and forgetting this is a common first error.
Why joblib and not pickle
joblib is built on Python's pickle and is the format scikit-learn's documentation recommends for estimators. Its advantage is efficient handling of large NumPy arrays, which fitted models contain in bulk. For a random forest, that means faster saves and loads and smaller memory overhead than plain pickle.
The format is still pickle underneath, which brings the following risks.
Safety and compatibility risks
Loading runs code
Unpickling can execute arbitrary code stored in the file. Only load artifacts you or your team produced and stored in a place you control.
If your service needs to accept models from outside, use a format that doesn't execute code, such as ONNX, and load it with a runtime built for that format.
Library versions must match
A pickled scikit-learn model records its class paths and internal attribute layout. Loading it under a different scikit-learn version may fail, or worse, load and behave differently. scikit-learn emits an InconsistentVersionWarning when versions differ. Treat that warning as an error in the service.
The practical rule is to pin the same versions in the training and serving environments:
scikit-learn==1.5.2
joblib==1.4.2
numpy==1.26.4Use the versions you actually trained with. You can find them by running pip freeze in the training environment.
Python version and platform
Pickled files can also depend on the Python version and on NumPy's internals. Train and serve with the same Python minor version (for example 3.11). If you build the serving image from python:3.11-slim, train with 3.11 as well.
Code the model depends on
Pickle stores references to classes and functions by name, not their source code. If your model includes a custom transformer defined in my_features.py, the service must be able to import my_features with the same name. A model that uses only built-in scikit-learn classes avoids this.
Save the preprocessing with the model
A common production failure is saving the classifier but not the preprocessing around it. If training scaled the inputs with StandardScaler, the service must scale them the same way. Otherwise predictions are wrong and nothing raises an error.
Use a Pipeline so that one artifact carries both steps:
import joblib
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
pipeline = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=200)),
])
pipeline.fit(X, y)
joblib.dump(pipeline, "pipeline.joblib")Calling predict on the loaded pipeline applies the scaler and then the classifier. The service code doesn't change. The main tutorial uses the plain random forest, which doesn't need scaling, but the pipeline approach is the safer default for real projects.
Keeping feature order stable
The model sees numbers by position, not by name. Column 0 was sepal_length during training, so it must be column 0 at serving time. If the service builds rows in a different order, the model still returns a prediction and it will be wrong.
Two habits prevent this:
- Build the row in one place in the service, with a fixed order matching training.
- Record the feature names next to the artifact, for example in a small JSON file or in your repository's documentation.
The iris order is sepal_length, sepal_width, petal_length, petal_width.
Where to store the artifact
For this tutorial, model.joblib sits beside main.py. That is fine for learning. In production, consider these options:
| Approach | Strength | Weakness |
|---|---|---|
| Copy the file into the Docker image | Simple, and the image is self-contained | Every model change needs an image rebuild |
| Download from object storage at startup | Model and code ship separately | Startup depends on the network and credentials |
| Model registry | Tracks versions and who approved them | More infrastructure to run |
The later chapters on containers and versioning return to this choice. For now, the point is that the service should treat the artifact as read-only input.
Verifying the round trip
Before building the service, check that the loaded model gives the same answers as the one in memory. This catches serialization problems early.
import joblib
import numpy as np
from sklearn.datasets import load_iris
X, _ = load_iris(return_X_y=True)
loaded = joblib.load("model.joblib")
predictions = loaded.predict(X)
print(predictions.shape)
print(np.bincount(predictions))The output is (150,) and [50 50 50]. A forest fitted on the full iris set predicts all 150 training rows, split evenly among three classes. If you kept the original model object around, you could also assert np.array_equal(model.predict(X), loaded.predict(X)).
Common errors
FileNotFoundError: model.joblib. The path is relative to the working directory, not to the script. Run the service from the folder that holds the file, or build an absolute path withpathlib.Path(__file__).parent.ModuleNotFoundErrorduring load. The artifact references a class or module that the serving environment can't import. Install it or include it in the image.InconsistentVersionWarning. Training and serving use different scikit-learn versions. Align them and retrain if needed.ValueError: Expected 2D array, got 1D array. You passed one flat list topredict. Wrap it in another list.ValueError: X has 3 features, but RandomForestClassifier is expecting 4. The service built a row with the wrong number of columns.
Exercises
Exercise
Your service loads a model that was trained with scikit-learn 1.3 while the service runs scikit-learn 1.5. The model loads and returns predictions. Why is this still a problem, and what should you do?
Show answer
The pickled model's internal layout may not match the newer library, so predictions can differ or break without a hard error. scikit-learn signals this with an InconsistentVersionWarning. Pin the same scikit-learn version in training and serving, and retrain with the serving version if you must upgrade.
Exercise
You trained a logistic regression on inputs scaled with StandardScaler, then saved only the classifier. The service sends raw measurements. What happens, and how do you fix it?
Show answer
The model returns predictions without any error, but they are unreliable because the inputs are on a different scale than during training. Fix it by saving a Pipeline that contains both the scaler and the classifier, so one artifact applies both steps in order.