!pip install -q tensorflow-recommenders
!pip install -q --upgrade tensorflow-datasets

"""
Explanation: Recommending movies: ranking
Learning Objectives

Get our data and split it into a training and test set.
Implement a ranking model.
Fit and evaluate it.

Introduction
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.
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.
Each learning objective will correspond to a #TODO in this student lab notebook -- try to complete this notebook first and then review the solution notebook
Imports
Let's first get our imports out of the way.
End of explanation
"""


# You can use any Python source file as a module by executing an import statement in some other Python source file.
# The import statement combines two operations; it searches for the named module, then it binds the
# results of that search to a name in the local scope.
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

"""
Explanation: Note: Please ignore the incompatibility errors and re-run the above cell before proceeding for the lab.
End of explanation
"""


# Show the currently installed version of TensorFlow
print("TensorFlow version: ",tf.version.VERSION)

"""
Explanation: This notebook uses TF2.x.
Please check your tensorflow version using the cell below.
End of explanation
"""


ratings = tfds.load("movielens/100k-ratings", split="train")

ratings = ratings.map(lambda x: {
    "movie_title": x["movie_title"],
    "user_id": x["user_id"],
    "user_rating": x["user_rating"]
})

"""
Explanation: Lab Task 1: Preparing the dataset
We're going to use the same data as the retrieval tutorial. This time, we're also going to keep the ratings: these are the objectives we are trying to predict.
End of explanation
"""


tf.random.set_seed(42)
shuffled = ratings.shuffle(100_000, seed=42, reshuffle_each_iteration=False)

# TODO 1a -- your code goes here

"""
Explanation: As before, we'll split the data by putting 80% of the ratings in the train set, and 20% in the test set.
End of explanation
"""


movie_titles = ratings.batch(1_000_000).map(lambda x: x["movie_title"])
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)))

"""
Explanation: 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.
End of explanation
"""


class RankingModel(tf.keras.Model):

  def __init__(self):
    super().__init__()
    embedding_dimension = 32

    # Compute embeddings for users.

    # TODO 2a -- your code goes here

    # Compute embeddings for movies.

    # TODO 2b -- your code goes here

    # Compute predictions.
    self.ratings = tf.keras.Sequential([
      # Learn multiple dense layers.
      tf.keras.layers.Dense(256, activation="relu"),
      tf.keras.layers.Dense(64, activation="relu"),
      # Make rating predictions in the final layer.
      tf.keras.layers.Dense(1)
  ])
    
  def call(self, inputs):

    user_id, movie_title = inputs

    user_embedding = self.user_embeddings(user_id)
    movie_embedding = self.movie_embeddings(movie_title)

    return self.ratings(tf.concat([user_embedding, movie_embedding], axis=1))

"""
Explanation: Lab Task 2: Implementing a model
Architecture
Ranking models do not face the same efficiency constraints as retrieval models do, and so we have a little bit more freedom in our choice of architectures.
A model composed of multiple stacked dense layers is a relatively common architecture for ranking tasks. We can implement it as follows:
End of explanation
"""


RankingModel()((["42"], ["One Flew Over the Cuckoo's Nest (1975)"]))

"""
Explanation: This model takes user ids and movie titles, and outputs a predicted rating:
End of explanation
"""


task = tfrs.tasks.Ranking(
  loss = tf.keras.losses.MeanSquaredError(),
  metrics=[tf.keras.metrics.RootMeanSquaredError()]
)

"""
Explanation: Loss and metrics
The 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 Ranking task object: a convenience wrapper that bundles together the loss function and metric computation. 
We'll use it together with the MeanSquaredError Keras loss in order to predict the ratings.
End of explanation
"""


class MovielensModel(tfrs.models.Model):

  def __init__(self):
    super().__init__()
    self.ranking_model: tf.keras.Model = RankingModel()
    self.task: tf.keras.layers.Layer = tfrs.tasks.Ranking(
      loss = tf.keras.losses.MeanSquaredError(),
      metrics=[tf.keras.metrics.RootMeanSquaredError()]
    )

  def compute_loss(self, features: Dict[Text, tf.Tensor], training=False) -> tf.Tensor:
    rating_predictions = self.ranking_model(
        (features["user_id"], features["movie_title"]))

    # The task computes the loss and the metrics.
    return self.task(labels=features["user_rating"], predictions=rating_predictions)

"""
Explanation: The task itself is a Keras layer that takes true and predicted as arguments, and returns the computed loss. We'll use that to implement the model's training loop.
The full model
We 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.
End of explanation
"""


model = MovielensModel()
model.compile(optimizer=tf.keras.optimizers.Adagrad(learning_rate=0.1))

"""
Explanation: Lab Task 3: Fitting and evaluating
After defining the model, we can use standard Keras fitting and evaluation routines to fit and evaluate the model.
Let's first instantiate the model.
End of explanation
"""


cached_train = train.shuffle(100_000).batch(8192).cache()
cached_test = test.batch(4096).cache()

"""
Explanation: Then shuffle, batch, and cache the training and evaluation data.
End of explanation
"""


model.fit(cached_train, epochs=3)

"""
Explanation: Then train the  model:
End of explanation
"""


# TODO 3a -- your code goes here

"""
Explanation: As the model trains, the loss is falling and the RMSE metric is improving.
Finally, we can evaluate our model on the test set:
End of explanation
"""


