244

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:

  1. pip install --upgrade pip
  2. pip install tensorflow==2.0.0-alpha0
  3. pip install keras
  4. pip install numpy==1.16.2

Execution:

  1. Execute command: import tensorflow as tf
  2. Execute command: sess = tf.Session()
4
  • Weird. I think it is not due to the TF version, but the complete TF installation is broken. See github.com/tensorflow/tensorflow/issues/… Commented Mar 13, 2019 at 13:33
  • 6
    TensorFlow 2.0 works around functions, not sessions. I think the initial idea was to keep tf.Session at least initially, but looking at the docs it seems it has finally have been scraped completely. Commented Mar 13, 2019 at 13:35
  • 6
    Oh it seems you can still access it through tf.compat.v1.Session. Commented Mar 13, 2019 at 13:37
  • @DmytroPrylipko I tried it before creating this question. It did not work for me. Commented Mar 14, 2019 at 7:24

17 Answers 17

404

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

Sign up to request clarification or add additional context in comments.

6 Comments

Using import tensorflow.compat.v1 as tf tf.disable_v2_behavior() gives me an error AttributeError: module 'tensorflow_core.compat.v1' has no attribute 'contrib'
Found this in TF 2.0 migration documentation It is still possible to run 1.X code, unmodified (except for contrib), in TensorFlow 2.0
Which TF version are you using when you get the tensorflow_core has no attribute error?
I have downloaded a few notebooks and I was facing these issues having imported statements at the top as mentioned in the answer helped me get rid of the irritating error.
How do I evaluate static .pb graph in TF2 then? Only through using tf1-feature like tf.compat.v1.Session(). In TF2 you're supposed to use eager mode always and no .pb?
|
117

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

1 Comment

Is there non-eager mode in TF2? Or eager mode is only suggested mode of execution? What if I want to have static .pb file in TF2? Is it possible? How do I evaluate it then in TF2?
41

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

1 Comment

I would rather say that in TF 2.0 Session() has been moved not removed. The need of using Session() has been removed.
7

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

Comments

4

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)

1 Comment

After 1.15.x there should be no other 1.x version of TF, unless some patches will come, but no improvements.
4

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

Comments

4

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) 

Comments

4

To work with TensorFlow 2.x, you should use tf.compat.v1.Session instead of tf.Session.

Comments

2
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() 

Comments

2

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

Comments

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

Comments

1

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

Comments

0

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 

Comments

0

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.

1 Comment

Does TF2 support non-eager mode at all? Or non-eager is just tf1 feature? How do I evaluate .pb graphs in tf2 then?
0

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

Comments

0

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,

Effective TensorFlow 2 Page Link

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.