tf.keras 连续两张图像丢失

tf.keras loss from two images in serial

我想使用 the paper 的稳定性训练方法并将其应用于非常简单的 CNN。
原理架构由以下给出:


如图所示,您根据输入图像 I 的输出 f(I) 计算损失 扰动图像 f(I') 的输出 I'.
我的问题是如何在没有两个 DNN 实例的情况下以有效的方式执行此操作, 因为我正在训练大型 3D 图像。换句话说:我如何连续处理两张图像并根据这两张图像计算损失?
我在 keras 中使用 tf2。

  1. 您可以先将 DNN 编写为 tf.keras 模型。

  2. 之后,您可以编写另一个模型,它接受两个图像输入,对一个图像应用一些高斯噪声,然后将它们传递给 DNN。

  3. 设计一个自定义损失函数,从两个输出中找到合适的损失。

这是一个演示代码:

from tensorflow.keras.layers import Input, Dense, Add, Activation, Flatten
from tensorflow.keras.models import Model
import tensorflow as tf
import numpy as np
import random


from tensorflow.python.keras.layers import Input, GaussianNoise, BatchNormalization

# shared DNN, this is the base model with a feature-space output, there is only once instance of the model
ip = Input(shape=(32,32,1)) # same as original inputs
f0 = Flatten()(ip)
d0 = Dense(10)(f0) # 10 dimensional feature embedding
dnn = Model(ip, d0)

# final model with two version of images and loss

input_1 = Input(shape=(32,32,1))
input_2 = Input(shape=(32,32,1))

g0 = GaussianNoise(0.5)(input_2)  # only input_2 passes through gaussian noise layer, you can design your own custom layer too

# passing the two images to same DNN

path1 = dnn(input_1) # no noise
path2 = dnn(g0) # noise

model = Model([input_1, input_2], [path1, path2])

def my_loss(y_true, y_pred):
  # calculate your loss based on your two outputs path1, path2
  pass

model.compile('adam', my_loss)
model.summary()