Sha*_*rny 5 keras tensorflow tensorflow-estimator
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)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:
Cannot find %s with name "%s" in Keras Model. It needs to match '
'one of the following:
Run Code Online (Sandbox Code Playgroud)
我在这里找到了一些关于这个主题的参考资料(奇怪的是它隐藏在主分支的TF文档中 - 与此相比)
如果您有同样的问题 - 请参阅下面的答案.可能会为您节省几个小时.
所以这里是交易。您必须确保您的自定义输入函数返回 {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
Run Code Online (Sandbox Code Playgroud)
现在,您已经有了名称,您需要转到自己的输入函数并对其进行更改,以便它将提供两个具有相应输入和输出名称的字典。
在我的示例中,在更改之前,输入函数返回 [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]))
Run Code Online (Sandbox Code Playgroud)
现在,TF 才能够将输入函数连接到 Keras 输入层。