【问题标题】:ValueError: Cannot feed value of shape (128, 28, 28) for Tensor 'Placeholder:0', which has shape '(?, 784)'ValueError:无法为具有形状“(?,784)”的张量“占位符:0”提供形状(128、28、28)的值
【发布时间】:2018-08-04 05:27:39
【问题描述】:

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

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

非常感谢您的帮助。

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数组的形状?

【问题讨论】:

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


    【解决方案1】:

    如果你仔细观察,你会发现你有两个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])

    【讨论】:

    • 现在我收到“ValueError: could not convert string to float:”。给出关于我的标签的错误,它是字符串。
    • 标签不应该是字符串。将它们编码成整数
    • 更改为 int。现在这个错误“InvalidArgumentError(参见上面的回溯):logits 和标签必须相同大小:logits_size=[128,15] labels_size=[1,128]”其中标签 = y
    猜你喜欢
    • 2018-03-01
    • 2023-03-19
    • 1970-01-01
    • 2017-12-06
    • 2018-06-06
    • 2018-08-03
    • 2018-03-24
    • 2020-11-18
    • 2022-08-12
    相关资源
    最近更新 更多