Skip main navigation

Hurry, only 9 days left to get one year of Unlimited learning for £249.99 £174.99. New subscribers only. T&Cs apply

Find out more

A recommender using matrix factorization in Python

Share your thoughts about matrix factorization.

Run and modify the following “svd-recommender.py” and share your experiences with others.

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

# Load your data (replace this with your dataset)
reader = Reader(line_format='user item rating', sep=',')
data = Dataset.load_from_file('data.txt', reader=reader)

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

# Use the SVD algorithm for matrix factorization
algo = SVD()
algo.fit(trainset)

# Make predictions on the test set
predictions = algo.test(testset)

# Evaluate the model's accuracy
accuracy.rmse(predictions)

# Replace 'user_id' and 'item_id' with the actual user and item IDs for which you want to get recommendations
user_id = 'user_id'
item_id = 'item_id'

# Get a prediction for a specific user and item
prediction = algo.predict(user_id, item_id)
print(f"Predicted rating for user {user_id} on item {item_id}: {prediction.est}")

The data.txt file should contain rows of data in the format specified by the Reader. In this case, the format is assumed to be “user item rating”, separated by commas.

user1, item1, 4.5
user1, item2, 3.0
user2, item1, 5.0
user2, item3, 2.5
user3, item2, 4.0
user3, item3, 3.5
This article is from the free online

Recommender Systems in Python

Created by
FutureLearn - Learning For Life

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now