Keras实例之手写数字识别

2017年9月5日 - 花瓣数据

导入相关模型

In [18]:
import numpy as np
# 导入keras模型
from keras.models import Sequential
# 导入keras网络层
from keras.layers import Dense,Dropout,Activation,Flatten
from keras.layers import Convolution2D,MaxPooling2D,Conv2D
# 导入numpy的实用工具
from keras.utils import np_utils
# 导入MNIST数据集
from keras.datasets import mnist
import matplotlib.pyplot as plt
%matplotlib inline

分割训练集、测试集

In [2]:
(X_train,y_train),(X_test,y_test) = mnist.load_data()

查看数据集形状

In [3]:
X_train.shape
Out[3]:
(60000, 28, 28)

查看图片的样子

In [4]:
plt.imshow(X_train[2])
Out[4]:
<matplotlib.image.AxesImage at 0x24ffa4b3eb8>

修改数据形状

In [5]:
X_train = X_train.reshape(X_train.shape[0],28,28,1)
X_test = X_test.reshape(X_test.shape[0],28,28,1)
In [6]:
X_train.shape
Out[6]:
(60000, 28, 28, 1)

二值化数据

In [7]:
# 数值转换
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')

X_train /= 255
X_test /= 255

查看部分数据

In [8]:
y_train.shape
Out[8]:
(60000,)
In [9]:
y_train[:10]
Out[9]:
array([5, 0, 4, 1, 9, 2, 1, 3, 1, 4], dtype=uint8)

将分类向量值转换为矩阵形式

In [10]:
y_train = np_utils.to_categorical(y_train,10)
y_test = np_utils.to_categorical(y_test,10)
In [11]:
y_train.shape
Out[11]:
(60000, 10)
In [12]:
y_train[:10]
Out[12]:
array([[ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.]])

定义模型

In [13]:
# 定义模型
model = Sequential()

为模型添加网络层

In [14]:
model.add(Conv2D(32,3,3,activation='relu',input_shape=(28,28,1)))
model.add(Conv2D(32,3,3,activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(128,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10,activation='softmax'))
c:\users\win10\appdata\local\programs\python\python35\lib\site-packages\ipykernel_launcher.py:1: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(32, (3, 3), input_shape=(28, 28, 1..., activation="relu")`
  """Entry point for launching an IPython kernel.
c:\users\win10\appdata\local\programs\python\python35\lib\site-packages\ipykernel_launcher.py:2: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(32, (3, 3), activation="relu")`
  

编译模型

In [15]:
# 编译模型
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])

训练模型

In [16]:
# 训练模型
model.fit(X_train,y_train,batch_size=32,epochs=10,verbose=1)
Epoch 1/10
60000/60000 [==============================] - 155s - loss: 0.1945 - acc: 0.9409   
Epoch 2/10
60000/60000 [==============================] - 153s - loss: 0.0847 - acc: 0.9743   
Epoch 3/10
60000/60000 [==============================] - 149s - loss: 0.0634 - acc: 0.9810   
Epoch 4/10
60000/60000 [==============================] - 154s - loss: 0.0530 - acc: 0.9834   
Epoch 5/10
60000/60000 [==============================] - 145s - loss: 0.0463 - acc: 0.9856   
Epoch 6/10
60000/60000 [==============================] - 142s - loss: 0.0386 - acc: 0.9874   
Epoch 7/10
60000/60000 [==============================] - 140s - loss: 0.0349 - acc: 0.9887   
Epoch 8/10
60000/60000 [==============================] - 146s - loss: 0.0305 - acc: 0.9903   
Epoch 9/10
60000/60000 [==============================] - 148s - loss: 0.0297 - acc: 0.9904   
Epoch 10/10
60000/60000 [==============================] - 153s - loss: 0.0270 - acc: 0.9916   
Out[16]:
<keras.callbacks.History at 0x24ffa4be940>

评估模型

In [17]:
# 评估模型
model.evaluate(X_test,y_test,verbose=0)
Out[17]:
[0.025390734457755481, 0.99270000000000003]