In the first part, you successfully built and deployed a recommendation model using deep learning with Amazon Personalize. This notebook will expand on that and will walk you through adding the ability to react to real time behavior of users. If their intent changes while browsing a movie, you will see revised recommendations based on that behavior. It will also showcase demo code for simulating user behavior selecting movies before the recommendations are returned.
Below we start with just importing libraries that we need to interact with Personalize
# Imports
import boto3
import json
import numpy as np
import pandas as pd
import time
import uuid
The line below will retrieve your shared variables from the first notebook.
%store -r
# Setup and Config
# Recommendations from Event data
personalize = boto3.client('personalize')
personalize_runtime = boto3.client('personalize-runtime')
# Establish a connection to Personalize's Event Streaming
personalize_events = boto3.client(service_name='personalize-events')
Before your recommendation system can respond to real time events you will need an event tracker, the code below will generate one and can be used going forward with this lab. Feel free to name it something more clever.
response = personalize.create_event_tracker(
name='MovieClickTracker',
datasetGroupArn=dataset_group_arn
)
print(response['eventTrackerArn'])
print(response['trackingId'])
TRACKING_ID = response['trackingId']
arn:aws:personalize:us-east-1:284105231590:event-tracker/a1b7dce4 f252168d-a73d-467a-b2e7-66071f5d6d78
event_tracker_arn = response['eventTrackerArn']
Above you'll see your tracking ID and this has been assigned to a variable so no further action is needed by you. The lines below are going to setup the data used for recommendations so you can render the list of movies later.
# First load items into memory
items = pd.read_csv('./ml-100k/u.item', sep='|', usecols=[0,1], encoding='latin-1', names=['ITEM_ID', 'TITLE'], index_col='ITEM_ID')
def get_movie_title(movie_id):
"""
Takes in an ID, returns a title
"""
movie_id = int(movie_id)-1
return items.loc[movie_id]['TITLE']
First we will render the recommendations again from the previous notebook:
recommendations_df
OriginalRecs | |
---|---|
0 | Schindler's List (1993) |
1 | Pulp Fiction (1994) |
2 | Usual Suspects, The (1995) |
3 | Raiders of the Lost Ark (1981) |
4 | Silence of the Lambs, The (1991) |
5 | Casablanca (1942) |
6 | Fugitive, The (1993) |
7 | Shawshank Redemption, The (1994) |
8 | Amadeus (1984) |
9 | Braveheart (1995) |
10 | Truth About Cats & Dogs, The (1996) |
11 | Sling Blade (1996) |
12 | One Flew Over the Cuckoo's Nest (1975) |
13 | Aladdin (1992) |
14 | Back to the Future (1985) |
15 | Time to Kill, A (1996) |
16 | Seven (Se7en) (1995) |
17 | E.T. the Extra-Terrestrial (1982) |
18 | Princess Bride, The (1987) |
19 | Godfather, The (1972) |
20 | Sleepers (1996) |
21 | Long Kiss Goodnight, The (1996) |
22 | Monty Python and the Holy Grail (1974) |
23 | Willy Wonka and the Chocolate Factory (1971) |
24 | GoodFellas (1990) |
The lines below provide a code sample that simulates a user interacting with a particular item, you will then get recommendations that differ from those when you started.
session_dict = {}
def send_movie_click(USER_ID, ITEM_ID):
"""
Simulates a click as an event
to send an event to Amazon Personalize's Event Tracker
"""
# Configure Session
try:
session_ID = session_dict[USER_ID]
except:
session_dict[USER_ID] = str(uuid.uuid1())
session_ID = session_dict[USER_ID]
# Configure Properties:
event = {
"itemId": str(ITEM_ID),
}
event_json = json.dumps(event)
# Make Call
personalize_events.put_events(
trackingId = TRACKING_ID,
userId= USER_ID,
sessionId = session_ID,
eventList = [{
'sentAt': int(time.time()),
'eventType': 'EVENT_TYPE',
'properties': event_json
}]
)
Immediately below this line will update the tracker as if the user has clicked a particular title.
If the table generated by the cells below does not shift the recommendations simply try another random 3 digit number in the cell above and run both cells again. You'll see a third column generated of recommendations.
# Pick a movie, we will use ID 270 or Gattaca
movie_to_click = 270
movie_title_clicked = get_movie_title(movie_to_click)
send_movie_click(USER_ID=str(user_id), ITEM_ID=movie_to_click)
After executing this block you will see the alterations in the recommendations now that you have event tracking enabled and that you have sent the events to the service.
get_recommendations_response = personalize_runtime.get_recommendations(
campaignArn = campaign_arn,
userId = str(user_id),
)
print("Recommendations for user: ", user_id)
item_list = get_recommendations_response['itemList']
recommendation_list = []
for item in item_list:
title = get_movie_title(item['itemId'])
recommendation_list.append(title)
new_rec_DF = pd.DataFrame(recommendation_list, columns = [movie_title_clicked])
recommendations_df = recommendations_df.join(new_rec_DF)
recommendations_df
Recommendations for user: 839
OriginalRecs | Full Monty, The (1997) | |
---|---|---|
0 | Schindler's List (1993) | Professional, The (1994) |
1 | Pulp Fiction (1994) | unknown |
2 | Usual Suspects, The (1995) | Amistad (1997) |
3 | Raiders of the Lost Ark (1981) | Chasing Amy (1997) |
4 | Silence of the Lambs, The (1991) | Muppet Treasure Island (1996) |
5 | Casablanca (1942) | Empire Strikes Back, The (1980) |
6 | Fugitive, The (1993) | River Wild, The (1994) |
7 | Shawshank Redemption, The (1994) | Midnight in the Garden of Good and Evil (1997) |
8 | Amadeus (1984) | Last of the Mohicans, The (1992) |
9 | Braveheart (1995) | Marvin's Room (1996) |
10 | Truth About Cats & Dogs, The (1996) | Seven (Se7en) (1995) |
11 | Sling Blade (1996) | Spitfire Grill, The (1996) |
12 | One Flew Over the Cuckoo's Nest (1975) | Citizen Ruth (1996) |
13 | Aladdin (1992) | Hoodlum (1997) |
14 | Back to the Future (1985) | Henry V (1989) |
15 | Time to Kill, A (1996) | I.Q. (1994) |
16 | Seven (Se7en) (1995) | Dr. Strangelove or: How I Learned to Stop Worr... |
17 | E.T. the Extra-Terrestrial (1982) | Starship Troopers (1997) |
18 | Princess Bride, The (1987) | Santa Clause, The (1994) |
19 | Godfather, The (1972) | Ref, The (1994) |
20 | Sleepers (1996) | Apocalypse Now (1979) |
21 | Long Kiss Goodnight, The (1996) | Star Trek: First Contact (1996) |
22 | Monty Python and the Holy Grail (1974) | Free Willy (1993) |
23 | Willy Wonka and the Chocolate Factory (1971) | Princess Bride, The (1987) |
24 | GoodFellas (1990) | Shanghai Triad (Yao a yao yao dao waipo qiao) ... |
You can see now that recommendations are altered by changing the movie that a user interacts with, this system can be modified to any application where users are interacting with a collection of items. These tools are available at any time to pull down and start exploring what is possible with the data you have.
Execute the cell below to store values needed for the cleanup notebook.
Finally when you are ready to remove the items from your account, open the Cleanup.ipynb
notebook and execute the steps there.
%store event_tracker_arn
Stored 'event_tracker_arn' (str)