Tensorflow reported an error when using session module: attributeerror: module ‘tensorflow’ has no attribute ‘session’, which has been solved

Geeks, please accept the hero post of 2021 Microsoft x Intel hacking contest>>>

After installing tensorflow 2.0, when using session, an error is reported: module ‘tensorflow’ has no attribute ‘session’:

Source code:

import tensorflow as tf
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
a=tf.constant(2)
b=tf.constant(3)
with tf.Session() as sess:
    print("a:%i" % sess.run(a),"b:%i" % sess.run(b))
    print("Additionwithconstants:%i" % sess.run(a+b))
    print("Multiplicationwithconstant:%i" % sess.run(a*b))

Error message:

The error means that the tensorflow module does not have the session attribute. Later, we found that there is no session attribute in tensorflow 2.0. If you are installing tensorflow 2.0 and want to use the session attribute, you can change TF. Session() to:

tf.compat.v1.Session()

This method can solve this kind of problem, not only for session attribute

When running again, the program reported another error:

The reason is that version 2.0 is not compatible with version 1.0

tf.compat.v1.disable_eager_execution()

It’s going to work

The official website of tensorflow_ eager_ The execution () method is interpreted as follows:

This function can only be called before any Graphs, Ops, or Tensors have been created. 
It can be used at the beginning of the program for complex migration projects from TensorFlow 1.x to 2.x.

translation: this function can only be called before creating any graph, operation or tensor. It can be used at the beginning of a complex migration project from tensorflow 1. X to 2. X

Similar Posts: