tensorflow CNN classfication 질문입니다

조회수 849회

CNN 코드에서 이러한 이러가 뜹니다 InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 409600 values, but the requested shape requires a multiple of 12288 [[Node: Reshape = ReshapeT=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"]]

import numpy as np import os from scipy.misc import imread, imresize import matplotlib.pyplot as plt import tensorflow as tf

cwd = os.getcwd() loadpath = cwd + "/../custom_data.npz"

l = np.load(loadpath) print(l.files)

#parse loaded data trainimg = l['trainimg']

trainlabel = l['trainlabel']

testimg = l['testimg']

testlabel = l['testlabel']

imgsize = l['imgsize']

categories = ['categories']

use_gray = l['use_gray']

nimgch = 3 ntrain = trainimg.shape[0] #495 train images

nclass = trainlabel.shape[1] #330test images

dim = trainimg.shape[1] #4096 dimensional input

ntest = testimg.shape[0] #5classes

network topologies

n_input = dim

n_channel = 64

n_classes = nclass

Inputs and outputs

x = tf.placeholder("float", [None, n_input])

y = tf.placeholder("float", [None, n_classes])

network parameters

stddev = 0.1

weights = {'c1': tf.Variable(tf.random_normal([7, 7, nimgch, n_channel], stddev = stddev)), 'd1': tf.Variable(tf.random_normal([n_channel*imgsize[0]*imgsize[1]//4, n_classes], stddev = stddev))}

biases = { 'c1': tf.Variable(tf.random_normal([n_channel], stddev = stddev)), 'd1': tf.Variable(tf.random_normal([n_classes], stddev = stddev)) }

Model

def CNN(_x, _w, _b):

#reshape
_x_r = tf.reshape(_x, shape = [-1, imgsize[0], imgsize[1], nimgch])

#convolution
_conv1 = tf.nn.conv2d(_x_r, _w['c1'], strides = [1, 1, 1, 1], padding='SAME')
#add bias
_conv2 = tf.nn.bias_add(_conv1, _b['c1'])
#relu
_conv3 = tf.nn.relu(_conv2)
# max pool
_pool = tf.nn.max_pool(_conv3, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding='SAME')
#vectorize
_dense = tf.reshape(_pool, [-1, _w['d1'].get_shape().as_list()[0]])
#dense
_logit = tf.add(tf.matmul(_dense, _w['d1']), _b['d1'])
_out = {
    'x_r': _x_r, 'conv1': _conv1, 'conv2': _conv2, 'conv3': _conv3
    , 'pool':_pool, 'dense': _dense, 'logit': _logit
}
return _out

prediction

cnnout = CNN(x, weights, biases)

loss and optimizer

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y, logits = cnnout['logit'])

optm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

corr = tf.equal(tf.argmax(cnnout['logit'], 1), tf.argmax(y, 1))

accr = tf.reduce_mean(tf.cast(corr, "float"))

initializer

init = tf.global_variables_initializer()

training_epochs = 50 batch_size = 100 disp_each = 5 plot_each = 10

sess = tf.Session()

sess.run(init)

for epoch in range(training_epochs):

total_batch = int(ntrain/batch_size)

randpermlist = np.random.permutation(ntrain)

sun_cost = 0
for i in range(total_batch):

    randidx = randpermlist[i*batch_size:min((i+1)*batch_size, ntrain-1)]

    batch_xs = trainimg[randidx, :]
    batch_ys = trainlabel[randidx, :]
    feeds = {x: batch_xs, y: batch_ys}
    sess.run(optm, feed_dict=feeds)
    sun_cost +=sess.run(cost, feed_dict=feeds)
avg_cost = sun_cost / total_batch

display

if (epoch+1) % disp_each == 0 or epoch == training_epochs-1:
    print("epoch: %03d/%03d cost: %.9f" %(epoch+1, training_epochs, avg_cost))
    feeds = {x: batch_xs, y: batch_ys}
    train_acc =sess.run(accr, feed_dict= feeds)
    print("train accuracy: %.3f" %(train_acc))
    feeds = {x:testimg, y: testlabel}
    test_acc = sess.run(accr, feed_dict = feeds)
    print("test accuracy: %.3f" %(test_acc))

만약 nimgch = 1(흑백 사진) 로둔다면 코드가 실행됩니다 nimgch = 3 (컬러 사진)으로 실행시키고 싶다면 어디서 에러가 뜬것일까요

  • (•́ ✖ •̀)
    알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)