1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
| import os import numpy as np import tensorflow as tf import tensorflow_recommenders as tfrs import tensorflow_datasets as tfds from google.colab import auth
resolver = tf.distribute.cluster_resolver.TPUClusterResolver('').connect('') strategy = tf.distribute.TPUStrategy(resolver)
gcs_bucket = 'gs://YOUR-BUCKET-NAME' auth.authenticate_user()
ratings = tfds.load( "movielens/100k-ratings", data_dir=gcs_bucket, 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"]), "user_rating": x["user_rating"], })
per_replica_batch_size = 16 movie_vocabulary_size = 2048 movie_embedding_size = 64 user_vocabulary_size = 2048 user_embedding_size = 64
shuffled = ratings.shuffle(100_000, seed=42, reshuffle_each_iteration=False) train = shuffled.take(80_000) test = shuffled.skip(80_000).take(20_000)
train_dataset = train.batch(per_replica_batch_size * strategy.num_replicas_in_sync,drop_remainder=True).cache() test_dataset = test.batch(per_replica_batch_size * strategy.num_replicas_in_sync,drop_remainder=True).cache()
distribute_train_dataset = strategy.experimental_distribute_dataset(train_dataset,options=tf.distribute.InputOptions (experimental_fetch_to_device=False)) distribute_test_dataset = strategy.experimental_distribute_dataset(test_dataset,options=tf.distribute.InputOptions (experimental_fetch_to_device=False))
optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.1)
user_table = tf.tpu.experimental.embedding.TableConfig(vocabulary_size=user_vocabulary_size, dim=user_embedding_size) movie_table = tf.tpu.experimental.embedding.TableConfig(vocabulary_size=movie_vocabulary_size, dim=movie_embedding_size) feature_config = { "movie_id": tf.tpu.experimental.embedding.FeatureConfig(table=movie_table), "user_id": tf.tpu.experimental.embedding.FeatureConfig(table=user_table) }
class EmbeddingModel(tfrs.models.Model):
def __init__(self): super().__init__() self.embedding_layer = tfrs.layers.embedding.TPUEmbedding(feature_config=feature_config, optimizer=optimizer) self.ratings = tf.keras.Sequential([ tf.keras.layers.Dense(256, activation="relu"), tf.keras.layers.Dense(64, activation="relu"), tf.keras.layers.Dense(1) ]) self.task: tf.keras.layers.Layer = tfrs.tasks.Ranking(loss=tf.keras.losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.NONE), metrics=[tf.keras.metrics.RootMeanSquaredError()])
def compute_loss(self, features, training=False): embedding = self.embedding_layer({ "user_id": features["user_id"], "movie_id": features["movie_id"] }) rating_predictions = self.ratings(tf.concat([embedding["user_id"], embedding["movie_id"]], axis=1))
return tf.reduce_sum(self.task(labels=features["user_rating"], predictions=rating_predictions)) * ( 1 / (per_replica_batch_size * strategy.num_replicas_in_sync))
def call(self, features, serving_config=None): embedding = self.embedding_layer( { "user_id": features["user_id"], "movie_id": features["movie_id"] }, serving_config=serving_config) return self.ratings(tf.concat([embedding["user_id"], embedding["movie_id"]], axis=1))
with strategy.scope(): model = EmbeddingModel() model.compile(optimizer=optimizer)
model.fit(distribute_train_dataset, steps_per_epoch=10, epochs=10)
model.evaluate(distribute_test_dataset, steps=10)
model_dir = os.path.join(gcs_bucket, "saved_model")
checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model) saved_tpu_model_path = checkpoint.save(os.path.join(model_dir, "ckpt"))
with strategy.scope(): checkpoint.restore(saved_tpu_model_path)
cpu_model = EmbeddingModel()
cpu_checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=cpu_model) cpu_checkpoint.restore(saved_tpu_model_path)
@tf.function def serve_tensors(features): return cpu_model(features)
signatures = { 'serving': serve_tensors.get_concrete_function( features={ 'movie_id': tf.TensorSpec(shape=(1,), dtype=tf.int32, name='movie_id'), 'user_id': tf.TensorSpec(shape=(1,), dtype=tf.int32, name='user_id'), }), }
tf.saved_model.save( cpu_model, export_dir=os.path.join(model_dir, 'exported_model'), signatures=signatures)
imported = tf.saved_model.load(os.path.join(model_dir, 'exported_model')) predict_fn = imported.signatures['serving']
input_batch = { 'movie_id': tf.constant(np.array([100]), dtype=tf.int32), 'user_id': tf.constant(np.array([30]), dtype=tf.int32) }
prediction = predict_fn(**input_batch)['output_0']
|