层序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 1,但收到的输入形状为

时间:2021-06-28 15:00:42

标签: python tensorflow machine-learning keras deep-learning

追溯:

<块引用>

ValueError: 层序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 1,但收到的输入具有形状 (None, 1, 300, 300)


import tensorflow as tf
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers import Conv2D, MaxPool2D
from keras.optimizers import SGD,RMSprop,Adam
from keras.utils import np_utils

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import os
import theano
from PIL import Image
from numpy import *

from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split

img_rows, img_cols = 300, 300
img_channels = 1

path1 = "./images"
path2 = "./resize"

listing = os.listdir(path1)
listing2 = list(listing)
num_samples=size(listing)

for i in range(len(listing)):
    if "jpg" in listing[i]:
        im = Image.open(path1 + '/' + listing[i])   
        img = im.resize((img_rows,img_cols))
        gray = img.convert('L')
        gray.save(path2 +'/' +  listing[i], "JPEG")
    elif "txt" in listing[i]:
        listing2.remove(listing[i])

imlist = os.listdir(path2)

im1 = array(Image.open(path2 + '/'+ imlist[0]))
m,n = im1.shape[0:2]
imnbr = len(imlist)

immatrix = array([array(Image.open(path2 + '/'+ im2)).flatten()
              for im2 in imlist],'f')
                
label=np.ones((num_samples,),dtype = int)
label[0:1260]=0
label[1260:2716]=1
label[2716:]=2
data,Label = shuffle(immatrix,label, random_state=2)
train_data = [data,Label]

img=immatrix[167].reshape(img_rows,img_cols)
plt.imshow(img)
plt.imshow(img,cmap='gray')
print (train_data[0].shape)
print (train_data[1].shape)


batch_size = 32
classes = 3
epochs = 20

filters = 32
pool = 2
conv = 3

(X, y) = (train_data[0],train_data[1])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)


X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')

X_train /= 255
X_test /= 255

print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')


Y_train = np_utils.to_categorical(y_train, classes)
Y_test = np_utils.to_categorical(y_test, classes)

i = 256
plt.imshow(X_train[i, 0], interpolation='nearest')
print("label : ", Y_train[i,:])


model = Sequential()
model.add(Convolution2D(filters, conv, conv, padding = 'valid',
                        input_shape = (img_rows, img_cols, 1),
                        data_format = "channels_last"))
model.add(Activation('relu'))

model.add(Convolution2D(filters, conv, conv, padding = 'valid'))
model.add(Activation('relu'))

model.add(Convolution2D(filters, conv, conv, padding = 'valid'))
model.add(Activation('relu'))


model.add(MaxPooling2D(pool_size = (pool, pool), strides = pool, padding = "valid"))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(classes))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])
print(model.summary())

hist = model.fit(X_train, Y_train, batch_size = batch_size, epochs = epochs,
              verbose=1, validation_data=(X_test, Y_test))

我尝试了各种方法,例如 ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 1,但我仍然面临同样的错误。请问有没有人有解决办法?

我知道问题出在线路上

model.add(Convolution2D(filters, conv, conv, padding = 'valid',
                        input_shape = (img_rows, img_cols, 1),
                        data_format = "channels_last"))

但我不太确定如何修复它。

谢谢!

1 个答案:

答案 0 :(得分:0)

这实际上是一个相当描述性/准确的错误消息。你给它的输入形状是 (batch, img_rows, img_cols, 1),但它清楚地看到图像是形状 (batch, 1, 300, 300)。所以看起来你只是一维设置错误。做一些类似的事情

train_data = tf.transpose(train_data, [0, 2, 3, 1])

你应该被设置