1

I encountered a problem that tf.set_random_seed is unable to generate a repeatable value when programming using Tensorflow on python. To be specific,

import tensorflow as tf
sd = 1
tf.set_random_seed(seed = sd)

tf.reset_default_graph()
sess = tf.InteractiveSession()
print(sess.run(tf.random_normal(shape=[1], mean=0, stddev=1)))

the code above outputs [1.3086201]. Then I ran the whole piece of code again, it doesn't outputs the expected value [1.3086201] but gives a new [-2.1209881].

Why would this happen and how to set a Tensorflow seed?

cs95
  • 274,032
  • 76
  • 480
  • 537
guorui
  • 698
  • 1
  • 6
  • 18
  • Possible duplicate of [Reproducible results in Tensorflow with tf.set\_random\_seed](https://stackoverflow.com/questions/51249811/reproducible-results-in-tensorflow-with-tf-set-random-seed) – STJ Sep 27 '19 at 22:22

1 Answers1

2

According to the docs, there are two types of seeds you can set when defining graph operations:

  1. The graph-level seed, which is set by tf.set_random_seed, and
  2. operation-level seeds which are placed in a variable initializer

Tensorflow then uses an elaborate set of rules (see the docs) to generate unique values for operations that rely on a seed. You can reproduce random output with a graph-level seed once you've initialized the variable, but subsequent re-initializations of that variable will usually yield different values.

In your code, you are re-initializing tf.random_normal each time you run your code, so it is different.


If you want tf.random_normal to generate the same unique sequence, no matter how many times it is re-initialized, you should set the operation-level seed instead,

sess = tf.InteractiveSession()

print(sess.run(tf.random_normal(shape=[1], mean=0, stddev=1, seed=1))) 
# -0.8113182
print(sess.run(tf.random_normal(shape=[1], mean=0, stddev=1, seed=1)))
# -0.8113182
cs95
  • 274,032
  • 76
  • 480
  • 537