<jupyter_start><jupyter_text>Recommending Movies: Retrieval Real-world recommender systems are often composed of two stages:1. The retrieval stage is responsible for selecting an initial set of hundreds of candidates from all possible candidates. The main objective of this model is to efficiently weed out all candidates that the user is not interested in. Because the retrieval model may be dealing with millions of candidates, it has to be computationally efficient.2. The ranking stage takes the outputs of the retrieval model and fine-tunes them to select the best possible handful of recommendations. Its task is to narrow down the set of items the user may be interested in to a shortlist of likely candidates.In this tutorial, we're going to focus on the first stage, retrieval. If you are interested in the ranking stage, have a look at our [ranking](basic_ranking) tutorial.Retrieval models are often composed of two sub-models:1. A query model computing the query representation (normally a fixed-dimensionality embedding vector) using query features.2. A candidate model computing the candidate representation (an equally-sized vector) using the candidate featuresThe outputs of the two models are then multiplied together to give a query-candidate affinity score, with higher scores expressing a better match between the candidate and the query.In this tutorial, we're going to build and train such a two-tower model using the Movielens dataset.We're going to:1. Get our data and split it into a training and test set.2. Implement a retrieval model.3. Fit and evaluate it.4. Export it for efficient serving by building an approximate nearest neighbours (ANN) index.  The datasetThe Movielens dataset is a classic dataset from the [GroupLens](https://grouplens.org/datasets/movielens/) research group at the University of Minnesota. It contains a set of ratings given to movies by a set of users, and is a workhorse of recommender system research.The data can be treated in two ways:1. It can be interpreted as expressesing which movies the users watched (and rated), and which they did not. This is a form of implicit feedback, where users' watches tell us which things they prefer to see and which they'd rather not see.2. It can also be seen as expressesing how much the users liked the movies they did watch. This is a form of explicit feedback: given that a user watched a movie, we can tell roughly how much they liked by looking at the rating they have given.In this tutorial, we are focusing on a retrieval system: a model that predicts a set of movies from the catalogue that the user is likely to watch. Often, implicit data is more useful here, and so we are going to treat Movielens as an implicit system. This means that every movie a user watched is a positive example, and every movie they have not seen is an implicit negative example.  ImportsLet's first get our imports out of the way.<jupyter_code>import os
import pprint
import tempfile

from typing import Dict, Text

import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_recommenders as tfrs<jupyter_output><empty_output><jupyter_text>Preparing the datasetLet's first have a look at the data.We use the MovieLens dataset from [Tensorflow Datasets](https://www.tensorflow.org/datasets). Loading `movie_lens/100k_ratings` yields a `tf.data.Dataset` object containing the ratings data and loading `movie_lens/100k_movies` yields a `tf.data.Dataset` object containing only the movies data.Note that since the MovieLens dataset does not have predefined splits, all data are under `train` split.<jupyter_code># Ratings data.
ratings = tfds.load("movie_lens/100k-ratings", split="train")
# Features of all the available movies.
movies = tfds.load("movie_lens/100k-movies", split="train")<jupyter_output><empty_output><jupyter_text>The ratings dataset returns a dictionary of movie id, user id, the assigned rating, timestamp, movie information, and user information:<jupyter_code>for x in ratings.take(1).as_numpy_iterator():
  pprint.pprint(x)<jupyter_output>{'bucketized_user_age': 45.0,
 'movie_genres': array([7]),
 'movie_id': b'357',
 'movie_title': b"One Flew Over the Cuckoo's Nest (1975)",
 'raw_user_age': 46.0,
 'timestamp': 879024327,
 'user_gender': True,
 'user_id': b'138',
 'user_occupation_label': 4,
 'user_occupation_text': b'doctor',
 'user_rating': 4.0,
 'user_zip_code': b'53211'}<jupyter_text>The movies dataset contains the movie id, movie title, and data on what genres it belongs to. Note that the genres are encoded with integer labels.<jupyter_code>for x in movies.take(1).as_numpy_iterator():
  pprint.pprint(x)<jupyter_output>{'movie_genres': array([4]),
 'movie_id': b'1681',
 'movie_title': b'You So Crazy (1994)'}<jupyter_text>In this example, we're going to focus on the ratings data. Other tutorials explore how to use the movie information data as well to improve the model quality.We keep only the `user_id`, and `movie_title` fields in the dataset.<jupyter_code>ratings = ratings.map(lambda x: {
    "movie_title": x["movie_title"],
    "user_id": x["user_id"],
})
movies = movies.map(lambda x: x["movie_title"])<jupyter_output><empty_output><jupyter_text>To fit and evaluate the model, we need to split it into a training and evaluation set. In an industrial recommender system, this would most likely be done by time: the data up to time $T$ would be used to predict interactions after $T$.In this simple example, however, let's use a random split, putting 80% of the ratings in the train set, and 20% in the test set.<jupyter_code>tf.random.set_seed(42)
shuffled = ratings.shuffle(100_000, seed=42, reshuffle_each_iteration=False)

