numpy - ValueError : Cannot feed value of shape (128, 28, 28) 对于张量 'Placeholder:0' ,其形状为 '(?, 784)'

标签 numpy tensorflow machine-learning neural-network training-data

我是 Tensorflow 和机器学习的新手,正在尝试使用 Tensorflow 和我的自定义输入数据来使用 CNN。但我收到下面附加的错误。

数据或图像大小为 28x28,带有 15 个标签。 我没有在这个脚本中得到 numpy reshape 的东西或错误。

非常感谢您的帮助。

enter image description here

import tensorflow as tf
import os
import skimage.data
import numpy as np
import random

def load_data(data_directory):
    directories = [d for d in os.listdir(data_directory) 
                   if os.path.isdir(os.path.join(data_directory, d))]
    labels = []
    images = []
    for d in directories:
        label_directory = os.path.join(data_directory, d)
        file_names = [os.path.join(label_directory, f) 
                      for f in os.listdir(label_directory) 
                      if f.endswith(".jpg")]
        for f in file_names:
            images.append(skimage.data.imread(f))
            labels.append(d)
        print(str(d)+' Completed')
    return images, labels

ROOT_PATH = "H:\Testing\TrainingData"
train_data_directory = os.path.join(ROOT_PATH, "Training")
test_data_directory = os.path.join(ROOT_PATH, "Testing")

print('Loading Data...')
images, labels = load_data(train_data_directory)
print('Data has been Loaded')

n_classes = 15
training_examples = 10500
test_examples = 4500
batch_size = 128

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')

def maxpool2d(x):
    return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')

def neural_network_model(x):
    weights = {'W_Conv1':tf.Variable(tf.random_normal([5,5,1,32])),
               'W_Conv2':tf.Variable(tf.random_normal([5,5,32,64])),
               'W_FC':tf.Variable(tf.random_normal([7*7*64, 1024])),
               'Output':tf.Variable(tf.random_normal([1024, n_classes]))}

    biases = {'B_Conv1':tf.Variable(tf.random_normal([32])),
               'B_Conv2':tf.Variable(tf.random_normal([64])),
               'B_FC':tf.Variable(tf.random_normal([1024])),
               'Output':tf.Variable(tf.random_normal([n_classes]))}   

    x = tf.reshape(x, shape=[-1,28,28,1])

    conv1 = conv2d(x, weights['W_Conv1'])
    conv1 = maxpool2d(conv1)

    conv2 = conv2d(conv1, weights['W_Conv2'])
    conv2 = maxpool2d(conv2)

    fc = tf.reshape(conv2, [-1, 7*7*64])
    fc = tf.nn.relu(tf.matmul(fc, weights['W_FC'])+biases['B_FC'])

    output = tf.matmul(fc, weights['Output'])+biases['Output']

    return output

def next_batch(num, data, labels):
    idx = np.arange(0 , len(data))
    np.random.shuffle(idx)
    idx = idx[:num]
    data_shuffle = [data[ i] for i in idx]
    labels_shuffle = [labels[ i] for i in idx]

    return np.asarray(data_shuffle), np.asarray(labels_shuffle)

def train_neural_network(x):
    prediction = neural_network_model(x)

    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 10
    with tf.Session() as sess:
        # OLD:
        #sess.run(tf.initialize_all_variables())
        # NEW:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(training_examples/batch_size)):
                epoch_x, epoch_y = next_batch(batch_size, images, labels)
                _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
                epoch_loss += c

            print('Epoch', epoch, 'completed out of',hm_epochs,'loss:',epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print('Accuracy:',accuracy.eval({x: images, y: labels}))

print('Training Neural Network...')
train_neural_network(x)

我做错了什么?需要修复什么以及如何修复 numpy 数组的形状?

最佳答案

如果仔细观察,您会发现有两个 x占位符:

x = tf.placeholder('float', [None, 784])  # global

...

x = tf.reshape(x, shape=[-1,28,28,1])     # in neural_network_model

其中一个在函数作用域内,因此在 train_neural_network 中不可见,所以 TensorFlow 采用 [?, 784] 的那个形状。你应该摆脱其中之一。

另请注意,您的训练数据的等级为 3,即 [batch_size, 28, 28] ,因此它与这些占位符中的任何一个都不直接兼容。

将其输入第一个 x ,取epoch_x.reshape([-1, 784]) 。对于第二个占位符(使其可见后),请使用 epoch_x.reshape([-1, 28, 28, 1]) .

关于numpy - ValueError : Cannot feed value of shape (128, 28, 28) 对于张量 'Placeholder:0' ,其形状为 '(?, 784)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48960010/

相关文章:

python - 使用 Open CV Python 将 alpha channel 添加到单色图像

python - 将 -inf 替换为零值

python - tf.fake_quant_with_min_max_args 和 tf.fake_quant_with_min_max_vars 有什么区别

python - tensorflow 入门

r - C5.0 决策树 - 名为 exit 且值为 1 的 c50 代码

python-3.x - 在 Python 中实现感知器算法时遇到问题

python - CNTK运行时错误

python - 从查找表返回索引,允许空值且未找到

python - Python 中长列表的高效过滤、映射和归约操作

node.js - Tensorflow JS和Electron Forge-在npm运行make后导入tensorflow js时出错