Skip to content

Commit

Permalink
Faster get neighbors using heap (#302)
Browse files Browse the repository at this point in the history
Co-authored-by: Nicolas Hug <contact@nicolas-hug.com>
  • Loading branch information
ppecheux and NicolasHug committed Aug 15, 2022
1 parent 3414ad9 commit 77e8b5d
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions surprise/prediction_algorithms/algo_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
class :class:`AlgoBase` from which every single prediction algorithm has to
inherit.
"""
import heapq


from .. import similarities as sims
Expand Down Expand Up @@ -285,9 +286,8 @@ def get_neighbors(self, iid, k):
all_instances = self.trainset.all_users
else:
all_instances = self.trainset.all_items

others = [(x, self.sim[iid, x]) for x in all_instances() if x != iid]
others.sort(key=lambda tple: tple[1], reverse=True)
k_nearest_neighbors = [j for (j, _) in others[:k]]
others = heapq.nlargest(k, others, key=lambda tple: tple[1])
k_nearest_neighbors = [j for (j, _) in others]

return k_nearest_neighbors

0 comments on commit 77e8b5d

Please sign in to comment.