def get_recommendations_KNN(user_id, nb_recommendations = 1): ''' Return a recommendation :param user: id of user you want a recommendation :param algorithm: "Funk" :return: ''' algo = algoKNN model = modelKNN recs = batch.recommend(algo, users,nb_recommendations, topn.UnratedCandidates(train), nprocs=None) recs = recs[recs['user'] == user_id] if not recs.empty: # select colums rows = recs[['item', 'score']] rows_dict = rows.to_dict(orient="records") recommendations = [] for entry in rows_dict: recommendations.append({ "item": int(entry['item']), "score": int(entry["score"]) }) # otherwise, nope, not found else: abort( 404, "No ratings for user with user_id {user_id} ".format(user_id=user_id) ) return recommendations
def test_uu_implicit_batch_accuracy(): from lenskit import batch, topn import lenskit.crossfold as xf ratings = lktu.ml100k.ratings algo = knn.UserUser(30, center=False, aggregate='sum') folds = list(xf.partition_users(ratings, 5, xf.SampleFrac(0.2))) all_test = pd.concat(f.test for f in folds) rec_lists = [] for train, test in folds: _log.info('running training') algo.fit(train.loc[:, ['user', 'item']]) cands = topn.UnratedCandidates(train) _log.info('testing %d users', test.user.nunique()) recs = batch.recommend(algo, test.user.unique(), 100, cands, n_jobs=2) rec_lists.append(recs) recs = pd.concat(rec_lists) rla = topn.RecListAnalysis() rla.add_metric(topn.ndcg) results = rla.compute(recs, all_test) user_dcg = results.ndcg dcg = user_dcg.mean() assert dcg >= 0.03
def get_topn(user,num_recommendations=10): #added argument num_recommendations=10 #algo = algoKNN #model = modelKNN # merged the code for get_topn and getRecommendaions into one function: recs = batch.recommend(algo, users,num_recommendations, topn.UnratedCandidates(train), nprocs=None) # changed arguments for batch.recommend recs = recs[recs['user'] == user] if not recs.empty: # select colums rows = recs[['item', 'score']] rows_dict = rows.to_dict(orient="records") recommendations = [] for entry in rows_dict: recommendations.append({ "item": int(entry['item']), "score": int(entry["score"]) }) # otherwise, nope, not found else: abort( 404, "No ratings for user with user_id {user_id} ".format(user_id=user) #user_id=user_id was changed to user_id=user ) return recommendations
def eval(train, test): _log.info('running training') train['rating'] = train.rating.astype(np.float_) algo.fit(train) users = test.user.unique() _log.info('testing %d users', len(users)) candidates = topn.UnratedCandidates(train) recs = batch.recommend(algo, users, 100, candidates) return recs
def test_unrated(): ratings = lktu.ml_pandas.renamed.ratings unrate = topn.UnratedCandidates(ratings) cs = unrate(100) items = ratings.item.unique() rated = ratings[ratings.user == 100].item.unique() assert len(cs) == len(items) - len(rated) assert len(np.intersect1d(cs, rated)) == 0
def eval(train, test): _log.info('running training') algo.fit(train) _log.info('testing %d users', test.user.nunique()) cand_fun = topn.UnratedCandidates(train) recs = batch.recommend(algo, test.user.unique(), 100, cand_fun, n_jobs=ncpus) return recs
def eval(train, test): _log.info('running training') algo.fit(train) _log.info('testing %d users', test.user.nunique()) cand_fun = topn.UnratedCandidates(train) recs = batch.recommend(algo, test.user.unique(), 100, cand_fun) # combine with test ratings for relevance data res = pd.merge(recs, test, how='left', on=('user', 'item')) # fill in missing 0s res.loc[res.rating.isna(), 'rating'] = 0 return res
def eval(train, test): train['rating'] = train.rating.astype(np.float_) _log.info('training CG') cg_algo.fit(train) _log.info('training LU') lu_algo.fit(train) users = test.user.unique() _log.info('testing %d users', len(users)) candidates = topn.UnratedCandidates(train) cg_recs = batch.recommend(cg_algo, users, 100, candidates, n_jobs=2) lu_recs = batch.recommend(lu_algo, users, 100, candidates, n_jobs=2) return pd.concat({ 'CG': cg_recs, 'LU': lu_recs }, names=['Method']).reset_index('Method')
def test_uu_implicit_batch_accuracy(): from lenskit import batch, topn import lenskit.crossfold as xf import lenskit.metrics.topn as lm ratings = lktu.ml100k.load_ratings() algo = knn.UserUser(30, center=False, aggregate='sum') folds = xf.partition_users(ratings, 5, xf.SampleFrac(0.2)) rec_lists = [] for train, test in folds: _log.info('running training') algo.fit(train.loc[:, ['user', 'item']]) cands = topn.UnratedCandidates(train) _log.info('testing %d users', test.user.nunique()) recs = batch.recommend(algo, test.user.unique(), 100, cands, test) rec_lists.append(recs) recs = pd.concat(rec_lists) user_dcg = recs.groupby('user').rating.apply(lm.dcg) dcg = user_dcg.mean() assert dcg >= 0.1
recs['Algorithm'] = aname return recs """ all_recs = [] test_data = [] for train, test in xf.partition_users(ratings[['user', 'item', 'rating']], 5, xf.SampleFrac(0.2)): test_data.append(test) # ItemItem # eval('ItemItem', algo_ii, train, test) #fittable = util.clone(algo) algo_ii.fit(train) users = test.user.unique() # the recommend function can merge rating values recs = batch.recommend(algo_ii, users, 100, topn.UnratedCandidates(train), test) # add the algorithm recs['Algorithm'] = 'ItemItem' all_recs.append(recs) # ItemItem # all_recs.append(eval('ALS', algo_als, train, test)) #fittable = util.clone(algo) algo_als.fit(train) users2 = test.user.unique() # the recommend function can merge rating values recs2 = batch.recommend(algo_als, users2, 100, topn.UnratedCandidates(train), test) # add the algorithm
def eval(train, test): model = algo.fit(train) users = test.user.unique() recs = batch.recommend(model, users, 20, topn.UnratedCandidates(train)) print('Recommended to test set of users.') return recs
print(modelAls.user_index_[0:10]) first = modelAls.user_index_[0] print(type(first)) firstUser = np.array([first], np.int64) # Get recommendation for a user # As als.BiasedMF is not implementing Recommend # We need to first adapt the model # https://lkpy.lenskit.org/en/stable/interfaces.html#recommendation # rec = Recommender.adapt(modelAls) # recs = rec.recommend(first, 10) #Gives error # Get 10 recommendations for a user (pandas dataframe) recs = batch.recommend(modelAls, firstUser, 10, topn.UnratedCandidates(train), test) print(recs) # Get the first recommended item firstRec = recs.iloc[0, 0] firstRecScore = recs.iloc[0, 1] print(firstRec) # Get the explanation of the recommendation # Get the index of the items items = modelAls.item_index_ # Find the index of the first item indexFirstRec = items.get_loc(firstRec) # Get the feature values of the user userProfile = modelAls.user_features_[0] itemProfile = modelAls.item_features_[indexFirstRec]