2

我目前正在使用一个名为LightFM的Python库。但是我在将交互传递给fit()方法时遇到了一些麻烦。使用LightFM创建稀疏矩阵并打印预测

Python版本:3 库:http://lyst.github.io/lightfm/docs/lightfm.html

的文档状态,我应该使以下类型的稀疏矩阵:相互作用(np.float32 coo_matrix形状的[n_users,n_items]) - 基质

,但我似乎无法使它发挥它总是建议一样...

更新:当执行它的top_items变量下面要说的没有垫这是哪个用户迭代的,而不是任何其他项目(牛肉或沙拉),所以它看起来像我做错了什么。它输出:['蛋糕 '奶酪']每次

这里是我的代码:

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]) 
+0

'不能使它工作'在这里是一个被禁止的短语!你必须告诉什么是错的。错误,结果错误等。具体问题出在哪里。 – hpaulj

+0

嘿@hpaulj我已经更新了我的答案,并回答了我认为在这里错了。谢谢:) – aat2703

回答

1
data = coo_matrix(data) 

可能不是你想要的东西;它是data的确切副本。不特别稀疏。

data代表什么?

我猜测你确实需要一个矩阵,主要是0和1,在data表示的坐标上。

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]]) 

这是较为典型的什么进入学习功能。

+0

这正是我需要的!我错过了数据之间的稀疏数据来创建实际的矩阵!谢谢! – aat2703