Created
March 14, 2019 21:47
-
-
Save victorkohler/67d7db955b373bd516b9c4b019f1dac8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#--------------------- | |
# MAKE RECOMMENDATION | |
#--------------------- | |
def make_recommendation(user_id=None, num_items=10): | |
"""Recommend items for a given user given a trained model | |
Args: | |
user_id (int): The id of the user we want to create recommendations for. | |
num_items (int): How many recommendations we want to return. | |
Returns: | |
recommendations (pandas.DataFrame): DataFrame with num_items artist names and scores | |
""" | |
# Grab our user matrix U | |
user_vecs = get_variable(graph, session, 'user_factors') | |
# Grab our item matrix V | |
item_vecs = get_variable(graph, session, 'item_factors') | |
# Grab our item bias | |
item_bi = get_variable(graph, session, 'item_bias').reshape(-1) | |
# Calculate the score for our user for all items. | |
rec_vector = np.add(user_vecs[user_id, :].dot(item_vecs.T), item_bi) | |
# Grab the indices of the top users | |
item_idx = np.argsort(rec_vector)[::-1][:num_items] | |
# Map the indices to artist names and add to dataframe along with scores. | |
artists, scores = [], [] | |
for idx in item_idx: | |
artists.append(item_lookup.artist.loc[item_lookup.artist_id == str(idx)].iloc[0]) | |
scores.append(rec_vector[idx]) | |
recommendations = pd.DataFrame({'artist': artists, 'score': scores}) | |
return recommendations | |
print(make_recommendation(user_id=0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment