Path: blob/master/examples/structured_data/ipynb/movielens_recommendations_transformers.ipynb
3508 views
A Transformer-based recommendation system
Author: Khalid Salama
Date created: 2020/12/30
Last modified: 2025/01/27
Description: Rating rate prediction using the Behavior Sequence Transformer (BST) model on the Movielens.
Introduction
This example demonstrates the Behavior Sequence Transformer (BST) model, by Qiwei Chen et al., using the Movielens dataset. The BST model leverages the sequential behaviour of the users in watching and rating movies, as well as user profile and movie features, to predict the rating of the user to a target movie.
More precisely, the BST model aims to predict the rating of a target movie by accepting the following inputs:
A fixed-length sequence of
movie_ids
watched by a user.A fixed-length sequence of the
ratings
for the movies watched by a user.A set of user features, including
user_id
,sex
,occupation
, andage_group
.A set of
genres
for each movie in the input sequence and the target movie.A
target_movie_id
for which to predict the rating.
This example modifies the original BST model in the following ways:
We incorporate the movie features (genres) into the processing of the embedding of each movie of the input sequence and the target movie, rather than treating them as "other features" outside the transformer layer.
We utilize the ratings of movies in the input sequence, along with the their positions in the sequence, to update them before feeding them into the self-attention layer.
Note that this example should be run with TensorFlow 2.4 or higher.
The dataset
We use the 1M version of the Movielens dataset. The dataset includes around 1 million ratings from 6000 users on 4000 movies, along with some user features, movie genres. In addition, the timestamp of each user-movie rating is provided, which allows creating sequences of movie ratings for each user, as expected by the BST model.
Setup
Prepare the data
Download and prepare the DataFrames
First, let's download the movielens data.
The downloaded folder will contain three data files: users.dat
, movies.dat
, and ratings.dat
.
Then, we load the data into pandas DataFrames with their proper column names.
Here, we do some simple data processing to fix the data types of the columns.
Each movie has multiple genres. We split them into separate columns in the movies
DataFrame.
Transform the movie ratings data into sequences
First, let's sort the the ratings data using the unix_timestamp
, and then group the movie_id
values and the rating
values by user_id
.
The output DataFrame will have a record for each user_id
, with two ordered lists (sorted by rating datetime): the movies they have rated, and their ratings of these movies.
Now, let's split the movie_ids
list into a set of sequences of a fixed length. We do the same for the ratings
. Set the sequence_length
variable to change the length of the input sequence to the model. You can also change the step_size
to control the number of sequences to generate for each user.
After that, we process the output to have each sequence in a separate records in the DataFrame. In addition, we join the user features with the ratings data.
With sequence_length
of 4 and step_size
of 2, we end up with 498,623 sequences.
Finally, we split the data into training and testing splits, with 85% and 15% of the instances, respectively, and store them to CSV files.
Define metadata
Encode input features
The encode_input_features
function works as follows:
Each categorical user feature is encoded using
layers.Embedding
, with embedding dimension equals to the square root of the vocabulary size of the feature. The embeddings of these features are concatenated to form a single input tensor.Each movie in the movie sequence and the target movie is encoded
layers.Embedding
, where the dimension size is the square root of the number of movies.A multi-hot genres vector for each movie is concatenated with its embedding vector, and processed using a non-linear
layers.Dense
to output a vector of the same movie embedding dimensions.A positional embedding is added to each movie embedding in the sequence, and then multiplied by its rating from the ratings sequence.
The target movie embedding is concatenated to the sequence movie embeddings, producing a tensor with the shape of
[batch size, sequence length, embedding size]
, as expected by the attention layer for the transformer architecture.The method returns a tuple of two elements:
encoded_transformer_features
andencoded_other_features
.
Create model inputs
Create a BST model
Run training and evaluation experiment
You should achieve a Mean Absolute Error (MAE) at or around 0.7 on the test data.
Conclusion
The BST model uses the Transformer layer in its architecture to capture the sequential signals underlying users’ behavior sequences for recommendation.
You can try training this model with different configurations, for example, by increasing the input sequence length and training the model for a larger number of epochs. In addition, you can try including other features like movie release year and customer zipcode, and including cross features like sex X genre.