[英]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
I want to have two losses in my tensorflow keras model and one of them takes an intermediate layer as input.我想在我的 tensorflow keras model 中有两个损失,其中一个将中间层作为输入。 This code works when I use keras but when it comes to tensorflow.keras I face the following error.
此代码在我使用 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]
)
Error:错误:
_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>]
Is it bug?是错误吗? please find the complete code in this NOTEBOOK .
请在此笔记本中找到完整的代码。
If running under the eager mode,tensorflow op will check if the inputs are of type "tensorflow.python.framework.ops.EagerTensor" and Keras ops are implemented as DAGs.如果在 Eager 模式下运行,tensorflow op 将检查输入是否为“tensorflow.python.framework.ops.EagerTensor”类型,并且 Keras 操作被实现为So the inputs to the eager mode will be of tensorflow.python.framework.ops.Tensor and this throws the error
所以急切模式的输入将是tensorflow.python.framework.ops.Tensor这会引发错误
You can change the input type to EagerTensor by explicitly telling tensorflow to run in the eager mode for Keras.您可以通过明确告诉 tensorflow 在 Keras 的急切模式下运行来将输入类型更改为 EagerTensor。
tf.config.experimental_run_functions_eagerly(True) tf.config.experimental_run_functions_eagerly(真)
Adding this statement should solve your issue.添加此语句应该可以解决您的问题。 Although note that there will be significant performance hits since you are running now in eager mode and recommended only for debugging, profiling etc.
尽管请注意,由于您现在在急切模式下运行并且仅推荐用于调试、分析等,因此会有显着的性能损失。
Replacing K.mean
to tf.reduce_mean
and accordingly all the keras backend functions to tensorflow functions solved the problem.将
K.mean
替换为tf.reduce_mean
并相应地将所有 keras 后端函数替换为 tensorflow 函数解决了该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.