【问题标题】:TensorFlow cannot feed value errorTensorFlow 无法输入值错误
【发布时间】:2017-09-19 04:53:40
【问题描述】:

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

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: 无法为形状为“(100, 784)”的张量“Placeholder:0”提供形状 (10000, 784) 的值

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

【问题讨论】:

    标签: python-3.x machine-learning tensorflow logistic-regression


    【解决方案1】:

    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)  #
    

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

    【讨论】:

    • 我明白了。还有其他解决方法吗?我正在其他地方恢复我的模型,我设置变量的方式很重要。
    • 如果您想将第一个维度保持为 100,则必须使用批量大小 100 来提供它。因此一个选项可能是分区 mnist.test.images(和 mnist.test.labels ) 到 100 个块,计算每个块的准确度,然后对准确度取平均值。
    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多