TensorFlow Recommenders: Quickstart

简介: 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.

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

目录
相关文章
|
存储 人工智能 自动驾驶
FMW 2023 | 阿里云存储邀您一同探讨“芯存储 AI未来”
8月29-30日,以“芯存储 AI未来”为主题的2023全球闪存峰会(FMW)在杭州开元名都大酒店举办。
596 0
|
存储 Kubernetes 持续交付
Docker 核心概念深度解析:探索容器、镜像和仓库在Docker生态系统中的重要作用和 应用
Docker 核心概念深度解析:探索容器、镜像和仓库在Docker生态系统中的重要作用和 应用
1207 0
|
移动开发 算法 调度
【贪心算法】一文让你学会“贪心”(贪心算法详解及经典案例)
贪心算法是一种非常常见的算法,它的简单和高效性使其在实际应用中被广泛使用。 贪心算法的核心思想是在每一步都采取当前状态下最优的选择,而不考虑未来可能产生的影响。虽然贪心算法不能保证总是得到最优解,但在很多情况下,它可以获得很好的结果。 本篇文章将介绍贪心算法的基本概念和一些经典应用,以及如何通过贪心算法来解决一些实际问题。希望通过本文的阅读,读者可以对贪心算法有更加深刻的理解,并能够在实际问题中应用贪心算法来得到更好的解决方案。 让我们暴打贪心算法吧!
6173 0
|
Oracle Java 关系型数据库
在 macOS 上安装 JDK 17
在 macOS 上安装 JDK JDK 支持基于 Intel (x64) 和 Apple Silicon (AArch64) 的 Mac 电脑。 本主题包括以下部分: 在 macOS 上安装 JDK 的系统要求 macOS JDK 安装说明符号 确定 macOS 上的默认 JDK 版本 在 macOS 上安装 JDK 在 macOS 上卸载 JDK macOS 安装常见问题
8790 0
|
6月前
|
SQL 分布式计算 运维
dataphin评测报告
本文是一篇关于Dataphin的使用总结与测评报告。作为一位开发工程师,作者在使用Dataphin过程中发现其具备数据规范化构建、全链路数据治理、数据资产化及跨平台兼容的优势,能有效降低开发门槛并提升效率。文章详细介绍了从进入工作台到数据规划、引入数据、数据处理、功能周期任务补数据、数据验证以及数据分析的全流程操作步骤,并通过截图辅助说明,帮助用户快速上手Dataphin,实现高效的数据开发与治理,在测评使用过程中整体感觉dataphin这个产品功能非常强大,能够为开发人员提高工作效率,界面也是比较清晰的感觉,容易初学者上手学习。
161 3
dataphin评测报告
|
人工智能 算法 Java
AI:互联网程序设计竞赛之蓝桥杯大赛的简介、奖项设置、大赛内容以及蓝桥杯与ACM(ICPC)的四个维度对比之详细攻略
AI:互联网程序设计竞赛之蓝桥杯大赛的简介、奖项设置、大赛内容以及蓝桥杯与ACM(ICPC)的四个维度对比之详细攻略
AI:互联网程序设计竞赛之蓝桥杯大赛的简介、奖项设置、大赛内容以及蓝桥杯与ACM(ICPC)的四个维度对比之详细攻略
|
JSON 安全 前端开发
类型安全的 Go HTTP 请求
类型安全的 Go HTTP 请求
|
人工智能 搜索推荐 前端开发
MindSearch技术详解,本地搭建媲美Perplexity的AI思·索应用!
MindSearch是书生·浦语团队提出的AI搜索框架,基于InternLM2.5 7B模型,采用multi-agent框架模拟人类思维,先规划再搜索,提高信息搜集的准确性和完整性。
|
Java Redis
Jedis之pipeline
Jedis之pipeline
202 0
|
安全 Linux 数据安全/隐私保护
阿里云镜像仓库:拉取和推送Docker镜像
阿里云镜像仓库:拉取和推送Docker镜像
41616 2
阿里云镜像仓库:拉取和推送Docker镜像