{"id":8706,"library":"tensorflow-recommenders","title":"TensorFlow Recommenders","description":"TensorFlow Recommenders (TFRS) is a library for building recommender system models using TensorFlow. It helps with the full workflow of building a recommender system: data preparation, model formulation, training, evaluation, and deployment. It's built on Keras and aims to have a gentle learning curve while still giving you the flexibility to build complex models.","status":"active","version":"0.7.7","language":"en","source_language":"en","source_url":"https://github.com/tensorflow/recommenders","tags":["tensorflow","recommenders","machine-learning","deep-learning","keras"],"install":[{"cmd":"pip install tensorflow-recommenders","lang":"bash","label":"Stable release"}],"dependencies":[{"reason":"TFRS is built on TensorFlow and specific versions are pinned in releases. Version 0.7.0 pins to >=2.9.0.","package":"tensorflow>=2.9.0"},{"reason":"Commonly used for loading benchmark datasets like MovieLens in tutorials and examples.","package":"tensorflow-datasets","optional":true},{"reason":"Used for efficient approximate nearest neighbor search, often integrated with TFRS for retrieval tasks.","package":"scann","optional":true}],"imports":[{"note":"The canonical import alias for tensorflow_recommenders is 'tfrs'.","wrong":"import tfrs","symbol":"tfrs","correct":"import tensorflow_recommenders as tfrs"},{"note":"Standard import for TensorFlow core functionalities.","symbol":"tf","correct":"import tensorflow as tf"},{"note":"Standard import for TensorFlow Datasets, frequently used with TFRS.","symbol":"tfds","correct":"import tensorflow_datasets as tfds"}],"quickstart":{"code":"import tensorflow as tf\nimport tensorflow_datasets as tfds\nimport tensorflow_recommenders as tfrs\n\n# Load the MovieLens 100K dataset\nratings = tfds.load('movielens/100k-ratings', split=\"train\")\nmovies = tfds.load('movielens/100k-movies', split=\"train\")\n\n# Prepare data by selecting relevant features\nratings = ratings.map(lambda x: {\"movie_title\": x[\"movie_title\"], \"user_id\": x[\"user_id\"]})\nmovies = movies.map(lambda x: x[\"movie_title\"])\n\n# Build vocabularies for user IDs and movie titles\nuser_ids_vocabulary = tf.keras.layers.StringLookup(mask_token=None)\nuser_ids_vocabulary.adapt(ratings.map(lambda x: x[\"user_id\"]))\n\nmovie_titles_vocabulary = tf.keras.layers.StringLookup(mask_token=None)\nmovie_titles_vocabulary.adapt(movies)\n\n# Define user and movie models using Keras Sequential\nuser_model = tf.keras.Sequential([\n    user_ids_vocabulary,\n    tf.keras.layers.Embedding(user_ids_vocabulary.vocabulary_size(), 32)\n])\nmovie_model = tf.keras.Sequential([\n    movie_titles_vocabulary,\n    tf.keras.layers.Embedding(movie_titles_vocabulary.vocabulary_size(), 32)\n])\n\n# Define the retrieval task with FactorizedTopK metric\ntask = tfrs.tasks.Retrieval(\n    metrics=tfrs.metrics.FactorizedTopK(\n        candidates=movies.batch(128).map(movie_model)\n    )\n)\n\n# Create a TFRS model\nclass MovieLensModel(tfrs.Model):\n  def __init__(self, user_model, movie_model):\n    super().__init__()\n    self.movie_model: tf.keras.Model = movie_model\n    self.user_model: tf.keras.Model = user_model\n    self.task: tf.keras.layers.Layer = task\n\n  def compute_loss(self, features: dict, training=False) -> tf.Tensor:\n    user_embeddings = self.user_model(features[\"user_id\"])\n    positive_movie_embeddings = self.movie_model(features[\"movie_title\"])\n\n    return self.task(user_embeddings, positive_movie_embeddings)\n\n# Compile and train the model\nmodel = MovieLensModel(user_model, movie_model)\nmodel.compile(optimizer=tf.keras.optimizers.Adagrad(0.1))\nmodel.fit(ratings.batch(4096), epochs=3)\n\n# Generate recommendations (example for a specific user)\nindex = tfrs.layers.factorized_top_k.BruteForce(model.user_model)\nindex.index_from_dataset(\n    movies.batch(100).map(lambda title: (title, model.movie_model(title)))\n)\n\n# Example: get recommendations for user with ID '42'\n_, titles = index(tf.constant([\"42\"]))\nprint(f\"Top 3 recommendations for user '42': {titles[0, :3].numpy().astype(str)}\")","lang":"python","description":"This quickstart builds a simple two-tower retrieval model for movie recommendations using the MovieLens 100K dataset. It demonstrates data loading, model definition (user and movie towers), task setup with FactorizedTopK metrics, training, and generating recommendations."},"warnings":[{"fix":"Use the `index_from_dataset` method for indexing with datasets to ensure correct alignment of embeddings and candidate identifiers.","message":"The `tfrs.layers.factorized_top_k.TopK` layer's indexing API changed in v0.6.0. Direct indexing with datasets is no longer supported in the same way.","severity":"breaking","affected_versions":">=0.6.0"},{"fix":"Update `FactorizedTopK` instantiation to use `ks=[k1, k2, ...]` instead of `k=k_value`. Remove the `metrics` argument if present.","message":"In v0.7.0, the `tfrs.metrics.FactorizedTopK` constructor parameters `k` was replaced with `ks` (a list of k values) and the `metrics` parameter was removed as it only makes sense with top-k metrics.","severity":"breaking","affected_versions":">=0.7.0"},{"fix":"Ensure that the `metrics` argument passed to `tfrs.tasks.Retrieval` is a list, even if it contains only one metric. E.g., `metrics=[tfrs.metrics.FactorizedTopK(...)]`.","message":"The `tfrs.tasks.Retrieval` task was updated in v0.7.3 to accept a *list* of factorized metrics, instead of a single optional metric.","severity":"breaking","affected_versions":">=0.7.3"},{"fix":"Remove the `batch_size` argument from `tfrs.layers.embedding.TPUEmbedding` constructor calls. The layer now supports dynamic input shapes.","message":"The `batch_size` argument for `tfrs.layers.embedding.TPUEmbedding` is deprecated and no longer required since v0.7.0.","severity":"deprecated","affected_versions":">=0.7.0"},{"fix":"Start with official tutorials and simple examples, progressively increasing complexity. Focus on understanding core concepts like embeddings, retrieval, and ranking tasks before building complex, production-ready models.","message":"TensorFlow Recommenders, while built on Keras, can have a steep learning curve due to its advanced concepts in recommendation systems and deep integration with TensorFlow.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure TensorFlow is correctly installed and compatible with your system. Update Visual C++ Redistributables (on Windows), or try reinstalling TensorFlow in a clean virtual environment, possibly specifying a CPU-only version if GPU issues are suspected. Verify your Python version meets TensorFlow's requirements.","cause":"This error typically indicates an issue with the TensorFlow installation itself, such as missing Visual C++ Redistributable packages on Windows, an incompatible Python version, or corrupted environment.","error":"ImportError: DLL load failed while importing _pywrap_tensorflow_internal: A dynamic link library (DLL) initialization routine failed."},{"fix":"Modify the `candidates` dataset passed to `index_from_dataset` to map each candidate item to a tuple of `(identifier, embedding)`. For example, `dataset.map(lambda title: (title, movie_model(title)))`.","cause":"This usually happens when using `index_from_dataset` on a `tfrs.layers.factorized_top_k.TopK` layer (e.g., `BruteForce`) but the dataset provided does not yield the expected format (e.g., just movie titles without their embeddings, or embeddings without their corresponding IDs).","error":"ValueError: The candidates dataset must produce (id, embedding) pairs or just embeddings for indexing."},{"fix":"Ensure your Keras model or layer is properly defined and has had its `build()` method called (implicitly by calling it on data, or explicitly). If loading from TF Hub, verify it's a TF2 SavedModel or handle TF1 Hub models correctly according to migration guides.","cause":"This error often occurs when trying to call a TensorFlow 2.x Keras model or layer that was not properly built or initialized, or when trying to load a TF1 Hub format model with TF2 `hub.load()`.","error":"TypeError: 'AutoTrackable' object is not callable"}]}