Keras提示错误:(检查输入时出错:预期conv2d_4_input具有4个尺寸)

时间:2019-06-13 20:39:39

标签: python keras deep-learning conv-neural-network

这是我在MNIST数据集上使用卷积神经网络的代码。不幸的是,Keras在通过网络时提示错误。感谢您的帮助。我想知道这种错误的原因。

这是错误:检查输入时出错:预期conv2d_4_input具有4维,但数组的形状为(45000,28,28)

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28,28, 1), padding= 'same'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu', padding= 'same'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu', padding= 'same'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dropout(0.4))
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
k = 4
num_val_samples = len(train_images) // k
num_epochs = 20
all_scores = []
for i in range(k):
    print('processing fold #', i)
    valid_data = train_images[i * num_val_samples: (i + 1) *
                          num_val_samples] 
    valid_labels = train_labels[i * num_val_samples: (i + 1) *
                                num_val_samples]
partial_train_images = np.concatenate(
    [train_images[:i * num_val_samples], train_images[(i + 1) * num_val_samples:]], axis=0)
partial_train_labels = np.concatenate([train_labels[:i * num_val_samples], train_labels[(i + 1) * num_val_samples:]],axis=0)

model.fit(partial_train_images, partial_train_labels,epochs=20, 
batch_size=1, verbose=0)
val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)
all_scores.append(val_mae)

我看过其他页面,那里的解决方案都没有帮助。

1 个答案:

答案 0 :(得分:0)

您未在数组中包括通道尺寸,对于灰度图像,它应该是具有一个元素的尺寸,因此每个样本均为(28, 28, 1)

partial_train_images = partial_train_images.reshape((-1, 28, 28, 1))
val_data = val_data.reshape((-1, 28, 28, 1))