繁体   English   中英

tf.keras 两个损失,中间层作为其中一个的输入错误:急切执行的输入 function 不能是 Keras 符号张量

[英]tf.keras two losses, with intermediate layers as input to of one of them error:Inputs to eager execution function cannot be Keras symbolic tensors

我想在我的 tensorflow keras model 中有两个损失,其中一个将中间层作为输入。 此代码在我使用 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>]

是错误吗? 请在此笔记本中找到完整的代码。

是数据的链接。

如果在 Eager 模式下运行,tensorflow op 将检查输入是否为“tensorflow.python.framework.ops.EagerTensor”类型,并且 Keras 操作被实现为所以急切模式的输入将是tensorflow.python.framework.ops.Tensor这会引发错误

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

tf.config.experimental_run_functions_eagerly(真)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM