TensorFlow 手寫體數字識別
以下資料來源於極客時間學習資料
• 手寫體數字 MNIST 數據集介紹
MNIST 數據集介紹
MNIST 是一套手寫體數字的圖像數據集,包含 60,000 個訓練樣例和 10,000 個測試樣例,
由紐約大學的 Yann LeCun 等人維護。

獲取 MNIST 數據集
MNIST 手寫體數字介紹
MNIST 圖像數據集使用形如[28,28]的二階數組來表示每個手寫體數字,數組中
的每個元素對應一個像素點,即每張圖像大小固定為 28x28 像素。
MNIST 數據集中的圖像都是256階灰度圖,即灰度值 0 表示白色(背景),255 表示
黑色(前景),使用取值為[0,255]的uint8數據類型表示圖像。為了加速訓練,我
們需要做數據規范化,將灰度值縮放為[0,1]的float32數據類型。
下載和讀取 MNIST 數據集
一個曾廣泛使用(如 chapter-2/basic-model.ipynb),如今被廢棄的(deprecated)方法:

tf.contrib.learn 模塊已被廢棄
需要注意的是,tf.contrib.learn 整個模塊均已被廢棄:

使用 Keras 加載 MNIST 數據集
tf.kera.datasets.mnist.load_data(path=‘mnist.npz’)
Arguments:
• path:本地緩存 MNIST 數據集(mnist.npz)的相對路徑(~/.keras/datasets)
Returns:
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
MNIST 數據集 樣例可視化

• MNIST Softmax 網絡介紹
感知機模型
1957年,受 Warren McCulloch 和 Walter Pitts 在神經元建模方面工作的啟發,心理學家 Frank
Rosenblatt 參考大腦中神經元信息傳遞信號的工作機制,發明了神經感知機模型
Perceptron 。
神經網絡
在機器學習和認知科學領域,人工神經網絡(ANN),簡稱神經網絡(NN)是一種模仿生物
神經網絡(動物的中樞神經系統,特別是大腦)的結構和功能的數學模型或計算模型,用於
對函數進行估計或近似。神經網絡是多層神經元的連接,上一層神經元的輸出,作為下一層
神經元的輸入。
線性不可分
激活函數(Activation Function)
為了實現神經網絡的非線性建模能力,解決一些線性不可分的問題,我們通常使用激活函數
來引入非線性因素。激活函數都采用非線性函數,常用的有Sigmoid、tanh、ReLU等。
全連接層( fully connected layers,FC )
全連接層是一種對輸入數據直接做線性變換的線性計算層。它是神經網絡中最常用的一種層,
用於學習輸出數據和輸入數據之間的變換關系。全連接層可作為特征提取層使用,在學習特
征的同時實現特征融合;也可作為最終的分類層使用,其輸出神經元的值代表了每個輸出類
別的概率。
前向傳播
簡化形式:
后向傳播( Back Propagation, BP)
BP算法的基本思想是通過損失函數
對模型參數進行求導,並根據復合函數求導常用的
“鏈式法則” 將不同層的模型參
數的梯度聯系起來,使得計算所有模型參數的梯度更簡單。BP算法的思想早在 1960s 就被提出來了。 直到1986年,
David Rumelhart 和 Geoffrey Hinton 等人發表了一篇后來成為經典的論文,清晰地描述了BP算法的框架,才使得BP算
法真正流行起來,並帶來了神經網絡在80年代的輝煌。
MNIST Softmax 網絡
將表示手寫體數字的形如 [784] 的一維向量作為輸入;中間定義2層 512 個神經元的隱藏層,具
備一定模型復雜度,足以識別手寫體數字;最后定義1層10個神經元的全聯接層,用於輸出10
個不同類別的“概率”。
Softmax :
• 實戰 MNIST Softmax 網絡
MNIST Softmax 網絡層
代碼:
加載 MNIST 數據集 from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data('mnist/mnist.npz') print(x_train.shape, type(x_train)) print(y_train.shape, type(y_train)) ''' (60000, 28, 28) <class 'numpy.ndarray'> (60000,) <class 'numpy.ndarray'> ''' 數據處理:規范化 # 將圖像本身從[28,28]轉換為[784,] X_train = x_train.reshape(60000, 784) X_test = x_test.reshape(10000, 784) print(X_train.shape, type(X_train)) print(X_test.shape, type(X_test)) ''' (60000, 784) <class 'numpy.ndarray'> (10000, 784) <class 'numpy.ndarray'> ''' # 將數據類型轉換為float32 X_train = X_train.astype('float32') X_test = X_test.astype('float32') # 數據歸一化 X_train /= 255 X_test /= 255 統計訓練數據中各標簽數量 import numpy as np import matplotlib.pyplot as plt label, count = np.unique(y_train, return_counts=True) print(label, count) ''' [0 1 2 3 4 5 6 7 8 9] [5923 6742 5958 6131 5842 5421 5918 6265 5851 5949] ''' fig = plt.figure() plt.bar(label, count, width = 0.7, align='center') plt.title("Label Distribution") plt.xlabel("Label") plt.ylabel("Count") plt.xticks(label) plt.ylim(0,7500) for a,b in zip(label, count): plt.text(a, b, '%d' % b, ha='center', va='bottom',fontsize=10) plt.show()
數據處理:one-hot 編碼

