【发布时间】:2020-12-29 20:20:18
【问题描述】:
我正在尝试在 Keras v2.4.3 中构建自定义损失函数: (如answer 中所述)
def vae_loss(x: tf.Tensor, x_decoded_mean: tf.Tensor,
original_dim=original_dim):
z_mean = encoder.get_layer('mean').output
z_log_var = encoder.get_layer('log-var').output
xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)
kl_loss = - 0.5 * K.sum(
1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
vae_loss = K.mean(xent_loss + kl_loss)
return vae_loss
但我认为它的行为与预期有很大不同(可能是因为我的 Keras 版本?),我收到了这个错误:
TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.
我认为这是因为 encoder.get_layer('mean').output 返回的是 KerasTensor 对象而不是 tf.Tensor 对象(正如其他答案所示)。
我在这里做错了什么?如何从自定义损失函数中访问给定层的输出?
【问题讨论】:
标签: python tensorflow machine-learning keras deep-learning