Start learning free

LESSON 119 OF 165 · MACHINE LEARNING: RECOMMENDERS

Recommend for One Customer in Python

Practice

The similarity table says which products go together. To recommend for one customer, give every product a score: the sum of its similarities to everything that customer bought. A product close to all of their purchases gets the biggest score. Then drop what they already own and keep the three highest scores.

A toy example: a customer bought Bread and Jam. Butter is 0.75 similar to Bread and 0.5 to Jam, so it scores 0.75 + 0.5 = 1.25. A Bag is 0.5 and 0.25, so it scores 0.75. Butter comes first.

The pandas tools: similarity[owned], with a list of names, keeps only those columns. .sum(axis=1) adds across each row and gives back a Series with one total per product (plain .sum() would add down each column instead). .drop(owned) gives back a copy without those labels, and .sort_values(ascending=False) gives back a copy sorted from the highest value down. The starting code already has bought(customer_id), which gives back the list of products a customer bought, and the line return list(scores.index[:3]), which gives back the first three names.

Your code prints three customers (an office fan, a kitchen fan and a home fan), then the check below it counts how many of the 292 customers get each product recommended:

5 ['Notebook', 'Pen'] -> ['Stapler', 'Gift card', 'Teapot']
13 ['Teapot'] -> ['Mug', 'Gift card', 'Lamp']
19 ['Plant'] -> ['Lamp', 'Gift card', 'Mug']
How many of the 292 customers get each product recommended:
Lamp         148
Mug          128
Pen          117
Teapot       112
Plant         99
Gift card     95
Notebook      91
Stapler       70

Your task: inside recommend, add up the similarity columns of the owned products in scores, drop the owned products and sort from the highest score down. Below the function, print the customers 5, 13 and 19 with what they bought and what they get recommended.


Assignment
Follow the Coding Tutorial to finish recommend(customer_id) and print three customers' recommendations.


Hint
Each owned product scores 1.00 with itself, so it would top the list: drop the owned products before you sort. Without the sort, [:3] just takes the first three names from A to Z.


STEP 1 OF 5
    Ctrl + Enter to check

    Rec Recommend 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