繁体   English   中英

Keras model 在训练期间有 2 个输入,但在推理期间只有 1 个输入

[英]Keras model with 2 inputs during training, but only 1 input during inference

我有一个 Keras model 在训练期间需要 2 个输入(并且有 2 个输出对应于 2 个损失函数)。

2 个输入和 2 个输出成对地相互连接。

因此在推理中,我实际上不需要传递第二个输入,也不需要第二个 output。

有没有办法使用predict方法使 Keras/tf.keras 只接受第一个输入并产生第一个 output 并忽略第二个输入和第二个 output。

我可以为第二个输入创建一个归零的 numpy 数组,但我想知道是否可以减少 memory 的使用或计算。

Tensorflow 应该能够做到这一点,因为它的图表是惰性的。 但是 Keras 能够做到这一点吗?

例子:

# assume second_batch is not needed
second_batch = np.zeros(shape=first_batch.shape)
results = model.predict((first_batch, second_batch))
# i only care about results[0]
# not results[1]

您始终可以使用相同的共享权重构造新的keras model,并指定所需的输入和 output 张量。

import tensorflow as tf

print('TensorFlow:', tf.__version__)


input_a = tf.keras.Input(shape=[224, 224, 3], name='input_a')
input_b = tf.keras.Input(shape=[224, 224, 3], name='input_b')

resnet_model = tf.keras.applications.ResNet50(include_top=False, pooling='avg')

xa = resnet_model(input_a)
xb = resnet_model(input_b)

output_a = tf.keras.layers.Dense(10, name='output_a', activation='softmax')(xa)
output_b = tf.keras.layers.Dense(10, name='output_b', activation='softmax')(xb)

training_model = tf.keras.Model(inputs=[input_a, input_b], outputs=[output_a, output_b])

[print('Training Model Input:', x.name, x.shape) for x in training_model.inputs]
print('')
[print('Training Model Output:', x.name, x.shape) for x in training_model.outputs]
print('')


inference_model = tf.keras.Model(inputs=[input_a], outputs=[output_a])

[print('Inference Model Input:', x.name, x.shape) for x in inference_model.inputs]
[print('Inference Model Output:', x.name, x.shape) for x in inference_model.outputs]

image = tf.random.uniform([1, 224, 224, 3])
predictions = inference_model(image, training=False)
print('')
print('Predictions:', predictions)

Output:

TensorFlow: 2.3.0-dev20200625
Training Model Input: input_a:0 (None, 224, 224, 3)
Training Model Input: input_b:0 (None, 224, 224, 3)

Training Model Output: output_a/Softmax:0 (None, 10)
Training Model Output: output_b/Softmax:0 (None, 10)

Inference Model Input: input_a:0 (None, 224, 224, 3)
Inference Model Output: output_a/Softmax:0 (None, 10)

Predictions: tf.Tensor(
[[0.01937425 0.17703871 0.08633    0.06593429 0.18057525 0.03161139
  0.01154568 0.09730788 0.01927926 0.31100336]], shape=(1, 10), dtype=float32)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM