大体思路
分解user-item矩阵,将user和item embedding到低维稠密的(维度默认为20)空间,然后利用ES的dense vector字段来计算user和item的相关性分数,或item和item之间的相似度分数。
步骤
准备数据
训练模型
模型导入es
生成推荐结果
依赖软件的版本
Python3
Elasticsearch 7.11.1
准备数据
在https://grouplens.org/datasets/movielens/1m/下载movie lens作为训练模型的数据
将movie lens数据放在D:\ml-data\movielens\ml-1m
创建一个目录D:\ml-data\movielens\ml-1m\libmf, 后面生成的所有数据都会放在这个目录中。
git clone git@github.com:ralgond/elasticsearch-recommender.git
cd elasticsearch-recommender
将movie lens的数据格式转化成libmf格式
cd scripts
python movielens_format_libmf.py
执行成功后你能在D:\ml-data\movielens\ml-1m\libmf中找到一个ratings.libmf文件
切割文件
python movielens_data_split.py
执行成功后ratings.libfm文件会被切割成2个文件:
ratings_train.libmf
ratings_test.libmf
训练模型
到https://www.csie.ntu.edu.tw/~cjlin/libmf/下载libmf-2.01.zip
解压libmf-2.01.zip至D:\Software\libmf-2.01
将D:\Software\libmf-2.01\windows加入到环境变量PATH中
打开cmd
进入目录D:\ml-data\movielens\ml-1m\libmf
执行
mf-train -k 20 ratings_train.libmf
会得到模型文件
ratings_train.libmf.model
将模型导入ES
首先创建users和movies索引,回到目录elasticsearch-recommender
cd scripts
python movielens_create_indices.py
然后生成用户评分历史文件,主要是用在推荐时过滤掉那些已经看过的电影
python movielens_user_rate_history.py
然后push用户数据到ES
python movielens_push_user_data.py
接着push movie数据到ES
python movielens_push_movie_data.py
利用es的搜索功能实现推荐
获取和id为1(电影名为Toy Story (1995))的电影的相似度最高的10部电影
python movielens_rec_similar_movie.py 1
得到如下结果:
Toy Story 2 (1999)
Bug's Life, A (1998)
Bull Durham (1988)
Big (1988)
Parenthood (1989)
Heaven Can Wait (1978)
Fantasia 2000 (1999)
Sting, The (1973)
Glory (1989)
When Harry Met Sally... (1989)
为用户1推荐最相关的10部电影
python movielens_rec_for_user.py 1
得到如下结果:
Marcello Mastroianni: I Remember Yes, I Remember (1997)
Smashing Time (1967)
Shawshank Redemption, The (1994)
Foreign Student (1994)
Leather Jacket Love Story (1997)
Raiders of the Lost Ark (1981)
It's a Wonderful Life (1946)
Sanjuro (1962)
Inherit the Wind (1960)
Bridge on the River Kwai, The (1957)