Start learning free

LESSON 130 OF 165 · MACHINE LEARNING: SERVING A MODEL

Send the Probability Too

Practice

A bare 0 or 1 hides how sure the model is: a customer with a 0.93 chance and one with a 0.54 chance both get a 1. A classifier can also give the probability behind its answer, and the client can use it, for example to email the surest customers first.

model.predict_proba(table) gives back one row per customer with two numbers: the chance of 0, then the chance of 1. You then pick the 0 or 1 yourself by comparing the chance of 1 with a cut, the threshold. Give the cut a name at the top of the file, so it can be moved in one place. Python's one-line if/else picks between two values:

ADULT_AGE = 18

def label_for(age):
    return "adult" if age >= ADULT_AGE else "child"

print(label_for(18))   # adult
print(label_for(12))   # child

Round the probability with round(probability, 3), so the answer is short and the same on every run. Your finished route must answer:

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

Your task: add the constant THRESHOLD = 0.5, write a helper answer_for(probability) that returns {"bought_again": ..., "probability": ...}, and make predict answer with the chance of 1 from predict_proba.


Assignment
Follow the Coding Tutorial to add the threshold, the answer_for helper and the probability to /predict.


Hint
In predict_proba(row)[0][1], row 0 is your only customer and column 1 is the chance of 1. A chance exactly at the threshold counts as a 1, so compare with >=.


STEP 1 OF 7
    Ctrl + Enter to check