Random choices in TensorFlow affect layer initialization, shuffled input batches, and sampled data augmentation. Setting a seed near the start of the program keeps those choices on a repeatable pseudorandom path during debugging, smoke tests, and small comparison runs.
The direct seed entry point for mixed TensorFlow and Keras scripts is tf.keras.utils.set_random_seed(). It sets Python's random seed, NumPy's global random seed, and TensorFlow's global random seed with one integer, which matches training code that also uses tf.random, tf.data, and ordinary NumPy calls.
A seed does not make every TensorFlow operation deterministic by itself. Separate generators such as np.random.default_rng() still need their own seed, and identical outputs on the same hardware and TensorFlow stack may need deterministic TensorFlow operations in addition to a fixed seed.
$ python3 -c "import tensorflow as tf; print(tf.__version__)" 2.21.0
seed-demo.py
.
import random import numpy as np import tensorflow as tf SEED = 7 tf.keras.utils.set_random_seed(SEED) generator = np.random.default_rng(SEED) print("Python random:", random.randint(0, 999)) print("NumPy global:", int(np.random.randint(0, 1000))) print("NumPy Generator:", int(generator.integers(0, 1000))) print( "TensorFlow:", tf.random.uniform((3,), minval=0, maxval=10, dtype=tf.int32).numpy().tolist(), )
tf.keras.utils.set_random_seed() does not seed a newly created np.random.default_rng() object, so pass SEED when the program creates one.
$ python3 seed-demo.py Python random: 331 NumPy global: 175 NumPy Generator: 944 TensorFlow: [4, 5, 7]
$ python3 seed-demo.py Python random: 331 NumPy global: 175 NumPy Generator: 944 TensorFlow: [4, 5, 7]
Matching values mean Python, NumPy's global generator, the explicitly seeded NumPy generator, and TensorFlow all started from the same seed state again.
SEED = 7 tf.keras.utils.set_random_seed(SEED) train_dataset = train_dataset.shuffle( 1000, seed=SEED, reshuffle_each_iteration=False, ) model = build_model() model.fit(train_dataset, epochs=5)
Call the seed function before layer creation, dataset shuffling, augmentation, or training. Calling it later does not rewind random work that already happened.
$ rm seed-demo.py