我的代码如下:
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个维度。
我应该在哪里编辑?
答案 0 :(得分:0)
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,)))
如果您想在2d中输入数据以通过保留图像的空间顺序来获得更高的准确度,而不是将它们展平为一长串数字而不是将模型架构更改为卷积神经网络(很多在线示例代码,特别是对于MNIST)。