Chapters
Python114 chapters

Exercises

Saving and Using a Model

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Save the trained pipeline, load it back, and predict with the loaded one.

Python needs scikit-learn, downloaded on first run
import joblib
from sklearn.datasets import load_iris
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X, y)
# save it, load it, and print a prediction
Exercise 2

Only the estimator was saved, so the scaler is lost. Save the whole pipeline instead.

Python needs scikit-learn, downloaded on first run
import joblib
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_iris(return_X_y=True)

scaler = StandardScaler().fit(X)
bare = LogisticRegression(max_iter=1000).fit(scaler.transform(X), y)
joblib.dump(bare, "model.joblib")

print(joblib.load("model.joblib").predict([[5.1, 3.5, 1.4, 0.2]])[0])
Exercise 3

Save the model together with its feature names and class names, then print the classes from the loaded file.

Python needs scikit-learn, downloaded on first run
import joblib
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression

data = load_iris()
model = LogisticRegression(max_iter=1000).fit(data.data, data.target)
# dump a dict holding the model, features and classes, then load and print the classes