我正在实现一个Tensorflow变分自编码器,完全照搬《使用Python进行深度学习》这本书中的代码。几天前代码还能完美运行,但从昨天开始就停止工作了(我没有更改代码)。
这段代码是一个生成模型,用于复制MNIST数据集中的图像。
具体的错误信息如下:
TypeError: An op outside of the function building code is being passeda “Graph” tensor. It is possible to have Graph tensorsleak out of the function building context by including atf.init_scope in your function building code.The graph tensor has name: dense_2/BiasAdd:0
我已经在下面的Google Colab文件中提供了代码,你可以自己尝试运行:
https://colab.research.google.com/drive/1ArmP3Nns2T_i-Yt-yDXoudp6Lhnw-ghu?usp=sharing
回答:
你定义的用于计算损失的自定义层,即CustomVariationalLayer
,正在访问模型中未直接传递给它的张量。这是被禁止的,因为启用了急切模式(eager mode),但层中的函数默认在图模式(graph mode)下执行。为了解决这个问题,你可以完全禁用急切模式,使用tf.compat.v1.disable_eager_execution()
,或者使用tf.config.run_functions_eagerly(True)
让所有函数以急切模式运行。
然而,上述两种解决方案可能并不理想,因为它们修改了TensorFlow的默认行为(特别是后者,因为它可能会降低性能)。因此,与其使用这些解决方案,你可以修改CustomVariationalLayer
的定义,将z_mean
和z_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])