Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions implicit/cpu/als.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,8 @@ def explain(self, userid, user_items, itemid, user_weights=None, N=10):
userid : int
The userid to explain recommendations for
user_items : csr_matrix
Sparse matrix containing the liked items for the user
A single row containing the user's liked items, or the full
user-item matrix with this user's interactions in row `userid`.
itemid : int
The itemid to explain recommendations for
user_weights : ndarray, optional
Expand All @@ -381,11 +382,13 @@ def explain(self, userid, user_items, itemid, user_weights=None, N=10):
if self.alpha != 1.0:
user_items = self.alpha * user_items

row = 0 if user_items.shape[0] == 1 else userid

# user_weights = Cholesky decomposition of Wu^-1
# from section 5 of the paper CF for Implicit Feedback Datasets
if user_weights is None:
A, _ = user_linear_equation(
self.item_factors, self.YtY, user_items, userid, self.regularization, self.factors
self.item_factors, self.YtY, user_items, row, self.regularization, self.factors
)
user_weights = scipy.linalg.cho_factor(A)
seed_item = self.item_factors[itemid]
Expand All @@ -396,7 +399,7 @@ def explain(self, userid, user_items, itemid, user_weights=None, N=10):
total_score = 0.0
h = []
h_len = 0
for other_itemid, confidence in nonzeros(user_items, userid):
for other_itemid, confidence in nonzeros(user_items, row):
if confidence < 0:
continue

Expand Down
19 changes: 19 additions & 0 deletions tests/als_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,25 @@ def test_explain():
assert items[:2] == top_items


@pytest.mark.parametrize("use_cached_weights", [False, True])
def test_explain_single_user_row(use_cached_weights):
user_items = csr_matrix([[1, 0, 1], [0, 2, 3], [2, 1, 0]], dtype=np.float32)
model = AlternatingLeastSquares(
factors=2, iterations=5, alpha=2, use_gpu=False, num_threads=1, random_state=23
)
model.fit(user_items, show_progress=False)

userid, itemid = 1, 0
expected_score, expected_contributions, weights = model.explain(userid, user_items, itemid)
assert sorted(item for item, _ in expected_contributions) == [1, 2]

score, contributions, _ = model.explain(
userid, user_items[userid], itemid, user_weights=weights if use_cached_weights else None
)
assert score == pytest.approx(expected_score)
assert contributions == expected_contributions


@pytest.mark.parametrize("use_gpu", [True, False] if HAS_CUDA else [False])
def test_small_nan(use_gpu):
# test out case where number of factors is larger than number of users:
Expand Down