在 Keras 中检查目标时出现 MNIST ValueError

MNIST ValueError when checking target in Keras

我的代码如下:

from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation

(x_train, y_train), (x_test, y_test) = mnist.load_data()
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)

model = Sequential()

model.add(Dense(output_dim=500, input_shape=(28, 28)))
model.add(Activation("tanh"))
model.add(Dense(10))
model.add(Activation("softmax"))

model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
model.fit(x_train, y_train, nb_epoch=50, batch_size=20)

这会出现以下错误:

ValueError: Error when checking target: expected activation_2 to have 3 dimensions, but got array with shape (60000, 10)

我认为形状 (60000, 10) 是 y_train 的形状,它有 2 个维度,而预期某处有 3 个维度。

我应该在哪里编辑?

MNIST 样本是 28 x 28 值(像素)的图像。您想要使用仅接受一维数字数组的 ANN 进行分类(将 ANN 的第一层想象成一排 500 长的神经元,这些神经元仅理解 500 长的数字行,但不理解 28x28 矩阵)。

要修复您的错误,您必须事先重塑数据:

(X_train, y_train), (X_test, y_test) = mnist.load_data()

X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')

Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)

...

model = Sequential()
model.add(Dense(512, input_shape=(784,)))

如果您想以二维方式输入数据以通过保留图像的空间顺序来获得更高的准确性,而不是将它们展平成一长串数字,那么您必须将模型架构更改为卷积神经网络网络(网上有很多示例代码,尤其是 MNIST)。