I have xtrain.shape as
(60000, 28, 28)
It means 60000 channels with image size 28 * 28
好的,它肯定不是那个意思;它的意思是60000个样本,而不是通道(MNIST是一个单通道数据集)。
在这种情况下没有必要重新发明轮子 - 可以看看Keras中的MNIST CNN示例:
from keras import backend as K
img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model = Sequential()
model.add(Convolution2D(32,3,activation='relu',input_shape=input_shape))
model.add(Dense(10, activation='softmax'))
您还应更改最终层的激活函数为
softmax
(并且很可能在最终密集层之前添加一些池化和展平层)。