python - 使用 LightFM 和打印预测创建稀疏矩阵

标签 python machine-learning scipy sparse-matrix recommendation-engine

我目前正在使用一个名为 LightFM 的 Python 库。但是我在将交互传递给 fit() 方法时遇到了一些问题。

Python 版本:3 图书馆:http://lyst.github.io/lightfm/docs/lightfm.html

文档指出我应该制作以下类型的稀疏矩阵:interactions (np.float32 coo_matrix of shape [n_users, n_items]) – the matrix

但我似乎无法让它工作它总是推荐相同的...

更新:执行它时,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 代表什么?

我猜你真的想要一个在 data 表示的坐标处主要包含 0 和 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]])

这是更典型的学习功能。

关于python - 使用 LightFM 和打印预测创建稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40323321/

相关文章:

python - keras 的 Model.train_on_batch 和 tensorflow 的 Session.run([train_optimizer]) 有什么区别?

apache-spark - Spark中LDA模型的在线学习

scipy.special.expn(n,x) 对于复数值?

python : Halton and Hammersley quasi random sequences

python - 有没有一种简单的方法可以从 CharField 填充 SlugField?

python - 为什么 View 函数在 Django 中需要一个请求参数?

python - 为什么偶数 Ns 比奇数 Ns 花费更长的时间?

python - 如何将 a= ['raj' 、 'rj' 、 'reba' ] 与 b=[1,2,2] (整数)相乘以获得 c = ['raj' 、 'rj' 、 'rj' 、 0x1045679 的输出10、 'reba']

python - 试图理解这个简单的 TensorFlow 代码

python - Python 的意外 FFT 结果