train = shuffled.take(80_000)
test = shuffled.skip(80_000).take(20_000)<jupyter_output><empty_output><jupyter_text>Let's also figure out unique user ids and movie titles present in the data. This is important because we need to be able to map the raw values of our categorical features to embedding vectors in our models. To do that, we need a vocabulary that maps a raw feature value to an integer in a contiguous range: this allows us to look up the corresponding embeddings in our embedding tables.<jupyter_code>movie_titles = movies.batch(1_000)
user_ids = ratings.batch(1_000_000).map(lambda x: x["user_id"])

unique_movie_titles = np.unique(np.concatenate(list(movie_titles)))
unique_user_ids = np.unique(np.concatenate(list(user_ids)))

unique_movie_titles[:10]<jupyter_output><empty_output><jupyter_text>Implementing a modelChoosing the architecure of our model a key part of modelling.Because we are building a two-tower retrieval model, we can build each tower separately and then combine them in the final model.  The query towerLet's start with the query tower.The first step is to decide on the dimensionality of the query and candidate representations:<jupyter_code>embedding_dimension = 32<jupyter_output><empty_output><jupyter_text>Higher values will correspond to models that may be more accurate, but will also be slower to fit and more prone to overfitting.The second is to define the model itself. Here, we're going to use Keras preprocessing layers to first convert user ids to integers, and then convert those to user embeddings via an `Embedding` layer. Note that we use the list of unique user ids we computed earlier as a vocabulary:  _Note: Requires TF 2.3.0_<jupyter_code>user_model = tf.keras.Sequential([
  tf.keras.layers.experimental.preprocessing.StringLookup(
      vocabulary=unique_user_ids, mask_token=None),
  # We add an additional embedding to account for unknown tokens.
  tf.keras.layers.Embedding(len(unique_user_ids) + 1, embedding_dimension)
])<jupyter_output><empty_output><jupyter_text>A simple model like this corresponds exactly to a classic [matrix factorization](https://ieeexplore.ieee.org/abstract/document/4781121) approach. While defining a subclass of `tf.keras.Model` for this simple model might be overkill, we can easily extend it to an arbitrarily complex model using standard Keras components, as long as we return an `embedding_dimension`-wide output at the end.  The candidate towerWe can do the same with the candidate tower.<jupyter_code>movie_model = tf.keras.Sequential([
  tf.keras.layers.experimental.preprocessing.StringLookup(
      vocabulary=unique_movie_titles, mask_token=None),
  tf.keras.layers.Embedding(len(unique_movie_titles) + 1, embedding_dimension)
])<jupyter_output><empty_output><jupyter_text>MetricsIn our training data we have positive (user, movie) pairs. To figure out how good our model is, we need to compare the affinity score that the model calculates for this pair to the scores of all the other possible candidates: if the score for the positive pair is higher than for all other candidates, our model is highly accurate.To do this, we can use the `tfrs.metrics.FactorizedTopK` metric. The metric has one required argument: the dataset of candidates that are used as implicit negatives for evaluation.In our case, that's the `movies` dataset, converted into embeddings via our movie model:<jupyter_code>metrics = tfrs.metrics.FactorizedTopK(
  candidates=movies.batch(128).map(movie_model)
)<jupyter_output><empty_output><jupyter_text>LossThe next component is the loss used to train our model. TFRS has several loss layers and tasks to make this easy.In this instance, we'll make use of the `Retrieval` task object: a convenience wrapper that bundles together the loss function and metric computation:<jupyter_code>task = tfrs.tasks.Retrieval(
  metrics=metrics
)<jupyter_output><empty_output><jupyter_text>The task itself is a Keras layer that takes the query and candidate embeddings as arguments, and returns the computed loss: we'll use that to implement the model's training loop.  The full modelWe can now put it all together into a model. TFRS exposes a base model class (`tfrs.models.Model`) which streamlines bulding models: all we need to do is to set up the components in the `__init__` method, and implement the `compute_loss` method, taking in the raw features and returning a loss value.The base model will then take care of creating the appropriate training loop to fit our model.<jupyter_code>class MovielensModel(tfrs.Model):

  def __init__(self, user_model, movie_model):
    super().__init__()
    self.movie_model: tf.keras.Model = movie_model
    self.user_model: tf.keras.Model = user_model
    self.task: tf.keras.layers.Layer = task

  def compute_loss(self, features: Dict[Text, tf.Tensor], training=False) -> tf.Tensor:
    # We pick out the user features and pass them into the user model.
    user_embeddings = self.user_model(features["user_id"])
    # And pick out the movie features and pass them into the movie model,
    # getting embeddings back.
    positive_movie_embeddings = self.movie_model(features["movie_title"])

    # The task computes the loss and the metrics.
    return self.task(user_embeddings, positive_movie_embeddings)<jupyter_output><empty_output><jupyter_text>The `tfrs.Model` base class is a simply convenience class: it allows us to compute both training and test losses using the same method.Under the hood, it's still a plain Keras model. You could achieve the same functionality by inheriting from `tf.keras.Model` and overriding the `train_step` and `test_step` functions (see [the guide](https://keras.io/guides/customizing_what_happens_in_fit/) for details):<jupyter_code>class NoBaseClassMovielensModel(tf.keras.Model):

  def __init__(self, user_model, movie_model):
    super().__init__()
    self.movie_model: tf.keras.Model = movie_model
    self.user_model: tf.keras.Model = user_model
    self.task: tf.keras.layers.Layer = task

  def train_step(self, features: Dict[Text, tf.Tensor]) -> tf.Tensor:

    # Set up a gradient tape to record gradients.
    with tf.GradientTape() as tape:

      # Loss computation.
      user_embeddings = self.user_model(features["user_id"])
      positive_movie_embeddings = self.movie_model(features["movie_title"])
      loss = self.task(user_embeddings, positive_movie_embeddings)

      # Handle regularization losses as well.
      regularization_loss = sum(self.losses)

      total_loss = loss + regularization_loss

    gradients = tape.gradient(total_loss, self.trainable_variables)
    self.optimizer.apply_gradients(zip(gradients, self.trainable_variables))

    metrics = {metric.name: metric.result() for metric in self.metrics}
    metrics["loss"] = loss
    metrics["regularization_loss"] = regularization_loss
    metrics["total_loss"] = total_loss

    return metrics

  def test_step(self, features: Dict[Text, tf.Tensor]) -> tf.Tensor:

    # Loss computation.
    user_embeddings = self.user_model(features["user_id"])
    positive_movie_embeddings = self.movie_model(features["movie_title"])
    loss = self.task(user_embeddings, positive_movie_embeddings)

    # Handle regularization losses as well.
    regularization_loss = sum(self.losses)

    total_loss = loss + regularization_loss

    metrics = {metric.name: metric.result() for metric in self.metrics}
    metrics["loss"] = loss
    metrics["regularization_loss"] = regularization_loss
    metrics["total_loss"] = total_loss

    return metrics<jupyter_output><empty_output><jupyter_text>In these tutorials, however, we stick to using the `tfrs.Model` base class to keep our focus on modelling and abstract away some of the boilerplate.  Fitting and evaluatingAfter defining the model, we can use standard Keras fitting and evaluation routines to fit and evaluate the model.Let's first instantiate the model.<jupyter_code>model = MovielensModel(user_model, movie_model)
