# Tensorflow 2.0 – AttributeError: module 'tensorflow' has no attribute 'Session'

## Question:

When I am executing the command `sess = tf.Session()`

in Tensorflow 2.0 environment, I am getting an error message as below:

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

System Information:

- OS Platform and Distribution: Windows 10
- Python Version: 3.7.1
- Tensorflow Version: 2.0.0-alpha0 (installed with pip)

Steps to reproduce:

Installation:

- pip install –upgrade pip
**pip install tensorflow==2.0.0-alpha0**- pip install keras
- pip install numpy==1.16.2

Execution:

- Execute command: import tensorflow as tf
- Execute command: sess = tf.Session()

## Answers:

According to `TF 1:1 Symbols Map`

, in TF 2.0 you should use `tf.compat.v1.Session()`

instead of `tf.Session()`

https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0

To get TF 1.x like behaviour in TF 2.0 one can run

```
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
```

but then one cannot benefit of many improvements made in TF 2.0. For more details please refer to the migration guide

https://www.tensorflow.org/guide/migrate

I faced this problem when I first tried python after installing `windows10 + python3.7(64bit) + anacconda3 + jupyter notebook.`

I solved this problem by refering to “https://vispud.blogspot.com/2019/05/tensorflow200a0-attributeerror-module.html“

I agree with

I believe “Session()” has been removed with TF 2.0.

I inserted two lines. One is `tf.compat.v1.disable_eager_execution()`

and the other is `sess = tf.compat.v1.Session()`

My Hello.py is as follows:

```
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
hello = tf.constant('Hello, TensorFlow!')
sess = tf.compat.v1.Session()
print(sess.run(hello))
```

If this is your code, the correct solution is to rewrite it to not use `Session()`

, since that’s no longer necessary in TensorFlow 2

If this is just code you’re running, you can downgrade to TensorFlow 1 by running

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

*(or whatever the latest version of TensorFlow 1 is)*

TF2 runs Eager Execution by default, thus removing the need for Sessions. If you want to run static graphs, the more proper way is to use `tf.function()`

in TF2. While Session can still be accessed via `tf.compat.v1.Session()`

in TF2, I would discourage using it. It may be helpful to demonstrate this difference by comparing the difference in hello worlds:

TF1.x hello world:

```
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(msg))
```

TF2.x hello world:

```
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
tf.print(msg)
```

For more info, see Effective TensorFlow 2

Using Anaconda + Spyder (Python 3.7)

[code]

```
import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
print(soma)
sess = tf.compat.v1.Session()
with sess:
print(sess.run(soma))
```

[console]

```
import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
Tensor("Const_8:0", shape=(), dtype=int32)
Out[18]: tensorflow.python.framework.ops.Tensor
print(soma)
Tensor("add_4:0", shape=(), dtype=int32)
sess = tf.compat.v1.Session()
with sess:
print(sess.run(soma))
5
```

For `TF2.x`

, you can do like this.

```
import tensorflow as tf
with tf.compat.v1.Session() as sess:
hello = tf.constant('hello world')
print(sess.run(hello))
```

`>>> b'hello world`

TF v2.0 supports Eager mode vis-a-vis Graph mode of v1.0. Hence, tf.session() is not supported on v2.0. Hence, would suggest you to rewrite your code to work in Eager mode.

Tensorflow 2.x support’s Eager Execution by default hence Session is not supported.

```
import tensorflow as tf
sess = tf.Session()
```

this code will show an Attribute error on version 2.x

to use version 1.x code in version 2.x

try this

```
import tensorflow.compat.v1 as tf
sess = tf.Session()
```

**Same problem occurred for me**

```
import tensorflow as tf
hello = tf.constant('Hello World ')
sess = tf.compat.v1.Session() *//I got the error on this step when I used
tf.Session()*
sess.run(hello)
```

Try replacing it with `tf.compact.v1.Session()`

I also faced same problem when I first tried Google Colab after updating **Windows 10**. Then I changed and inserted two lines,

`tf.compat.v1.disable_eager_execution()`

`sess = tf.compat.v1.Session()`

As a result, everything goes OK

use this:

```
sess = tf.compat.v1.Session()
```

if there is an error, use the following

```
tf.compat.v1.disable_eager_execution()
sess = tf.compat.v1.Session()
```

If you’re doing it while some imports like,

```
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np
```

Then I suggest you to follow these steps,

NOTE: For TensorFlow2 and for CPU Process only

Step 1: Tell your code to act as if the compiler is TF1 and disable TF2 behavior, use the following code:

```
import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
```

Step 2: While importing libraries, remind your code that it has to act like TF1, yes EVERYTIME.

```
tf.disable_v2_behavior()
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np
```

Conclusion: This should work, let me know if something goes wrong, also if it is GPU, then do mention to add a backend code for keras. Also, TF2 does not support session there is a separate understanding for that and has been mentioned on TensorFlow, the link is:

TensorFlow Page for using Sessions in TF2

Other major TF2 changes have been mentioned in this link, it is long but please go through it, use Ctrl+F for assistance. Link,

```
import tensorflow._api.v2.compat.v1 as tf
tf.disable_v2_behavior()
```

For Tensorflow 2.0 and later, try this.

```
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
a = tf.constant(5)
b = tf.constant(6)
c = tf.constant(7)
d = tf.multiply(a,b)
e = tf.add(c,d)
f = tf.subtract(a,c)
with tf.compat.v1.Session() as sess:
outs = sess.run(f)
print(outs)
```

It is not easy as you think, running TF 1.x with TF 2.x environment I found some errors and need to reviews of some variables usages when I fixed the problems on the neuron networks on the Internet. Transform to TF 2.x is better idea.

( Easier and adaptive )

### TF 2.X

```
while not done:
next_obs, reward, done, info = env.step(action)
env.render()
img = tf.keras.preprocessing.image.array_to_img(
img,
data_format=None,
scale=True
)
img_array = tf.keras.preprocessing.image.img_to_array(img)
predictions = model_self_1.predict(img_array) ### Prediction
### Training: history_highscores = model_highscores.fit(batched_features, epochs=1 ,validation_data=(dataset.shuffle(10))) # epochs=500 # , callbacks=[cp_callback, tb_callback]
```

### TF 1.X

```
with tf.compat.v1.Session() as sess:
saver = tf.compat.v1.train.Saver()
saver.restore(sess, tf.train.latest_checkpoint(savedir + '\invader_001'))
train_loss, _ = sess.run([loss, training_op], feed_dict={X:o_obs, y:y_batch, X_action:o_act})
for layer in mainQ_outputs:
model.add(layer)
model.add(tf.keras.layers.Flatten() )
model.add(tf.keras.layers.Dense(6, activation=tf.nn.softmax))
predictions = model.predict(obs) ### Prediction
### Training: summ = sess.run(summaries, feed_dict={X:o_obs, y:y_batch, X_action:o_act})
```