Skip to content

Instantly share code, notes, and snippets.

@tedtieken
Forked from LouisdeBruijn/recalculate_user.py
Created March 4, 2025 02:02
Show Gist options
  • Select an option

  • Save tedtieken/8ea931609ffbed54cc0e2b052d6894fa to your computer and use it in GitHub Desktop.

Select an option

Save tedtieken/8ea931609ffbed54cc0e2b052d6894fa 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