How to save and load a Machine Learning model in Python
After training a Machine Learning model, retraining it every time you need a prediction wastes time and resources. The solution is to save the model to a file and load it when you need it — in a script, an API, or a production service. You'll learn how to save and load a model with joblib, the most common approach in the scikit-learn ecosystem, using a ready-to-run example.
Prerequisites
- Python 3.9 or later installed.
- scikit-learn installed with
pip install scikit-learn.joblibis already included as a dependency. - Basic knowledge of how to train a model (we use a simple, reproducible example).
Step 1: Train an example model
To keep the result reproducible, we train a classifier on the Iris dataset, which ships with scikit-learn. You can swap in any model of your own — the saving process is the same.
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(random_state=42)
model.fit(X_train, y_train)
print("Accuracy:", model.score(X_test, y_test))
Step 2: Save the model with joblib.dump
Once the model is trained, saving it to disk is a single line. The joblib.dump function takes the model object and a file name; by convention we use the .joblib extension.
import joblib
joblib.dump(model, "iris_model.joblib")
This creates the file iris_model.joblib in the current folder, holding everything the model learned. scikit-learn recommends joblib over the standard pickle because it is more efficient at storing objects with large NumPy arrays, such as those inside forests or neural networks.
Step 3: Load the model and make a prediction
In another script — or on another day — you load the model with joblib.load and use it as if you had just trained it. Note that you don't need to call fit again.
import joblib
loaded_model = joblib.load("iris_model.joblib")
# Predict a new sample (4 measurements of one flower)
new_sample = [[5.1, 3.5, 1.4, 0.2]]
print("Predicted class:", loaded_model.predict(new_sample))
The loaded model has exactly the same state as the original, so it returns the same predictions.
Step 4: Save the whole Pipeline (avoid a common mistake)
A very common mistake is to save only the model and forget the preprocessing — for example, the StandardScaler that normalized the data. If training used transformed data, prediction must apply exactly the same transformation. The safe approach is to bundle everything into a Pipeline and save the whole pipeline as a single file.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
pipeline.fit(X_train, y_train)
joblib.dump(pipeline, "iris_pipeline.joblib")
Now the file stores the scaling and the model. When you load the pipeline, preprocessing is applied automatically before every prediction, so you no longer risk forgetting a step.
Verify the result
To confirm the save worked, compare the predictions of the original model with those of the loaded model — they must be identical:
import numpy as np
original = model.predict(X_test)
loaded = joblib.load("iris_model.joblib").predict(X_test)
print("Identical?", np.array_equal(original, loaded)) # True
Also check that the iris_model.joblib file exists in the folder. If you see a version warning when loading, make sure you use the same scikit-learn version you saved with, because different versions can cause incompatibilities.
Security: only load.joblibfiles from sources you trust. Likepickle, joblib can execute code while loading a file, so never open models from an unknown origin.
Conclusion
You can now save and load a model with joblib and, more importantly, save the full Pipeline so preprocessing always travels with the model. The natural next step is to version your files (for example, iris_model_v1.joblib) and serve predictions through an API. What will you name your first model in production?