错误提示:FailedPreconditionError: 尝试在Tensorflow中使用未初始化的变量

75
我正在学习TensorFlow教程,其中使用一种“奇怪”的格式上传数据。我希望使用NumPy或pandas格式的数据,以便与scikit-learn的结果进行比较。
我从Kaggle获取数字识别数据:https://www.kaggle.com/c/digit-recognizer/data
以下是来自TensorFlow教程的代码(可以正常工作):
# Stuff from tensorflow tutorial 
import tensorflow as tf

sess = tf.InteractiveSession()

x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

cross_entropy = -tf.reduce_sum(y_ * tf.log(y))

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

在这里,我读取数据,剥离目标变量并将数据分成测试和训练数据集(所有这些都运行良好):

# Read dataframe from training data
csvfile='train.csv'
from pandas import DataFrame, read_csv
df = read_csv(csvfile)

# Strip off the target data and make it a separate dataframe.
Target = df.label
del df["label"]

# Split data into training and testing sets
msk = np.random.rand(len(df)) < 0.8
dfTest = df[~msk]
TargetTest = Target[~msk]
df = df[msk]
Target = Target[msk]

# One hot encode the target
OHTarget=pd.get_dummies(Target)
OHTargetTest=pd.get_dummies(TargetTest)

现在,当我试图运行训练步骤时,会出现FailedPreconditionError错误:
for i in range(100):
    batch = np.array(df[i*50:i*50+50].values)
    batch = np.multiply(batch, 1.0 / 255.0)
    Target_batch = np.array(OHTarget[i*50:i*50+50].values)
    Target_batch = np.multiply(Target_batch, 1.0 / 255.0)
    train_step.run(feed_dict={x: batch, y_: Target_batch})

这是完整的错误信息:

---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-82-967faab7d494> in <module>()
      4     Target_batch = np.array(OHTarget[i*50:i*50+50].values)
      5     Target_batch = np.multiply(Target_batch, 1.0 / 255.0)
