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生态系统中的重要作用和 应用
1262 0
|
人工智能 算法 Java
AI:互联网程序设计竞赛之蓝桥杯大赛的简介、奖项设置、大赛内容以及蓝桥杯与ACM(ICPC)的四个维度对比之详细攻略
AI:互联网程序设计竞赛之蓝桥杯大赛的简介、奖项设置、大赛内容以及蓝桥杯与ACM(ICPC)的四个维度对比之详细攻略
AI:互联网程序设计竞赛之蓝桥杯大赛的简介、奖项设置、大赛内容以及蓝桥杯与ACM(ICPC)的四个维度对比之详细攻略
|
7月前
|
SQL 分布式计算 运维
dataphin评测报告
本文是一篇关于Dataphin的使用总结与测评报告。作为一位开发工程师,作者在使用Dataphin过程中发现其具备数据规范化构建、全链路数据治理、数据资产化及跨平台兼容的优势,能有效降低开发门槛并提升效率。文章详细介绍了从进入工作台到数据规划、引入数据、数据处理、功能周期任务补数据、数据验证以及数据分析的全流程操作步骤,并通过截图辅助说明,帮助用户快速上手Dataphin,实现高效的数据开发与治理,在测评使用过程中整体感觉dataphin这个产品功能非常强大,能够为开发人员提高工作效率,界面也是比较清晰的感觉,容易初学者上手学习。
189 3
dataphin评测报告
|
网络协议 网络架构
ensp中BGP(边界网关协议)基础原理及配置命令
ensp中BGP(边界网关协议)基础原理及配置命令
1096 0
微信小游戏制作工具关于游戏屏幕适配,看这篇就够了!
微信小游戏制作工具关于游戏屏幕适配,看这篇就够了!
635 0
|
机器学习/深度学习 SQL 数据采集
【数据分析】————面试总结
【数据分析】————面试总结
1310 0
|
机器学习/深度学习 数据采集 监控
【数据挖掘实战】——基于水色图像的水质评价(LM神经网络和决策树)
项目地址:Datamining_project: 数据挖掘实战项目代码
1078 0
|
搜索推荐 算法 开发者
推荐引擎的算法原理|学习笔记
快速学习推荐引擎的算法原理
446 0
推荐引擎的算法原理|学习笔记
|
存储 Ubuntu 计算机视觉
ubuntu16.04搭建港科大vins mono运行环境
ubuntu16.04搭建港科大vins mono运行环境
550 0
ubuntu16.04搭建港科大vins mono运行环境
|
机器学习/深度学习 运维 自然语言处理
《2023云原生实战案例集》——06 医疗健康——硅基仿生 业务全面Serverless容器化的增效降本之旅
《2023云原生实战案例集》——06 医疗健康——硅基仿生 业务全面Serverless容器化的增效降本之旅