Python 如何将tf.lookup表与TensorFlow 2.0 keras和MLFlow一起使用

Python 如何将tf.lookup表与TensorFlow 2.0 keras和MLFlow一起使用,python,tensorflow,keras,lookup-tables,Python,Tensorflow,Keras,Lookup Tables,我花了大约5个小时的时间试图让TF2.0KerasAPI与TF.lookup API一起工作。我的训练脚本还使用了DataBricks和mlflow.keras。MLFlow要求对模型进行序列化,我认为这正是造成问题的原因。问题是:如何将tf.lookup表与TensorFlow 2.0 keras模型API和MLFlow一起使用 我在尝试将功能性keras API直接用于table.lookup时遇到了序列化方面的keras问题: table = tf.lookup.StaticVocabul

我花了大约5个小时的时间试图让TF2.0KerasAPI与TF.lookup API一起工作。我的训练脚本还使用了DataBricks和
mlflow.keras
。MLFlow要求对模型进行序列化,我认为这正是造成问题的原因。问题是:如何将tf.lookup表与TensorFlow 2.0 keras模型API和MLFlow一起使用

我在尝试将功能性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
变量

在这里分享解决方案,为他人省去一些痛苦。这是我发现有效的解决方案:

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)

层。Lambda似乎不喜欢upvalue。

这不是一个真正的问题,是吗?考虑编辑你的帖子只包括一个精心准备的问题,并随时张贴并接受自己的答案。