python - 如何在丢失之前运行两次keras模型?

标签 python tensorflow keras deep-learning

我想计算一个损失函数,它在不同的输入上两次使用网络的输出。例如假设,

first_output = model(first_input)
second_output = model(second_input)
loss = mean_absolute_error(first_output, second_output)

如何在 tensorflow 或 keras 中实现这一点?

更新:谢谢大家的回复。我想重新实现 this paper在 keras 或 tensorflow 中。正如其中所解释的那样,GAN 中作为鉴别器的“批评家”网络有两个输入并一个一个地运行它们并根据输出和计算梯度计算损失函数。主要问题是如何在 tensorflow 或 keras 中实现?

最佳答案

您可以尝试使用 keras.layers.merge .我以前用它来制作连体网络,例如:

first_output = model(first_input)
second_output = model(second_input)
mae = lambda x: mean_absolute_error(x[0], x[1])
distance = merge(inputs=[first_output, second_output],
                 mode=mae,
                 output_shape=lambda x: x[0],
                 name='mean_absolute_error')

对于 Siamese 网络示例,您通常会使用类似以下内容对此距离度量做出一些预测:

prediction = Dense(2, activation='softmax', name='prediction')(distance)
model = Model([first_input, second_input], prediction, name='siamese_net')
model.compile(optimizer=Adam(),
              loss=some_loss_function)

使用 keras.models.Modelkeras.layers.Dense对于那个例子。

请注意,keras.layers.merge(我相信)在最新版本的 Keras 中已弃用,这真是令人遗憾。我认为要对最现代的 Keras 做一些类似的事情,你需要使用 keras.layers.Concatenate结合两个结果,然后是 keras.layers.Lambda应用函数。

关于python - 如何在丢失之前运行两次keras模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405717/

相关文章:

python - 在 Pandas Groupby 中使用列和行多索引值,无需拆栈

tensorflow - 如何在 Google Colab 中将 TensorFlow 2.0 设置为默认版本

python - TensorFlow 2.0 中神经网络的问题

python - 在不平坦的表面上定位物体

python - 为什么 l.insert(0, i) 在 python 中比 l.append(i) 慢?

tensorflow - 如何将经过训练的 TF1 protobuf 模型加载到 TF2 中?

tensorflow - 使用 Tensorflow 的多元时间序列 RNN。使用 LSTM 单元或类似单元可以实现吗?

python - 如何为 keras 中的 LSTM 回归准备输入数据?

python - 在使用 tensorflow 作为后端的 keras 上,我的预测分数是否会太高(一类为 100%)?

python - 在python中过滤大型稀疏矩阵