更改损失函数后,为什么我会收到“TypeError:您正在传递 KerasTensor...”?

问题描述 投票:0回答:1

我正在做一个张量流项目。但我遇到了无法解决的错误。

当我改变损失函数时

来自

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

我会看到此错误消息

`类型错误:在用户代码中:

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版本导致的问题吗?因为在我添加 deltaT1 后出错了,我模仿这个存储库的第 41 行编写了它。 https://github.com/chenchao666/Contrast-enhanced-MRI-Synthesis/blob/master/HRNet(3D)/utils.py

python tensorflow keras deep-learning
1个回答
0
投票

当模型的输出与您正在使用的损失函数之间不匹配时,错误消息“TypeError:您正在传递 KerasTensor”通常会出现在深度学习模型中。当您更改损失函数并且计算中涉及的张量的形状或类型不再兼容时,通常会出现此错误。

以下是您可能遇到此错误的一些常见原因以及解决方法:

  1. 输出和损失函数不匹配:

    • 确保模型的输出(即最后一层)和传递给损失函数的目标值具有相同的形状和数据类型。
    • 例如,如果您的模型输出概率(例如,使用 softmax 激活),并且您使用的是分类交叉熵损失,那么您的目标值应该是 one-hot 编码的。
  2. 损失函数参数:

    • 某些损失函数具有需要正确设置的参数,更改损失函数可能需要调整这些参数。
    • 检查您正在使用的新损失函数的文档,并确保正确传递所需的参数。
  3. 模型架构

    • 更改损失函数可能会影响模型的整体架构。
    • 验证模型的输出层是否符合新损失函数的要求。例如,如果从回归损失切换到分类损失,则可能需要更改输出层中的激活函数。
  4. 数据预处理:

    • 确保您的输入数据预处理与您对损失函数所做的更改保持一致。
    • 如果您的损失函数和模型输出发生显着变化,可能需要调整数据预处理,例如 one-hot 编码。
  5. 标签格式:

    • 仔细检查您的目标标签(基本事实)是否采用新损失函数的正确格式。
    • 例如,如果您从二进制交叉熵切换到分类交叉熵,则您的标签应该是单热编码或分类格式。
  6. 调试与打印:

    • 使用打印语句或调试工具检查代码中不同点的张量的形状和值。这可以帮助您查明错误发生的位置。

以下是在更改 Keras 模型中的损失函数时如何调整代码的示例:

# Example: Changing loss function from mean squared error to categorical cross-entropy

# Original model with MSE loss
model = Sequential()
model.add(Dense(10, input_shape=(input_dim,)))
model.compile(optimizer='adam', loss='mean_squared_error')

# Updated model with categorical cross-entropy loss
model = Sequential()
model.add(Dense(10, input_shape=(input_dim,), activation='softmax'))  # Adjust the output layer
model.compile(optimizer='adam', loss='categorical_crossentropy')

# Ensure your data preprocessing and labels match the new loss function.

通过仔细检查和调整模型的架构、数据预处理和目标标签以匹配新损失函数的要求,您应该能够解决“TypeError”问题。

© www.soinside.com 2019 - 2024. All rights reserved.