text stringlengths 0 4.99k |
|---|
123/123 [==============================] - 1s 6ms/step - loss: 0.3088 - sparse_categorical_accuracy: 0.8559 |
Epoch 9/10 |
123/123 [==============================] - 1s 6ms/step - loss: 0.3066 - sparse_categorical_accuracy: 0.8573 |
Epoch 10/10 |
123/123 [==============================] - 1s 6ms/step - loss: 0.3048 - sparse_categorical_accuracy: 0.8573 |
Model training finished |
Evaluating the model on the test data... |
62/62 [==============================] - 2s 5ms/step - loss: 0.3140 - sparse_categorical_accuracy: 0.8533 |
Test accuracy: 85.33% |
Recommending movies using a model trained on Movielens dataset. |
Introduction |
This example demonstrates Collaborative filtering using the Movielens dataset to recommend movies to users. The MovieLens ratings dataset lists the ratings given by a set of users to a set of movies. Our goal is to be able to predict ratings for movies a user has not yet watched. The movies with the highest predicted ratings can then be recommended to the user. |
The steps in the model are as follows: |
Map user ID to a \"user vector\" via an embedding matrix |
Map movie ID to a \"movie vector\" via an embedding matrix |
Compute the dot product between the user vector and movie vector, to obtain the a match score between the user and the movie (predicted rating). |
Train the embeddings via gradient descent using all known user-movie pairs. |
References: |
Collaborative Filtering |
Neural Collaborative Filtering |
import pandas as pd |
import numpy as np |
from zipfile import ZipFile |
import tensorflow as tf |
from tensorflow import keras |
from tensorflow.keras import layers |
from pathlib import Path |
import matplotlib.pyplot as plt |
First, load the data and apply preprocessing |
# Download the actual data from http://files.grouplens.org/datasets/movielens/ml-latest-small.zip\" |
# Use the ratings.csv file |
movielens_data_file_url = ( |
\"http://files.grouplens.org/datasets/movielens/ml-latest-small.zip\" |
) |
movielens_zipped_file = keras.utils.get_file( |
\"ml-latest-small.zip\", movielens_data_file_url, extract=False |
) |
keras_datasets_path = Path(movielens_zipped_file).parents[0] |
movielens_dir = keras_datasets_path / \"ml-latest-small\" |
# Only extract the data the first time the script is run. |
if not movielens_dir.exists(): |
with ZipFile(movielens_zipped_file, \"r\") as zip: |
# Extract files |
print(\"Extracting all the files now...\") |
zip.extractall(path=keras_datasets_path) |
print(\"Done!\") |
ratings_file = movielens_dir / \"ratings.csv\" |
df = pd.read_csv(ratings_file) |
First, need to perform some preprocessing to encode users and movies as integer indices. |
user_ids = df[\"userId\"].unique().tolist() |
user2user_encoded = {x: i for i, x in enumerate(user_ids)} |
userencoded2user = {i: x for i, x in enumerate(user_ids)} |
movie_ids = df[\"movieId\"].unique().tolist() |
movie2movie_encoded = {x: i for i, x in enumerate(movie_ids)} |
movie_encoded2movie = {i: x for i, x in enumerate(movie_ids)} |
df[\"user\"] = df[\"userId\"].map(user2user_encoded) |
df[\"movie\"] = df[\"movieId\"].map(movie2movie_encoded) |
num_users = len(user2user_encoded) |
num_movies = len(movie_encoded2movie) |
df[\"rating\"] = df[\"rating\"].values.astype(np.float32) |
# min and max ratings will be used to normalize the ratings later |
min_rating = min(df[\"rating\"]) |
max_rating = max(df[\"rating\"]) |
print( |
\"Number of users: {}, Number of Movies: {}, Min rating: {}, Max rating: {}\".format( |
num_users, num_movies, min_rating, max_rating |
) |
) |
Number of users: 610, Number of Movies: 9724, Min rating: 0.5, Max rating: 5.0 |
Prepare training and validation data |
df = df.sample(frac=1, random_state=42) |
x = df[[\"user\", \"movie\"]].values |
# Normalize the targets between 0 and 1. Makes it easy to train. |
y = df[\"rating\"].apply(lambda x: (x - min_rating) / (max_rating - min_rating)).values |
# Assuming training on 90% of the data and validating on 10%. |
train_indices = int(0.9 * df.shape[0]) |
x_train, x_val, y_train, y_val = ( |
x[:train_indices], |
x[train_indices:], |
y[:train_indices], |
y[train_indices:], |
) |
Create the model |
We embed both users and movies in to 50-dimensional vectors. |
The model computes a match score between user and movie embeddings via a dot product, and adds a per-movie and per-user bias. The match score is scaled to the [0, 1] interval via a sigmoid (since our ratings are normalized to this range). |
EMBEDDING_SIZE = 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.