----> 6     train_step.run(feed_dict={x: batch, y_: Target_batch})

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in run(self, feed_dict, session)
   1265         none, the default session will be used.
   1266     """
-> 1267     _run_using_default_session(self, feed_dict, self.graph, session)
   1268
   1269

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in _run_using_default_session(operation, feed_dict, graph, session)
   2761                        "the operation's graph is different from the session's "
   2762                        "graph.")
-> 2763   session.run(operation, feed_dict)
   2764
   2765

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict)
    343
    344     # Run request and get response.
--> 345     results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
    346
    347     # User may have fetched the same tensor multiple times, but we

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_run(self, target_list, fetch_list, feed_dict)
    417         # pylint: disable=protected-access
    418         raise errors._make_specific_exception(node_def, op, e.error_message,
--> 419                                               e.code)
    420         # pylint: enable=protected-access
    421       raise e_type, e_value, e_traceback

FailedPreconditionError: Attempting to use uninitialized value Variable_1
     [[Node: gradients/add_grad/Shape_1 = Shape[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_1)]]
Caused by op u'gradients/add_grad/Shape_1', defined at:
  File "/Users/user32/anaconda/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    ...........

...which was originally created as op u'add', defined at:
  File "/Users/user32/anaconda/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
[elided 17 identical lines from previous traceback]
  File "/Users/user32/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 3066, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-45-59183d86e462>", line 1, in <module>
    y = tf.nn.softmax(tf.matmul(x,W) + b)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/math_ops.py", line 403, in binary_op_wrapper
    return func(x, y, name=name)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/gen_math_ops.py", line 44, in add
    return _op_def_lib.apply_op("Add", x=x, y=y, name=name)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 633, in apply_op
    op_def=op_def)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1710, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 988, in __init__
    self._traceback = _extract_stack()

有什么想法可以解决这个问题吗?
11个回答

94

FailedPreconditionError是由于程序在尝试读取一个变量(名为"Variable_1")在初始化之前引起的。在TensorFlow中,所有变量都必须通过运行它们的“initializer”操作进行明确初始化。为方便起见,在训练循环之前执行以下语句可以运行当前会话中的所有变量初始化器:

tf.initialize_all_variables().run()

请注意,本答案假设您在问题中使用的是tf.InteractiveSession,这允许您运行操作而不必指定会话。对于非交互式用途,更常见的是使用tf.Session,并进行如下初始化:

init_op = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init_op)

16
请使用tf.global_variables_initializer,因为tf.initialize_all_variables()将被弃用。 - Beginner

64

tf.initialize_all_variables()已被弃用。请改为使用以下方式初始化tensorflow变量:

tf.global_variables_initializer()

一个常见的使用示例是:

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

sess.run(tf.global_variables_initializer()) 和 tf.global_variables_initializer() 有什么区别?通常你会看到后者。 - dv3
2
@dv3 像 TensorFlow 中的所有其他内容一样,创建操作和运行操作之间存在区别。我认为这就是为什么“initialize_all_variables”被替换为“global_variables_initializer”的原因:名称“initialize_all_variables”听起来像它会执行初始化,但实际上它只是创建了操作。 - mdaoust
请注意,该方法现在是tf.initialize_all_variables()。 - jesses.co.tt
1
@jesses.co.tt - 答案是正确的;tf.initialize_all_variables() 已经被弃用了。请参见:https://www.tensorflow.org/api_docs/python/tf/initialize_all_variables - ruhong
@user3144836的答案完美地解决了问题。在我的情况下,我将整个代码块封装在with例程下面,这样就清除了所有错误。谢谢。 - God Bennett

16

从官方文档中,FailedPreconditionError

该异常通常在运行读取未初始化的tf.Variable操作时抛出。

在您的情况下,错误甚至说明了哪个变量未初始化:Attempting to use uninitialized value Variable_1。TF教程之一详细解释了关于变量的很多内容,包括它们的创建/初始化/保存/加载

基本上,要初始化变量,您有三个选项:

我几乎总是使用第一种方法。记得将它放在会话里运行。所以你会得到像这样的结果:

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

如果您想获取更多关于变量的信息,请阅读此文档,了解如何report_uninitialized_variables和检查is_variable_initialized


4

在使用变量之前,您必须对其进行初始化。

如果在初始化变量之前尝试评估它们,则会遇到以下问题:FailedPreconditionError: Attempting to use uninitialized value tensor.

最简单的方法是使用tf.global_variables_initializer()一次性初始化所有变量。

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)

您可以使用sess.run(init)运行初始化程序,而不获取任何值。

如果只想初始化变量的子集,则可以使用tf.variables_initializer()列出这些变量:

var_ab = tf.variables_initializer([a, b], name="a_and_b")
with tf.Session() as sess:
    sess.run(var_ab)

您也可以使用tf.Variable.initializer单独初始化每个变量。

# create variable W as 784 x 10 tensor, filled with zeros
W = tf.Variable(tf.zeros([784,10])) with tf.Session() as sess:
    sess.run(W.initializer)

3

我从一个完全不同的案例中得到了这个错误信息。似乎是tensorflow中的异常处理程序引起的。您可以检查Traceback中的每一行。在我的情况下,它发生在tensorflow/python/lib/io/file_io.py中,因为该文件包含一个不同的bug,其中self.__modeself.__name没有初始化,并且需要调用self._FileIO__modeself_FileIO__name


3

如果您使用的是TensorFlow版本> 3.2,您可以使用以下命令:

x1 = tf.Variable(5)
y1 = tf.Variable(3)

z1 = x1 + y1

init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    init.run()
    print(sess.run(z1))

输出:8 将被显示。

3
FailedPreconditionError 是由于会话尝试读取未初始化的变量而导致的。
Tensorflow 1.11.0 版本开始,您需要执行以下操作:
init_op = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init_op)

3

虽然用途不同,但是将您的会话设置为默认会话对我有用:

with sess.as_default():
    result = compute_fn([seed_input,1])

这是一个很明显的错误,一旦你解决了它,就会变得非常显而易见。

我的用例如下:
1)将keras VGG16存储为tensorflow图形
2)作为图形加载kers VGG16
3)在图形上运行tf函数并获得:

FailedPreconditionError: Attempting to use uninitialized value block1_conv2/bias
     [[Node: block1_conv2/bias/read = Identity[T=DT_FLOAT, _class=["loc:@block1_conv2/bias"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](block1_conv2/bias)]]
     [[Node: predictions/Softmax/_7 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_168_predictions/Softmax", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

3

TensorFlow 2.0 兼容的解决方案: 在 TensorFlow 版本 >= 2.0 中,如果我们使用 Graph Mode,初始化所有变量的命令来修复 FailedPreconditionError 如下所示:

tf.compat.v1.global_variables_initializer

这只是 variables_initializer(global_variables()) 的快捷方式。

它返回一个操作(Op),用于初始化图中的全局变量。


即使在2.3中使用tf.data进行初始化后,我仍然看到这个错误。https://stackoverflow.com/questions/64094061/failedpreconditionerror-getnext-failed-because-the-iterator-has-not-been-init - Nitin

2

当我使用tf.train.string_input_producer()tf.train.batch()时遇到问题,初始化本地变量之前启动Coordinator可以解决该问题。当我在启动Coordinator后初始化本地变量时,会出现错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接