Start learning free

LESSON 64 OF 165 · MACHINE LEARNING: DOING IT RIGHT

Save and Load a Model

Practice

Training takes data and time, so you train once and save the result to a file. Later, the shop's app loads that file and predicts for new customers without training again. What you save is the fitted object itself, with everything it learned.

Saving and loading: joblib.dump(thing, file_name) writes any Python object to a file. joblib.load(file_name) reads the file and gives back the same object, ready to use.

import joblib
prices = {"Notebook": 7, "Pen": 2}
joblib.dump(prices, "prices.joblib")
back = joblib.load("prices.joblib")
print(back["Pen"])  # 2

What to save: your pipeline has two fitted steps. The StandardScaler learned each column's mean and spread, and the LogisticRegression learned its weights on the scaled numbers. pipeline[-1] gives back the last step, the model alone, like the last item of a list. Save only that, and the loaded model gets raw numbers it never learned on: no error, just different answers. Save the whole pipeline, and new rows are scaled the way the training rows were.

To compare two arrays of answers, (a == b).sum() counts the rows where they agree: == compares them row by row into Trues and Falses, and .sum() counts the Trues.

Your script must print (the last line comes from a check that runs after your code and loads model.joblib):

Trained pipeline, score: 0.72
Only the model, same answers: 55 of 75
Whole pipeline, same answers: 75 of 75
model.joblib holds: Pipeline

Your task: the starting code trains a pipeline that scales the columns and predicts bought_again, keeps its answers for X_test in answers and prints its score. Save only pipeline[-1] to "only_model.joblib", load it back into only_model and count how many of its answers match. Then save the whole pipeline to "model.joblib", load it into loaded and count again.


Assignment
Follow the Coding Tutorial to save and load the model alone, then the whole pipeline, and compare their answers with the trained pipeline's.


Hint
joblib.dump takes the object first and the file name second; joblib.load takes only the file name. Count the matching answers with (... == answers).sum(), and print len(answers) after "of".


STEP 1 OF 6
    Ctrl + Enter to check