From 7ca1e5456a554fb761893d269e8558f916ad8abd Mon Sep 17 00:00:00 2001 From: Andrew Burkard Date: Tue, 14 Jan 2020 16:51:56 -0800 Subject: [PATCH 1/2] Fix bug where als explain may return fewer than N contributions when user_items has negative confidence values --- implicit/als.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/implicit/als.py b/implicit/als.py index d864967f..7f43716e 100644 --- a/implicit/als.py +++ b/implicit/als.py @@ -258,6 +258,7 @@ def explain(self, userid, user_items, itemid, user_weights=None, N=10): total_score = 0.0 h = [] + h_len = 0 for i, (itemid, confidence) in enumerate(nonzeros(user_items, userid)): if confidence < 0: continue @@ -267,8 +268,9 @@ def explain(self, userid, user_items, itemid, user_weights=None, N=10): score = weighted_item.dot(factor) * confidence total_score += score contribution = (score, itemid) - if i < N: + if h_len < N: heapq.heappush(h, contribution) + h_len += 1 else: heapq.heappushpop(h, contribution) From 44a577c077f79b0dcf909fe4b9674b249c42031f Mon Sep 17 00:00:00 2001 From: Andrew Burkard Date: Tue, 14 Jan 2020 16:54:44 -0800 Subject: [PATCH 2/2] enumerate is no longer necessary since loop counter is unused --- implicit/als.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/implicit/als.py b/implicit/als.py index 7f43716e..a486cd02 100644 --- a/implicit/als.py +++ b/implicit/als.py @@ -259,7 +259,7 @@ def explain(self, userid, user_items, itemid, user_weights=None, N=10): total_score = 0.0 h = [] h_len = 0 - for i, (itemid, confidence) in enumerate(nonzeros(user_items, userid)): + for itemid, confidence in nonzeros(user_items, userid): if confidence < 0: continue