1. 程式人生 > >學習筆記TF024:TensorFlow實現Softmax Regression(回歸)識別手寫數字

學習筆記TF024:TensorFlow實現Softmax Regression(回歸)識別手寫數字

概率 none nump 簡單 測試數據 python dice bat desc

TensorFlow實現Softmax Regression(回歸)識別手寫數字。MNIST(Mixed National Institute of Standards and Technology database),簡單機器視覺數據集,28X28像素手寫數字,只有灰度值信息,空白部分為0,筆跡根據顏色深淺取[0, 1], 784維,丟棄二維空間信息,目標分0~9共10類。數據加載,data.read_data_sets, 55000個樣本,測試集10000樣本,驗證集5000樣本。樣本標註信息,label,10維向量,10種類one-hot編碼。訓練集訓練模型,驗證集檢驗效果,測試集評測模型(準確率、召回率、F1-score)。

算法設計,Softmax Regression訓練手寫數字識別分類模型,估算類別概率,取概率最大數字作模型輸出結果。類特征相加,判定類概率。模型學習訓練調整權值。softmax,各類特征計算exp函數,標準化(所有類別輸出概率值為1)。y = softmax(Wx+b)。

NumPy使用C、fortran,調用openblas、mkl矩陣運算庫。TensorFlow密集復雜運算在Python外執行。定義計算圖,運算操作不需要每次把運算完的數據傳回Python,全部在Python外面運行。

import tensor flow as tf,載入TensorFlow庫。less = tf.InteractiveSession(),創建InteractiveSession,註冊為默認session。不同session的數據、運算,相互獨立。x = tf.placeholder(tf.float32, [None,784]),創建Placeholder 接收輸入數據,第一參數數據類型,第二參數代表tensor shape 數據尺寸。None不限條數輸入,每條輸入為784維向量。

tensor存儲數據,一旦使用掉就會消失。Variable在模型訓練叠代中持久化,長期存在,每輪叠代更新。Softmax Regression模型的Variable對象weights、biases 初始化為0。模型訓練自動學習合適值。復雜網絡,初始化方法重要。w = tf.Variable(tf.zeros([784, 10])),784特征維數,10類。Label,one-hot編碼後10維向量。

Softmax Regression算法,y = tf.nn.softmax(tf.matmul(x, W) + b)。tf.nn包含大量神經網絡組件。tf.matmul,矩陣乘法函數。TensorFlow將forward、backward內容自動實現,只要定義好loss,訓練自動求導梯度下降,完成Softmax Regression模型參數自動學習。

定義loss function描述問題模型分類精度。Loss越小,模型分類結果與真實值越小,越精確。模型初始參數全零,產生初始loss。訓練目標是減小loss,找到全局最優或局部最優解。cross-entropy,分類問題常用loss function。y預測概率分布,y‘真實概率分布(Label one-hot編碼),判斷模型對真實概率分布預測準確度。cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))。定義placeholder,輸入真實label。tf.reduce_sum求和,tf.reduce_mean每個batch數據結果求均值。

定義優化算法,隨機梯度下降SGD(Stochastic Gradient Descent)。根據計算圖自動求導,根據反向傳播(Back Propagation)算法訓練,每輪叠代更新參數減小loss。提供封裝優化器,每輪叠代feed數據,TensorFlow在後臺自動補充運算操作(Operation)實現反向傳播和梯度下降。train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)。調用tf.train.GradientDescentOptimizer,設置學習速度0.5,設定優化目標cross-entropy,得到訓練操作train_step。

tf.global_variables_initializer().run()。TensorFlow全局參數初始化器tf.golbal_variables_initializer。

batch_xs,batch_ys = mnist.train.next_batch(100)。訓練操作train_step。每次隨機從訓練集抽取100條樣本構成mini-batch,feed給 placeholder,調用train_step訓練樣本。使用小部分樣本訓練,隨機梯度下降,收斂速度更快。每次訓練全部樣本,計算量大,不容易跳出局部最優。

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmzx(y_,1)),驗證模型準確率。tf.argmax從tensor尋找最大值序號,tf.argmax(y,1)求預測數字概率最大,tf.argmax(y_,1)找樣本真實數字類別。tf.equal判斷預測數字類別是否正確,返回計算分類操作是否正確。

accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)),統計全部樣本預測正確度。tf.cast轉化correct_prediction輸出值類型。

print(accuracy.eval({x: mnist.test.images,y_: mnist.test.labels}))。測試數據特征、Label輸入評測流程,計算模型測試集準確率。Softmax Regression MNIST數據分類識別,測試集平均準確率92%左右。

TensorFlow 實現簡單機器算法步驟:
1?定義算法公式,神經網絡forward計算。
2?定義loss,選定優化器,指定優化器優化loss。
3?叠代訓練數據。
4?測試集、驗證集評測準確率。

定義公式只是Computation Graph,只有調用run方法,feed數據,計算才執行。

    from tensorflow.examples.tutorials.mnist import input_data
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    print(mnist.train.images.shape, mnist.train.labels.shape)
    print(mnist.test.images.shape, mnist.test.labels.shape)
    print(mnist.validation.images.shape, mnist.validation.labels.shape)
    import tensorflow as tf
    sess = tf.InteractiveSession()
    x = tf.placeholder(tf.float32, [None, 784])
    W = tf.Variable(tf.zeros([784, 10]))
    b = tf.Variable(tf.zeros([10]))
    y = tf.nn.softmax(tf.matmul(x, W) + b)
    y_ = tf.placeholder(tf.float32, [None, 10])
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
    tf.global_variables_initializer().run()
    for i in range(1000):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        train_step.run({x: batch_xs, y_: batch_ys})
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))


參考資料:
《TensorFlow實踐》

歡迎付費咨詢(150元每小時),我的微信:qingxingfengzi

學習筆記TF024:TensorFlow實現Softmax Regression(回歸)識別手寫數字