aat*_*703 5 python recommendation-engine machine-learning scipy sparse-matrix
我目前正在使用名为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])
Run Code Online (Sandbox Code Playgroud)
data = coo_matrix(data)
Run Code Online (Sandbox Code Playgroud)
可能不是你想要的;它是 的精确复制品data。不是特别稀疏。
代表什么data?
我猜测您确实想要一个在 表示的坐标处大部分为 0 和 1 的矩阵data。
In [20]: data = [
...: [1, 0],
...: [2, 1],
...: [3, 2],
...: [4, 3]
...: ]
Run Code Online (Sandbox Code Playgroud)
可能不是你想要的:
In [21]: ds = sparse.coo_matrix(data)
In [22]: ds.A
Out[22]:
array([[1, 0],
[2, 1],
[3, 2],
[4, 3]])
Run Code Online (Sandbox Code Playgroud)
再试一次:
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]])
Run Code Online (Sandbox Code Playgroud)
这是学习功能中更典型的情况。