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

目录
相关文章
|
存储 Kubernetes 持续交付
Docker 核心概念深度解析:探索容器、镜像和仓库在Docker生态系统中的重要作用和 应用
Docker 核心概念深度解析:探索容器、镜像和仓库在Docker生态系统中的重要作用和 应用
1194 0
|
5月前
|
SQL 分布式计算 运维
dataphin评测报告
本文是一篇关于Dataphin的使用总结与测评报告。作为一位开发工程师,作者在使用Dataphin过程中发现其具备数据规范化构建、全链路数据治理、数据资产化及跨平台兼容的优势,能有效降低开发门槛并提升效率。文章详细介绍了从进入工作台到数据规划、引入数据、数据处理、功能周期任务补数据、数据验证以及数据分析的全流程操作步骤,并通过截图辅助说明,帮助用户快速上手Dataphin,实现高效的数据开发与治理,在测评使用过程中整体感觉dataphin这个产品功能非常强大,能够为开发人员提高工作效率,界面也是比较清晰的感觉,容易初学者上手学习。
156 3
dataphin评测报告
|
人工智能 算法 Java
AI:互联网程序设计竞赛之蓝桥杯大赛的简介、奖项设置、大赛内容以及蓝桥杯与ACM(ICPC)的四个维度对比之详细攻略
AI:互联网程序设计竞赛之蓝桥杯大赛的简介、奖项设置、大赛内容以及蓝桥杯与ACM(ICPC)的四个维度对比之详细攻略
AI:互联网程序设计竞赛之蓝桥杯大赛的简介、奖项设置、大赛内容以及蓝桥杯与ACM(ICPC)的四个维度对比之详细攻略
|
数据采集 机器学习/深度学习 数据可视化
了解数据科学面试中的Python数据分析重点,包括Pandas(DataFrame)、NumPy(ndarray)和Matplotlib(图表绘制)。
【7月更文挑战第5天】了解数据科学面试中的Python数据分析重点,包括Pandas(DataFrame)、NumPy(ndarray)和Matplotlib(图表绘制)。数据预处理涉及缺失值(dropna(), fillna())和异常值处理。使用describe()进行统计分析,通过Matplotlib和Seaborn绘图。回归和分类分析用到Scikit-learn,如LinearRegression和RandomForestClassifier。
229 3
|
人工智能 搜索推荐 前端开发
MindSearch技术详解,本地搭建媲美Perplexity的AI思·索应用!
MindSearch是书生·浦语团队提出的AI搜索框架,基于InternLM2.5 7B模型,采用multi-agent框架模拟人类思维,先规划再搜索,提高信息搜集的准确性和完整性。
|
Java Redis
Jedis之pipeline
Jedis之pipeline
200 0
|
网络协议 网络架构
ensp中BGP(边界网关协议)基础原理及配置命令
ensp中BGP(边界网关协议)基础原理及配置命令
977 0
|
机器学习/深度学习 存储 分布式计算
【王喆-推荐系统】线上服务篇-(task5)部署离线模型
(1)业界主流的模型服务方法有 4 种,分别是预存推荐结果或 Embeding 结果、预训练 Embeding+ 轻量级线上模型、利用 PMML 转换和部署模型以及 TensorFlow Serving。
1293 0
【王喆-推荐系统】线上服务篇-(task5)部署离线模型
|
域名解析 Ubuntu 网络协议
如何在 Ubuntu 20.04 上安装和使用 Docker Compose
Docker Compose 是一个命令行工具,通过它你可以定义和编排多容器 Docker 应用,本文将为大家讲解如何在 Ubuntu 20.04 上安装最新版的 Docker Compose。
20182 0
如何在 Ubuntu 20.04 上安装和使用 Docker Compose
微信小游戏制作工具关于游戏屏幕适配,看这篇就够了!
微信小游戏制作工具关于游戏屏幕适配,看这篇就够了!
539 0