TensorFlow cannot feed value 错误

TensorFlow cannot feed value error

我正在实施逻辑回归函数。它非常简单并且可以正常工作,直到我到达我想要计算其准确性的部分。这是我的逻辑回归...

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

# tf Graph Input
x = tf.get_variable("input_image", shape=[100,784], dtype=tf.float32)
x_placeholder = tf.placeholder(tf.float32, shape=[100, 784])
assign_x_op = x.assign(x_placeholder).op

y = tf.placeholder(shape=[100,10], name='input_label', dtype=tf.float32)  # 0-9 digits recognition => 10 classes


# set model weights
W = tf.get_variable("weights", shape=[784, 10], dtype=tf.float32, initializer=tf.random_normal_initializer())
b = tf.get_variable("biases", shape=[1, 10], dtype=tf.float32, initializer=tf.zeros_initializer())

# construct model
logits = tf.matmul(x, W) + b
pred = tf.nn.softmax(logits)  # Softmax

# minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices=1))

# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(cost)

# initializing the variables
init = tf.global_variables_initializer()

saver = tf.train.Saver()

# launch the graph
with tf.Session() as sess:

    sess.run(init)

    # training cycle
    for epoch in range(FLAGS.training_epochs):
        avg_cost = 0
        total_batch = int(mnist.train.num_examples/FLAGS.batch_size)
        # loop over all batches
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batch_size)
            # Assign the contents of `batch_xs` to variable `x`.
            sess.run(assign_x_op, feed_dict={x_placeholder: batch_xs})
            _, c = sess.run([optimizer, cost], feed_dict={y: batch_ys})

            # compute average loss
            avg_cost += c / total_batch
        # display logs per epoch step
        if (epoch + 1) % FLAGS.display_step == 0:
            print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost))

    save_path = saver.save(sess, "/tmp/model.ckpt")
    print("Model saved in file: %s" % save_path)
    print("Optimization Finished!")

如您所见,它是一个基本的逻辑回归和函数,并且运行良好。

重要的是不要 batch_size100

现在,在截断上面的代码后,我尝试以下...

# list of booleans to determine the correct predictions
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
print(correct_prediction.eval({x_placeholder:mnist.test.images, y:mnist.test.labels}))

# calculate total accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

但是代码在 correct_prediction 上失败。我收到以下错误...

% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape()))) ValueError: Cannot feed value of shape (10000, 784) for Tensor 'Placeholder:0', which has shape '(100, 784)'

我想我收到这个错误是因为我试图为 x 分配占位符的值。我怎样才能解决这个问题?我需要 reshape 数组吗?

x_placeholder = tf.placeholder(tf.float32, shape=[100, 784])

y = tf.placeholder(shape=[100,10], name='input_label', dtype=tf.float32)  # 0-9 

避免将第一个维度固定为 100,因为它禁止您使用任何其他批量大小(因此,如果 mnist.test.images 中的图像数量不同于 100,您将收到错误消息)。而是将它们指定为 None:

x_placeholder = tf.placeholder(tf.float32, shape=[None, 784])

y = tf.placeholder(shape=[None,10], name='input_label', dtype=tf.float32)  #

然后你可以使用任何批量大小