model.compile(optimizer=tf.keras.optimizers.Adagrad(learning_rate=0.1))<jupyter_output><empty_output><jupyter_text>Then shuffle, batch, and cache the training and evaluation data.<jupyter_code>cached_train = train.shuffle(100_000).batch(8192).cache()
cached_test = test.batch(4096).cache()<jupyter_output><empty_output><jupyter_text>Then train the  model:<jupyter_code>model.fit(cached_train, epochs=3)<jupyter_output>Epoch 1/3
10/10 [==============================] - 5s 464ms/step - factorized_top_k: 0.0508 - factorized_top_k/top_1_categorical_accuracy: 3.2500e-04 - factorized_top_k/top_5_categorical_accuracy: 0.0046 - factorized_top_k/top_10_categorical_accuracy: 0.0117 - factorized_top_k/top_50_categorical_accuracy: 0.0808 - factorized_top_k/top_100_categorical_accuracy: 0.1566 - loss: 69885.1072 - regularization_loss: 0.0000e+00 - total_loss: 69885.1072
Epoch 2/3
10/10 [==============================] - 5s 453ms/step - factorized_top_k: 0.1006 - factorized_top_k/top_1_categorical_accuracy: 0.0021 - factorized_top_k/top_5_categorical_accuracy: 0.0168 - factorized_top_k/top_10_categorical_accuracy: 0.0346 - factorized_top_k/top_50_categorical_accuracy: 0.1626 - factorized_top_k/top_100_categorical_accuracy: 0.2866 - loss: 67523.3714 - regularization_loss: 0.0000e+00 - total_loss: 67523.3714
Epoch 3/3
10/10 [==============================] - 5s 454ms/step - factorized_top_k: 0.1136 - factorized_top[...]<jupyter_text>As the model trains, the loss is falling and a set of top-k retrieval metrics is updated. These tell us whether the true positive is in the top-k retrieved items from the entire candidate set. For example, a top-5 categorical accuracy metric of 0.2 would tell us that, on average, the true positive is in the top 5 retrieved items 20% of the time.Note that, in this example, we evaluate the metrics during training as well as evaluation. Because this can be quite slow with large candidate sets, it may be prudent to turn metric calculation off in training, and only run it in evaluation. Finally, we can evaluate our model on the test set:<jupyter_code>model.evaluate(cached_test, return_dict=True)<jupyter_output>5/5 [==============================] - 1s 169ms/step - factorized_top_k: 0.0782 - factorized_top_k/top_1_categorical_accuracy: 0.0010 - factorized_top_k/top_5_categorical_accuracy: 0.0097 - factorized_top_k/top_10_categorical_accuracy: 0.0226 - factorized_top_k/top_50_categorical_accuracy: 0.1248 - factorized_top_k/top_100_categorical_accuracy: 0.2328 - loss: 31079.0635 - regularization_loss: 0.0000e+00 - total_loss: 31079.0635<jupyter_text>Test set performance is much worse than training performance. This is due to two factors:1. Our model is likely to perform better on the data that it has seen, simply because it can memorize it. This overfitting phenomenon is especially strong when models have many parameters. It can be mediated by model regularization and use of user and movie features that help the model generalize better to unseen data.2. The model is re-recommending some of users' already watched movies. These known-positive watches can crowd out test movies out of top K recommendations.The second phenomenon can be tackled by excluding previously seen movies from test recommendations. This approach is relatively common in the recommender systems literature, but we don't follow it in these tutorials. If not recommending past watches is important, we should expect appropriately specified models to learn this behaviour automatically from past user history and contextual information. Additionally, it is often appropriate to recommend the same item multiple times (say, an evergreen TV series or a regularly purchased item).  Making predictionsNow that we have a model, we would like to be able to make predictions. We can use the `tfrs.layers.ann.BruteForce` layer to do this.<jupyter_code># Create a model that takes in raw query features, and
index = tfrs.layers.ann.BruteForce(model.user_model)
# recommends movies out of the entire movies dataset.
index.index(movies.batch(100).map(model.movie_model), movies)

