tensorflow:占位符未在交互式会话中定义

时间:2017-12-30 07:19:35

标签: tensorflow

我在model()中定义了一个张量,并在另一个方法model_accuracy()中的相同交互式会话中使用它。遇到错误,指出占位符未在model_accuracy()方法中定义。有人能告诉我我在这里失踪了什么吗?

sess = tf.InteractiveSession()

def model_accuracy(X_train, Y_train, Z3, Y):
  predict_op = tf.argmax(Z3, 1)
  correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  train_accuracy = accuracy.eval({X: X_train, Y: Y_train})


def model():
  X = tf.placeholder(tf.float32, shape=...)
  Y = tf.placeholder(tf.float32, shape=...)
  W1 = tf.get_variable("W1", ...)
  W2 = tf.get_variable("W2", ...)
  Z1 = tf.nn.conv2d(X, W1, ...)
  A1 = tf.nn.relu(Z1)
  P1 = tf.nn.max_pool(A1, ...)
  Z2 = tf.nn.conv2d(P1, W2, ...)
  A2 = tf.nn.relu(Z2)
  P2 = tf.nn.max_pool(A2, ...)
  P2 = tf.contrib.layers.flatten(P2)
  Z3 = tf.contrib.layers.fully_connected(P2, ...)
  sess.run(tf.global_variables_initializer())
  ... # define optimizer and cost tensors using Z3 and Y
  sess.run([optimizer, cost], feed_dict = {X: X_train, Y: Y_train}) # for n epochs
  return Z3, Y

然后我这样打电话给model()model_accuracy()

Z3, Y = model() # runs fine
model_accuracy(X_train, Y_train, Z3, Y) # fails

这是错误:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-33-2da12d45d5f6> in <module>()
----> 1 model_accuracy(X_train, Y_train, Z3, Y)

<ipython-input-32-3b1eef80d775> in model_accuracy(X_train, Y_train, X_test, Y_test, Z3, Y, sess)
      7     accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
----> 8     train_accuracy = accuracy.eval({X: X_train, Y: Y_train}, session = sess)    
NameError: name 'X' is not defined

1 个答案:

答案 0 :(得分:0)

虽然model_accuracy()使用与model()相同的会话,但feed_dict需要在范围内输入所有变量。通过传递到X函数将model_accuracy()添加到范围时工作。