[英]Creating a sparse matrix with LightFM and print predictions
我目前正在使用名为LightFM的Python库。 但是我在将交互传递给fit()方法时遇到了一些麻烦。
Python版本:3库: http : //lyst.github.io/lightfm/docs/lightfm.html
文档说明我应该创建一个以下类型的稀疏矩阵: interaction(np.float32 coo_matrix of shape [n_users,n_items]) - 矩阵
但我似乎无法使它工作,它始终建议相同...
更新 :当执行它时,top_items变量说出以下内容,无论它迭代哪个用户而不是任何其他项目(牛肉或沙拉),所以看起来我做错了。 它每次输出:['Cake''Cheese']
这是我的代码:
import numpy as np
from lightfm.datasets import fetch_movielens
from lightfm import LightFM
from scipy.sparse import coo_matrix
import scipy.sparse as sparse
import scipy
// Users, items
data = [
[1, 0],
[2, 1],
[3, 2],
[4, 3]
]
items = np.array(["Cake", "Cheese", "Beef", "Salad"])
data = coo_matrix(data)
#create model
model = LightFM(loss='warp')
#train model
model.fit(data, epochs=30, num_threads=2)
// Print training data
print(data)
def sample_recommendation(model, data, user_ids):
#number of users and movies in training data
n_users, n_items = data.shape
#generate recommendations for each user we input
for user_id in user_ids:
#movies our model predicts they will like
scores = model.predict(user_id, np.arange(n_items))
#rank them in order of most liked to least
top_items = items[np.argsort(-scores)]
print(top_items)
sample_recommendation(model, data, [1,2])
data = coo_matrix(data)
可能不是你想要的; 它是data
的精确复制品。 不是特别稀疏。
data
代表什么?
我猜你真的想要一个大多数为0的矩阵,并且在data
代表的坐标处为1。
In [20]: data = [
...: [1, 0],
...: [2, 1],
...: [3, 2],
...: [4, 3]
...: ]
可能不是你想要的:
In [21]: ds = sparse.coo_matrix(data)
In [22]: ds.A
Out[22]:
array([[1, 0],
[2, 1],
[3, 2],
[4, 3]])
再试一次:
In [23]: data=np.array(data)
In [24]: ds=sparse.coo_matrix((np.ones(4,int),(data[:,0],data[:,1])))
In [25]: ds
Out[25]:
<5x4 sparse matrix of type '<class 'numpy.int32'>'
with 4 stored elements in COOrdinate format>
In [26]: ds.A
Out[26]:
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
这是学习功能的典型特征。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.