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

目录
相关文章
|
机器学习/深度学习 自然语言处理 搜索推荐
TensorFlow详解
TensorFlow是一个开源的机器学习框架,由Google开发。它是一个强大、高度可扩展的计算框架,可以用于各种机器学习任务,包括图像和语音识别、自然语言处理、推荐系统等。 TensorFlow 是一种由 Google 开发的开源机器学习框架,它可以帮助我们构建和训练机器学习模型。无论您是一名初学者还是一名专业人士,本文将为您提供一份完整的 TensorFlow 指南,帮助您了解 TensorFlow 的基础知识,以及如何在实际项目中应用它。
167 0
|
6月前
|
机器学习/深度学习 TensorFlow 算法框架/工具
精通 TensorFlow 1.x:11~15(2)
精通 TensorFlow 1.x:11~15(2)
79 0
|
6月前
|
机器学习/深度学习 TensorFlow API
TensorFlow的扩展库:TensorFlow Probability与TensorFlow Quantum
【4月更文挑战第17天】TensorFlow的扩展库TensorFlow Probability和TensorFlow Quantum开辟了机器学习和量子计算新纪元。TensorFlow Probability专注于概率推理和统计分析,集成深度学习,支持贝叶斯推断和变分推断,提供自动微分及丰富的概率模型工具。其Bijector组件允许复杂随机变量转换,增强建模能力。另一方面,TensorFlow Quantum结合量子计算与深度学习,处理量子数据,构建量子-经典混合模型,应用于化学模拟、量子控制等领域,内置量子计算基元和高性能模拟器。
|
机器学习/深度学习 数据可视化 数据挖掘
PyTorch Geometric (PyG) 入门教程
PyTorch Geometric是PyTorch1的几何图形学深度学习扩展库。本文旨在通过介绍PyTorch Geometric(PyG)中常用的方法等内容,为新手提供一个PyG的入门教程。
PyTorch Geometric (PyG) 入门教程
|
TensorFlow API 算法框架/工具
Tensorflow:from tensorflow.keras import layers 报错
Tensorflow:from tensorflow.keras import layers 报错
454 0
|
机器学习/深度学习 算法 Java
TensorFlow Lite介绍
TensorFlow Lite是为了解决TensorFlow在移动平台和嵌入式端过于臃肿而定制开发的轻量级解决方案,是与TensorFlow完全独立的两个项目,与TensorFlow基本没有代码共享。TensorFlow本身是为桌面和服务器端设计开发的,没有为ARM移动平台定制优化,因此如果直接用在移动平台或者嵌入式端会“水土不服”。
504 0
|
机器学习/深度学习 TensorFlow 算法框架/工具
TensorFlow HOWTO 1.3 逻辑回归
TensorFlow HOWTO 1.3 逻辑回归
81 0
|
TensorFlow 算法框架/工具
TensorFlow HOWTO 1.1 线性回归
TensorFlow HOWTO 1.1 线性回归
41 0
|
TensorFlow 算法框架/工具 开发工具
TF学习——TF之TensorFlow Slim:TensorFlow Slim的简介、安装、使用方法之详细攻略
TF学习——TF之TensorFlow Slim:TensorFlow Slim的简介、安装、使用方法之详细攻略
TF学习——TF之TensorFlow Slim:TensorFlow Slim的简介、安装、使用方法之详细攻略
|
TensorFlow 算法框架/工具 Python
成功解决tensorflow\contrib\learn\python\learn\datasets\mnist.py: maybe_download (from tensorflow.contri
成功解决tensorflow\contrib\learn\python\learn\datasets\mnist.py: maybe_download (from tensorflow.contri