ValueError:无法为张量为'(?,2500)'的张量'Placeholder_34:0'输入形状(24500、50、50、1)的值

时间:2019-04-04 08:04:25

标签: python tensorflow machine-learning deep-learning conv-neural-network

这是kaggle比赛中的猫对狗问题。我的代码看起来像是正确的,但仍然是一个值错误,使我很烦。我想我已经给出了正确的输入大小,但是仍然出现错误。 请帮助我找出错误。 这是我的完整代码:

import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
from random import shuffle
import tensorflow
from tqdm import tqdm                                                       

TRAIN_DIR = 'C:\\Users\Kashif\PycharmProjects\DeepLearning-Tensorflow (Sentdex)\Learnings\Cat_VS_Dog\TrainingData'
TEST_DIR = 'C:\\Users\Kashif\PycharmProjects\DeepLearning-Tensorflow (Sentdex)\Learnings\Cat_VS_Dog\TestingData'
IMG_SIZE = 50

MODEL_NAME = 'dogvscat-{}-{}.model'.format(LR, '2conv-basic')


def label_img(img):
    word_label = img.split('.')[-3]
    if word_label == 'cat': return [1,0]
    elif word_label == 'dog': return [0,1]


def create_train_data():
    training_data = []
    for img in tqdm(os.listdir(TRAIN_DIR)):
        label = label_img(img)
        path = os.path.join(TRAIN_DIR,img)
        img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))
        training_data.append([np.array(img),np.array(label)])
    shuffle(training_data)
    np.save('train_data.npy', training_data)
    return training_data


def process_test_data():
    testing_data=[]
    for img in tqdm(os.listdir(TEST_DIR)):
        path = os.path.join(TEST_DIR, img)
        img_num = img.split('.')[0]
        img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE),  (IMG_SIZE, IMG_SIZE))
        testing_data.append([np.array(img), img_num])

    np.save('test_data.npy', testing_data)
    return testing_data


train_data = create_train_data()


learning_rate = 0.01
epochs = 10
batch_size = 128
n_classes = 2

drop_out = 0.8
filter_h_w = 5
depth_in = 1
depth_out_1 = 32
depth_out_2 = 64

x = tf.placeholder('float', [None, IMG_SIZE * IMG_SIZE])
y = tf.placeholder('float', [None, n_classes])

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 conv_nural_network(x):

    weights = {
               'W_conv1': tf.Variable(tf.random_normal([filter_h_w, filter_h_w, depth_in, depth_out_1])),
               'W_conv2': tf.Variable(tf.random_normal([filter_h_w, filter_h_w, depth_out_1, depth_out_2])),
               'W_fc': tf.Variable(tf.random_normal([ int(IMG_SIZE/4) * int(IMG_SIZE/4) * depth_out_2, 1024])),
               'out': tf.Variable(tf.random_normal([1024, n_classes]))
              }

    biases = {
              'b_conv1': tf.Variable(tf.random_normal([depth_out_1])),
              'b_conv2': tf.Variable(tf.random_normal([depth_out_2])),
              'b_fc': tf.Variable(tf.random_normal([1024])),
              'out': tf.Variable(tf.random_normal([n_classes]))
             }

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

    conv1 = tf.nn.relu(conv2d(x, weights['W_conv1']) + biases['b_conv1'])
    conv1 = maxpool2d(conv1)

    conv2 = tf.nn.relu(conv2d(conv1, weights['W_conv2']) + biases['b_conv2'])
    conv2 = maxpool2d(conv2)

    fc = tf.reshape(conv2, [-1, int(IMG_SIZE/4) * int(IMG_SIZE/4) * depth_out_2])
    fc = tf.nn.relu(tf.matmul(fc, weights['W_fc']) + biases['b_fc'])
    fc = tf.nn.dropout(fc, drop_out)

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

    return output



train = train_data[:-500]
test = train_data[-500:]

train_X = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE,IMG_SIZE,1)
train_y = [i[1] for i in train]

test_X = np.array([i[0] for i in test]).reshape(-1,IMG_SIZE,IMG_SIZE,1)
test_y = [i[1] for i in test]



def train_neural_network(x):
    prediction = conv_nural_network(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)

    init = tf.global_variables_initializer()
    loss_trace = []
    accuracy_trace = []

    with tf.Session() as sess:
        sess.run(init)
        for i in range(epochs):
            sess.run(optimizer, feed_dict={x: train_X, y: train_y})
            loss = sess.run(cost_function, feed_dict={x: train_X, y: train_y})
            accuracy = np.mean(np.argmax(sess.run(prediction,feed_dict={x:train_X,y:train_y}),axis=1) == np.argmax(train_y,axis=1))
            loss_trace.append(loss)
            accuracy_trace.append(accuracy)
            print('Epoch:', (i + 1), 'loss:', loss, 'accuracy:', accuracy)

        print('Final training result:', 'loss:', loss, 'accuracy:', accuracy)
        loss_test = sess.run(cost_function, feed_dict={x: test_X, y: test_y})
        test_pred = np.argmax(sess.run(prediction, feed_dict={x: test_X, y: test_y}), axis=1)
        accuracy_test = np.mean(test_pred == np.argmax(test_y, axis=1))
        print('Results on test dataset:', 'loss:', loss_test, 'accuracy:', accuracy_test)


train_neural_network(x)

此错误随后出现。出现值错误,但我不知道输入错误的类型。

ValueError                                Traceback (most recent call last)
<ipython-input-91-7682c5a4d0ec> in <module>
     25 
     26 
---> 27 train_neural_network(x)

<ipython-input-91-7682c5a4d0ec> in train_neural_network(x)
     11         sess.run(init)
     12         for i in range(epochs):
---> 13             sess.run(optimizer, feed_dict={x: train_X, y: train_y})
     14             loss = sess.run(cost_function, feed_dict={x: train_X, y: train_y})
     15             accuracy = np.mean(np.argmax(sess.run(prediction,feed_dict={x:train_X,y:train_y}),axis=1) == np.argmax(train_y,axis=1))


ValueError: Cannot feed value of shape (24500, 50, 50, 1) for Tensor 'Placeholder_34:0', which has shape '(?, 2500)'

0 个答案:

没有答案