Debug School

rakesh kumar
rakesh kumar

Posted on

Tensor flow Attribute Error

yesterday when i run the command i got error

my code is

import tensorflow as tf

# Define TensorFlow operations
a = tf.constant(2)
b = tf.constant(3)
c = tf.add(a, b)  # Addition operation

# Run the TensorFlow operations inside a session
with tf.Session() as sess:
    result = sess.run(c)
    print("Result:", result)
Enter fullscreen mode Exit fullscreen mode

Error


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[7], line 9
      6 c = tf.add(a, b)  # Addition operation
      8 # Run the TensorFlow operations inside a session
----> 9 with tf.Session() as sess:
     10     result = sess.run(c)
     11     print("Result:", result)

AttributeError: module 'tensorflow' has no attribute 'Session'
Enter fullscreen mode Exit fullscreen mode

Solution
It seems like you're trying to run TensorFlow 1.x code in an environment with TensorFlow 2.x installed. In TensorFlow 2.x, the session-based execution has been replaced with eager execution by default, and the tf.Session() class is no longer available.

To fix the error, you have two options:

Enable Eager Execution (TensorFlow 2.x):
With eager execution enabled, TensorFlow operations are executed immediately and you don't need to explicitly create a session.Here's your code modified for TensorFlow 2.x with eager execution:

import tensorflow as tf

# Define TensorFlow operations
a = tf.constant(2)
b = tf.constant(3)
c = tf.add(a, b)  # Addition operation

# Run the TensorFlow operations
result = c.numpy()  # Convert TensorFlow tensor to NumPy array
print("Result:", result)
Enter fullscreen mode Exit fullscreen mode

output

Result: 5

Top comments (0)