[英]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.