from keras.utils import np_utils n_classes = 10 print("Shape before one-hot encoding: ", y_train.shape) Y_train = np_utils.to_categorical(y_train, n_classes) print("Shape after one-hot encoding: ", Y_train.shape) Y_test = np_utils.to_categorical(y_test, n_classes) ''' Shape before one-hot encoding: (60000,) Shape after one-hot encoding: (60000, 10) ''' print(y_train[0]) print(Y_train[0]) ''' 5 [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] ''' 使用 Keras sequential model 定義神經網絡 softmax 網絡層from keras.models import Sequential from keras.layers.core import Dense, Activation model = Sequential() model.add(Dense(512, input_shape=(784,))) model.add(Activation('relu')) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('softmax')) 編譯模型
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')
訓練模型,並將指標保存到 history 中
history = model.fit(X_train, Y_train, batch_size=128, epochs=5, verbose=2, validation_data=(X_test, Y_test)) ''' Train on 60000 samples, validate on 10000 samples Epoch 1/5 - 5s - loss: 0.2240 - acc: 0.9331 - val_loss: 0.1050 - val_acc: 0.9668 Epoch 2/5 - 5s - loss: 0.0794 - acc: 0.9753 - val_loss: 0.0796 - val_acc: 0.9756 Epoch 3/5 - 5s - loss: 0.0494 - acc: 0.9847 - val_loss: 0.0714 - val_acc: 0.9774 Epoch 4/5 - 6s - loss: 0.0353 - acc: 0.9886 - val_loss: 0.0906 - val_acc: 0.9731 Epoch 5/5 - 6s - loss: 0.0277 - acc: 0.9909 - val_loss: 0.0735 - val_acc: 0.9782 ''' 可視化指標 fig = plt.figure() plt.subplot(2,1,1) plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('Model Accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='lower right') plt.subplot(2,1,2) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper right') plt.tight_layout() plt.show()
保存模型
import os import tensorflow.gfile as gfile save_dir = "./mnist/model/" if gfile.Exists(save_dir): gfile.DeleteRecursively(save_dir) gfile.MakeDirs(save_dir) model_name = 'keras_mnist.h5' model_path = os.path.join(save_dir, model_name) model.save(model_path) print('Saved trained model at %s ' % model_path) ''' Saved trained model at ./mnist/model/keras_mnist.h5 ''' 加載模型 from keras.models import load_model mnist_model = load_model(model_path) 統計模型在測試集上的分類結果 loss_and_metrics = mnist_model.evaluate(X_test, Y_test, verbose=2) print("Test Loss: {}".format(loss_and_metrics[0])) print("Test Accuracy: {}%".format(loss_and_metrics[1]*100)) predicted_classes = mnist_model.predict_classes(X_test) correct_indices = np.nonzero(predicted_classes == y_test)[0] incorrect_indices = np.nonzero(predicted_classes != y_test)[0] print("Classified correctly count: {}".format(len(correct_indices))) print("Classified incorrectly count: {}".format(len(incorrect_indices))) ''' Test Loss: 0.07348056956584333 Test Accuracy: 97.82% Classified correctly count: 9782 Classified incorrectly count: 218 '''
• MNIST CNN 網絡介紹
CNN 簡介
CNN模型是一種以卷積為核心的前饋神經網絡模型。 20世紀60年代,Hubel和Wiesel在研究貓腦
皮層中用於局部敏感和方向選擇的神經元時發現其獨特的網絡結構可以有效地降低反饋神經網
絡的復雜性,繼而提出了卷積神經網絡(ConvoluTIonal Neural Networks,簡稱CNN)。
卷積(Convolution)
卷積是分析數學中的一種基礎運算,其中對輸入數據做運算時所用到的函數稱為卷積核。
設:f(x), g(x)是R上的兩個可積函數,作積分:
可以證明,關於幾乎所有的實數x,上述積分是存在的。這樣,隨着x的不同取值,這個積分就
定義了一個如下的新函數,稱為函數f與g的卷積
卷積層(Convolutional Layer, conv)
卷積層是使用一系列卷積核與多通道輸入數據做卷積的線性計算層。卷積層的提出是為了利用
輸入數據(如圖像)中特征的局域性和位置無關性來降低整個模型的參數量。卷積運算過程與
圖像處理算法中常用的空間濾波是類似的。因此,卷積常常被通俗地理解為一種“濾波”過程,
卷積核與輸入數據作用之后得到了“濾波”后的圖像,從而提取出了圖像的特征。
池化層(Pooling)
池化層是用於縮小數據規模的一種非線性計算層。為了降低特征維度,我們需要對輸入數據進
行采樣,具體做法是在一個或者多個卷積層后增加一個池化層。池化層由三個參數決定:(1)
池化類型,一般有最大池化和平均池化兩種;(2)池化核的大小k;(3)池化核的滑動間隔s。
下圖給出了一種的池化層示例。其中,2x2大小的池化窗口以2個單位距離在輸入數據上滑動。
在池化層中,如果采用最大池化類型,則輸出為輸入窗口內四個值的最大值;如采用平均池化
類型,則輸出為輸入窗口內四個值的平均值

