天天看點

movielens推薦系統_谷歌開源Tensorflow推薦器TensorFlow Recommenders

movielens推薦系統_谷歌開源Tensorflow推薦器TensorFlow Recommenders
作者:時晴 公衆号:煉丹筆記

最近Google開源了基于Tensorflow的推薦器, 一個新的開源Tensorflow包。它的特點可以總結為下面四個:

  • 它有助于開發和評估靈活的候選nomination模型;
  • 它可以很容易地将商品、使用者和上下文資訊合并到推薦模型中;
  • 它可以訓練多任務模型,幫助優化多個推薦目标;
  • 它使用TensorFlow Serving為最終模型提供服務。

這些特性非常容易使用,因為TFRS包含了不同的子產品,可以幫助使用者輕松地定制各個層和名額。TFRS還形成了一個内聚的整體,使得各個元件能夠非常好地協調。重點在于能使預設設定合理化,使常見任務更加直覺且易于實作,并提供更複雜和自定義的推薦,使其更靈活。

TensorFlow Recommenders是使用TensorFlow建構推薦系統模型的庫。它有助于建構推薦系統的完整工作流程,包括:

資料準備、模型制定、模型訓練、模型評估和部署等

該模型是建立在Keras之上的,更加便于建構複雜模型。

安裝&案例

1. 安裝

先安裝Tensorflow 2.x,然後使用pip進行安裝即可。

# !pip install  tensorflow_datasets
# !pip install tensorflow-recommenders 
           

2. 簡單案例

我們用Movielens 100K資料為例建構矩陣分解模型

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") 
           

選擇基礎特征

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)
           

使用教程

因為該項目剛剛開始,是以教程不是很多,我們僅舉一個簡單的例子,有興趣的可以去參考文獻學習,内容很少,非常适合初學者。

movielens推薦系統_谷歌開源Tensorflow推薦器TensorFlow Recommenders

我們先使用帶有TFRS的MovieLens 100K資料集建構一個簡單的矩陣分解模型。我們可以使用此模型為給定使用者推薦電影。

入門代碼

1. 安裝TFRS & 資料集
pip install -q tensorflow-recommenders
pip install -q --upgrade tensorflow-datasets
           
2. 導入功能子產品
from typing import Dict, Text
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_recommenders as tfrs
           
3. 讀取資料
# 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
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.

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 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. 模型訓練&評估
# 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

我是一品煉丹師時晴,歡迎大家關注我們的公衆号:

煉丹筆記