Random initialization can make otherwise identical Keras runs start from different weights, which obscures whether a code change affected the result. keras.utils.set_random_seed() resets Keras plus Python, NumPy, and backend random generators from one integer.
Place the seed call before creating models, random layers, shuffled datasets, or random tensors. Reusing the seed at the same point reproduces the same pseudorandom sequence, while consuming extra random values changes later results.
A seed controls pseudorandom state but does not make every accelerator, distributed, or custom operation deterministic. Compare runs on the same software and hardware when exact reproduction matters, and enable backend-specific operation determinism only when the runtime supports it.
Steps to set a random seed in Keras:
- Create seed_demo.py with the JAX backend selection and imports.
- seed_demo.py
import os os.environ["KERAS_BACKEND"] = "jax" import keras import numpy as np
- Append the seeded Dense layer builder to seed_demo.py.
- seed_demo.py
def build_kernel(seed): keras.utils.set_random_seed(seed) model = keras.Sequential( [ keras.Input(shape=(3,)), keras.layers.Dense(4, activation="relu"), ] ) return keras.ops.convert_to_numpy(model.weights[0])
- Append comparisons for repeated and changed seed values.
- seed_demo.py
first = build_kernel(123) repeat = build_kernel(123) changed = build_kernel(124) print(f"backend: {keras.backend.backend()}") print(f"same seed matches: {np.array_equal(first, repeat)}") print(f"different seed changes weights: {not np.array_equal(first, changed)}") print(f"first weight with seed 123: {first[0, 0]:.6f}") print(f"first weight with seed 124: {changed[0, 0]:.6f}")
- Verify the same-seed and changed-seed weight behavior with seed_demo.py.
$ python seed_demo.py backend: jax same seed matches: True different seed changes weights: True first weight with seed 123: 0.889069 first weight with seed 124: -0.449857
Both True checks are required: the repeated seed must reproduce the kernel, and the changed seed must alter it.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.