#基于mnist数据集的手写数字识别

#构造了三层全连接层组成的多层感知机,最后一层为输出层

#基于Keras 2.1.1 Tensorflow 1.4.0

代码:

 1 import keras
 2 from keras.datasets import mnist 
 3 from keras.models import Sequential 
 4 from keras.layers import Dense,Dropout
 5 from keras.optimizers import RMSprop
 6 
 7 (x_train,y_train),(x_test,y_test) = mnist.load_data()
 8 #载入数据,第一次运行时会从外部网络下载数据集到对应目录下
 9 print(x_train.shape,y_train.shape)
10 print(x_test.shape,y_test.shape)
11 
12 # import matplotlib.pyplot as plt
13 # im = plt.imshow(x_train[0],cmap='gray')
14 # plt.show()
15 # im2 = plt.imshow(x_train[1],cmap='gray')
16 # plt.show()
17 x_train = x_train.reshape(60000,784)
18 x_test = x_test.reshape(10000,784)
19 x_train = x_train.astype('float32')
20 x_train = x_train.astype('float32')
21 print(x_train.shape)
22 x_train = x_train/255
23 x_test = x_test/255
24 y_train = keras.utils.to_categorical(y_train,10)
25 y_test = keras.utils.to_categorical(y_test,10)
26 
27 model = Sequential()
28 model.add(Dense(512,activation='relu',input_shape=(784,)))
29 model.add(Dropout(0.2))
30 model.add(Dense(512,activation='relu'))
31 model.add(Dropout(0.2))
32 model.add(Dense(10,activation='softmax'))
33 model.summary()
34 model.compile(loss='categorical_crossentropy',optimizer=RMSprop(),metrics=['accuracy'])
35 model.fit(x_train,y_train,batch_size=64,epochs=2,verbose=1,validation_data=(x_test,y_test))
36 score = model.evaluate(x_test,y_test,verbose=1)
37 print('Test loss:',score[0])
38 print('Test accuracy',score[1])

结果:

Test loss: 0.123420921481
Test accuracy 0.9682