Start learning free

LESSON 129 OF 165 · MACHINE LEARNING: SERVING A MODEL

A /predict Route in Python

Practice

Your file already trains a model when it starts: a scikit-learn pipeline that guesses from five numbers whether a customer will buy again. To let other programs use it, you serve it: a route takes a customer's numbers as JSON and answers with the model's guess. The numbers travel in the request body, so the route answers POST.

A model reads tables, not dicts. A list holding one dict makes a one-row DataFrame, and columns= picks which keys become columns, and in what order. Keys you don't list are left out:

house = {"size": 50, "rooms": 2, "city": "Oslo"}
row = pd.DataFrame([house], columns=["rooms", "size"])
print(row)
#    rooms  size
# 0      2    50

model.predict(table) gives back a numpy array with one answer per row. The model must get its columns in the order it was trained with, and its answer is a numpy number, which jsonify can't write until you turn it into a plain int.

Your finished route must answer the test requests like this:

POST /predict  {"visits": 10, "orders": 4, "spent": 260, "days_since_last": 15, "returned_item": 0}
   →  200  {"bought_again": 1}
POST /predict  {"visits": 2, "orders": 1, "spent": 15, "days_since_last": 240, "returned_item": 1}
   →  200  {"bought_again": 0}
POST /predict  {"customer_id": 42, "returned_item": 0, "days_since_last": 40, "spent": 160, "orders": 3, "visits": 7}
   →  200  {"bought_again": 1}
POST /predict  {"visits": 5, "orders": 2, "spent": 90, "days_since_last": 40, "returned_item": 0}
   →  200  {"bought_again": 0}

Your task: below app, add a POST /predict route that reads the JSON body, builds a one-row DataFrame with the COLUMNS, asks the model, and answers {"bought_again": 1} or {"bought_again": 0}.


Assignment
Follow the Coding Tutorial to build the /predict route that serves the model.


Hint
Extra keys such as customer_id are fine: columns=COLUMNS leaves them out. model.predict(row) gives an array, so take its item at index 0, and wrap it in int() so jsonify can write it.


STEP 1 OF 6
    Ctrl + Enter to check

    Serve Predict in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free