簡體   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