Sub topic 2
Saving and loading the model
This chapter assumes you can train a scikit-learn model, run Python scripts, and read basic terminal output. You do not need any web knowledge yet.
Why the model must live in a file
Training and serving run in different processes, often on different machines and at different times. The service cannot retrain on every start, because that is slow and the result can change. Instead, training writes the fitted model to disk. The service reads that file. The file is called a model artifact.
Saving the model
Scikit-learn models are Python objects that hold learned values, such as tree splits. The joblib library serializes them efficiently, including large NumPy arrays. This script trains a small classifier on the iris dataset and saves it.
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")Running it creates model.joblib in the current directory. Setting random_state=0 makes the training repeatable, which helps when you compare artifacts later.
Loading the model in another process
To confirm the artifact works on its own, load it in a fresh Python session. Do not reuse the training script's variables.
import joblib
model = joblib.load("model.joblib")
print(model.predict([[5.1, 3.5, 1.4, 0.2]]))The output is a NumPy array such as [0]. The value is a class index, not a species name. The service you build later returns this index.
Note that the input is a list of rows. Even one sample must be wrapped in an outer list, because predict expects a two-dimensional shape of rows by features. A flat list raises a ValueError.
Common errors
- Version mismatch. A file saved with one scikit-learn version may fail or behave differently under another. Loading can raise warnings or exceptions. Pin the same library versions in training and serving.
- Wrong working directory.
joblib.load("model.joblib")uses a relative path. If you start the service from another folder, you getFileNotFoundError. Use an absolute path or set the working directory deliberately. - Feature order. The model does not store column names when trained on plain arrays. The serving code must pass features in the same order used in training. For iris that is sepal length, sepal width, petal length, petal width.
What to store alongside the model
The artifact alone does not tell you which data or code produced it. Even in a small project, record the scikit-learn version, the training date, and the feature order in a note or a small JSON file next to the model. A later chapter on versioning builds on this habit.
| Item | Why it matters |
|---|---|
| Library versions | Prevents load failures and silent behavior changes |
| Feature order | Keeps request fields mapped to the right columns |
| Training date | Helps you tell artifacts apart |
Exercise
You trained a model on your laptop and saved it with joblib. The service in production raises an error when loading it. Name two likely causes and one way to prevent each.
Show answer
One cause is a scikit-learn version difference between training and serving. Prevent it by pinning the same version in both environments. Another cause is a wrong relative path, giving FileNotFoundError. Prevent it by using an absolute path or starting the service from the directory that holds the file.