我想制作一个可重用的RANDOM TENSOR x并将SAME张量分配给VARIABLE y。这意味着在Session.run()期间它们应该具有相同的值。 但事实并非如此。那么,为什么y不等于x? 请帮助分析并确认下面的示例代码段。谢谢。
更新: 连续多次应用sess.run(x)和sess.run(y)之后,确认x每次都变化,而y保持稳定。为什么?
import tensorflow as tf
x = tf.random_normal([3], seed = 1)
y = tf.Variable(initial_value = x) # expect y get the same random tensor as x
diff = tf.subtract(x, y)
avg = tf.reduce_mean(diff)
sess = tf.InteractiveSession()
sess.run(y.initializer)
print('x0:', sess.run(x))
print('y0:', sess.run(y))
print('x1:', sess.run(x))
print('y1:', sess.run(y))
print('x2:', sess.run(x))
print('y2:', sess.run(y))
print('diff:', sess.run(diff))
print('avg:', sess.run(avg)) # expected as 0.0
sess.close()
输出:TENSOR x更改每个sess.run(x)
x0: [ 0.55171245 -0.13107552 -0.04481386]
y0: [-0.8113182 1.4845988 0.06532937]
x1: [-0.67590594 0.28665832 0.3215887 ]
y1: [-0.8113182 1.4845988 0.06532937]
x2: [1.2409041 0.44875884 0.33140722]
y2: [-0.8113182 1.4845988 0.06532937]
diff: [ 1.2404865 -1.4525002 0.05412297]
avg: -0.04116
答案 0 :(得分:1)
真正的原因是: x = tf.random_normal(种子=初始种子) 每次应用sess.run()都会不断发展,但是如果再次重启,则会产生相同的序列。每次运行代码时,我们将得到相同的张量x0-x1-x2 ... Here给出了有关随机种子的一些解释。
要保证第一次运行后具有相同的x,我们需要将其重新初始化。不确定我的情况是否有体面的方法。但是我们可以将x设置为变量,并使用固定种子进行初始化。 tf.get_variable或tf.Variable都可以。我发现this answer符合我的问题。
这是我的最终代码。可以。
import tensorflow as tf
initializer = tf.random_normal_initializer(seed = 1)
x = tf.get_variable(name = 'x', shape = [3], dtype = tf.float32, initializer = initializer)
y = tf.Variable(initial_value = x)
diff = tf.subtract(x, y)
avg = tf.reduce_mean(diff)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
print('x0:', sess.run(x))
print('y0:', sess.run(y))
print('x1:', sess.run(x))
print('y1:', sess.run(y))
print('x2:', sess.run(x))
print('y2:', sess.run(y))
print('diff:', sess.run(diff))
print('avg:', sess.run(avg))
sess.close()
x0: [-0.8113182 1.4845988 0.06532937]
y0: [-0.8113182 1.4845988 0.06532937]
x1: [-0.8113182 1.4845988 0.06532937]
y1: [-0.8113182 1.4845988 0.06532937]
x2: [-0.8113182 1.4845988 0.06532937]
y2: [-0.8113182 1.4845988 0.06532937]
diff: [0. 0. 0.]
avg: 0.0