Skip to content

Instantly share code, notes, and snippets.

@LouisdeBruijn
Last active August 28, 2019 11:59
Show Gist options
  • Save LouisdeBruijn/e4249e6e2dc317dccee2e3d165da4cd1 to your computer and use it in GitHub Desktop.
Save LouisdeBruijn/e4249e6e2dc317dccee2e3d165da4cd1 to your computer and use it in GitHub Desktop.
Recalculate item and user vectors on-the-fly
def recalculate_user(user_ratings):
'''adds new user and its liked items to sparse matrix and returns recalculated recommendations'''
alpha = 40
m = load_npz('sparse_user_item.npz')
n_users, n_movies = m.shape
ratings = [alpha for i in range(len(user_ratings))]
m.data = np.hstack((m.data, ratings))
m.indices = np.hstack((m.indices, user_ratings))
m.indptr = np.hstack((m.indptr, len(m.data)))
m._shape = (n_users+1, n_movies)
# recommend N items to new user
with open('model.sav', 'rb') as pickle_in:
model = pickle.load(pickle_in)
recommended, _ = zip(*model.recommend(n_users, m, recalculate_user=True))
return recommended, map_movies(recommended)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment