TensorFlow
Python
Error Troubleshooting
Machine Learning
Coding Debugging

TensorFlow 'module' object has no attribute 'global_variables_initializer'

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

The error AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer' occurs when running TensorFlow 1.x code on TensorFlow 2.x. In TF 2.x, eager execution is the default, so sessions, placeholders, and explicit variable initialization are no longer needed. The fix depends on your situation: for quick migration, use tf.compat.v1.global_variables_initializer() with tf.compat.v1.Session(). For a proper upgrade, rewrite the code using TF 2.x patterns (eager execution, tf.function, Keras layers) which eliminate the need for global_variables_initializer entirely.

Why the Error Occurs

TensorFlow 1.x used a "define-then-run" model where you built a computation graph first and executed it inside a Session:

python
1# TensorFlow 1.x code
2import tensorflow as tf
3
4# Define graph
5x = tf.placeholder(tf.float32, shape=[None, 784])
6W = tf.Variable(tf.zeros([784, 10]))
7b = tf.Variable(tf.zeros([10]))
8y = tf.matmul(x, W) + b
9
10# Initialize variables
11init = tf.global_variables_initializer()
12
13# Run in session
14with tf.Session() as sess:
15    sess.run(init)
16    result = sess.run(y, feed_dict={x: data})

TensorFlow 2.x removed these functions from the top-level tf namespace. tf.global_variables_initializer, tf.Session, tf.placeholder, and tf.reset_default_graph no longer exist at tf.*.

Fix 1: Use tf.compat.v1 (Quick Migration)

The tf.compat.v1 module provides all TF 1.x APIs:

python
1import tensorflow as tf
2
3# Disable TF2 behavior to use TF1-style sessions
4tf.compat.v1.disable_v2_behavior()
5
6x = tf.compat.v1.placeholder(tf.float32, shape=[None, 784])
7W = tf.Variable(tf.zeros([784, 10]))
8b = tf.Variable(tf.zeros([10]))
9y = tf.matmul(x, W) + b
10
11init = tf.compat.v1.global_variables_initializer()
12
13with tf.compat.v1.Session() as sess:
14    sess.run(init)
15    result = sess.run(y, feed_dict={x: data})

Without disable_v2_behavior

You can use tf.compat.v1 selectively without disabling all TF2 features:

python
1import tensorflow as tf
2
3# Create a TF1-style graph context
4with tf.compat.v1.Graph().as_default():
5    x = tf.compat.v1.placeholder(tf.float32, shape=[None, 10])
6    W = tf.Variable(tf.random.normal([10, 5]))
7    y = tf.matmul(x, W)
8
9    init = tf.compat.v1.global_variables_initializer()
10
11    with tf.compat.v1.Session() as sess:
12        sess.run(init)
13        result = sess.run(y, feed_dict={x: np.random.randn(3, 10)})
14        print(result.shape)  # (3, 5)

TF 2.x uses eager execution — operations run immediately, no session or initializer needed:

python
1import tensorflow as tf
2import numpy as np
3
4# Variables are initialized immediately
5W = tf.Variable(tf.zeros([784, 10]))
6b = tf.Variable(tf.zeros([10]))
7
8# Operations execute eagerly
9x = tf.constant(np.random.randn(1, 784).astype(np.float32))
10y = tf.matmul(x, W) + b
11print(y.numpy())  # Works immediately, no session needed
python
1import tensorflow as tf
2
3# Define model with Keras
4model = tf.keras.Sequential([
5    tf.keras.layers.Dense(128, activation='relu', input_shape=(784,)),
6    tf.keras.layers.Dropout(0.2),
7    tf.keras.layers.Dense(10, activation='softmax')
8])
9
10model.compile(optimizer='adam',
11              loss='sparse_categorical_crossentropy',
12              metrics=['accuracy'])
13
14# Variables are initialized automatically
15model.fit(x_train, y_train, epochs=5)
16predictions = model.predict(x_test)

TF 2.x with tf.function (Graph Performance)

python
1import tensorflow as tf
2
3W = tf.Variable(tf.random.normal([10, 5]))
4b = tf.Variable(tf.zeros([5]))
5
6@tf.function  # Compiles to graph for performance
7def forward(x):
8    return tf.matmul(x, W) + b
9
10x = tf.constant([[1.0] * 10])
11result = forward(x)
12print(result)  # No session needed

Common TF 1.x to 2.x Replacements

TF 1.xTF 2.x
tf.Session()Eager execution (no session needed)
tf.global_variables_initializer()Variables auto-initialize
tf.placeholder()Use tf.function arguments or tf.keras.Input
tf.reset_default_graph()Not needed (no global graph)
sess.run(tensor)tensor.numpy()
sess.run(op, feed_dict={...})Call the function directly
tf.contrib.*Moved to tf.keras, tf-addons, or removed
tf.train.AdamOptimizertf.keras.optimizers.Adam
tf.layers.densetf.keras.layers.Dense

Automated Migration Script

TensorFlow provides an automated conversion tool:

bash
1# Convert a single file
2tf_upgrade_v2 --infile old_code.py --outfile new_code.py
3
4# Convert an entire directory
5tf_upgrade_v2 --intree ./old_project/ --outtree ./new_project/
6
7# Preview changes without writing
8tf_upgrade_v2 --infile old_code.py --outfile /dev/null --reportfile report.txt

The tool replaces tf.Session with tf.compat.v1.Session, tf.placeholder with tf.compat.v1.placeholder, and so on. It produces working code but does not rewrite the logic for idiomatic TF 2.x — manual refactoring is still needed for a clean migration.

Common Pitfalls

  • Using tf.compat.v1 as a permanent solution: While tf.compat.v1 works, it disables many TF 2.x optimizations like eager execution and tf.function tracing. It is meant as a migration bridge, not a long-term approach. Plan to refactor to native TF 2.x patterns.
  • Mixing TF 1.x and TF 2.x patterns: Calling tf.compat.v1.disable_v2_behavior() affects the entire process. You cannot use eager TF 2.x code alongside Session-based code in the same script without careful scoping using tf.compat.v1.Graph().as_default().
  • Forgetting that Keras handles initialization automatically: If you use tf.keras.layers.Dense(...), variables are created and initialized when the layer is first called. Explicitly calling any initializer is unnecessary and may cause confusion.
  • Running tf_upgrade_v2 and assuming the code is fully migrated: The upgrade script adds tf.compat.v1 prefixes mechanically. The resulting code works but still uses the outdated session-based pattern. True migration means rewriting to use eager execution, Keras, and tf.function.
  • Installing TensorFlow 1.x to avoid the error: Pinning tensorflow==1.15 works short-term but prevents access to new features, performance improvements, and security patches. TF 1.x is no longer supported or receiving updates.

Summary

  • The error occurs because tf.global_variables_initializer was removed from the top-level tf namespace in TensorFlow 2.x
  • Quick fix: use tf.compat.v1.global_variables_initializer() with tf.compat.v1.Session()
  • Proper fix: rewrite using TF 2.x eager execution where variables auto-initialize and sessions are not needed
  • Use tf.keras for model building — it handles variable creation and initialization automatically
  • Run tf_upgrade_v2 for automated conversion, then manually refactor for idiomatic TF 2.x code

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.