Module 17 · Recommender systems · Lesson 59 of 66
Collaborative filtering
Predict ratings from similar users or similar items, then from hidden factors with SVD.
In this lesson · about 25 minutes
- Build user and item similarity matrices with cosine distance
- Predict ratings and measure them with RMSE
- Explain matrix factorization and use SVD
Now we predict the actual rating a user would give a movie they haven't seen. First, split the ratings 75/25 into training and test sets, and lay each out as a full matrix: 943 users by 1,682 movies, with 0 where there's no rating.
Memory-based filtering
- User-based: "users like you liked this". Find users whose ratings resemble yours and average their ratings for the movie.
- Item-based: "people who liked this also liked that". Find movies rated similarly to ones you rated.
Similarity is measured with the cosine between two rating vectors: 1 means they point the same way. scikit-learn's pairwise_distances(..., metric='cosine') gives the cosine distance, which is 1 minus the similarity.
The training matrix
Exercise
Similarity matrices
Compute user_similarity with pairwise_distances(train_data_matrix, metric='cosine'), and item_similarity the same way on the transposed matrix (train_data_matrix.T). End with both shapes.
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
column_names = ['user_id', 'item_id', 'rating', 'timestamp']
df = pd.read_csv('u.data', sep='\t', names=column_names)
movie_titles = pd.read_csv('Movie_Id_Titles.csv')
df = pd.merge(df, movie_titles, on='item_id')
from sklearn.model_selection import train_test_split
from sklearn.metrics.pairwise import pairwise_distances
n_users = df.user_id.nunique()
n_items = df.item_id.nunique()
train_data, test_data = train_test_split(df, test_size=0.25, random_state=101)
train_data_matrix = np.zeros((n_users, n_items))
for line in train_data.itertuples():
train_data_matrix[line.user_id - 1, line.item_id - 1] = line.rating
test_data_matrix = np.zeros((n_users, n_items))
for line in test_data.itertuples():
test_data_matrix[line.user_id - 1, line.item_id - 1] = line.rating
def rmse(prediction, ground_truth):
prediction = prediction[ground_truth.nonzero()].flatten()
ground_truth = ground_truth[ground_truth.nonzero()].flatten()
return np.sqrt(np.mean((prediction - ground_truth) ** 2))To predict, take a weighted average of other ratings, weighted by similarity. For users we first subtract each user's average rating, because some people rate everything high and others low, then add it back.
An RMSE above 3 stars is poor, partly because this simple version treats unrated movies as 0. It's a starting point that's easy to understand.
Model-based filtering with SVD
A better idea: assume each user and each movie can be described by a few hidden factors, such as how much of a sci-fi fan someone is and how sci-fi a movie is. A rating is roughly the match between the two. Matrix factorization finds those factors by splitting the big ratings matrix into smaller ones. Singular value decomposition (SVD) does this: X ≈ U · S · Vᵀ, where U describes users, Vᵀ describes movies, and S weights the factors. Keeping only the top k factors and multiplying back gives a prediction for every cell.
Exercise
Predict with SVD
Use svds(train_data_matrix, k=20) to get u, s, vt. Rebuild the predictions as X_pred = np.dot(np.dot(u, np.diag(s)), vt) and end with rmse(X_pred, test_data_matrix).
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
column_names = ['user_id', 'item_id', 'rating', 'timestamp']
df = pd.read_csv('u.data', sep='\t', names=column_names)
movie_titles = pd.read_csv('Movie_Id_Titles.csv')
df = pd.merge(df, movie_titles, on='item_id')
from sklearn.model_selection import train_test_split
from sklearn.metrics.pairwise import pairwise_distances
n_users = df.user_id.nunique()
n_items = df.item_id.nunique()
train_data, test_data = train_test_split(df, test_size=0.25, random_state=101)
train_data_matrix = np.zeros((n_users, n_items))
for line in train_data.itertuples():
train_data_matrix[line.user_id - 1, line.item_id - 1] = line.rating
test_data_matrix = np.zeros((n_users, n_items))
for line in test_data.itertuples():
test_data_matrix[line.user_id - 1, line.item_id - 1] = line.rating
def rmse(prediction, ground_truth):
prediction = prediction[ground_truth.nonzero()].flatten()
ground_truth = ground_truth[ground_truth.nonzero()].flatten()
return np.sqrt(np.mean((prediction - ground_truth) ** 2))Exercises solved: 0 of 2
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.