Deep Learning with Python code no longer working. "TypeError: An op outside of the function building code is being passed a "Graph" tensor."

Deep Learning with Python code no longer working. "TypeError: An op outside of the function building code is being passed a "Graph" tensor."

我正在实现一个 Tensorflow 变分自动编码器,完全从“使用 Python 进行深度学习”一书中复制代码。直到几天前,代码还可以正常工作,但从昨天开始它就停止工作了(我没有更改代码)。

该代码用于生成模型,可以从 MNIST 数据集中复制图像。

具体报错信息如下:

TypeError: An op outside of the function building code is being passed a "Graph" tensor. It is possible to have Graph tensors leak out of the function building context by including a tf.init_scope in your function building code. The graph tensor has name: dense_2/BiasAdd:0

我已经在下面的 Google 协作文件中提供了代码,因此您可以自己尝试 运行:

https://colab.research.google.com/drive/1ArmP3Nns2T_i-Yt-yDXoudp6Lhnw-ghu?usp=sharing

您定义的用于计算损失的自定义层,即 CustomVariationalLayer,正在访问尚未直接传递给它的模型张量。这是不允许的,因为启用了 eager 模式,但图层中的函数默认在图形模式下执行。要解决此问题,您可以使用 tf.compat.v1.disable_eager_execution() 完全禁用 eager 模式,或者使用 tf.config.run_functions_eagerly(True) 使所有功能 运行 eagerly。

但是,上述两种解决方案可能都不可取,因为它们正在修改 TF 的默认行为(尤其是后一种,因为它可能会降低性能)。因此,您可以修改 CustomVariationalLayer 的定义以将 z_meanz_log_var 作为其其他输入,而不是使用这些解决方案:

class CustomVariationalLayer(keras.layers.Layer):
    def vae_loss(self, x, z_decoded, z_mean, z_log_var):
        # ...

    def call(self, inputs):
        x = inputs[0]
        z_decoded = inputs[1]
        z_mean = inputs[2]
        z_log_var = inputs[3]
        loss = self.vae_loss(x, z_decoded, z_mean, z_log_var)
        # ...

y = CustomVariationalLayer()([input_img, z_decoded, z_mean, z_log_var])