【问题标题】:Keras Model with 2 inputs during training, but only 1 during inferencingKeras 模型在训练期间有 2 个输入,但在推理期间只有 1 个
【发布时间】:2021-09-10 17:16:13
【问题描述】:

之前有人问过类似的问题,但答案并不令人满意。

给定一个使用 keras 中的功能 API 制作的模型。

在训练模型时,我们有两个输入和一个输出。一种输入是图像。另一个输入是自定义损失函数所需的一组成本。

然而,在推理过程中,我们将只获得图像作为输入,并且没有任何成本。因此只有一个输入和一个输出。

如何调整在两个输入上训练过的相同模型进行推理?

训练时的模型有点像这样:

input1 = Input(shape=(64,64,3)) #RGB Image
input2 = Input(shape=(4,))#Costs associated with the image, input to the custom loss function
conv1 = Conv2D(16, 3 , padding = 'same', activation = 'relu')(input1)
#Other layers
output = Dense(6)(x) # last layer gives classification output

model = Model(inputs = [input1, input2] , outputs = output)
model.compile(loss = custom_loss_function(input2) , optimizer = 'adam')

这是训练期间的模型。

当图像只需要一个输入并且没有成本输入时,在推理过程中该怎么做?

【问题讨论】:

    标签: python tensorflow keras deep-learning computer-vision


    【解决方案1】:

    您可以将推理模型包装在训练模型中。

    在伪代码中:

    def make_model():
      input1 = Input(...)
      conv1 = Conv2D(16, 3 , padding = 'same', activation = 'relu')(input1)
    #Other layers
      output = Dense(6)(x) # last layer gives classification output
      return keras.Model(input1, output)
    
    def make_train_model():
      input1 = Input(...)
      input2 = Input(...)
      m_inner = make_model()
      output = m_inner(input1)
      model = keras.Model([input1, input2], output)
      model.compile(...)
      return model, m_inner
    

    您可以使用模型进行训练并保存内部模型以进行推理。

    【讨论】:

    • 我们可以直接将 m_inner 传递给输出,还是必须像这样获取输出层:model =keras.Model([input1,input2], m_inner.outputs)
    • @ArkaMaji 编辑了答案。最干净的解决方案是使用内部模型作为层。您也可以使用 m_inner.outputs,但使用模型是层这一事实更加优雅和可组合。
    【解决方案2】:

    如果不影响前向传递,只需使用“虚拟”输入

    【讨论】:

      猜你喜欢
      • 2020-10-15
      • 2019-02-02
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      • 2021-08-13
      • 2020-03-20
      相关资源
      最近更新 更多