Create Sparse Matrix with LightFM and Print Prediction

I am currently working with a Python library called LightFM. But I'm having problems passing interactions to fit ().

Python version: 3 Library: http://lyst.imtqy.com/lightfm/docs/lightfm.html

The documentation states that I should make a sparse matrix of the following type: interactions (np.float32 coo_matrix forms [n_users, n_items]) - matrix

But I can’t make it work, it always recommends the same ...

Updated : when it is executed, the variable top_items will say the following no matter which user iterates, and not any other elements (beef or salad), so it seems to me that I'm doing something wrong. He outputs: ['Cake' 'Cheese'] every time

Here is my code:

    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])
+4
source share
1 answer
 data = coo_matrix(data)

probably not what you want; This is an exact copy data. Not particularly rare.

What does it mean data?

I'm going to assume that you really need a matrix with most of the 0s and 1s in the coordinates represented data.

In [20]: data = [
    ...:     [1, 0], 
    ...:     [2, 1], 
    ...:     [3, 2],
    ...:     [4, 3]
    ...: ]

maybe not what you want:

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

, .

+2

Source: https://habr.com/ru/post/1659291/


All Articles