Repeatable Keras experiments need the same random state before model initialization, data shuffling, augmentation, and backend operations run. keras.utils.set_random_seed() sets Python, NumPy, and backend framework seeds from one call.
Call the seed utility before creating layers, initializers, datasets, or random tensors. Reusing the same seed at the start of the same code path should reproduce initial weights and predictions for deterministic operations.
Random seeds do not guarantee full hardware determinism in every distributed, accelerator, or cuDNN-backed path. Treat this as the starting point for repeatability, then add backend-specific determinism settings only when the target runtime needs them and supports them.
$ python -m pip install --upgrade keras jax
import os os.environ["KERAS_BACKEND"] = "jax" import keras import numpy as np def seeded_prediction(seed): keras.utils.set_random_seed(seed) model = keras.Sequential( [ keras.Input(shape=(3,)), keras.layers.Dense(5, activation="relu"), keras.layers.Dense(1, activation="sigmoid"), ] ) sample = np.array([[0.25, 0.50, 0.75]], dtype="float32") return model.predict(sample, verbose=0), model.get_weights()[0].copy() prediction_a, kernel_a = seeded_prediction(123) prediction_b, kernel_b = seeded_prediction(123) prediction_c, kernel_c = seeded_prediction(124) print(f"backend: {keras.backend.backend()}") print("seed used for first two runs: 123") print(f"matching initial kernel: {np.allclose(kernel_a, kernel_b)}") print(f"matching prediction: {np.allclose(prediction_a, prediction_b)}") print(f"different seed changes kernel: {not np.allclose(kernel_a, kernel_c)}") print(f"prediction with seed 123: {prediction_a[0, 0]:.6f}") print(f"prediction with seed 124: {prediction_c[0, 0]:.6f}")
The proof compares both initial weights and a prediction result because layer initializers are the common source of surprising non-repeatability.
$ python set_random_seed.py backend: jax seed used for first two runs: 123 matching initial kernel: True matching prediction: True different seed changes kernel: True prediction with seed 123: 0.683945 prediction with seed 124: 0.357631
matching initial kernel: True and matching prediction: True prove that the same seeded code path reproduced the initializer and prediction result.
import keras keras.utils.set_random_seed(123)
Set the seed before creating models, loading randomized datasets, or constructing augmentation layers.