Skip to content

Instantly share code, notes, and snippets.

@victorkohler
Created March 14, 2019 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorkohler/67d7db955b373bd516b9c4b019f1dac8 to your computer and use it in GitHub Desktop.
Save victorkohler/67d7db955b373bd516b9c4b019f1dac8 to your computer and use it in GitHub Desktop.
#---------------------
# 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