gpt4 book ai didi

python - Keras提示错误: (Error when checking input: expected conv2d_4_input to have 4 dimensions)

转载 作者:太空宇宙 更新时间:2023-11-03 20:46:10 26 4
gpt4 key购买 nike

这是我在 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)

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

最佳答案

您没有在数组中包含 channel 维度,对于灰度图像,它应该是具有一个元素的维度,因此每个样本都是(28, 28, 1):

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

关于python - Keras提示错误: (Error when checking input: expected conv2d_4_input to have 4 dimensions),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56588281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com