Skip to content

Commit a3d72f8

Browse files
committed
Truncate recommend() result to caller's N when filter_items is set (Fixes benfred#736)
1 parent 8a95dbe commit a3d72f8

1 file changed

Lines changed: 7 additions & 1 deletion

File tree

‎implicit/nearest_neighbours.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,12 @@ def recommend(
7272
if filter_items is not None and items is not None:
7373
raise ValueError("Can't specify both filter_items and items")
7474

75+
# Preserve the caller-requested result count: when filter_items is
76+
# set we over-fetch by len(filter_items) so that the post-filter
77+
# slice still has enough rows to satisfy N, but the final result
78+
# must be truncated to the originally-requested N (not the
79+
# inflated value). See https://github.com/benfred/implicit/issues/736
80+
requested_n = N
7581
if filter_items is not None:
7682
N += len(filter_items)
7783
elif items is not None:
@@ -91,7 +97,7 @@ def recommend(
9197

9298
if filter_items is not None:
9399
mask = np.isin(ids, filter_items, invert=True)
94-
ids, scores = ids[mask][:N], scores[mask][:N]
100+
ids, scores = ids[mask][:requested_n], scores[mask][:requested_n]
95101

96102
elif items is not None:
97103
mask = np.isin(ids, items)

0 commit comments

Comments
 (0)