【问题标题】:tf.keras two losses, with intermediate layers as input to of one of them error:Inputs to eager execution function cannot be Keras symbolic tensorstf.keras 两个损失,中间层作为其中一个的输入错误:急切执行函数的输入不能是 Keras 符号张量
【发布时间】:2020-07-25 04:05:51
【问题描述】:

我想在我的 tensorflow keras 模型中有两个损失,其中一个将中间层作为输入。 此代码在我使用 keras 时有效,但在涉及 tensorflow.keras 时,我遇到以下错误。

def loss_VAE(input_shape, z_mean, z_var, weight_L2=0.1, weight_KL=0.1):

  def loss_VAE_(y_true, y_pred):
      c, H, W, D = input_shape
      n = c * H * W * D

      loss_L2 = K.mean(K.square(y_true - y_pred), axis=(1, 2, 3, 4)) # original axis value is (1,2,3,4).

      loss_KL = (1 / n) * K.sum(
          K.exp(z_var) + K.square(z_mean) - 1. - z_var,
          axis=-1
      )

      return weight_L2 * loss_L2 + weight_KL * loss_KL

  return loss_VAE_

def loss_gt(e=1e-8):

  def loss_gt_(y_true, y_pred):
      intersection = K.sum(K.abs(y_true * y_pred), axis=[-3,-2,-1])
      dn = K.sum(K.square(y_true) + K.square(y_pred), axis=[-3,-2,-1]) + e

      return - K.mean(2 * intersection / dn, axis=[0,1])

  return loss_gt_


model.compile(
    adam(lr=1e-4),
    [loss_gt(dice_e), loss_VAE(input_shape, z_mean, z_var, weight_L2=weight_L2, weight_KL=weight_KL)],
    # metrics=[dice_coefficient]
)

错误:

_SymbolicException: Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'Dec_VAE_VDraw_Var/Identity:0' shape=(None, 128) dtype=float32>, <tf.Tensor 'Dec_VAE_VDraw_Mean/Identity:0' shape=(None, 128) dtype=float32>]

这是错误吗? 请在NOTEBOOK 中找到完整的代码。

THIS 是指向数据的链接。

【问题讨论】:

    标签: python tensorflow keras loss-function tf.keras


    【解决方案1】:

    如果在 eager 模式下运行,tensorflow op 将检查输入是否为“tensorflow.python.framework.ops.EagerTensor”类型,并且 Keras ops 被实现为 DAG。因此,渴望模式的输入将是 tensorflow.python.framework.ops.Tensor,这会引发错误

    您可以通过明确告诉 tensorflow 在 Keras 的 Eager 模式下运行来将输入类型更改为 EagerTensor。

    tf.config.experimental_run_functions_eagerly(True)

    添加此语句应该可以解决您的问题。虽然请注意,由于您现在在急切模式下运行并且仅推荐用于调试、分析等,因此性能会受到显着影响。

    【讨论】:

    • 这解决了第一个错误但导致另一个错误:TypeError: Can not convert a NoneType into a Tensor or Operation.
    • 没什么。我编辑了问题,添加了指向数据的链接,以备不时之需
    • 尝试像this 那样训练你的代码。这会奏效。并制作 tf.config.experimental_run_functions_eagerly(False)
    • 我已经尝试过自定义循环,但是在应用渐变时遇到了问题。
    【解决方案2】:

    将 K.mean 替换为 tf.reduce_mean 并相应地将所有 keras 后端函数替换为 tensorflow 函数解决了该问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-26
      • 2020-07-30
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多