如何在TensorFlow 2.0 keras和MLFlow中使用tf.lookup表

问题描述 投票:1回答:1

我花了最后5个小时左右的时间,尝试使TF 2.0 keras API与tf.lookup API一起使用。我的训练脚本也使用DataBricks和mlflow.keras。 MLFlow要求对模型进行序列化,这对我造成了问题。问题是:如何在TensorFlow 2.0 keras模型API和MLFlow中使用tf.lookup表。

当尝试直接将功能性Keras API与table.lookup一起使用时,我遇到了序列化的keras问题:

table = tf.lookup.StaticVocabularyTable(tf.lookup.TextFileInitializer(vocab_path, tf.string, 0, tf.int64, 1, delimiter=","), 1)
categorical_indices = table.lookup(categorical_input)

将上面的调用包装在tf.keras.layers.Lambda层中没有帮助。我遇到与资源句柄相关的错误或缺少tf变量...

python tensorflow keras lookup-tables
1个回答
1
投票

在此处共享解决方案,以减轻其他人的痛苦。这是我发现可以使用的解决方案:

vocab_path = os.path.join(mount_point, 'category_vocab.csv')

class VocabLookup(layers.Layer):
  def __init__(self, vocab_path, num_oov_buckets, **kwargs):
    self.vocab_path = vocab_path
    self.num_oov_buckets = num_oov_buckets
    super(VocabLookup, self).__init__(**kwargs)

  def build(self, input_shape):

    vocab_initializer = tf.lookup.TextFileInitializer(
      self.vocab_path, tf.string, 0, tf.int64, 1, delimiter=",")
    self.table = tf.lookup.StaticVocabularyTable(vocab_initializer, self.num_oov_buckets)

    self.built = True

  def call(self, inputs):
    return self.table.lookup(inputs)

  def get_config(self):
    return {'vocab_path': self.vocab_path, 'num_oov_buckets': self.num_oov_buckets}

lookup_table = VocabLookup(vocab_path, 1)

categorical_indices = lookup_table(categorical_input)

[基本上,如果要引用任何外部变量(包括tf或tensorflow模块),请不要使用layers.Lambda。例如,这对我不起作用:

def reduce_sum(x):
  return tf.reduce_sum(x, axis=1)

embedding_sum = layers.Lambda(reduce_sum)

categorical_features = embedding_sum(categorical_embeddings)

但是这可行:

class ReduceSum(layers.Layer):
  def call(self, inputs):
    return tf.reduce_sum(inputs, axis=1)

embedding_sum = ReduceSum()
categorical_features = embedding_sum(categorical_embeddings)

layers.Lambda似乎不喜欢升值。

© www.soinside.com 2019 - 2024. All rights reserved.