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

目录
相关文章
|
缓存 安全 网络协议
socket是并发安全的吗 2
socket是并发安全的吗
1200 0
|
4月前
|
数据可视化 JavaScript Java
Maven dependency:tree 的 8 个高级用法
本文深入讲解 Maven dependency:tree 命令的 8 个高级用法,涵盖依赖冲突排查、传递依赖分析、版本升级建议等实战场景。通过企业级真实案例,展示如何利用这个强大工具快速定位和解决复杂的依赖问题。提供可视化分析方法、自动化脚本工具和企业级依赖管理规范,让你掌握专业级的依赖分析技能。
Maven dependency:tree 的 8 个高级用法
|
9月前
|
运维 安全 数据安全/隐私保护
qBittorrent Docker 企业级部署(生产环境终版)
本文从企业运维视角,系统梳理 qBittorrent 在 Docker 中的生产级部署规范,涵盖版本锁定、最小权限、安全隔离、资源限制、健康检查等核心要点,明确测试、生产、PT 专用等场景边界,提供可直接纳入企业 Wiki 的标准化方案,杜绝“能跑就行”的临时配置,实现长期稳定运行。
976 5
|
10月前
|
监控 搜索推荐 算法
《京东API揭秘:如何让你的商品在京东平台快速曝光?》
在京东电商生态中,商品曝光至关重要。本文详解如何通过京东开放平台API,实现商品高效上架、搜索推荐优化、精准营销投放与数据驱动迭代,全面提升商品可见性与竞争力。(238字)
|
开发者 Docker Python
从零开始:使用Docker容器化你的Python Web应用
从零开始:使用Docker容器化你的Python Web应用
960 4
|
JSON 算法 API
拼多多API跨店比价功能,选品效率提升60%!
拼多多推出API跨店比价功能,助力商家与消费者高效选品。通过自动化比价与智能算法,实现选品效率提升60%。开发者可快速集成,优化采购与购物体验。智能高效,抢占市场先机。了解详情:https://o0b.cn/evan
1186 0
|
机器学习/深度学习 自然语言处理 监控
命名实体识别(Named Entity Recognition, NER)
命名实体识别(NER)是自然语言处理的重要任务,旨在从文本中识别并分类特定实体,如人名、地点、组织等。通过BIO等标注模式,利用HMM、CRF及深度学习模型如RNN、LSTM、Transformer等进行实体识别。预训练模型如BERT显著提升了NER的性能。NER广泛应用于新闻分析、生物医学等领域,是信息提取、知识图谱构建等任务的基础。
2323 3
|
存储 缓存 算法
JDK11升级后竟让内存利用率飙升到90%以上?
JDK11升级后竟让内存利用率飙升到90%以上?
|
人工智能 数据可视化 网络安全
Dify与DeepSeek的深度融合——构建您的专属AI助手
在当今数据驱动、AI为王的时代,Dify与DeepSeek作为领先的AI开发工具和大模型引擎,为企业和个人提供高效智能的解决方案。Dify是面向AI应用开发的低代码平台,集成预训练模型、可视化界面和无缝部署功能;DeepSeek则是高性能、低成本的开源大语言模型,具备多轮推理能力。两者结合并通过私有化部署,确保数据安全与合规,极大提升开发效率和业务生产力。阿里云计算巢提供了两者的私有化部署方案,帮助用户快速搭建专属AI应用。
1373 1
|
存储 人工智能 Cloud Native
重磅!阿里云公有云产品及战略能力全球第二
重磅!阿里云公有云产品及战略能力全球第二
1065 5

热门文章

最新文章