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

别说谁变了你拦得住时间么 提交于 2021-01-28 05:11:08

问题


I'm implementing a Tensorflow Variational Autoencoder, copying the code exactly from the book "Deep Learning with Python". Up until a few days ago, the code was working perfectly but as of yesterday it has stopped working (I have not changed the code).

The code is for a generative model which can replicate images from the MNIST dataset.

The specific error message is below:

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

I have made the code available in the Google Collaborative file below, so you can try running it yourself:

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


回答1:


The custom layer you have defined to compute the loss, i.e. CustomVariationalLayer, is accessing tensors of the model which have not been passed to it directly. This is not allowed since eager mode is enabled but the function in the layer is by default executed in graph mode. To resolve this issue, you can either disable eager mode entirely using tf.compat.v1.disable_eager_execution(), or instead use tf.config.run_functions_eagerly(True) to make all the functions run eagerly.

However, both of above solutuons may not be desirable since they are modifying the default behavior of TF (especially the latter one, since it might reduce the performance). Therefore, instead of using those solutions, you can modify the definition of CustomVariationalLayer to take z_mean and z_log_var as its other inputs:

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])


来源:https://stackoverflow.com/questions/63271841/deep-learning-with-python-code-no-longer-working-typeerror-an-op-outside-of-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!