Start learning free

LESSON 39 OF 165 · MACHINE LEARNING: YOUR FIRST MODEL

Predict for a New Customer in Python

Practice

A model is only useful if you can ask it about someone it has never seen. You do that by giving it a row that looks exactly like the rows in X: the same columns, with the same names, in the same order. model.feature_names_in_ gives back the names of the columns the model learned from, in that order.

pd.DataFrame(...) builds a table from a dict: each key becomes a column name and each list holds that column's values, top to bottom. Two values per list give two rows; one value per list gives one row:

pair = pd.DataFrame({"visits": [5, 8], "orders": [1, 0]})
print(pair.to_string())
#    visits  orders
# 0       5       1
# 1       8       0

model.predict(new) gives back an array with one answer per row, so [0] takes the only one. model.predict_proba(new) gives back one row of two chances, and [0, 1] takes row 0, column 1: the chance of a 1. If the columns come in another order, scikit-learn stops with a ValueError instead of quietly reading orders as visits.

Your finished script prints this (the last three lines come from the lesson's check, which swaps two of your columns):

The model learned from: ['visits', 'orders', 'spent', 'days_since_last', 'returned_item']
   visits  orders  spent  days_since_last  returned_item
0      12       3    180               15              0
Will buy again: 1
Chance: 0.854
Columns in another order: ValueError
  The feature names should match those that were passed during fit.
  Feature names must be in the same order as they were in fit.

Your task: below the print, build a one-row DataFrame new for a customer with 12 visits, 3 orders, 180 spent, 15 days since the last order and no returned item. Print it with .to_string(), then print the model's answer for it and its chance of a 1, rounded to 3 digits.


Assignment
Follow the Coding Tutorial to build a one-row DataFrame for a new customer and ask the model about it.


Hint
Write the dict's keys in the same order as the list the script prints first: visits, orders, spent, days_since_last, returned_item. Wrap each value in a list, like [12].


STEP 1 OF 4
    Ctrl + Enter to check

    Ml New Customer 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