推荐系统中的增量协同过滤算法
cf-step的Python项目详细描述
CF STEP-增量协同过滤
Incremental learning for recommender systems
cfstep是一个用python编写的开源库,支持快速实现增量学习推荐系统。这个图书馆是研究项目CloudDBAppliance的副产品。在
安装
运行pip install cf-step
在您的环境中安装库。在
如何使用
对于本例,我们将使用流行的movielens数据集。数据集已从MovieLens网站收集并提供了评级数据集。根据数据集的大小,在不同的时间段收集数据集。在
首先让我们在pandas DataFrame
中加载数据。我们假设读者已经下载了1Mmovielense数据集,并将其解压到/tmp
文件夹中。在
To avoid creating a user and movie vocabularies we turn each user and movie to a categorical feature and use the pandas convenient cat attribute to get the codes
# local# load the datacol_names=['user_id','movie_id','rating','timestamp']ratings_df=pd.read_csv('/tmp/ratings.dat',delimiter='::',names=col_names,engine='python')# transform users and movies to categorical featuresratings_df['user_id']=ratings_df['user_id'].astype('category')ratings_df['movie_id']=ratings_df['movie_id'].astype('category')# use the codes to avoid creating separate vocabulariesratings_df['user_code']=ratings_df['user_id'].cat.codes.astype(int)ratings_df['movie_code']=ratings_df['movie_id'].cat.codes.astype(int)ratings_df.head()^{pr2}$
使用这些代码,我们可以看到数据集中有多少用户和电影。在
# localn_users=ratings_df['user_code'].max()+1n_movies=ratings_df['movie_code'].max()+1print(f'There are {n_users} unique users and {n_movies} unique movies in the movielens dataset.')
There are 6040 unique users and 3706 unique movies in the movielens dataset.
我们将按时间戳对数据进行排序,以便模拟流事件。在
# localdata_df=ratings_df.sort_values(by='timestamp')
Step
模型只支持正反馈。因此,我们将把评分为5分视为正面反馈,并放弃其他任何评价。我们想用1
来识别喜欢,用{
# local# more than 4 -> 1, less than 5 -> 0data_df['preference']=np.where(data_df['rating']>4,1,0)# keep only ones and discard the othersdata_df_cleaned=data_df.loc[data_df['preference']==1]data_df_cleaned.head()^{pr2}$
接下来,让我们初始化我们的模型。在
# localnet=SimpleCF(n_users,n_movies,factors=128,mean=0.,std=.1)objective=lambdapred,targ:targ-predoptimizer=SGD(net.parameters(),lr=0.06)device='cuda'iftorch.cuda.is_available()else'cpu'model=Step(net,objective,optimizer,device=device)
最后,让我们获取20%的数据来适应引导模型,并创建我们将使用的Pytorch数据集。在
# localpct=int(data_df_cleaned.shape[0]*.2)bootstrapping_data=data_df_cleaned[:pct]
我们将从我们的数据帧创建一个数据集。我们提取四个元素:
- 用户代码
- 电影代码
- 评级
- 偏好
# localfeatures=['user_code','movie_code','rating']target=['preference']data_set=TensorDataset(torch.tensor(bootstrapping_data[features].values),torch.tensor(bootstrapping_data[target].values))
创建我们将使用的Pytorch数据加载器。对于在线培训,批大小应始终为1
。在
# localdata_loader=DataLoader(data_set,batch_size=512,shuffle=False)
现在,让我们使用batch_fit()的方法来引导我们的模型。在
# localmodel.batch_fit(data_loader)
100%|██████████| 89/89 [00:01<00:00, 81.00it/s]
然后,为了模拟流媒体,我们得到剩余的数据并创建一个不同的数据集。在
# localdata_df_step=data_df_cleaned.drop(bootstrapping_data.index)data_df_step=data_df_step.reset_index(drop=True)data_df_step.head()# create the DataLoaderstream_data_set=TensorDataset(torch.tensor(data_df_step[features].values),torch.tensor(data_df_step[target].values))stream_data_loader=DataLoader(stream_data_set,batch_size=1,shuffle=False)
模拟流。。。在
# localk=10# we keep only the top 10 recommendationsrecalls=[]known_users=[]withtqdm(total=len(stream_data_loader))aspbar:foridx,(features,preferences)inenumerate(stream_data_loader):itr=idx+1user=features[:,0]item=features[:,1]rtng=features[:,2]pref=preferencesifuser.item()inknown_users:predictions=model.predict(user,k)recall=recall_at_k(predictions.tolist(),item.tolist(),k)recalls.append(recall)model.step(user,item,rtng,pref)else:model.step(user,item,rtng,pref)known_users.append(user.item())pbar.update(1)
100%|██████████| 181048/181048 [15:23<00:00, 195.94it/s]
最后但并非最不重要的是,我们将召回@10公制,使用5k元素的移动平均窗口。在
# localavgs=moving_avg(recalls,5000)plt.title('Recall@10')plt.xlabel('Iterations')plt.ylabel('Metric')plt.ylim(0.,.1)plt.plot(avgs)plt.show()
最后,保存模型的权重。在
# localmodel.save(os.path.join('artefacts','positive_step.pt'))
参考文献
- Vinagre,J.,Jorge,A.M.,&Gama,J.(2014年7月)。纯正反馈推荐的快速增量矩阵分解。在国际用户建模,适应和个性化会议(第459-470页)。斯普林格,查姆。在
- Hu,Y.,Koren,Y.和Volinsky,C.(2008年12月)。隐式反馈数据集的协同过滤。2008年第八届IEEE国际数据挖掘会议(第263-272页)。Ieee。在
- 项目
标签: