Reading history

Save and Load Machine Learning Models in Python with joblib

6 min read 1 views

Learn to save and load scikit-learn models with joblib: keep the whole pipeline, compress files, store feature names and versions, and load models safely.

Training a model can take minutes or hours. You do not want to repeat that every time someone needs a prediction. Instead, you save the trained model to a file once, then load it in any program that needs it, such as a website, an app or a nightly report. In this lesson you will save and load scikit-learn models with joblib, keep the preprocessing with the model, and store the details you need to use it safely later.

In this lesson you will learn

  • How to save and load a model with joblib.dump and joblib.load
  • Why you should save the whole pipeline, not just the model
  • How to shrink model files with compression
  • How to store feature names and version details next to the model
  • The security rule for loading model files

You should know scikit-learn pipelines and Python JSON and file handling.

Saving and Loading a Pipeline

joblib is installed with scikit-learn. It is like Python’s pickle but handles the large NumPy arrays inside models more efficiently. We train a breast cancer classifier, save it, load it back and confirm nothing changed.

import os
import tempfile
import joblib
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
# Save the WHOLE pipeline, so the scaler travels with the model
pipe = make_pipeline(StandardScaler(), RandomForestClassifier(random_state=0))
pipe.fit(X_tr, y_tr)

folder = tempfile.mkdtemp()
path = os.path.join(folder, "cancer_model.joblib")
joblib.dump(pipe, path)                               # save to disk
print(f"saved {os.path.basename(path)}: {os.path.getsize(path) // 1024} KB")

loaded = joblib.load(path)                            # load it back
same = np.array_equal(pipe.predict(X_te), loaded.predict(X_te))
print("same predictions after loading:", same)
print(f"test accuracy of loaded model: {loaded.score(X_te, y_te):.3f}")

joblib.dump(pipe, path, compress=3)                   # smaller file
print(f"compressed: {os.path.getsize(path) // 1024} KB")

Output

saved cancer_model.joblib: 321 KB
same predictions after loading: True
test accuracy of loaded model: 0.972
compressed: 64 KB
  • joblib.dump(object, path) writes any Python object to a file. joblib.load(path) rebuilds it exactly.
  • The loaded model makes the same predictions and has the same 97.2% accuracy. Loading is instant; no training happens.
  • We saved the pipeline, so the fitted scaler is inside the file. If you saved only the forest, every program would have to rebuild the scaler with exactly the same means and spreads.
  • A random forest stores 100 trees, so the file is 321 KB. With compress=3 it drops to 64 KB. Compression makes saving and loading a little slower. Levels run from 0 to 9, and 3 is a good balance.
  • We used tempfile.mkdtemp() to get a safe folder for the demo. In your own project, use a path like "models/cancer_model.joblib".

Saving Details Next to the Model

A model file alone does not say which columns it expects or which library version made it. Store that in a small JSON file beside the model. Then any program that loads the model can check it is being used correctly.

import json
import os
import tempfile
import joblib
import pandas as pd
import sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# Loan approvals, trained on a DataFrame so column names are remembered
train = pd.DataFrame({
    "income":   [20, 35, 50, 65, 80, 25, 45, 90, 30, 70],
    "debt":     [15, 10, 20,  5, 10, 20,  5, 30, 25,  8],
    "approved": [ 0,  1,  1,  1,  1,  0,  1,  1,  0,  1],
})
features = ["income", "debt"]
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(train[features], train["approved"])

folder = tempfile.mkdtemp()
joblib.dump(model, os.path.join(folder, "loan.joblib"))
info = {"features": features, "sklearn_version": sklearn.__version__, "trained_rows": len(train)}
with open(os.path.join(folder, "loan.json"), "w") as f:
    json.dump(info, f)

# ---- later, in another program ----
model = joblib.load(os.path.join(folder, "loan.joblib"))
with open(os.path.join(folder, "loan.json")) as f:
    info = json.load(f)
if info["sklearn_version"] != sklearn.__version__:
    print("warning: model was saved with a different scikit-learn")

def predict(rows):
    df = pd.DataFrame(rows)[info["features"]]   # same columns, same order
    return model.predict_proba(df)[:, 1].round(2)

new = [{"debt": 6, "income": 60}, {"income": 22, "debt": 18}]
print("columns the model expects:", list(model.feature_names_in_))
print("approval chance:", predict(new))

Output

columns the model expects: ['income', 'debt']
approval chance: [0.92 0.35]
  • The JSON file records the feature list, the scikit-learn version and how many rows the model learned from.
  • The loading part warns if the installed scikit-learn differs from the one that saved the model. Files are not guaranteed to work across versions.
  • Models trained on a DataFrame remember their column names in feature_names_in_.
  • The first new row lists debt before income. Our predict function reorders the columns using the saved list, so the order of the input does not matter.
  • The applicant earning 60 with debt 6 gets a 92% approval chance; the one earning 22 with debt 18 gets 35%.

Ways to Save a Model

MethodGood forWatch out for
joblibscikit-learn models; the usual choiceSame Python and library versions needed
pickleAny Python objectSlower and larger for big arrays
skopsSharing models more safelyA separate package
ONNXRunning in other languages or on phonesNeeds a converter; not every model is supported

Security rule

Loading a joblib or pickle file can run code hidden inside it. Only load model files you created yourself or got from a source you fully trust. Never load a model file sent by a stranger.

Common Mistakes

  1. Saving the model but not the preprocessing. Save the full pipeline so scaling and encoding come along.
  2. Loading with a different scikit-learn version. Pin your versions, for example in requirements.txt, and record them with the model.
  3. Passing columns in a different order. Use a DataFrame with named columns, or reorder with a saved list.
  4. Retraining on every request. Load the model once when the program starts, then reuse it for every prediction.

Practice Exercises

Exercise 1. Add the test accuracy and the date of training to the JSON file in sv2.py.

Show answer
from datetime import date
info["trained_on"] = date.today().isoformat()
info["test_accuracy"] = round(float(test_score), 3)

Compute test_score on a held-out set first. float and round are needed because JSON cannot store NumPy number types.

Exercise 2. A web app predicts for each visitor. Where should joblib.load go: inside the predict function or at the top of the program?

Show answer

At the top, so it runs once when the app starts. Loading inside the function would read the file from disk on every request and slow the app down.

Frequently Asked Questions

What file extension should I use for a joblib model?

Any extension works, but .joblib is the common choice and makes the format clear. Some people use .pkl.

Can I keep training a loaded model with new data?

Only for models that support partial_fit, such as SGDClassifier and MultinomialNB. Calling fit on a loaded model throws away what it learned and starts again.

Summary

  • joblib.dump saves a trained model; joblib.load brings it back instantly.
  • Save the whole pipeline so preprocessing travels with the model.
  • Keep feature names and versions in a JSON file beside it.
  • Only load model files from sources you trust.

Next: Machine Learning Project: Customer Segmentation.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *