Python
TensorFlow
ImportError
set_random_seed
Debugging

ImportError cannot import name 'set_random_seed' from 'tensorflow' CUserspolonAnaconda3libsite-packagestensorflow__init__.py

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

When developing machine learning models with TensorFlow, you will inevitably run into import errors as the library evolves across major versions. One particularly confusing error is ImportError: cannot import name 'set_random_seed' from 'tensorflow'. This happens because tf.set_random_seed was removed in TensorFlow 2.x and replaced with a new API location, so code written for TensorFlow 1.x breaks when run against a newer installation.

Why This Error Occurs

In TensorFlow 1.x, you could set a global random seed for reproducibility like this:

python
import tensorflow as tf

tf.set_random_seed(42)

When TensorFlow 2.0 arrived, the team reorganized the entire API surface. Many top-level functions were moved into submodules, renamed, or removed entirely. The function tf.set_random_seed was replaced by tf.random.set_seed. If you attempt the old import on a TensorFlow 2.x installation, Python raises an ImportError because the name simply does not exist at tensorflow.__init__ anymore.

The Fix: Use the Updated API

The correct way to set a global random seed in TensorFlow 2.x is:

python
import tensorflow as tf

tf.random.set_seed(42)

This single change resolves the import error. The function behaves the same way as the old one: it seeds TensorFlow's internal random number generators so that operations like weight initialization, dropout, and data shuffling produce reproducible results.

Handling Code That Must Support Both Versions

If you maintain a library or codebase that needs to run on both TensorFlow 1.x and 2.x, you can write a compatibility wrapper:

python
1import tensorflow as tf
2
3def set_global_seed(seed):
4    """Set TensorFlow global random seed across versions."""
5    if hasattr(tf.random, 'set_seed'):
6        # TensorFlow 2.x
7        tf.random.set_seed(seed)
8    elif hasattr(tf, 'set_random_seed'):
9        # TensorFlow 1.x
10        tf.set_random_seed(seed)
11    else:
12        raise RuntimeError("Unsupported TensorFlow version")
13
14set_global_seed(42)

This approach uses hasattr to detect which API is available at runtime, avoiding the ImportError entirely.

Full Reproducibility Requires More Than One Seed

Setting the TensorFlow seed alone does not guarantee fully reproducible results. Python's built-in random module and NumPy also use their own random states. For true reproducibility, seed all three:

python
1import os
2import random
3import numpy as np
4import tensorflow as tf
5
6SEED = 42
7
8os.environ['PYTHONHASHSEED'] = str(SEED)
9random.seed(SEED)
10np.random.seed(SEED)
11tf.random.set_seed(SEED)

Setting PYTHONHASHSEED ensures that Python's hash-based operations (like dictionary ordering in older Python versions) are also deterministic. This is especially important when your data pipeline includes shuffling or hashing steps.

Other Commonly Moved Functions in TensorFlow 2.x

The set_random_seed rename is not an isolated case. Here are several other functions that moved between versions:

python
1# TensorFlow 1.x → TensorFlow 2.x
2# tf.Session()         → tf.compat.v1.Session()  (eager mode is default in 2.x)
3# tf.placeholder()     → removed (use tf.function inputs)
4# tf.global_variables_initializer() → tf.compat.v1.global_variables_initializer()
5# tf.train.AdamOptimizer → tf.keras.optimizers.Adam

If you are migrating a large TensorFlow 1.x codebase, the official migration script can automate many of these renames:

bash
tf_upgrade_v2 --infile old_script.py --outfile new_script.py

This command-line tool scans your code and rewrites the deprecated API calls to their TensorFlow 2.x equivalents.

Common Pitfalls

  • Copying old tutorials verbatim. Many TensorFlow 1.x tutorials still rank highly in search results. Always check the TensorFlow version the tutorial targets before copying import statements.
  • Using tf.compat.v1 as a permanent fix. While tf.compat.v1.set_random_seed works in TensorFlow 2.x, relying on the compatibility module indefinitely means you miss performance improvements and new features in the native 2.x API.
  • Forgetting to seed NumPy and Python's random module. TensorFlow operations may call into NumPy internally, so seeding only TensorFlow does not guarantee reproducibility across your entire pipeline.
  • Assuming GPU results will be deterministic. Even with all seeds set, GPU floating-point operations can produce non-deterministic results due to parallel reduction ordering. Set TF_DETERMINISTIC_OPS=1 if you need strict determinism.
  • Installing mismatched TensorFlow and Keras versions. In TensorFlow 2.x, Keras is bundled as tf.keras. Installing a standalone keras package alongside TensorFlow can cause conflicting imports and confusing errors.

Summary

  • The ImportError for set_random_seed occurs because TensorFlow 2.x moved this function to tf.random.set_seed.
  • Replace tf.set_random_seed(seed) with tf.random.set_seed(seed) to fix the error immediately.
  • For cross-version compatibility, use hasattr checks to call the correct function at runtime.
  • Full reproducibility requires seeding Python, NumPy, and TensorFlow together, and optionally enabling deterministic GPU operations.
  • Use the tf_upgrade_v2 migration tool to automatically update deprecated API calls across an entire codebase.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the 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