pythontensorflowmachine-learningtensorrandom-seed

Tensorflow's random.truncated_normal returns different results with the same seed


The following lines are supposed to get the same result:

import tensorflow as tf
print(tf.random.truncated_normal(shape=[2],seed=1234))
print(tf.random.truncated_normal(shape=[2],seed=1234))

But I got:

tf.Tensor([-0.12297685 -0.76935077], shape=(2,), dtype=tf.float32)
tf.Tensor([0.37034193 1.3367208 ], shape=(2,), dtype=tf.float32)

Why?


Solution

  • This seems to be intentional, see the docs here. Specifically the "Examples" section.

    What you need is stateless_truncated_normal:

    print(tf.random.stateless_truncated_normal(shape=[2],seed=[1234, 1]))
    print(tf.random.stateless_truncated_normal(shape=[2],seed=[1234, 1]))
    

    Gives me

    tf.Tensor([1.0721238  0.10303579], shape=(2,), dtype=float32)
    tf.Tensor([1.0721238  0.10303579], shape=(2,), dtype=float32)
    

    Note: The seed needs to be two numbers here, I honestly don't know why (the docs don't say).