FailedPreconditionError tensorflow

时间:2017-01-19 20:28:32

标签: tensorflow

为什么这个简单的代码会出错?

 inputs = tf.Variable(np.random.rand(2,2))

 tf.global_variables_initializer()     

 with tf.Session() as sess:
      sess.run(tf.reduce_mean(inputs))

它给了我:

FailedPreconditionError (see above for traceback): Attempting to use  uninitialized value Variable_4
 [[Node: Variable_4/read = Identity[T=DT_DOUBLE, _class=["loc:@Variable_4"], _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_4)]]

1 个答案:

答案 0 :(得分:4)

tf.global_variables_initializer()会返回您必须执行的操作。实际上,这个操作在初始化全局变量时。

因此,请改为:

init_op = tf.global_variables_initializer()

并在会话中执行它。

with tf.Session() as sess:
    sess.run(init_op)

此外,不要混合图形定义和图形执行在逻辑上更好。

在会话外定义图形,然后执行操作。这是代码的改进版本。

import tensorflow as tf
import numpy as np

inputs = tf.Variable(np.random.rand(2,2))
init_op =  tf.global_variables_initializer()     

mean_op = tf.reduce_mean(inputs)

with tf.Session() as sess:
    sess.run(init_op)
    mean_value = sess.run(mean_op)
    print(mean_value)

顺便说一句,我建议您阅读tensorflow入门页面:https://www.tensorflow.org/get_started/