运行 会话多次 tf.random returns 不同的 conv2d 值

Running session multiple times with tf.random returns different values for conv2d

import tensorflow as tf 
import numpy as np 

x_tf = tf.placeholder('float',[None, 2, 5, 1])
x_np = np.random.noraml(0,1,[1,2,5,1])

# ======== filter option1 and option2 ===========
f_np = np.random.normal(0,1,[1,3,1,1])
f_tf = tf.constant(f_np,'float') # option 1
f_tf = tf.random_normal([1,3,1,1]) # option 2
# ===============================================

x_conv = tf.nn.conv2d(x_tf,f_tf,[1,1,1,1],'SAME')

with tf.Session() as sess:
     tf.global_variables_initializer().run()
     x_conv_np  = sess.run(x_conv, feed_dict={x_tf: x_np})
     x_conv_np2 = sess.run(x_conv, feed_dict={x_tf: x_np})

如果我 运行 上面的代码带有选项 1,我得到 x_conv_npx_conv_np2 相同的值 但是,当我 运行 上面的选项 2 时,我得到 x_conv_npx_conv_np2 的不同值。

我猜 tf.random_normal 每次会话 运行 时都会被初始化。 这是注定要发生的吗? 即使我执行 tf.set_random_seed 也会发生这种情况 有人可以解释 TensorFlow 如何在会话为 运行 时初始化其 运行dom 变量吗?

所有 random number ops in TensorFlow (including tf.random_normal()) 每次运行时都会采样一​​个新的随机张量:

TensorFlow has several ops that create random tensors with different distributions. The random ops are stateful, and create new random values each time they are evaluated.

如果你想对分布进行一次采样,然后 re-use 结果,你应该使用 tf.Variable 并通过 运行 tf.random_normal() 初始化一次。例如,下面的代码将打印相同的随机值两次:

f_tf = tf.Variable(tf.random_normal([1, 3, 1, 1]))
# ...
init_op = tf.global_variables_initializer()
# ...
with tf.Session() as sess:
  sess.run(init_op)
  print(sess.run(f_tf))
  print(sess.run(f_tf))