Tensorflow:Keras、Estimators 和自定义输入函数
Tensorflow: Keras, Estimators and custom input function
TF1.4 使 Keras 成为不可或缺的一部分。
当尝试使用适当的输入函数(即不使用 tf.estimator.inputs.numpy_input_fn)从 Keras 模型创建 Estimator 时,事情不起作用,因为 Tensorflow 无法将模型与输入函数融合。
我正在使用 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 (strangely enough its hidden in the TF docs in the master branch - compare to this)
如果您有同样的问题 - 请参阅下面我的回答。可能会为您节省几个小时。
所以这是交易。您必须确保您的自定义输入函数 returns 是 {inputs} 字典和 {outputs} 字典。
字典键必须与您的 Keras input/output 层名称匹配。
来自 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 returns 是字典而不是列表。
为了解决这个问题,我们需要把它包装成一个字典:
image_batch_dict = dict(zip(keras_input_names_list , [image_batch]))
label_batch_dict = dict(zip(keras_target_names_list , [label_batch]))
只有现在,TF 才能将输入函数连接到 Keras 输入层。
TF1.4 使 Keras 成为不可或缺的一部分。 当尝试使用适当的输入函数(即不使用 tf.estimator.inputs.numpy_input_fn)从 Keras 模型创建 Estimator 时,事情不起作用,因为 Tensorflow 无法将模型与输入函数融合。
我正在使用 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 (strangely enough its hidden in the TF docs in the master branch - compare to this)
如果您有同样的问题 - 请参阅下面我的回答。可能会为您节省几个小时。
所以这是交易。您必须确保您的自定义输入函数 returns 是 {inputs} 字典和 {outputs} 字典。 字典键必须与您的 Keras input/output 层名称匹配。
来自 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 returns 是字典而不是列表。
为了解决这个问题,我们需要把它包装成一个字典:
image_batch_dict = dict(zip(keras_input_names_list , [image_batch]))
label_batch_dict = dict(zip(keras_target_names_list , [label_batch]))
只有现在,TF 才能将输入函数连接到 Keras 输入层。