【问题标题】:expected dense_218_input to have 2 dimensions, but got array with shape (512, 28, 28, 1)预计 dense_218_input 有 2 维,但得到的数组形状为 (512, 28, 28, 1)
【发布时间】:2025-12-31 16:50:02
【问题描述】:

我正在尝试在 keras 中扩充我的 MNIST 数据集,但由于某种原因它无法正常工作。任何帮助将不胜感激。

部分代码:

x_train = x_train.reshape(x_train.shape[0],28, 28,1)
x_test = x_test.reshape(x_test.shape[0],28, 28,1)

x_train = x_train.reshape(x_train.shape[0],28, 28,1)
x_test = x_test.reshape(x_test.shape[0],28, 28,1)


datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.2,
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.2)


model.compile(loss='categorical_crossentropy',
              optimizer= adam,
              metrics=['accuracy'])


train_gen = datagen.flow(x_train, r_train, batch_size=batch_size)

history2 = model.fit_generator(train_gen,
                              steps_per_epoch=int(np.ceil(x_train.shape[0] / float(batch_size))),
                              epochs=epochs)


# history = model.fit(x_train, r_train,
#                     batch_size=batch_size,
#                     epochs=epochs,
#                     verbose=1,
#                     validation_data=(x_test, r_test))

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

错误:

ValueError:检查输入时出错:预期dense_218_input 有2 维,但得到的数组形状为(512, 28, 28, 1)

【问题讨论】:

标签: deep-learning keras mnist


【解决方案1】:

dense_218_input 应该是一个 numpy 二维数组,而不是形状:(512, 28, 28, 1)。您可以使用numpy.reshape 对其进行重塑。

【讨论】:

    最近更新 更多