1

我正在实施逻辑回归函数。这是非常简单的,并正常工作,直到我到我想要计算其准确性的部分。这是我的逻辑回归...TensorFlow无法填充数值错误

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这个数组吗?

回答

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

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

+0

我明白了。有没有其他解决方法?我正在其他地方恢复我的模型,并且我设置变量的方式非常重要。 – Bolboa

+1

如果要将第一维维持为100,则必须以批处理大小100填充它。因此,一个选项可能是将mnist.test.images(和mnist.test.labels)划分为100个块,计算他们每个人的准确性,然后平均的准确度。 –