keras搭建网络自己写损失函数时出现的报错bool` is not allowed in Graph execution

前提是keras搭建神经网络,然后自己写的损失函数

 def ls_generator_loss(self,recon_x, mu, logvar):
        """
        recon_x: generating images
        x: origin images
        mu: latent mean
        logvar: latent log variance
        """
        loss0 = 0.5 * K.mean((recon_x - 1) ** 2)
        # KL divergence
        loss_kl = 0.5 * K.sum(K.square(mu) +
                              K.exp(logvar) - 1. - logvar, axis=1)
        return K.mean(loss0 + loss_kl)

利用.compile函数把loss定义进去:

gan.compile(loss=self.ls_generator_loss(validity,z_mean,z_logvar), optimizer=Adam(0.0002, 0.5),metrics=['mean_squared_error'])

结果报错

tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.

请问这种问题如何处理