谷歌开源Tensorflow推荐器TFRS

2021-05-14 16:01:36 浏览数 (1)

Tensorflow Recommenders

简介

最近Google开源了基于Tensorflow的推荐器, 一个新的开源Tensorflow包。它的特点可以总结为下面四个:

  • 它有助于开发和评估灵活的候选nomination模型;
  • 它可以很容易地将商品、用户和上下文信息合并到推荐模型中;
  • 它可以训练多任务模型,帮助优化多个推荐目标;
  • 它使用TensorFlow Serving为最终模型提供服务。

这些特性非常容易使用,因为TFRS包含了不同的模块,可以帮助用户轻松地定制各个层和指标。TFRS还形成了一个内聚的整体,使得各个组件能够非常好地协调。重点在于能使默认设置合理化,使常见任务更加直观且易于实现,并提供更复杂和自定义的推荐,使其更灵活。

TensorFlow Recommenders是使用TensorFlow构建推荐系统模型的库。它有助于构建推荐系统的完整工作流程,包括:数据准备、模型制定、模型训练、模型评估和部署等

该模型是建立在Keras之上的,更加便于构建复杂模型。

安装&案例

1. 安装

先安装Tensorflow 2.x,然后使用pip进行安装即可。

代码语言:javascript复制
# !pip install  tensorflow_datasets
# !pip install tensorflow-recommenders 

2. 简单案例

我们用Movielens 100K数据为例构建矩阵分解模型

代码语言:javascript复制
from typing import Dict, Text 
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_recommenders as tfrs


# Ratings数据.
ratings = tfds.load('movie_lens/100k-ratings', split="train")
# movies的所有Features .
movies = tfds.load('movie_lens/100k-movies', split="train") 
代码语言:javascript复制
# 选择基础特征
ratings = ratings.map(lambda x: {
    "movie_id": tf.strings.to_number(x["movie_id"]),
    "user_id": tf.strings.to_number(x["user_id"])
})
movies = movies.map(lambda x: tf.strings.to_number(x["movie_id"]))

# 构建模型
class Model(tfrs.Model): 
  def __init__(self):
    super().__init__()

    # Set up user representation.
    self.user_model = tf.keras.layers.Embedding(
        input_dim=2000, output_dim=64)
    # Set up movie representation.
    self.item_model = tf.keras.layers.Embedding(
        input_dim=2000, output_dim=64)
    # Set up a retrieval task and evaluation metrics over the
    # entire dataset of candidates.
    self.task = tfrs.tasks.Retrieval(
            metrics=tfrs.metrics.FactorizedTopK(
            candidates=movies.batch(128).map(self.item_model)
        )
    )

  def compute_loss(self, features: Dict[Text, tf.Tensor], training=False) -> tf.Tensor: 
    user_embeddings  = self.user_model(features["user_id"])
    movie_embeddings = self.item_model(features["movie_id"]) 
    return self.task(user_embeddings, movie_embeddings)


model = Model()
model.compile(optimizer=tf.keras.optimizers.Adagrad(0.5))

# 随机shuffle对训练集和测试集进行分割,Randomly shuffle data and split between train and test.
tf.random.set_seed(42)
shuffled = ratings.shuffle(100_000, seed=42, reshuffle_each_iteration=False)

train = shuffled.take(80_000)
test  = shuffled.skip(80_000).take(20_000)

# 模型训练.
model.fit(train.batch(4096), epochs=5)

# 模型评估.
model.evaluate(test.batch(4096), return_dict=True)

使用教程

因为该项目刚刚开始,所以教程不是很多,我们仅举一个简单的例子,有兴趣的可以去参考文献学习,内容很少,非常适合初学者。

我们先使用带有TFRS的MovieLens 100K数据集构建一个简单的矩阵分解模型。我们可以使用此模型为给定用户推荐电影。

入门代码

1. 安装TFRS & 数据集
代码语言:javascript复制
pip install -q tensorflow-recommenders
pip install -q --upgrade tensorflow-datasets
2. 导入功能模块
代码语言:javascript复制
from typing import Dict, Text
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_recommenders as tfrs
3. 读取数据
代码语言:javascript复制
# 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"])
4. 构建词汇表并且将用户id和电影的title转为整数,用于后续embedding
代码语言:javascript复制
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)
5. 模型定义

我们继承tfrs.Model来定义TFRS模型,并且实现compute_loss.

代码语言:javascript复制
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)

定义两个模型&检索任务。

代码语言:javascript复制
# 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)
  )
)
6. 模型训练&评估
代码语言:javascript复制
# 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.ann.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]}")

小结

这是TensorFlow Recommenders Team使用TensorFlow构建推荐系统模型的库。目前是工程的前期,有志之士可以速速加入学习,今后大师指日可待!加油加油加油⛽️!

参考文献

  1. Github:https://github.com/tensorflow/recommenders
  2. Tutorial:https://www.tensorflow.org/recommenders/examples/quickstart
  3. API:https://www.tensorflow.org/recommenders/api_docs/python/tfrs/
  4. Google Open-Sources TensorFlow Recommenders (TFRS): Helping Users Find What They Love

我是一品炼丹师时晴,欢迎大家关注我们的公众号哦!

0 人点赞