AttributeError: module ‘tensorflow’ has no attribute ‘global_variables_initializer’ error occurs when you try to “access tf.global_variables_initializer() directly from the tensorflow module rather than from the tf.compat.v1 module.”
Diagram
How to fix the error
Here are the ways to fix the AttributeError: module ‘tensorflow’ has no attribute ‘global_variables_initializer’ error:
- Using TensorFlow 1.x Compatibility Mode
- Updating your code for TensorFlow 2.x
- Explicitly Enable TensorFlow 1.x Behavior in TensorFlow 2.x
- Switching to TensorFlow 1.x
Solution 1: Using TensorFlow 1.x Compatibility Mode
In TensorFlow 2.x, you can use tf.compat.v1 to access functions available in TensorFlow 1.x but not directly available in TensorFlow 2.x.
You should use like this:
import tensorflow as tf
init = tf.compat.v1.global_variables_initializer()
Solution 2: Updating Your Code for TensorFlow 2.x
If you’re using TensorFlow 2.x, the idiomatic way to initialize variables is to not initialize them manually at all. In TensorFlow 2.x, variables are initialized automatically the first time they are used.
Solution 3: Explicitly Enable TensorFlow 1.x Behavior in TensorFlow 2.x
If you have existing code written for TensorFlow 1.x, and you don’t want to update the code, you can enable TensorFlow 1.x behavior globally within TensorFlow 2.x by using tf.compat.v1.disable_eager_execution().
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
init = tf.compat.v1.global_variables_initializer()
This makes TensorFlow 2.x behave more like 1.x, but it’s generally not recommended unless you have a good reason to stick with the 1.x behavior.
Solution 4: Switch to TensorFlow 1.x
If the rest of your codebase is dependent on TensorFlow 1.x, you may consider using TensorFlow 1.x instead of 2.x. However, note that TensorFlow 1.x is not actively developed, and it’s generally recommended to use TensorFlow 2.x for new projects.
That’s it!
Related posts
AttributeError: module ‘tensorflow’ has no attribute ‘logging’
AttributeError: module ‘tensorflow’ has no attribute ‘feature_column’
AttributeError: module ‘tensorflow._api.v2.train’ has no attribute ‘GradientDescentOptimizer’
AttributeError: module ‘tensorflow’ has no attribute ‘log’
AttributeError: module ‘tensorflow’ has no attribute ‘Session’
AttributeError: module ‘tensorflow’ has no attribute ‘GPUOptions’
AttributeError: module ‘tensorflow’ has no attribute ‘gfile’

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.