You need to enable JavaScript to run this app. 多输出模型结合add_loss与Keras损失新增自定义SSIM损失报错求解
优惠活动
大模型
产品
解决方案
定价
更多

多输出模型结合add_loss与Keras损失新增自定义SSIM损失报错求解

Keras自定义损失与内置损失结合使用报错相关提问

问题背景

我之前在另一篇帖子中讨论过相关问题,当时通过如下方案解决了Keras多输出自定义损失的问题:

def MyLoss(true1, true2, out1, out2, out3):
    loss1 = tf.keras.losses.someloss1(out1, true1)
    loss2 = tf.keras.losses.someloss2(out2, true2)
    loss3 = tf.keras.losses.someloss3(out2, out3)
    loss = loss1 + loss2 + loss3
    return loss

input1 = Input(shape=input1_shape)
input2 = Input(shape=input2_shape)

# 无需关注具体写法,仅参考实现思路
output1 = Submodel1()([input1,input2]) 
output2 = Submodel2()(output1)
output3 = Sumbodel3()(output1)

true1 = Input(shape=true1shape)
true2 = Input(shape=true2shape)

model = Model([input1,input2,true1,true2], [output1,output2,output3])
model.add_loss(MyLoss(true1, true2, output1, output2, output3))
model.compile(optimizer='adam', loss=None)

model.fit(x=[input1 ,input2 ,true1,true2], y=None, epochs=n_epochs)

当时我使用的全部是Keras内置损失函数,现在需要新增两个SSIM自定义损失,将其与内置损失结合使用,我的模型结构如下:
模型结构示意图

我尝试了如下实现方式:

def SSIMLoss(y_true, y_pred):
    return 1-tf.reduce_mean(tf.image.ssim(y_true, y_pred, 1.0))

def MyLoss(true1, true2, out1, out2, out3):
    loss1 = tf.keras.losses.someloss1(out1, true1)
    customloss1 = SSIMLoss(out1,true1)
    loss2 = tf.keras.losses.someloss2(out2, true2)
    loss3 = tf.keras.losses.someloss3(out2, out3)
    customloss2 = SSIMLoss(out2,out3)
    loss = loss1 + loss2 + loss3 + customloss1 + customloss2
    return loss

运行后触发报错:
OperatorNotAllowedInGraphError: using a tf.Tensor as a Python bool is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.

我给SSIMLoss函数加上@tf.function装饰器后,又触发新的报错:
_SymbolicException: Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'input_43:0' shape=(None, 128, 128, 1) dtype=float32>, <tf.Tensor 'conv2d_109/Sigmoid:0' shape=(None, 128, 128, 1) dtype=float32>]

我找到了相关的Keras损失与add_loss结合使用的issue,猜测是该原因导致的问题,但不知道如何修复,求可行的解决方案。


解决方案

报错根源是tf.image.ssim内部存在隐式布尔判断,图执行模式下传入符号张量时会触发类型错误,无需加@tf.function装饰器,按如下步骤调整即可:

  1. 确保传入损失的张量为4维格式[batch, height, width, channels],像素值范围和你指定的动态范围(代码中为1.0)匹配
  2. 改用继承tf.keras.losses.Loss的类实现自定义SSIM损失,避免隐式类型判断

修正后的SSIM损失实现

import tensorflow as tf

class SSIMLoss(tf.keras.losses.Loss):
    def __init__(self, max_val=1.0, **kwargs):
        super().__init__(**kwargs)
        self.max_val = max_val

    def call(self, y_true, y_pred):
        # 显式固定维度,避免内部隐式判断触发错误
        y_true = tf.ensure_shape(y_true, (None, None, None, 1))
        y_pred = tf.ensure_shape(y_pred, (None, None, None, 1))
        ssim = tf.image.ssim(y_true, y_pred, max_val=self.max_val)
        return 1 - tf.reduce_mean(ssim)

修正后的总损失与模型编译

# 初始化自定义损失实例
ssim_loss = SSIMLoss(max_val=1.0)

def MyLoss(true1, true2, out1, out2, out3):
    loss1 = tf.keras.losses.someloss1(out1, true1)
    customloss1 = ssim_loss(out1, true1)
    loss2 = tf.keras.losses.someloss2(out2, true2)
    loss3 = tf.keras.losses.someloss3(out2, out3)
    customloss2 = ssim_loss(out2, out3)
    # 可根据需求调整各损失的权重系数,平衡训练效果
    loss = loss1 + loss2 + loss3 + 0.1 * customloss1 + 0.1 * customloss2
    return loss

# 模型构建逻辑和之前完全一致,编译时可按需开启run_eagerly调试
model.compile(optimizer='adam', loss=None, run_eagerly=False)

如果调整后仍然报错,可在model.compile时临时设置run_eagerly=True开启急切执行,确认损失计算逻辑无误后再关闭即可。


内容的提问来源于stack exchange,提问作者Negreanu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 06:36:04