expected dense_218_input to have 2 dimensions, but

2019-08-23 11:44发布

问题:

I am trying to augment my MNIST dataset in keras but for some reason its not working. Any help will be appreciated.

Part of the code:

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])

error:

ValueError: Error when checking input: expected dense_218_input to have 2 dimensions, but got array with shape (512, 28, 28, 1)

回答1:

The dense_218_input should be a numpy 2d-array instead of shape: (512, 28, 28, 1). You can reshape it with numpy.reshape.