Dropout 層
Dropout 是常用的一種正則化方法,Dropout層是一種正則化層。全連接層參數量非常龐大(占
據了CNN模型參數量的80%~90%左右),發生過擬合問題的風險比較高,所以我們通常需要
一些正則化方法訓練帶有全連接層的CNN模型。在每次迭代訓練時,將神經元以一定的概率值
暫時隨機丟棄,即在當前迭代中不參與訓練。
Flatten
將卷積和池化后提取的特征攤平后輸入全連接網絡,這里與 MNIST softmax 網絡的輸入層類似。
MNIST CNN 輸入特征,MNIST Softmax 輸入原圖。

MNIST CNN 示意圖
• 實戰 MNIST CNN 網絡
代碼
加載 MNIST 數據集 from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data('mnist/mnist.npz') print(x_train.shape, type(x_train)) print(y_train.shape, type(y_train)) ''' (60000, 28, 28) <class 'numpy.ndarray'> (60000,) <class 'numpy.ndarray'> ''' 數據處理:規范化
from keras import backend as K img_rows, img_cols = 28, 28 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) print(x_train.shape, type(x_train)) print(x_test.shape, type(x_test)) ''' (60000, 28, 28, 1) <class 'numpy.ndarray'> (10000, 28, 28, 1) <class 'numpy.ndarray'> ''' # 將數據類型轉換為float32 X_train = x_train.astype('float32') X_test = x_test.astype('float32') # 數據歸一化 X_train /= 255 X_test /= 255 print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') ''' 60000 train samples 10000 test samples ''' 統計訓練數據中各標簽數量 import numpy as np import matplotlib.pyplot as plt label, count = np.unique(y_train, return_counts=True) print(label, count) ''' [0 1 2 3 4 5 6 7 8 9] [5923 6742 5958 6131 5842 5421 5918 6265 5851 5949] ''' fig = plt.figure() plt.bar(label, count, width = 0.7, align='center') plt.title("Label Distribution") plt.xlabel("Label") plt.ylabel("Count") plt.xticks(label) plt.ylim(0,7500) for a,b in zip(label, count): plt.text(a, b, '%d' % b, ha='center', va='bottom',fontsize=10) plt.show()
數據處理:one-hot 編碼

