Search code examples
python-3.xgraphtensorflow2.0attributeerror

TensorFlow 2: detecting to which graph a certain node belong


I just started (self) learning TensorFlow and I decided to follow the book "Learning TensorFlow" which I found in my local library. Unfortunately in the book they are using TensorFlow 1.x, while I want to use the 2.4 version.

I have some troubles in replicating an example from Chapter 3. The point of the code is to create a new empty computing graph, create a node (i.e. in this case a constant) and then figure out whether the node belongs to the default graph or to the newly created one. Here is the code from the book, which should work fine with TensorFlow1:

import tensorflow as tf
print(tf.get_default_graph())

g = tf.Graph()      # This creates a new empty graph
a = tf.constant(5)  # This creates a node

print(a.graph is g)
print(a.graph is tf.get_default_graph())

I did realize that the attribute get_default_graph() is no longer available in TensorFlow 2 and I substituted with tf.compat.v1.get_default_graph() but I still get the following error:

AttributeError: Tensor.graph is meaningless when eager execution is enabled.

Any help will be very much appreciated! Thanks in advance!


Solution

  • After import tensorflow need disable eager execution, like below:

    import tensorflow as tf
    
    tf.compat.v1.disable_eager_execution()
    
    print(tf.compat.v1.get_default_graph())
    
    g = tf.Graph()      # This creates a new empty graph
    a = tf.constant(5)  # This creates a node
    
    print(a.graph is g)
    print(a.graph is tf.compat.v1.get_default_graph())