种草:如何用卷积神经网络CNN识别手写数字集?

  7 Total params: 623290

  8 ____________________________________________________________________________________________________

  9 Train alt="物联网" width="550" height="138" />

  代码:

  1 #coding: utf-8

  2 #Simple CNN

  3 import numpy

  4 from keras.datasets import mnist

  5 from keras.models import Sequential

  6 from keras.layers import Dense

  7 from keras.layers import Dropout

  8 from keras.layers import Flatten

  9 from keras.layers.convolutional import Convolution2D

  10 from keras.layers.convolutional import MaxPooling2D

  11 from keras.utils import np_utils

  12

  13 seed = 7

  14 numpy.random.seed(seed)

  15

  16 #加载数据

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

  18 # reshape to be [samples][channels][width][height]

  19 X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')

  20 X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')

  21

  22 # normalize inputs from 0-255 to 0-1

  23 X_train = X_train / 255

  24 X_test = X_test / 255

  25

  26 # one hot encode outputs

  27 y_train = np_utils.to_categorical(y_train)

  28 y_test = np_utils.to_categorical(y_test)

  29 num_classes = y_test.shape[1]

  30

  31 # define a simple CNN model

  32 def baseline_model():

  33 # create model

  34 model = Sequential()

  35 model.add(Convolution2D(32, 5, 5, border_mode='valid', input_shape=(1, 28, 28), activation='relu'))

  36 model.add(MaxPooling2D(pool_size=(2, 2)))

  37 model.add(Dropout(0.2))

  38 model.add(Flatten())

  39 model.add(Dense(128, activation='relu'))

  40 model.add(Dense(num_classes, activation='softmax'))

  41 # Compile model

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

  43 return model

  44

  45 # build the model

  46 model = baseline_model()

  47

  48 # Fit the model

  49 model.fit(X_train, y_train, validation_data=http://www.netofthings.cn/JieJueFangAn/2016-07/(X_test, y_test), nb_epoch=10, batch_size=128, verbose=2)

  50

  51 # Final evaluation of the model

  52 scores = model.evaluate(X_test, y_test, verbose=0)

  53 print("CNN Error: %.2f%%" % (100-scores[1]*100))

  结果:

  1 ____________________________________________________________________________________________________

  2 Layer (type) Output Shape Param # Connected to

  3 ====================================================================================================

  4 convolution2d_1 (Convolution2D) (None, 32, 24, 24) 832 convolution2d_input_1[0][0]

  5 ____________________________________________________________________________________________________

  6 maxpooling2d_1 (MaxPooling2D) (None, 32, 12, 12) 0 convolution2d_1[0][0]

  7 ____________________________________________________________________________________________________

  8 dropout_1 (Dropout) (None, 32, 12, 12) 0 maxpooling2d_1[0][0]

  9 ____________________________________________________________________________________________________

  10 flatten_1 (Flatten) (None, 4608) 0 dropout_1[0][0]

  11 ____________________________________________________________________________________________________

  12 dense_1 (Dense) (None, 128) 589952 flatten_1[0][0]

  13 ____________________________________________________________________________________________________

  14 dense_2 (Dense) (None, 10) 1290 dense_1[0][0]

  15 ====================================================================================================

  16 Total params: 592074

  17 ____________________________________________________________________________________________________

  18 Train on 60000 samples, validate on 10000 samples

  19 Epoch 1/10

  20 32s - loss: 0.2412 - acc: 0.9318 - val_loss: 0.0754 - val_acc: 0.9766

  21 Epoch 2/10

  22 32s - loss: 0.0726 - acc: 0.9781 - val_loss: 0.0534 - val_acc: 0.9829

  23 Epoch 3/10

  24 32s - loss: 0.0497 - acc: 0.9852 - val_loss: 0.0391 - val_acc: 0.9858

  25 Epoch 4/10

  26 32s - loss: 0.0413 - acc: 0.9870 - val_loss: 0.0432 - val_acc: 0.9854

  27 Epoch 5/10

  28 34s - loss: 0.0323 - acc: 0.9897 - val_loss: 0.0375 - val_acc: 0.9869

  29 Epoch 6/10

  30 36s - loss: 0.0281 - acc: 0.9909 - val_loss: 0.0424 - val_acc: 0.9864