即使变量已初始化,Tensor流也会引发未初始化的错误

时间:2018-11-19 23:35:20

标签: python tensorflow

我正在尝试使用tensorflow在python中编写程序,以使用具有隐藏层的神经网络来拟合具有不同模式的数据。我遇到代码错误,指出变量b2未初始化。但是我已经初始化了它,不明白我在这里缺少什么。

这是assignment(在这里可以理解数据集)的一部分,在解决它时卡在这里。

指向colab笔记本的链接为here

初始化行看起来像

W1 = tf.Variable(np.random.uniform(low=-0.01, high=0.01, size=(hidden, 2)), name="W1")
b1 = tf.Variable(np.random.uniform(low=-0.01, high=0.01, size=(hidden, 1)), name="b1")
W2 = tf.Variable(np.random.uniform(low=-0.01, high=0.01, size=(classes, hidden)), name="W2")
b2 = tf.Variable(np.random.uniform(low=-0.01, high=0.01, size=(classes, 1)), name="b2")

下面显示了计算图的代码段。

operation = "ReLU" # "Sigmoid"
o = tf.add(tf.matmul(W1, p), b1)
# ReLU or Sigmoid
if operation == "ReLU":
  z = tf.zeros((hidden, 1), dtype=tf.float64)
  output = tf.maximum(o, z)
else:
  output = tf.sigmoid(o)
foutput = tf.add(tf.matmul(W2, output), b2)
crossentropy = tf.log(tf.exp(foutput) / tf.reduce_sum(tf.exp(foutput), 0))
init = tf.initialize_all_variables()
with tf.Session() as sess:
  ce = sess.run([crossentropy], feed_dict={p : inputs, t : targets, lr : 0.01})
print(ce)

错误消息

FailedPreconditionError                   Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1333     try:
-> 1334       return fn(*args)
   1335     except errors.OpError as e:

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
   1318       return self._call_tf_sessionrun(
-> 1319           options, feed_dict, fetch_list, target_list, run_metadata)
   1320 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
   1406         self._session, options, feed_dict, fetch_list, target_list,
-> 1407         run_metadata)
   1408 

FailedPreconditionError: Attempting to use uninitialized value b2
     [[{{node b2/read}} = Identity[T=DT_DOUBLE, _device="/job:localhost/replica:0/task:0/device:CPU:0"](b2)]]

1 个答案:

答案 0 :(得分:0)

在计算交叉熵之前,您还需要在图中运行init函数:

with tf.Session() as sess:
  sess.run(init)
  ce = sess.run([crossentropy], feed_dict={p : inputs, t : targets, lr : 0.01})

此外,tf.initialize_all_variables()也已弃用。请改用tf.global_variables_initializer()