Solving Tensorflow AttributeError: module ‘tensorflow’ has no attribute ‘Session’ in Python

Tensorflow AttributeError: module ‘tensorflow’ has no attribute ‘Session’ in Python is a Python error which sometimes occurs when you use tf.Session().

In this article I am going to try and solve the error while I try to explain why the error is actually popping up, we will also introduce some solutions that worked for other developers and see if those solutions can solve the error in your particular situation.

Explaining the Error : Tensorflow AttributeError: module ‘tensorflow’ has no attribute ‘Session’ in Python

The problem happens sometimes when you use tf.Session() in tensorflow version 2.

The error message should look like the error in the example bellow.

Please do not confuse this error with another error, hence why you should double check the error message bellow.

                                                                       #
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'Session'
                                                                       #

Bellow I will present multiple solutions some have worked for me and others have worked for other developers.

Solution 1 : use tf.function()

If you want to run static graphs the best way is to use tf.function() in TensorFlow 2. It is generally not recommended to use tf.Session() in TensorFlow 2.

Bellow is An example of how you can use tf.function().

                                                                       #
import tensorflow as tf
data = tf.constant('My name is Tommy!')
tf.print(data)
                                                                       #

If tf.function() does not solve your problem, please try the solution bellow.

Solution 2 : downgrade to Tensorflow 1.

The third solution is to TensorFlow 1. Most developers will avoid this option and that is exactly why I kept it to the last section of this blog post.

You can use Session() just fine in Tensorflow 1. That is why this is a great solution for those who are okay with downgrading to Tensorflow 1.

                                                                       #
pip3 install --upgrade --force-reinstall tensorflow-gpu==1.15.0 
                                                                       #

The solutions above should solve your issue. If the issue persists, I am sorry I tried doing my best with this blog post.

If the solutions above helped you, consider supporting us on Kofi, any help is appreciated.

Summing-up

Thank you for reading, we are at the end of this article, I did my best to help you solve this error with this guide and included the solution that worked for me and other solutions that I found relevant.

Thanks, keep coding and cheers. If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/