-
Notifications
You must be signed in to change notification settings - Fork 58
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
10 changed files
with
203 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,3 +13,4 @@ algorithms. | |
knn | ||
mf | ||
hpf | ||
implicit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
Implicit | ||
======== | ||
|
||
.. module:: lenskit.algorithms.implicit | ||
|
||
This module provides a LensKit bridge to the implicit_ library implementing | ||
several implicit-feedback recommenders. | ||
|
||
.. _implicit: https://implicit.readthedocs.io/en/latest/ | ||
|
||
.. autoclass:: ALS | ||
:members: | ||
|
||
.. autoclass:: BPR | ||
:members: |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
from collections import namedtuple | ||
import pandas as pd | ||
import numpy as np | ||
|
||
from implicit.als import AlternatingLeastSquares | ||
from implicit.bpr import BayesianPersonalizedRanking | ||
|
||
from ..matrix import sparse_ratings | ||
from . import Trainable, Recommender | ||
|
||
ImplicitModel = namedtuple('ImplicitModel', [ | ||
'algo', 'matrix', 'users', 'items' | ||
]) | ||
ImplicitModel.__doc__ = ''' | ||
Model for *implicit*-backed recommenders. | ||
Attributes: | ||
algo(implicit.RecommenderBase): the underlying algorithm. | ||
matrix(scipy.sparse.csr_matrix): the user-item matrix. | ||
users(pandas.Index): the user ID to user position index. | ||
items(pandas.Index): the item ID to item position index. | ||
''' | ||
|
||
|
||
class BaseRec(Trainable, Recommender): | ||
""" | ||
Base class for Implicit-backed recommenders. | ||
""" | ||
def __init__(self, algo, *args, **kwargs): | ||
self.algo_class = algo | ||
self.algo_args = args | ||
self.algo_kwargs = kwargs | ||
|
||
def train(self, ratings): | ||
matrix, users, items = sparse_ratings(ratings, scipy=True) | ||
iur = matrix.T.tocsr() | ||
|
||
algo = self.algo_class(*self.algo_args, **self.algo_kwargs) | ||
algo.fit(iur) | ||
|
||
return ImplicitModel(algo, matrix, users, items) | ||
|
||
def recommend(self, model: ImplicitModel, user, n=None, candidates=None, ratings=None): | ||
try: | ||
uid = model.users.get_loc(user) | ||
except KeyError: | ||
return pd.DataFrame({'item': []}) | ||
|
||
if candidates is None: | ||
recs = model.algo.recommend(uid, model.matrix, N=n) | ||
else: | ||
cands = model.items.get_indexer(candidates) | ||
cands = cands[cands >= 0] | ||
recs = model.algo.rank_items(uid, model.matrix, cands) | ||
|
||
if n is not None: | ||
recs = recs[:n] | ||
rec_df = pd.DataFrame.from_records(recs, columns=['item_pos', 'score']) | ||
rec_df['item'] = model.items[rec_df.item_pos] | ||
return rec_df.loc[:, ['item', 'score']] | ||
|
||
|
||
class ALS(BaseRec): | ||
""" | ||
LensKit interface to :py:mod:`implicit.als`. | ||
""" | ||
def __init__(self, *args, **kwargs): | ||
""" | ||
Construct an ALS recommender. The arguments are passed as-is to | ||
:py:class:`implicit.als.AlternatingLeastSquares`. | ||
""" | ||
super().__init__(AlternatingLeastSquares, *args, **kwargs) | ||
|
||
|
||
class BPR(BaseRec): | ||
""" | ||
LensKit interface to :py:mod:`implicit.bpr`. | ||
""" | ||
def __init__(self, *args, **kwargs): | ||
""" | ||
Construct an ALS recommender. The arguments are passed as-is to | ||
:py:class:`implicit.als.BayesianPersonalizedRanking`. | ||
""" | ||
super().__init__(BayesianPersonalizedRanking, *args, **kwargs) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
import logging | ||
|
||
import pandas as pd | ||
import numpy as np | ||
|
||
from pytest import mark | ||
|
||
import lk_test_utils as lktu | ||
|
||
try: | ||
from lenskit.algorithms import implicit | ||
have_implicit = True | ||
except ImportError: | ||
have_implicit = False | ||
|
||
_log = logging.getLogger(__name__) | ||
|
||
simple_df = pd.DataFrame({'item': [1, 1, 2, 3], | ||
'user': [10, 12, 10, 13], | ||
'rating': [4.0, 3.0, 5.0, 2.0]}) | ||
|
||
|
||
@mark.slow | ||
@mark.skipif(not have_implicit, reason='implicit not installed') | ||
def test_implicit_als_train_rec(): | ||
algo = implicit.ALS(25) | ||
ratings = lktu.ml_pandas.renamed.ratings | ||
|
||
model = algo.train(ratings) | ||
assert model is not None | ||
|
||
recs = algo.recommend(model, 100, n=20) | ||
assert len(recs) == 20 | ||
|
||
|
||
@mark.slow | ||
@mark.eval | ||
@mark.skipif(not have_implicit, reason='implicit not installed') | ||
@mark.skipif(not lktu.ml100k.available, reason='ML100K data not present') | ||
def test_implicit_als_batch_accuracy(): | ||
import lenskit.crossfold as xf | ||
from lenskit import batch, topn | ||
import lenskit.metrics.topn as lm | ||
|
||
ratings = lktu.ml100k.load_ratings() | ||
|
||
algo = implicit.ALS(25) | ||
|
||
def eval(train, test): | ||
_log.info('running training') | ||
train['rating'] = train.rating.astype(np.float_) | ||
model = algo.train(train) | ||
users = test.user.unique() | ||
_log.info('testing %d users', len(users)) | ||
candidates = topn.UnratedCandidates(train) | ||
recs = batch.recommend(algo, model, users, 100, candidates, test) | ||
return recs | ||
|
||
folds = xf.partition_users(ratings, 5, xf.SampleFrac(0.2)) | ||
recs = pd.concat(eval(train, test) for (train, test) in folds) | ||
|
||
_log.info('analyzing recommendations') | ||
ndcg = recs.groupby('user').rating.apply(lm.ndcg) | ||
_log.info('ndcg for users is %.4f', ndcg.mean()) | ||
assert ndcg.mean() > 0 | ||
|
||
|
||
@mark.slow | ||
@mark.skipif(not have_implicit, reason='implicit not installed') | ||
def test_implicit_bpr_train_rec(): | ||
algo = implicit.BPR(25) | ||
ratings = lktu.ml_pandas.renamed.ratings | ||
|
||
model = algo.train(ratings) | ||
assert model is not None | ||
|
||
recs = algo.recommend(model, 100, n=20) | ||
assert len(recs) == 20 |