Save and load models

joblib.dump, joblib.load, and the download chip.

joblib.dump writes a fitted estimator to /uploads. After Run, click on the chip. joblib.load reads it back. Dump the pipeline, not a naked model, if you scaled or encoded.

Goal

Dump a fitted pipeline, load it, and check that predictions match.

Dump and load

import os
import joblib
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=80, n_features=4, random_state=0)
clf = LogisticRegression(max_iter=200)
clf.fit(X, y)
joblib.dump(clf, "model.joblib")
loaded = joblib.load("model.joblib")
print("uploads:", os.listdir("/uploads"))
print("same predict", np.array_equal(clf.predict(X[:8]), loaded.predict(X[:8])))

Pipeline

import joblib
from sklearn.datasets import make_classification
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=80, n_features=4, random_state=0)
pipe = Pipeline(
    [
        ("scale", StandardScaler()),
        ("clf", LogisticRegression(max_iter=200)),
    ]
)
pipe.fit(X, y)
joblib.dump(pipe, "pipe.joblib")
loaded = joblib.load("pipe.joblib")
print(loaded.predict(X[:5]))

Loading pipe.joblib restores the scaler means and the classifier weights together.

Pitfall

A model dumped from this tab is a Python pickle. Load it in a matching sklearn version. Do not load joblib files from untrusted people — pickle can run code.