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

2024-04-25 22:04:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Keras模型,在训练期间需要2个输入(2个输出对应2个损失函数)

2个输入和2个输出成对连接

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

有没有办法让Keras/tf.Keras使用predict方法只接受第一个输入并生成第一个输出,而忽略第二个输入和第二个输出

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

Tensorflow应该能够做到这一点,因为它的图形是惰性的。但凯拉斯有能力做到这一点吗

例如:

# 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]

Tags: 方法函数模型numpytfbatchnotpredict
1条回答
网友
1楼 · 发布于 2024-04-25 22:04:03

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

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)

输出:

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)

相关问题 更多 >