python - 如何将可训练参数添加到 Tensorflow2 Keras 模型损失函数中
问题描述
我正在尝试使用 Keras(Tensorflow2)训练图像降噪器网络。对于损失函数,我想使用类似 ( a1 * L1_loss + a2 * L2_loss) 的东西,其中a1和a2是可训练的,这意味着在我给它们初始值之后,它们可以在每次训练迭代中得到更新。但是我在这里停留了一段时间,并且知道我应该如何实现这一点。
这是一些示例代码,
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 来进行训练。
虽然我可以通过这种方式添加两个权重参数,但这些权重是不可训练的,并且它们不会随着训练而改变。如果有人对此问题有一些想法,真的希望得到一些提示或示例。任何帮助表示赞赏!
解决方案
推荐阅读
- javascript - 如何在币安 api 中设置买单
- excel - 如何使用 Randomize 使我的 UDF 成为非易失性?
- react-native - 使用 React Navigation 测试 React Native 的问题
- tkinter - Tkinter 避免/禁用窗口移动(或其拖动)
- python - 通过 PID 获取脚本名称
- ffmpeg - 如何使用 ffmpeg 从 SDP 录制视频?
- macos - 如何修复 macOS 上的 VS Code“模块...针对不同的 Node.js 版本编译”错误?
- android - 适用于 android-R 和旧版 Android API 30 的系统映像
- discord.js - Heroku 中的 MongoDB 问题
- javascript - 如何从 Promise 中获取值并将其存储在变量中以供进一步使用