TensorFlow Recommenders: Quickstart

XianxinMao 2021-07-30 11:02:52

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

...全文
1830 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
随着文化消费升级与演出市场发展,剧场票务面临售卖效率低、防伪弱、会员价值挖掘不足等问题:固定售价无法反映供需变化,抢票并发导致超卖与重复下单,纸质票核销效率低且易伪造。本文设计并实现了剧场演出票务与会员运营管理系统。 系统采用Java 17与Spring Boot 3.x构建后端,Vue 3构建管理端,微信小程序作为购票入口,MySQL 8.0为主数据库,Redis承担座位锁、缓存与防重功能,并通过微信支付完成在线支付,实现演出发布、在线选座购票、电子票核销、会员积分、周边商城与数据统计的全流程数字化管理。系统采用前后端分离分层架构,划分为演出管理、选座购票、票务核销、会员运营、数据统计五大模块,支持多剧场多场次统一管理。 本文提出三项创新:一是动态票价与座位分区定价机制(DPM),根据上座率、距开演时间动态调整票价,实测热门场次平均票价提升约12%;二是选座并发防护与票务防重机制(SCP),通过座位级Redis分布式锁、条件更新与票码唯一约束三重防护,实测200并发选座零超卖、票码零重复;三是会员画像与演出精准推荐机制(MIR),基于购票历史、观演偏好与积分构建画像,结合协同过滤实现精准推荐,实测推荐点击率提升18%。 测试表明:200并发抢购热门场次座位零超卖、票码零重复,电子票核销平均38ms,防重拦截率100%,高峰并发下平均响应400ms以内。本文为剧场运营提供覆盖票务销售-核销-会员运营-数据决策全链路的一体化方案,为座位管理、票务安全与会员精细化运营提供可复用技术范式。 【课程报告内容】 摘要 第1章 绪论 第2章 相关技术与理论 第3章 系统需求分析 第4章 系统总体设计 第5章 系统详细设计与实现 第6章 系统测试与分析 第7章 总结与展望 参考文献 附件-实现指南

19

社区成员

发帖
与我相关
我的任务
社区描述
开发&划水&摸鱼&Bug灌水乐园 五湖四海的开发工程师们,来!
学习方法跳槽考研 企业社区 上海·徐汇区
社区管理员
  • 文;
  • 护理学_李天使
  • 王大师王文峰
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. CSDN 划水乐园
  2. CSDN 划水乐园
  3. CSDN 划水乐园
  4. CSDN 划水乐园

试试用AI创作助手写篇文章吧