天天看點

讀書筆記(一) Keras MNIST手寫數字識别資料

《TensorFlow+Keras深度學習人工智能實踐應用》讀書筆記

選擇MNIST手寫資料識别資料集是因為其資料量不多,而且是單色的圖像,比較簡單,很适合自己這種初學者用來練習建立模型、訓練、預測。

MNIST資料集共有資料項60000項、測試資料10000項。MNIST資料集中的每一項資料都由images(數字圖像)與label(真實的數字)所組成。

讀書筆記(一) Keras MNIST手寫數字識别資料

一、下載下傳MNIST資料集

  1. 導入Kears及相關子產品
import numpy as np        //導入numpy子產品,numpy支援維數組與矩陣運算
import pandas as pd       
from keras.utils import np_utils     //導入keras.utils是為了後續要将label标簽轉換為One-Hot Encoding(一位有效編碼)
np.random.seed(10)      //設定seed可以産生的随機資料
           

運作結果會顯示

Using Tensorflow backend

表示Keras自動以TensorFlow作為Backend。

  1. 導入Keras子產品

    由于Keras已經提供了現成的子產品可以幫助我們下載下傳并讀取MNIST資料,是以先導入MNIST子產品。

from keras.datasets import mnist
           
  1. 第一次進行MNIST資料的下載下傳
(x_train_image, y_train_label),\
(x_test_image, y_test_label) = mnist.load_data()
           

第一次執行mnist.load()方法時,程式會檢查使用者目錄下是否有MNIST資料集,如果沒有,就會下載下傳檔案,是以運作時間比較長。

  1. 檢視MNIST資料
print('train data=',len(x_train_image))
print('test data=',len(x_test_image))
           

運作結果為train data=60000,test data=10000

即資料分為兩部分:train訓練資料60000項,test測試資料10000項。

二、檢視訓練資料

  1. 訓練資料是由images與labels組成的
print('x_train_image:',x_train_image.shape)
print('y_train_label:',y_train_label.shape)
           

運作結果為x_train_image:(60000,28,28) y_train_label:(60000,)

image與label共60000項,image是單色的數字圖像,label是數字圖像的真實值。

  1. 定義plot_image函數顯示數字圖像

    為了能夠顯示images數字圖像,我們建立下列plot_image函數:

import matplotlib.pyplot as plt
def plot_image(image):
    fig = plt.gcf()
    fig.set_size_inches(2,2)    //設定顯示圖形的大小
    plt.imshow(image, cmap='binary')   //使用plt.imshow顯示圖形,傳入參數image是28x28的圖形,cmap參數設定為binary,以黑白灰階顯示
    plt.show()    //開始繪圖
           
  1. 執行plot_image函數檢視第0個數字圖像

    程式調用

    plot_image(x_train_image[0])

    讀書筆記(一) Keras MNIST手寫數字識别資料
  2. 檢視第0項label資料

運作結果為5

第0項label資料是第0個數字圖像的真實值,是以是5。

三、檢視多項訓練資料

  1. 建立plot_images_labels_prediction()函數

    建立下列函數友善我們檢視數字圖形、真實的數字與預測結果。

import matplotlib.pyplot as plt
def plot_images_labels_prediction(images,labels,prediction,idx,num=10):
//images(數字圖像)、labels(真實值)、prediction(預測結果)、idx(開始顯示的資料index)、num(要顯示的資料項數,預設是10,不超過25)
    fig = plt.gcf()       
    fig.set_size_inches(12,14)      //設定圖形的大小
    if num>25: num=25   //如果要顯示的資料項數大于25,就設定為25,以免發生錯誤
    for i in range(0,num):    //畫出num個數字圖形
        ax=plt.subplot(5,5,1+i)     //建立subgraph子圖形為5行5列
        ax.imshow(images[idx],cmap='binary')   //畫出subgraph子圖形
        title="label="+str(labels[idx])    //設定子圖形标簽title,顯示标簽字段
        if len(prediction)>0:       //如果傳入了預測結果
            title+=",prediction="+str(prediction[idx])    //标題
            
        ax.set_title(title,fontsize=10)     //設定子圖形的标題
        ax.set_xticks([]);ax.set_yticks([])    //設定不顯示刻度
        idx+=1    //讀取下一項
    plt.show      //開始畫圖
           
  1. 檢視訓練資料的前10項資料

    執行下列函數顯示前10項訓練資料。目前還沒有預測結果(prediction),是以傳入空list[],從第0項資料開始一直顯示到第9項資料。

讀書筆記(一) Keras MNIST手寫數字識别資料

3. 檢視test測試資料

print('x_test_image:',x_test_image.shape)
print('y_test_label:',y_test_label.shape)
           

運作結果:x_test_image: (10000, 28, 28)

y_test_label: (10000,)

4.顯示test測試資料

執行下列函數,顯示前10項測試資料

讀書筆記(一) Keras MNIST手寫數字識别資料

四、多層感覺器模型預處理

1、features資料預處理

feature(數字圖像特征)資料預處理可分為下列兩個步驟:
  • 将原本28x28的數字圖像以reshape轉換為一維的向量,其長度是784,并且轉換為Float
  • 數字圖像image數字标準化
  1. 檢視image的shape

    檢視每一個數字圖像的shape是28x28

print('x_train_image:',x_train_image.shape)
print('y_train_label:',y_train_label.shape)
           

運作結果:x_train_image: (60000, 28, 28)

y_train_label: (60000,)

  1. 将image以reshape轉換

    将原本28x28的二維數字圖像以reshape轉換為一維的向量,再以astype轉換為Float,共784個浮點數

x_Train = x_train_image.reshape(60000, 784).astype('float32')
x_Test = X_test_image.reshape(10000, 784).astype('float32')
           
  1. 檢視轉換為一維向量的shape

    檢視每一個數字圖像是784個浮點數

print('x_train:',x_Train.shape)
print('x_test:',x_Test.shape)
           

運作結果:x_train: (60000, 784)

x_test: (10000, 784)

  1. 檢視images圖像的内容

    檢視images第0項的内容

    x_train_image[0]

    讀書筆記(一) Keras MNIST手寫數字識别資料
    根據執行結果,大部分都是0,少部分是數字。每一個數字都是從0到255的值,代表圖形每一個點灰階的深淺
  2. 将數字圖像images的數字标準化

    images的數字标準化可以提高後續訓練模型的準确率,是以images的數字都是從0到255的值,是以最簡單的标準化方式是除以255

x_Train_normalize = x_Train/255
x_Test_normalize = x_Test/255
           
  1. 檢視數字圖像images數字标準化後的結果

    x_Train_normalize[0]

    讀書筆記(一) Keras MNIST手寫數字識别資料

2、label資料預處理

label(數字圖像真實的值)标簽字段原本是0~9的數字,必須以One-Hot Encoding(一位有效編碼)轉換為10個0或1的組合,例如數字7經過One-Hot Encoding轉換後是0000000100,正好對應輸出層的10個神經元。

  1. 檢視原本的label标簽字段

    檢視訓練資料label标簽字段的前5項訓練資料

    y_train_label[:5]

    運作結果:array([5, 0, 4, 1, 9], dtype=uint8)
  2. label标簽字段進行One-Hot-Encoding轉換
y_TrainOneHot = np_utils.to_categorical(y_train_label)   
y_TestOneHot = np_utils.to_categorical(y_test_label)
           
  1. 檢視進行One-Hot-Encoding轉換之後的label标簽字段

    y_TrainOneHot[:5]

    讀書筆記(一) Keras MNIST手寫數字識别資料

繼續閱讀