Tensorflow:初始化因变量

时间:2018-08-16 17:54:05

标签: variables tensorflow initialization

我正在尝试根据其他变量的值初始化一些变量。这是一个最小的脚本:

redux-devtools-extension

这将引发以下异常:

a = tf.Variable(1, name='a')
b = a + 2
c = tf.Variable(b, name='c')
d = c + 3
e = tf.Variable(d, name='e')
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run([a, c, e]))

但是如果我删除变量e,它将正常工作:

FailedPreconditionError (see above for traceback): Attempting to use 
uninitialized value a.

我试图通过在声明e之前使用a = tf.Variable(1, name='a') b = a + 2 c = tf.Variable(b, name='c') d = c + 3 #e = tf.Variable(d, name='e') with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run([a, c])) # [1, 3] 来解决此问题,但是它不起作用。

1 个答案:

答案 0 :(得分:0)

如果意图是照原样执行代码,则可以这样做。

with tf.Session() as sess:
    a = tf.Variable(1, name='a')
    a.initializer.run()
    b = a + 2
    c = tf.Variable(b, name='c')
    d = c + 3
    e = tf.Variable(d, name='e')
    sess.run(tf.global_variables_initializer())
    print(sess.run([a, c, e]))

对此的进一步研究是here