keras—多層感知器MLP—MNIST手寫數字識別


  一、手寫數字識別

現在就來說說如何使用神經網絡實現手寫數字識別。 在這里我使用mind manager工具繪制了要實現手寫數字識別需要的模塊以及模塊的功能: 
神經網絡思維導圖

其中隱含層節點數量(即神經細胞數量)計算的公式(這只是經驗公式,不一定是最佳值):  

m=n+l−−−−√+am=n+l+a 
m=log2nm=log2⁡n 
m=nl−−√m=nl 
  • m: 隱含層節點數
  • n: 輸入層節點數
  • l:輸出層節點數
  • a:1-10之間的常數

本例子當中:

  • 輸入層節點n:784
  • 輸出層節點:10 (表示數字 0 ~ 9)
  • 隱含層選30個,訓練速度雖然快,但是准確率卻只有91% 左右,如果將這個數字變為100 或是300,其訓練速度回慢一些

    ,但准確率可以提高到93%~94% 左右。

    因為這是使用的MNIST的手寫數字訓練數據,所以它的圖像的分辨率是28 * 28,也就是有784個像素點,其下載地址為:http://yann.lecun.com/exdb/mnist/

    二、查看數據程序

  • 48000作為訓練數據,12000作為驗證數據,10000作為預測數據
  •  1 #coding=utf-8
     2 import numpy as np             #導入模塊,numpy是擴展鏈接庫
     3 import pandas as pd             #類似一個本地的excel,偏向現在的非結構化的數據庫
     4 import tensorflow as tf
     5 import keras
     6 from keras.utils import np_utils
     7 np.random.seed(10)            #設置seed可以產生的隨機數據
     8 from keras.datasets import mnist  #導入模塊,下載讀取mnist數據
     9 (x_train_image,y_train_label),\
    10 (x_test_image,y_test_label)=mnist.load_data() #下載讀取mnist數據
    11 print('train data=',len(x_train_image))
    12 print('test data=',len(x_test_image))
    13 print('x_train_image:',x_train_image.shape)
    14 print('y_train_label:',y_train_label.shape) #查看數據
    15 import matplotlib.pyplot as plt
    16 def plot_image(image):                      #定義顯示函數
    17     fig=plt.gcf()
    18     fig.set_size_inches(2,2)           #設置顯示圖形的大小
    19     plt.imshow(image,cmap='binary')    #黑白灰度顯示
    20     plt.show()                         #開始畫圖
    21 y_train_label[0]                       #查看第0項label數據
    22 import matplotlib.pyplot as plt
    23 def plot_image_labels_prediction(image,lables,prediction,idx,num=10):#顯示多項數據
    24     fig=plt.gcf()
    25     fig.set_size_inches(12,14)        #設置顯示圖形的大小
    26     if num>25:num=25
    27     for i in range(0,num):            #畫出num個數字圖形
    28         ax=plt.subplot(5,5,i+1)       #建立subplot字圖形為5行5列
    29         ax.imshow(image[idx],cmap='binary')   #畫出subgraph
    30         title="lable="+str(lables[idx])       #設置字圖形title,顯示標簽字段
    31         if len(prediction)>0:                 #如果傳入了預測結果
    32             title+=",predict="+str(prediction[idx])     #標題
    33         ax.set_title(title,fontsize=10)                 #設置字圖形的標題
    34         ax.set_xticks([]);ax.set_yticks([])             #設置不顯示刻度
    35         idx+=1                               #讀取下一項
    36     plt.show()
    37 plot_image_labels_prediction(x_train_image,y_train_label,[],0,10)#查看訓練數據前10項
    38 plot_image_labels_prediction(x_test_image,y_test_label,[],0,10)  #查看測試數據前10項

      

    三、運行結果



  • 四、訓練預測識別程序

  •  1 #coding=utf-8
     2 #1.數據預處理
     3 import numpy as np             #導入模塊,numpy是擴展鏈接庫
     4 import pandas as pd
     5 import tensorflow
     6 import keras
     7 from keras.utils import np_utils
     8 np.random.seed(10)            #設置seed可以產生的隨機數據
     9 from keras.datasets import mnist  #導入模塊,下載讀取mnist數據
    10 (x_train_image,y_train_label),\
    11 (x_test_image,y_test_label)=mnist.load_data() #下載讀取mnist數據
    12 print('train data=',len(x_train_image))
    13 print('test data=',len(x_test_image))
    14 print('x_train_image:',x_train_image.shape)
    15 print('y_train_label:',y_train_label.shape)
    16 import matplotlib.pyplot as plt
    17 def plot_image(image):
    18     fig=plt.gcf()
    19     fig.set_size_inches(2,2)
    20     plt.imshow(image,cmap='binary')
    21     plt.show()
    22 y_train_label[0]
    23 import matplotlib.pyplot as plt
    24 def plot_image_labels_prediction(image,lables,prediction,idx,num=10):
    25     fig=plt.gcf()
    26     fig.set_size_inches(12,14)
    27     if num>25:num=25
    28     for i in range(0,num):
    29         ax=plt.subplot(5,5,i+1)
    30         ax.imshow(image[idx],cmap='binary')
    31         title="lable="+str(lables[idx])
    32         if len(prediction)>0:
    33             title+=",predict="+str(prediction[idx])
    34         ax.set_title(title,fontsize=10)
    35         ax.set_xticks([]);ax.set_yticks([])
    36         idx+=1
    37     plt.show()
    38 plot_image_labels_prediction(x_train_image,y_train_label,[],0,10)
    39 plot_image_labels_prediction(x_test_image,y_test_label,[],0,10)
    40 x_Train=x_train_image.reshape(60000,784).astype('float32') #以reshape轉化成784個float
    41 x_Test=x_test_image.reshape(10000,784).astype('float32')
    42 x_Train_normalize=x_Train/255    #將features標准化
    43 x_Test_normalize=x_Test/255
    44 y_Train_OneHot=np_utils.to_categorical(y_train_label)#將訓練數據和測試數據的label進行one-hot encoding轉化
    45 y_Test_OneHot=np_utils.to_categorical(y_test_label)
    46 #2.建立模型
    47 from keras.models import Sequential #可以通過Sequential模型傳遞一個layer的list來構造該模型,序慣模型是多個網絡層的線性堆疊
    48 from keras.layers import Dense    #全連接層
    49 model=Sequential()
    50 #建立輸入層、隱藏層
    51 model.add(Dense(units=256,
    52                 input_dim=784,
    53                 kernel_initializer='normal',
    54                 activation='relu'))
    55 #建立輸出層
    56 model.add(Dense(units=10,
    57                 kernel_initializer='normal',
    58                 activation='softmax'))
    59 print(model.summary())
    60 #3、進行訓練
    61 #對訓練模型進行設置,損失函數、優化器、權值
    62 model.compile(loss='categorical_crossentropy',
    63               optimizer='adam',metrics=['accuracy'])
    64 # 設置訓練與驗證數據比例,80%訓練,20%測試,執行10個訓練周期,每一個周期200個數據,顯示訓練過程2次
    65 train_history=model.fit(x=x_Train_normalize,
    66                         y=y_Train_OneHot,validation_split=0.2,
    67                         epochs=10,batch_size=200,verbose=2)
    68 #顯示訓練過程
    69 import matplotlib.pyplot as plt
    70 def show_train_history(train_history,train,validation):
    71     plt.plot(train_history.history[train])
    72     plt.plot(train_history.history[validation])
    73     plt.title('Train History')
    74     plt.ylabel(train)
    75     plt.xlabel('Epoch')
    76     plt.legend(['train','validation'],loc='upper left')    #顯示左上角標簽
    77     plt.show()
    78 show_train_history(train_history,'acc','val_acc')   #畫出准確率評估結果
    79 show_train_history(train_history,'loss','val_loss') #畫出誤差執行結果
    80 #以測試數據評估模型准確率
    81 scores=model.evaluate(x_Test_normalize,y_Test_OneHot)   #創建變量存儲評估后的准確率數據,(特征值,真實值)
    82 print()
    83 print('accuracy',scores[1])
    84 #進行預測
    85 prediction=model.predict_classes(x_Test)
    86 prediction
    87 plot_image_labels_prediction(x_test_image,y_test_label,prediction,idx=340)

     

     
  • 五、運行結果

  •  

     

     

  • 評估模型准確率結果為:0.9754
  •  

     

  • 預測結果:有一個潦草的5預測錯誤為3
  •  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM