FailedPreconditionError:尝试在Tensorflow中使用未初始化

时间:2015-11-30 14:41:20

标签: python pandas classification tensorflow

我正在使用TensorFlow tutorial,它使用的是一个很奇怪的"格式以上传数据。我想对数据使用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 个答案:

答案 0 :(得分:73)

FailedPreconditionError出现是因为程序在初始化之前尝试读取变量(名为"Variable_1")。在TensorFlow中,必须通过运行&#34;初始化程序&#34;来显式初始化所有变量。操作。为方便起见,您可以通过在训练循环之前执行以下语句来运行当前会话中的所有变量初始值设定项:

tf.initialize_all_variables().run()

请注意,此答案假设您正在使用tf.InteractiveSession,这使您可以在不指定会话的情况下运行操作。对于非交互式用途,更常见的是使用tf.Session,并按如下方式初始化:

init_op = tf.initialize_all_variables()

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

答案 1 :(得分:46)

tf.initialize_all_variables()已弃用。而是使用以下内容初始化tensorflow变量:

tf.global_variables_initializer()

常见的用法是:

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

答案 2 :(得分:13)

从官方文档FailedPreconditionError

  

运行操作时最常引发此异常   在初始化之前读取一个tf.Variable。

在您的情况下,错误甚至解释了未初始化的变量:Attempting to use uninitialized value Variable_1。其中一篇TF教程解释了很多关于变量的问题,他们的creation/initialization/saving/loading

基本上要初始化变量,你有3个选项:

我几乎总是使用第一种方法。记住你应该把它放在会话运行中。所以你会得到这样的东西:

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

如果您对有关变量的更多信息感到好奇,请阅读this documentation以了解如何report_uninitialized_variables并检查is_variable_initialized

答案 3 :(得分:2)

我从一个完全不同的案例中收到此错误消息。似乎tensorflow中的异常处理程序引发了它。您可以检查Traceback中的每一行。在我的情况下,它发生在tensorflow/python/lib/io/file_io.py,因为此文件包含一个不同的错误,其中self.__modeself.__name未初始化,并且需要调用self._FileIO__mode ,而self_FileIO__name代替。

答案 4 :(得分:2)

不同的用例,但将会话设置为默认会话对我来说很有用:

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

这是一个很明显的错误之一,一旦你解决了它。

我的用例如下:
1)将keras VGG16存储为张量流图 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"]()]]

答案 5 :(得分:1)

当我遇到tf.train.string_input_producer()tf.train.batch()这个问题时,在我开始之前初始化局部变量协调器解决了问题。我在启动协调器后初始化局部变量时遇到错误。

答案 6 :(得分:1)

FailedPreconditionError 出现的原因是会话正在尝试读取尚未初始化的变量。

Tensorflow 版本1.11.0开始,您需要执行以下操作:

Command back = new Command("Back") {
     public void actionPerformed(ActionEvent ev) {

       showBack();
    }
};

答案 7 :(得分:1)

Tensorflow 2.0兼容答案:在Tensorflow版本> = 2.0中,用于初始化所有变量(如果使用图形模式)的命令可修复 FailedPreconditionError 如下所示:

tf.compat.v1.global_variables_initializer

这只是variables_initializer(global_variables())

的快捷方式

它返回一个Op,该Op初始化图中的全局变量。

答案 8 :(得分:1)

在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 将显示。

答案 9 :(得分:0)

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

如果尝试在初始化变量之前求值,您将遇到: FailedPreconditionError: Attempting to use uninitialized value tensor.

最简单的方法是使用tf.global_variables_initializer()

一次初始化所有变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
    tf.run(init)

您使用tf.run(init)运行初始化程序,而无需获取任何值。

要仅初始化变量的子集,请使用tf.variables_initializer()列出变量:

var_ab = tf.variables_initializer([a, b], name="a_and_b")
with tf.Session() as sess:
    tf.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:
    tf.run(W.initializer)

答案 10 :(得分:0)

在最近的TensorFlow版本中可能发生了某些变化,因为对于我来说,运行

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

在安装任何模型之前似乎都能解决问题。大多数较旧的示例和评论似乎都建议tf.global_variables_initializer()