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
快速部署K8s仪表板,助力管理轻松搞定!
快速部署K8s仪表板,助力管理轻松搞定!
408 0
|
5月前
|
人工智能 自然语言处理 NoSQL
GraphRAG实践:企业知识库从文本检索到知识图谱推理的架构升级路径
GraphRAG将企业知识库从“文档检索”升级为“关系推理”,通过构建实体-关系图谱,支持多跳推理、全局分析与因果溯源,破解传统RAG在复杂决策、跨系统关联和趋势研判中的局限,推动AI真正理解业务。
569 0
|
6月前
|
数据可视化 JavaScript Java
Maven dependency:tree 的 8 个高级用法
本文深入讲解 Maven dependency:tree 命令的 8 个高级用法,涵盖依赖冲突排查、传递依赖分析、版本升级建议等实战场景。通过企业级真实案例,展示如何利用这个强大工具快速定位和解决复杂的依赖问题。提供可视化分析方法、自动化脚本工具和企业级依赖管理规范,让你掌握专业级的依赖分析技能。
Maven dependency:tree 的 8 个高级用法
|
6月前
OpenCode新版与Spec-Kit新版
本文详解OpenCode+Spec-Kit组合安装报错原因:新版OpenCode(1.14.28)与Spec-Kit不兼容,后者已移除OpenCode模板。解决方案为锁定旧版本——OpenCode 1.4.7 + specify-cli 0.4.1,可完美规避兼容性问题。(239字)
588 0
|
人工智能 数据处理 数据库
多源 RAG 自动化处理:从 0 到 1 构建事件驱动的实时 RAG 应用
当企业想用大模型和内部非公开信息打造智能问答系统时,RAG(Retrieval-Augmented Generation,检索增强生成)已成为必备技术。然而,在实际落地中,构建 RAG 应用的数据准备过程繁琐复杂且充满挑战,让很多企业和开发者望而却步。本文将介绍构建 RAG 的最佳实践:通过阿里云事件总线 EventBridge 提供的多源 RAG 处理方案,基于事件驱动架构为企业 AI 应用打造高效、可靠、自动化的数据管道,轻松解决 RAG 数据处理难题。
1012 90
|
7月前
|
存储 人工智能 数据可视化
食品与环境实验室数据杂乱?智能实验室管理系统应用方案
本方案针对食品与环境实验室数据杂乱、溯源难、合规风险高等痛点,打造智能LIMS系统:实现检测数据自动采集、统一归档、全流程溯源;集成样品、设备、耗材、质控、报告全模块管理;支持AI预警、RFID溯源、可视化大屏,满足CNAS/CMA认证要求,助力实验室数字化、智能化升级。
|
11月前
|
运维 安全 数据安全/隐私保护
qBittorrent Docker 企业级部署(生产环境终版)
本文从企业运维视角,系统梳理 qBittorrent 在 Docker 中的生产级部署规范,涵盖版本锁定、最小权限、安全隔离、资源限制、健康检查等核心要点,明确测试、生产、PT 专用等场景边界,提供可直接纳入企业 Wiki 的标准化方案,杜绝“能跑就行”的临时配置,实现长期稳定运行。
1091 5
|
机器学习/深度学习 算法 安全
大模型微调 PPO 原理 —— 零基础也能懂的强化学习微调逻辑
本文通俗解析PPO算法在大模型RLHF微调中的核心作用:以人类反馈为依据,通过奖励模型量化偏好,借助“近端约束”实现安全、稳定、渐进的策略优化,解决传统微调无偏好导向与更新不稳的痛点。零基础可懂,附实操平台入口。
|
12月前
|
监控 搜索推荐 算法
《京东API揭秘:如何让你的商品在京东平台快速曝光?》
在京东电商生态中,商品曝光至关重要。本文详解如何通过京东开放平台API,实现商品高效上架、搜索推荐优化、精准营销投放与数据驱动迭代,全面提升商品可见性与竞争力。(238字)
|
JSON 数据挖掘 数据格式
Pandas处理JSON文件read_json()一文详解+代码展示
Pandas处理JSON文件read_json()一文详解+代码展示
2375 0
Pandas处理JSON文件read_json()一文详解+代码展示