# Get recommendations.
_, titles = index(tf.constant(["42"]))
print(f"Recommendations for user 42: {titles[0, :3]}")<jupyter_output>Recommendations for user 42: [b'Bridges of Madison County, The (1995)'
 b'Father of the Bride Part II (1995)' b'Rudy (1993)']<jupyter_text>Of course, the `BruteForce` layer is going to be too slow to serve a model with many possible candidates. The following sections shows how to speed this up by using an approximate retrieval index.  Model servingAfter the model is trained, we need a way to deploy it.In a two-tower retrieval model, serving has two components:- a serving query model, taking in features of the query and transforming them into a query embedding, and- a serving candidate model. This most often takes the form of an approximate nearest neighbours (ANN) index which allows fast approximate lookup of candidates in response to a query produced by the query model.  Exporting a query model to servingExporting the query model is easy: we can either serialize the Keras model directly, or export it to a `SavedModel` format to make it possible to serve using [TensorFlow Serving](https://www.tensorflow.org/tfx/guide/serving).To export to a `SavedModel` format, we can do the following:<jupyter_code>model_dir = './models'
!mkdir $model_dir
# Export the query model.
path = '{}/query_model'.format(model_dir)
model.user_model.save(path)
# Load the query model
loaded = tf.keras.models.load_model(path, compile=False)
query_embedding = loaded(tf.constant(["10"]))

print(f"Query embedding: {query_embedding[0, :3]}")<jupyter_output>WARNING:tensorflow:11 out of the last 11 calls to <function recreate_function.<locals>.restored_function_body at 0x7f85d75cce18> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for  more details.<jupyter_text>Building a candidate ANN indexExporting candidate representations is more involved. Firstly, we want to pre-compute them to make sure serving is fast; this is especially important if the candidate model is computationally intensive (for example, if it has many or wide layers; or uses complex representations for text or images). Secondly, we would like to take the precomputed representations and use them to construct a fast approximate retrieval index.We can use [Annoy](https://github.com/spotify/annoy) to build such an index.Annoy isn't included in the base TFRS package. To install it, run:  We can now create the index object.<jupyter_code>from annoy import AnnoyIndex

index = AnnoyIndex(embedding_dimension, "dot")<jupyter_output><empty_output><jupyter_text>Then take the candidate dataset and transform its raw features into embeddings using the movie model:<jupyter_code>print(movies)
movie_embeddings = movies.enumerate().map(lambda idx, title: (idx, title, model.movie_model(title)))

print(movie_embeddings.as_numpy_iterator().next())<jupyter_output>(0, b'You So Crazy (1994)', array([ 0.02039416,  0.15982407,  0.0063992 , -0.02597233,  0.12776582,
       -0.07474077, -0.14477485, -0.03757067,  0.09737739,  0.05545571,
        0.06205893,  0.00479794, -0.1288748 , -0.09362403,  0.03417863,
       -0.03058628, -0.02924258, -0.09905305, -0.08250699, -0.12956885,
       -0.00052435, -0.07832637, -0.00451247,  0.04807298, -0.07815737,
       -0.18195164,  0.10836799, -0.01164408, -0.10894814, -0.03122996,
       -0.10479282, -0.09899054], dtype=float32))<jupyter_text>And then index the movie_id, movie embedding pairs into our Annoy index:<jupyter_code>%%time

movie_id_to_title = dict((idx, title) for idx, title, _ in movie_embeddings.as_numpy_iterator())

# We unbatch the dataset because Annoy accepts only scalar (id, embedding) pairs.
for movie_id, _, movie_embedding in movie_embeddings.as_numpy_iterator():
  index.add_item(movie_id, movie_embedding)

# Build a 10-tree ANN index.
index.build(10)<jupyter_output><empty_output><jupyter_text>We can then retrieve nearest neighbours:<jupyter_code>for row in test.batch(1).take(3):
  query_embedding = model.user_model(row["user_id"])[0]
  candidates = index.get_nns_by_vector(query_embedding, 3)
  print(f"User ID: {row['user_id']}, Candidates: {[movie_id_to_title[x] for x in candidates]}.")

print(type(candidates))<jupyter_output><class 'list'>
{'fraction_non_alphanumeric': 0.08210414074995558, 'fraction_numerical': 0.03252177003732006, 'mean_word_length': 5.3710727427115765, 'pattern_counts': {'":': 2, '<': 92, '<?xml version=': 0, '>': 95, 'https://': 8, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '24', 'dir': 'jupyter-structured-clean-dedup', 'id': '554', 'license': 'Apache-2.0', 'n_tokens_mistral': 7088, 'n_tokens_neox': 6434, 'n_words': 2530, 'path': '02_usecases/sagemaker_recommendations/wip/02_Recommenders_Retrieval_AdHoc.ipynb', 'repo_name': 'MarcusFra/workshop', 'size': '22508'}