typestar

Saving a fitted model in Python

joblib writes the whole fitted pipeline, preprocessing included.

import joblib
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=500))
model.fit(X, y)

joblib.dump(model, "iris.joblib")
restored = joblib.load("iris.joblib")

print(restored.predict(X[:3]))
print(f"{restored.score(X, y):.3f}")

How it works

  1. Dump the pipeline, not just the final estimator.
  2. A loaded model predicts without refitting.
  3. Pin your library versions: a pickle is not a stable format.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
463
Tokens
110
Three-star pace
115 tpm

At the three-star pace of 115 tokens a minute, this run takes about 57 seconds.

Type this snippet

Step 3 of 3 in Beyond the basics, step 24 of 25 in Machine learning with scikit-learn.

← Previous Next →