【问题标题】:Digit Recognition Prob数字识别概率
【发布时间】:2019-09-30 18:35:28
【问题描述】:

神经网络和 AI 的新手。 正在跟进博客以创建数字识别系统。

卡在这里:

 File "main.py", line 61, in <module>
     X: batch_x, Y: batch_y, keep_prob: dropout
   File "C:\Users\umara\AppData\Local\Programs\Python\Python37\lib\site- 
   packages\tensorflow\python\client\session.py", line 929, in run
     run_metadata_ptr)
   File "C:\Users\umara\AppData\Local\Programs\Python\Python37\lib\site- 
   packages\tensorflow\python\client\session.py", line 1128, in _run
     str(subfeed_t.get_shape())))
 ValueError: Cannot feed value of shape (128, 28, 28, 1) for Tensor 'Placeholder:0', which has shape '(?, 784)'

我也尝试过这些示例:

n_train = [d.reshape(28,28, 1) for d in mnist.train.num_examples]    
test_features =[d.reshape(28, 28, 1) for d in mnist.test.images]      
n_validation =[d.reshape(28, 28, 1) for d in mnist.validation.num_examples]

代码:

import numpy as np
from PIL import Image
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#Import data from MNIST DATA SET and save it in a folder
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#n_train = [d.reshape(28, 28, 1) for d in mnist.train.num_examples]
n_train = mnist.train.num_examples
#train_features = 
#test_features = [d.reshape(28, 28, 1) for d in mnist.test.images]
#n_validation = [d.reshape(28, 28, 1) for d in mnist.validation.num_examples]
n_validation = mnist.validation.num_examples
n_test = mnist.test.num_examples
n_input = 784
n_hidden1 = 522
n_hidden2 = 348
n_hidden3 = 232
n_output = 10
learning_rate = 1e-4
n_iterations = 1000
batch_size = 128
dropout = 0.5
#X = tf.placeholder(tf.float32,[None, 28, 28, 1])
#X = tf.placeholder("float", [None, n_input])
X = tf.placeholder(tf.float32 , [None , 784])
#X = tf.reshape(X , [-1 , 784])
Y = tf.placeholder("float", [None, n_output])
keep_prob = tf.placeholder(tf.float32)
weights = {
    'w1': tf.Variable(tf.truncated_normal([n_input, n_hidden1], stddev=0.1)),
    'w2': tf.Variable(tf.truncated_normal([n_hidden1, n_hidden2], stddev=0.1)),
    'w3': tf.Variable(tf.truncated_normal([n_hidden2, n_hidden3], stddev=0.1)),
    'out': tf.Variable(tf.truncated_normal([n_hidden3, n_output], stddev=0.1)),
}
biases = {
    'b1': tf.Variable(tf.constant(0.1, shape=[n_hidden1])),
    'b2': tf.Variable(tf.constant(0.1, shape=[n_hidden2])),
    'b3': tf.Variable(tf.constant(0.1, shape=[n_hidden3])),
    'out': tf.Variable(tf.constant(0.1, shape=[n_output]))
}
layer_1 = tf.add(tf.matmul(X, weights['w1']), biases['b1'])
layer_2 = tf.add(tf.matmul(layer_1, weights['w2']), biases['b2'])
layer_3 = tf.add(tf.matmul(layer_2, weights['w3']), biases['b3'])
layer_drop = tf.nn.dropout(layer_3, keep_prob)
output_layer = tf.matmul(layer_drop, weights['out']) + biases['out']
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(
        labels=Y, logits=output_layer
        ))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_pred = tf.equal(tf.argmax(output_layer, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(n_iterations):
    batch_x, batch_y = mnist.train.next_batch(batch_size)
    batch_x = np.reshape(batch_x,(-1,28,28,1))
    sess.run(train_step, feed_dict={
        X: batch_x, Y: batch_y, keep_prob: dropout
        })

    # print loss and accuracy (per minibatch)
    if i % 100 == 0:
        minibatch_loss, minibatch_accuracy = sess.run(
            [cross_entropy, accuracy],
            feed_dict={X: batch_x, Y: batch_y, keep_prob: 1.0}
            )
        print(
            "Iteration",
            str(i),
            "\t| Loss =",
            str(minibatch_loss),
            "\t| Accuracy =",
            str(minibatch_accuracy)
            )
test_accuracy = sess.run(accuracy, feed_dict={X: mnist.test.images, Y: mnist.test.labels, keep_prob: 1.0})
print("\nAccuracy on test set:", test_accuracy)
img = np.invert(Image.open("n55.png").convert('L')).ravel()
prediction = sess.run(tf.argmax(output_layer, 1), feed_dict={X: [img]})
print ("Prediction for test image:", np.squeeze(prediction))

【问题讨论】:

    标签: python python-3.x tensorflow neural-network artificial-intelligence


    【解决方案1】:

    你的错误:

     ValueError: Cannot feed value of shape (128, 28, 28, 1) for Tensor 'Placeholder:0', which has shape '(?, 784)'
    

    说您的张量需要形状 (?, 784) 的值,但您输入了 128 个形状 (28,28) 的图像。

    28*28 = 784

    因此,请尝试通过执行以下操作将您的数据重塑为 (128,784):

    n_train = [d.reshape(784) for d in mnist.train.num_examples]    
    test_features =[d.reshape(784) for d in mnist.test.images]      
    n_validation =[d.reshape(784) for d in mnist.validation.num_examples]
    

    如果将列表转换为 numpy 数组,则可以打印形状:

    import numpy as np
    print(np.array(n_train).shape)
    

    应该打印(number_of_samples, 784)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-04
      • 2021-03-12
      • 2018-12-24
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      相关资源
      最近更新 更多