Reputation: 11
I am trying to build a LightFM hybrid recommender (still learning ML) but at the end of it all, when I try to get the recommendations, I run into this error. I've looked at several posts regarding this error on Stackoverflow but none of them quite helped me. Please see my code below.
import pandas as pd
from lightfm import LightFM
from lightfm.data import Dataset as DS
import numpy as np
# Load data from a CSV file
data = pd.read_csv('my_data.csv')
# Create a dataset object
datasetfm = DS()
# Fit the dataset with data
datasetfm.fit(users=data['UserId'], items=data['ItemId'])
# Build the interaction matrix
(interactions, weights) = datasetfm.build_interactions([(row['UserId'], row['ItemId'], row['Weight']) for index, row in data.iterrows()])
# Create the model
model = LightFM(loss='warp')
# Train the model
model.fit(interactions, epochs=30, num_threads=2)
# function to get recommendations for a user
def get_recommendations(user_id, model, dataset):
n_users, n_items = dataset.interactions_shape()
user_ids = dataset.mapping()[0]
item_ids = dataset.mapping()[2]
known_positives = data[data['UserId'] == user_id]['Item'].tolist()
scores = model.predict(user_ids[user_id], np.arange(n_items))
top_items = item_ids[scores.argsort()[::-1]]
recommendations = [item for item in top_items if item not in known_positives]
return recommendations[:10] # Return the top 10 recommendations
# Usage
user_id = 1 # userID to get recommendations for
recommendations = get_recommendations(user_id, model, datasetfm)
I've tried to sort the array in descending order in a different way but that ended up getting the same error unfortunately. Other than that, most of the posts on StackOverflow point to the same issue with plots but I'm not trying to plot anything in the code.
Upvotes: 0
Views: 306