You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改自定义损失函数后出现KerasTensor TypeError的技术问询

自定义损失函数修改后触发KerasTensor类型错误的排查

原损失函数实现

def custom_loss(y_true,y_pred):
    L1_loss = keras.mean(keras.abs(y_true - y_pred), axis=-1)
    ssim_loss = 1 - (tf.reduce_mean(tf.image.ssim(y_true, y_pred, max_val=1.0, filter_size=5)))
    loss = L1_loss + 2.0 * SSIM_loss
    return loss

修改后的损失函数实现

def custom_loss(deltaT1):
  def total_loss(y_true,y_pred):
    L1_loss = keras.mean(keras.abs(y_true - y_pred), axis=-1)
    ssim_loss = 1 - (tf.reduce_mean(tf.image.ssim(y_true, y_pred, max_val=1.0, filter_size=5)))
    mask_loss = keras.mean(keras.abs(y_true-y_pred)*deltaT1,axis=-1)
    loss = 1.0 * L1_loss + 5.0 * ssim_loss + 1.0 * mask_loss
    return loss
  return total_loss

触发的错误信息

TypeError: in user code:

File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1284, in train_function  *
    return step_function(self, iterator)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1268, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1249, in run_step  **
    outputs = model.train_step(data)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1051, in train_step
    loss = self.compute_loss(x, y, y_pred, sample_weight)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1109, in compute_loss
    return self.compiled_loss(
File "/usr/local/lib/python3.10/dist-packages/keras/engine/compile_utils.py", line 317, in __call__
    self._total_loss_mean.update_state(
File "/usr/local/lib/python3.10/dist-packages/keras/utils/metrics_utils.py", line 77, in decorated
    update_op = update_state_fn(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/keras/metrics/base_metric.py", line 140, in update_state_fn
    return ag_update_state(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/keras/metrics/base_metric.py", line 477, in update_state  **
    sample_weight = tf.__internal__.ops.broadcast_weights(
File "/usr/local/lib/python3.10/dist-packages/keras/engine/keras_tensor.py", line 283, in __array__
    raise TypeError(

TypeError: You are passing KerasTensor(type_spec=TensorSpec(shape=(), dtype=tf.float32, name=None), name='Placeholder:0', description="created by layer 'tf.cast_5'"), an intermediate Keras symbolic input/output, to a TF API that does not allow registering custom dispatchers, such as `tf.cond`, `tf.function`, gradient tapes, or `tf.map_fn`. Keras Functional model construction only supports TF API calls that *do* support dispatching, such as `tf.math.add` or `tf.reshape`. Other APIs cannot be called directly on symbolic Kerasinputs/outputs. You can work around this limitation by putting the operation in a custom Keras layer `call` and calling that layer on this symbolic input/output.

模型拟合代码片段

model.compile(optimizer=optimizer, loss=custom_loss(mask), metrics=metrics)

....

with tf.device('/gpu:0'):
  history = model.fit(train_img_datagen,
                      steps_per_epoch=steps_per_epoch,
                      epochs=epochs,
                      verbose=1,
                      validation_data=val_img_datagen,
                      validation_steps=val_steps_per_epoch,
                      callbacks=[callbacks])

疑问

修改后的损失函数写法参考了第三方仓库的代码,请问这是TensorFlow版本差异导致的问题吗?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 20:23:08