ValueError: 层序列_6 的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 1

时间:2021-02-22 00:12:46

标签: python tensorflow keras neural-network conv-neural-network

我正在尝试创建一个用于二元分类的卷积神经网络,它可以区分正常人脸和中风患者的人脸。

按照 this tutorial 中使用的方法,我创建了 CNN,它在输入 MNIST 数据集时工作。我还按照 this StackOverflow thread 中建议的方法将我的图像导入神经网络。下面显示的是我的代码。

Strokes = glob.glob('C:\\Users\\Colin\\CNNImages\\Strokes\\*.*')
RegularFaces = glob.glob('C:\\Users\\Colin\\CNNImages\\RegularFaces\\*.*')

data = []
labels = []

for i in Strokes:   
    image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', 
    target_size= (128,128))
    image=np.array(image)
    data.append(image)
    labels.append(0)
for i in RegularFaces:   
    image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', 
    target_size= (128,128))
    image=np.array(image)
    data.append(image)
    labels.append(1)


data = np.array(data)
labels = np.array(labels)

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(data, labels, test_size=0.2,
                                                random_state=42)

batch_size = 128
num_classes = 2
epochs = 12

# input image dimensions
img_rows, img_cols = 128, 128

x_train = x_train.reshape(864,128,128,3)
x_test = x_test.reshape(216,128,128,3)

print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=(28,28,1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))

score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

当我运行代码时,我收到以下错误:ValueError: Input 0 of layer sequential_6 is incompatible with the layer: expected axis -1 of input shape to have value 1 but received input with shape (None, 128, 128, 3)。我将如何阻止此错误发生?

1 个答案:

答案 0 :(得分:0)

更改这行代码:-

model.add(Conv2D(32, kernel_size=(3, 3),
             activation='relu',
             input_shape=(28,28,1)))

对此:-

model.add(Conv2D(32, kernel_size=(3, 3),
             activation='relu',
             input_shape=(28,28,3)))

您在模型 l 中的 input_shape 参数必须与您在上面变换的图像尺寸一致。