from keras.utils import np_utils n_classes = 10 print("Shape before one-hot encoding: ", y_train.shape) Y_train = np_utils.to_categorical(y_train, n_classes) print("Shape after one-hot encoding: ", Y_train.shape) Y_test = np_utils.to_categorical(y_test, n_classes) ''' Shape before one-hot encoding: (60000,) Shape after one-hot encoding: (60000, 10) ''' print(y_train[0]) print(Y_train[0]) ''' 5 [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] ''' 使用 Keras sequential model 定義 MNIST CNN 網絡 from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D model = Sequential() ## Feature Extraction # 第1層卷積,32個3x3的卷積核 ,激活函數使用 relu model.add(Conv2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) # 第2層卷積,64個3x3的卷積核,激活函數使用 relu model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu')) # 最大池化層,池化窗口 2x2 model.add(MaxPooling2D(pool_size=(2, 2))) # Dropout 25% 的輸入神經元 model.add(Dropout(0.25)) # 將 Pooled feature map 攤平后輸入全連接網絡 model.add(Flatten()) ## Classification # 全聯接層 model.add(Dense(128, activation='relu')) # Dropout 50% 的輸入神經元 model.add(Dropout(0.5)) # 使用 softmax 激活函數做多分類,輸出各數字的概率 model.add(Dense(n_classes, activation='softmax')) 查看 MNIST CNN 模型網絡結構 model.summary() '''_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 26, 26, 32) 320 _________________________________________________________________ conv2d_2 (Conv2D) (None, 24, 24, 64) 18496 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 12, 12, 64) 0 _________________________________________________________________ dropout_1 (Dropout) (None, 12, 12, 64) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 9216) 0 _________________________________________________________________ dense_1 (Dense) (None, 128) 1179776 _________________________________________________________________ dropout_2 (Dropout) (None, 128) 0 _________________________________________________________________ dense_2 (Dense) (None, 10) 1290 ================================================================= Total params: 1,199,882 Trainable params: 1,199,882 Non-trainable params: 0 _________________________________________________________________ ''' for layer in model.layers: print(layer.get_output_at(0).get_shape().as_list()) ''' [None, 26, 26, 32] [None, 24, 24, 64] [None, 12, 12, 64] [None, 12, 12, 64] [None, None] [None, 128] [None, 128] [None, 10] ''' 編譯模型 model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam') 訓練模型,並將指標保存到 history 中
history = model.fit(X_train, Y_train, batch_size=128, epochs=5, verbose=2, validation_data=(X_test, Y_test)) ''' Train on 60000 samples, validate on 10000 samples Epoch 1/5 - 64s - loss: 0.2603 - acc: 0.9205 - val_loss: 0.0581 - val_acc: 0.9825 Epoch 2/5 - 68s - loss: 0.0924 - acc: 0.9729 - val_loss: 0.0420 - val_acc: 0.9855 Epoch 3/5 - 69s - loss: 0.0714 - acc: 0.9786 - val_loss: 0.0325 - val_acc: 0.9891 Epoch 4/5 - 68s - loss: 0.0582 - acc: 0.9820 - val_loss: 0.0322 - val_acc: 0.9889 Epoch 5/5 - 68s - loss: 0.0497 - acc: 0.9849 - val_loss: 0.0310 - val_acc: 0.9900 ''' 可視化指標 fig = plt.figure() plt.subplot(2,1,1) plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('Model Accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='lower right') plt.subplot(2,1,2) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper right') plt.tight_layout() plt.show()
保存模型

import os import tensorflow.gfile as gfile save_dir = "./mnist/model/" if gfile.Exists(save_dir): gfile.DeleteRecursively(save_dir) gfile.MakeDirs(save_dir) model_name = 'keras_mnist.h5' model_path = os.path.join(save_dir, model_name) model.save(model_path) print('Saved trained model at %s ' % model_path) ''' Saved trained model at ./mnist/model/keras_mnist.h5 ''' 加載模型 from keras.models import load_model mnist_model = load_model(model_path) 統計模型在測試集上的分類結果 loss_and_metrics = mnist_model.evaluate(X_test, Y_test, verbose=2) print("Test Loss: {}".format(loss_and_metrics[0])) print("Test Accuracy: {}%".format(loss_and_metrics[1]*100)) predicted_classes = mnist_model.predict_classes(X_test) correct_indices = np.nonzero(predicted_classes == y_test)[0] # incorrect_indices = np.nonzero(predicted_classes != y_test)[0] incorrect_indices = np.nonzero(predicted_classes != y_test) print("Classified correctly count: {}".format(len(correct_indices))) # print("Classified incorrectly count: {}".format(len(incorrect_indices))) print("Classified incorrectly count: {}".format(incorrect_indices)) type(incorrect_indices) ''' Test Loss: 0.03102766538519645 Test Accuracy: 99.0% Classified correctly count: 9900 Classified incorrectly count: (array([ 321, 582, 659, 674, 717, 740, 947, 1014, 1033, 1039, 1112, 1182, 1226, 1232, 1242, 1260, 1319, 1326, 1393, 1414, 1527, 1530, 1549, 1709, 1717, 1737, 1790, 1878, 1901, 2035, 2040, 2043, 2109, 2118, 2130, 2135, 2293, 2387, 2454, 2462, 2597, 2630, 2654, 2896, 2921, 2939, 2995, 3005, 3030, 3073, 3422, 3503, 3520, 3558, 3597, 3727, 3767, 3780, 3808, 3853, 3906, 3941, 3968, 4075, 4176, 4238, 4248, 4256, 4294, 4497, 4536, 4571, 4639, 4740, 4761, 4807, 4860, 4956, 5246, 5749, 5937, 5955, 6071, 6091, 6166, 6576, 6597, 6625, 6651, 6783, 8527, 9009, 9015, 9019, 9024, 9530, 9664, 9729, 9770, 9982], dtype=int64),) ''' Out[25]: tuple