首页 > 解决方案 > 如何将可训练参数添加到 Tensorflow2 Keras 模型损失函数中

问题描述

我正在尝试使用 Keras(Tensorflow2)训练图像降噪器网络。对于损失函数,我想使用类似 ( a1 * L1_loss + a2 * L2_loss) 的东西,其中a1a2是可训练的,这意味着在我给它们初始值之后,它们可以在每次训练迭代中得到更新。但是我在这里停留了一段时间,并且知道我应该如何实现这一点。

这是一些示例代码,

model_input = Input(shape=self.input_shape)
l1_weight = tf.Variable(0.5, trainable=True, name='L1_Loss_weight')
l2_weight = tf.Variable(0.5, trainable=True, name='L2_Loss_weight')
model_output= Conv3D(filters=self.filters, kernel_size=self.kernel_size, padding='same')(model_input)

self.model = Model(inputs=model_input,
                   outputs=model_output)
optimizer = tf.keras.optimizers.SGD()
model_loss = mixed_loss(L1_weight=l1_weight, L2_weight=l2_weight)
self.model.compile(optimizer=optimizer,
                   loss=model_loss)

我的损失函数定义为

def mixed_loss(L1_weight, L2_weight):
    def mixed(y_true, y_pred):
        return L1_weight * mean_absolute_error(y_true, y_pred) + L2_weight * mean_squared_error(y_true, y_pred)
    return mixed

然后我使用 fit() 函数传递包含训练数据的 tf.data.Dataset 来进行训练。

虽然我可以通过这种方式添加两个权重参数,但这些权重是不可训练的,并且它们不会随着训练而改变。如果有人对此问题有一些想法,真的希望得到一些提示或示例。任何帮助表示赞赏!

标签: pythontensorflowkeras

解决方案


推荐阅读