Start learning free

LESSON 133 OF 165 · MACHINE LEARNING: SERVING A MODEL

Train Once, Load at Start

Practice

Right now your app learns from customers.csv every time it starts. With a big table, every start waits for the training; and if the file changed in between, the app quietly serves a different model. Real services train once, save the fitted model to a file, and load that file at every start.

Saving and loading: joblib.dump(thing, file_name) writes a Python object to a file, and joblib.load(file_name) gives it back as it was. os.path.exists(file_name) tells you whether a file is there:

prices = {"Mug": 12, "Notebook": 7}
joblib.dump(prices, "prices.joblib")
saved = joblib.load("prices.joblib")
print(saved["Mug"])                     # 12
print(os.path.exists("prices.joblib"))  # True

For the model, save the whole fitted pipeline, scaler and model together, so the loaded copy scales and predicts exactly as before. A health route tells whoever runs your app that it is up and which model it serves. model.feature_names_in_ holds the columns the pipeline was fitted on, in order; list() turns them into a list jsonify can write.

The requests your code must answer. The check puts a saved model.joblib in place before your file starts, so your file must load it, not train; it also deletes the file and calls train() to see that it saves the pipeline.

GET /health
  →  200  {"version": "v1", "columns": ["visits", "orders", "spent", "days_since_last", "returned_item"]}
POST /predict  {"visits": 10, "orders": 4, "spent": 260, "days_since_last": 15, "returned_item": 0}
  →  200  {"bought_again": 1, "probability": 0.928}

Your task: at the end of train, save pipeline to "model.joblib". Below train, call it only when that file doesn't exist yet, then load the file into model. At the end of the file, add GET /health answering MODEL_VERSION as "version" and the model's columns as "columns".


Assignment
Follow the Coding Tutorial to save the model in train, load it at start, and add the /health route.


Hint
Only train() goes inside the if; the load line sits below it, so it runs on every start. For the columns, use list(model.feature_names_in_).


STEP 1 OF 7
    Ctrl + Enter to check