TensorFlow Recommenders: Quickstart

XianxinMao 2021-07-30 11:01:38

In this tutorial, we build a simple matrix factorization model using the MovieLens 100K dataset with TFRS. We can use this model to recommend movies for a given user.

Import TFRS

from typing import Dict, Text
​
import numpy as np
import tensorflow as tf
​
import tensorflow_datasets as tfds
import tensorflow_recommenders as tfrs

Read the data

# Ratings data.
ratings = tfds.load('movielens/100k-ratings', split="train")
# Features of all the available movies.
movies = tfds.load('movielens/100k-movies', split="train")
​
# Select the basic features.
ratings = ratings.map(lambda x: {
    "movie_title": x["movie_title"],
    "user_id": x["user_id"]
})
movies = movies.map(lambda x: x["movie_title"])

Build vocabularies to convert user ids and movie titles into integer indices for embedding layers:

user_ids_vocabulary = tf.keras.layers.experimental.preprocessing.StringLookup(mask_token=None)
user_ids_vocabulary.adapt(ratings.map(lambda x: x["user_id"]))
​
movie_titles_vocabulary = tf.keras.layers.experimental.preprocessing.StringLookup(mask_token=None)
movie_titles_vocabulary.adapt(movies)

Define a model

We can define a TFRS model by inheriting from tfrs.Model and implementing the compute_loss method:

class MovieLensModel(tfrs.Model):
  # We derive from a custom base class to help reduce boilerplate. Under the hood,
  # these are still plain Keras Models.
​
  def __init__(
      self,
      user_model: tf.keras.Model,
      movie_model: tf.keras.Model,
      task: tfrs.tasks.Retrieval):
    super().__init__()
​
    # Set up user and movie representations.
    self.user_model = user_model
    self.movie_model = movie_model
​
    # Set up a retrieval task.
    self.task = task
​
  def compute_loss(self, features: Dict[Text, tf.Tensor], training=False) -> tf.Tensor:
    # Define how the loss is computed.
​
    user_embeddings = self.user_model(features["user_id"])
    movie_embeddings = self.movie_model(features["movie_title"])
​
    return self.task(user_embeddings, movie_embeddings)

Define the two models and the retrieval task.

# Define user and movie models.
user_model = tf.keras.Sequential([
    user_ids_vocabulary,
    tf.keras.layers.Embedding(user_ids_vocabulary.vocab_size(), 64)
])
movie_model = tf.keras.Sequential([
    movie_titles_vocabulary,
    tf.keras.layers.Embedding(movie_titles_vocabulary.vocab_size(), 64)
])
​
# Define your objectives.
task = tfrs.tasks.Retrieval(metrics=tfrs.metrics.FactorizedTopK(
    movies.batch(128).map(movie_model)
  )
)

Fit and evaluate it.

Create the model, train it, and generate predictions:

# Create a retrieval model.
model = MovieLensModel(user_model, movie_model, task)
model.compile(optimizer=tf.keras.optimizers.Adagrad(0.5))
​
# Train for 3 epochs.
model.fit(ratings.batch(4096), epochs=3)
​
# Use brute-force search to set up retrieval using the trained representations.
index = tfrs.layers.factorized_top_k.BruteForce(model.user_model)
index.index(movies.batch(100).map(model.movie_model), movies)
​
# Get some recommendations.
_, titles = index(np.array(["42"]))
print(f"Top 3 recommendations for user 42: {titles[0, :3]}")

代码地址: https://codechina.csdn.net/csdn_codechina/enterprise_technology/-/blob/master/NLP_recommend/TensorFlow%20Recommenders:%20Quickstart.ipynb

...全文
25 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

7,340

社区成员

发帖
与我相关
我的任务
社区描述
因为缘分,所以猿粉! 这里有“入门级选手”必备的成长路线图,为“程序员后备队”提供技术大咖直播指导,丰富的学习资料已经等候多时,请查收! 陪伴猿粉共同成长,提升技术不在话下;右边扫码关注微信公众号。
其他 其他
社区管理员
  • 高校俱乐部
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

       2021年“C站百所高校巡讲” “C站名企参观”等活动,火热报名中, 与CSDN创始人蒋涛、各路技术大咖面对面!

       现招募CSDN高校俱乐部的部长并组建本校CSDN高校俱乐部,我们希望你是高校在校生且是IT技术爱好者,校内社交圈,有强烈的责任心,熟悉社团工作,有校园活动组织经验,在高校能够建立长足发展的学习型俱乐部,我们期待您的加入,CSDN高校俱乐部将赋予以下权益:

  • 高校巡讲:骨灰级专家线下巡讲
  • 线上直播:技术大咖线上分享
  • 线下沙龙:学习精英线下沙龙讨论
  • 学习小组:任务驱动,免费学习
  • 能力认证:对标大厂,高薪就业
  • 技术竞赛:竞赛选拔,实战演练
  • 企业游学:到大厂参观并学习
  • 企业招聘:面向俱乐部成员专属招聘
  • 专属博客:给各俱乐部搭建社区云
  • 电子书卡:给俱乐部成员提供学习资源
  • 组织logo:设计旗帜,活动宣传

 联系方式:

  • 电话:张老师-17734567851(同微)
  • 邮箱:student@csdn.net
  • Q Q:1218227747

试试用AI创作助手写篇文章吧