Home Artificial Intelligence Leveraging Surprise Library for Recommender Systems in Python

Leveraging Surprise Library for Recommender Systems in Python

1
Leveraging Surprise Library for Recommender Systems in Python

import surprise
from surprise import Dataset
from surprise import SVD
from surprise.model_selection import train_test_split
from surprise import accuracy

# Load the book-crossing dataset
data = Dataset.load_builtin(‘book-crossing’)

# Split the info into training and testing sets
trainset, testset = train_test_split(data, test_size=0.2)

# Define the matrix factorization-based algorithm
algo = SVD()

# Train the algorithm on the training set
algo.fit(trainset)

# Predict rankings for the test set
predictions = algo.test(testset)

# Evaluate the accuracy of the model
accuracy.rmse(predictions)

# Get top-N book recommendations for a particular user
user_id = str(276729)
top_n = 5

# Get the inner id of the user
user_inner_id = algo.trainset.to_inner_uid(user_id)

# Get an inventory of book recommendations for the user
recommendations = algo.get_top_n(user_inner_id, k=top_n)

# Print the top-N book recommendations for the user
for book_id, predicted_rating in recommendations:
book_title = algo.trainset.to_raw_iid(book_id)
print(f”Book: {book_title}, Predicted Rating: {predicted_rating}”)

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here