07 訓練Tensorflow識別手寫數字


    打開Python Shell,輸入以下代碼:

 1 import tensorflow as tf
 2 from tensorflow.examples.tutorials.mnist import input_data
 3 
 4 # 獲取數據(如果存在就讀取,不存在就下載完再讀取)
 5 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
 6 
 7 # 輸入
 8 x = tf.placeholder("float", [None, 784]) #輸入占位符(每張手寫數字784個像素點)
 9 y_ = tf.placeholder("float", [None,10]) #輸入占位符(這張手寫數字具體代表的值,0-9對應矩陣的10個位置)
10 
11 # 計算分類softmax會將xW+b分成10類,對應0-9
12 W = tf.Variable(tf.zeros([784,10])) #權重
13 b = tf.Variable(tf.zeros([10])) #偏置
14 y = tf.nn.softmax(tf.matmul(x,W) + b) # 輸入矩陣x與權重矩陣W相乘,加上偏置矩陣b,然后求softmax(sigmoid函數升級版,可以分成多類)
15 
16 # 計算偏差和
17 cross_entropy = -tf.reduce_sum(y_*tf.log(y))
18 
19 # 使用梯度下降法(步長0.01),來使偏差和最小
20 train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
21 
22 # 初始化變量
23 init = tf.global_variables_initializer()
24 sess = tf.Session()
25 sess.run(init)
26 
27 for i in range(10): # 訓練10次
28   batch_xs, batch_ys = mnist.train.next_batch(100) # 隨機取100個手寫數字圖片
29   sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # 執行梯度下降算法,輸入值x:batch_xs,輸入值y:batch_ys
30 
31 # 計算訓練精度
32 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
33 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
34 print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) #運行精度圖,x和y_從測試手寫圖片中取值

    執行該段代碼,輸出0.8002。訓練10次得到80.02%的識別准確度,還是可以的。

    說明:由於網絡原因,手寫數字圖片可能無法下載,可以直接下載本人做好的程序,里面已經包含了手寫圖片資源和py腳本。

    鏈接:http://pan.baidu.com/s/1cmYSXK 密碼:va2z

    參考資料:

    1、《面向機器學習初學者的 MNIST 初級教程》:http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html

   

                 

   

   

   

 


免責聲明!

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



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