Tensorflow:Keras,Estimators和自定义输入功能

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

TF1.4使Keras成为不可或缺的一部分。当尝试使用具有propratery输入功能的Keras模型创建Estimators时(即,不使用tf.estimator.inputs.numpy_input_fn)事情不起作用,因为Tensorflow无法将模型与Input函数融合。

我使用的是tf.keras.estimator.model_to_estimator

keras_estimator = tf.keras.estimator.model_to_estimator(
            keras_model = keras_model,
            config = run_config)

train_spec = tf.estimator.TrainSpec(input_fn=train_input_fn, 
                                    max_steps=self.train_steps)
eval_spec = tf.estimator.EvalSpec(input_fn=eval_input_fn,
                                  steps=None)

tf.estimator.train_and_evaluate(keras_estimator, train_spec, eval_spec)

我收到以下错误消息:

    Cannot find %s with name "%s" in Keras Model. It needs to match '
              'one of the following:

我找到了一些关于这个主题的参考资料here(奇怪的是它隐藏在主分支的TF文档中 - 与this相比)

如果您有同样的问题 - 请参阅下面的答案。可能会为您节省几个小时。

tensorflow keras tensorflow-estimator
1个回答
4
投票

所以这里是交易。您必须确保自定义输入函数返回{inputs}字典和{outputs}字典。字典键必须与您的Keras输入/输出层名称匹配。

来自TF文档:

首先,恢复Keras模型的输入名称,这样我们就可以将它们用作Estimator输入函数的特征列名称

这是对的。我是这样做的:

# Get inputs and outout Keras model name to fuse them into the infrastructure.
keras_input_names_list = keras_model.input_names
keras_target_names_list = keras_model.output_names

现在,您有了名称,您需要转到自己的输入函数并进行更改,以便它将提供两个带有相应输入和输出名称的字典。

在我的例子中,在更改之前,输入函数返回[image_batch],[label_batch]。这基本上是一个错误,因为声明inputfn返回字典而不是列表。

要解决这个问题,我们需要将其包装成一个字典:

image_batch_dict = dict(zip(keras_input_names_list , [image_batch]))
label_batch_dict = dict(zip(keras_target_names_list , [label_batch]))

只有现在,TF才能将输入功能连接到Keras输入层。

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