連載 | Tensorflow教程一:30行代碼搞定手寫識別

2022-01-01 圖靈機器人

作者簡介:劉子瑛,阿里巴巴作業系統框架專家;CSDN 博客專家。工作十餘年,一直對數學與人工智慧算法相關、新程式語言、新開發方法等相關領域保持濃厚的興趣。樂於通過技術分享促進新技術進步。

連載說明:上周在公眾號內分享劉老師教程後反響很好,所以本次特意轉載劉老師系列教程,逐步引導大家了解Tensorflow深度學習框架,對人工智感興趣的小夥伴可要抓緊收藏學習嘍~

以下為正文

去年買了幾本講tensorflow的書,結果今年看的時候發現有些樣例代碼所用的API已經過時了。看來自己維護一個保持更新的Tensorflow的教程還是有意義的。這是寫這一系列的初心。 


快餐教程系列希望能夠儘可能降低門檻,少講,講透。 


為了讓大家在一開始就看到一個美好的場景,而不是停留在漫長的基礎知識積累上,參考網上的一些教程,我們直接一開始就直接展示用tensorflow實現MNIST手寫識別的例子。然後基礎知識我們再慢慢講。

Tensorflow安裝速成教程


由於Python是跨平臺的語言,所以在各系統上安裝tensorflow都是一件相對比較容易的事情。GPU加速的事情我們後面再說。

Linux平臺安裝tensorflow


我們以Ubuntu 16.04版為例,首先安裝python3和pip3。pip是python的包管理工具。

1sudo apt install python3
2sudo apt install python3-pip

然後就可以通過pip3來安裝tensorflow:

1pip3 install tensorflow 


MacOS安裝tensorflow


建議使用Homebrew來安裝python。

1brew install python3

安裝python3之後,還是通過pip3來安裝tensorflow.

1pip3 install tensorflow 


Windows平臺安裝Tensorflow


Windows平臺上建議通過Anaconda來安裝tensorflow。

然後打開Anaconda Prompt,輸入:

1conda create -n tensorflow pip
2activate tensorflow
3pip install 

這樣就安裝好了Tensorflow。

我們迅速來個例子試下好不好用:

1import tensorflow as tf
2a = tf.constant(1)
3b = tf.constant(2)
4c = a * b
5sess = tf.Session()
6print(sess.run(c))

輸出結果為2. 


Tensorflow顧名思義,是一些Tensor張量的流組成的運算。 


運算需要一個Session來運行。如果print(c)的話,會得到

1Tensor("mul_1:0", shape=(), dtype=int32)

就是說這是一個乘法運算的Tensor,需要通過Session.run()來執行。

入門捷徑:線性回歸


我們首先看一個最簡單的機器學習模型,線性回歸的例子。 


線性回歸的模型就是一個矩陣乘法:

1tf.multiply(X, w)

然後我們通過調用Tensorflow計算梯度下降的函數tf.train.GradientDescentOptimizer來實現優化。 


我們看下這個例子代碼,只有30多行,邏輯還是很清晰的。

例子來自github上大牛的工作:https://github.com/nlintz/TensorFlow-Tutorials,不是我的原創。

1import tensorflow as tf
2import numpy as np
3trX = np.linspace(-1, 1, 101)
4trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 
5X = tf.placeholder("float") 
6Y = tf.placeholder("float")
7def model(X, w):
8    return tf.multiply(X, w) 
9w = tf.Variable(0.0, name="weights") 
10y_model = model(X, w)
11cost = tf.square(Y - y_model) 
12train_op = tf.train.GradientDescentOptimizer(0.01).minimize(cost) 
13
14with tf.Session() as sess:
15    
16    tf.global_variables_initializer().run()
17    for i in range(100):
18        for (x, y) in zip(trX, trY):
19            sess.run(train_op, feed_dict={X: x, Y: y})
20    print(sess.run(w)) 

最終會得到一個接近2的值,比如我這次運行的值為1.9183811

多種方式搞定手寫識別


線性回歸不過癮,我們直接一步到位,開始進行手寫識別。

我們採用深度學習三巨頭之一的Yann Lecun教授的MNIST數據為例。如上圖所示,MNIST的數據是28x28的圖像,並且標記了它的值應該是什麼。

線性模型:logistic回歸


我們首先不管三七二十一,就用線性模型來做分類。 


算上注釋和空行,一共加起來30行左右,我們就可以解決手寫識別這麼困難的問題啦!請看代碼:

1import tensorflow as tf
2import numpy as np
3from tensorflow.examples.tutorials.mnist import input_data
4def init_weights(shape):
5    return tf.Variable(tf.random_normal(shape, stddev=0.01))
6def model(X, w):
7    return tf.matmul(X, w) 
8mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
9trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
10X = tf.placeholder("float", [None, 784])
11Y = tf.placeholder("float", [None, 10])
12w = init_weights([784, 10]) 
13py_x = model(X, w)
14cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) 
15train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) 
16predict_op = tf.argmax(py_x, 1) 
17with tf.Session() as sess:
18    tf.global_variables_initializer().run()
19    for i in range(100):
20        for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):
21            sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})
22        print(i, np.mean(np.argmax(teY, axis=1) ==
23                         sess.run(predict_op, feed_dict={X: teX})))

經過100輪的訓練,我們的準確率是92.36%。

無腦的淺層神經網絡


用了最簡單的線性模型,我們換成經典的神經網絡來實現這個功能。神經網絡的圖如下圖所示。

我們還是不管三七二十一,建立一個隱藏層,用最傳統的sigmoid函數做激活函數。其核心邏輯還是矩陣乘法,這裡面沒有任何技巧。

1h = tf.nn.sigmoid(tf.matmul(X, w_h)) 
2return tf.matmul(h, w_o) 

完整代碼如下,仍然是40多行,不長:

1import tensorflow as tf
2import numpy as np
3from tensorflow.examples.tutorials.mnist import input_data
4
5def init_weights(shape):
6    return tf.Variable(tf.random_normal(shape, stddev=0.01))
7def model(X, w_h, w_o):
8    h = tf.nn.sigmoid(tf.matmul(X, w_h)) 
9    return tf.matmul(h, w_o) 
10mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
11trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
12X = tf.placeholder("float", [None, 784])
13Y = tf.placeholder("float", [None, 10])
14w_h = init_weights([784, 625])
15w_o = init_weights([625, 10])
16py_x = model(X, w_h, w_o)
17cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) 
18train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) 
19predict_op = tf.argmax(py_x, 1)
20with tf.Session() as sess:
21tf.global_variables_initializer().run()
22  for i in range(100):
23  for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):
24  sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})
25   print(i, np.mean(np.argmax(teY, axis=1) ==
26    sess.run(predict_op, feed_dict={X: teX})))

第一輪運行,我這次的準確率只有69.11% ,第二次就提升到了82.29%。最終結果是95.41%,比Logistic回歸的強! 


請注意我們模型的核心那兩行代碼,完全就是無腦地全連接做了一個隱藏層而己,這其中沒有任何的技術。完全是靠神經網絡的模型能力。

深度學習時代的方案 - ReLU和Dropout顯神通


上一個技術含量有點低,現在是深度學習的時代了,我們有很多進步。比如我們知道要將sigmoid函數換成ReLU函數。

我們還知道要做Dropout了。於是我們還是一個隱藏層,寫個更現代一點的模型吧:

1X = tf.nn.dropout(X, p_keep_input)
2h = tf.nn.relu(tf.matmul(X, w_h))
3h = tf.nn.dropout(h, p_keep_hidden)
4h2 = tf.nn.relu(tf.matmul(h, w_h2))
5h2 = tf.nn.dropout(h2, p_keep_hidden)
6return tf.matmul(h2, w_o)

除了ReLU和dropout這兩個技巧,我們仍然只有一個隱藏層,表達能力沒有太大的增強。並不能算是深度學習。

1import tensorflow as tf
2import numpy as np
3from tensorflow.examples.tutorials.mnist import input_data
4def init_weights(shape):
5    return tf.Variable(tf.random_normal(shape, stddev=0.01))
6def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden): 
7    X = tf.nn.dropout(X, p_keep_input)
8    h = tf.nn.relu(tf.matmul(X, w_h))
9    h = tf.nn.dropout(h, p_keep_hidden)
10    h2 = tf.nn.relu(tf.matmul(h, w_h2))
11    h2 = tf.nn.dropout(h2, p_keep_hidden)
12    return tf.matmul(h2, w_o)
13mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
14trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
15X = tf.placeholder("float", [None, 784])
16Y = tf.placeholder("float", [None, 10])
17w_h = init_weights([784, 625])
18w_h2 = init_weights([625, 625])
19w_o = init_weights([625, 10])
20p_keep_input = tf.placeholder("float")
21p_keep_hidden = tf.placeholder("float")
22py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden)
23cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))
24train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
25predict_op = tf.argmax(py_x, 1)
26with tf.Session() as sess:
27    
28tf.global_variables_initializer().run()
29for i in range(100):
30for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):
31sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],
32p_keep_input: 0.8, p_keep_hidden: 0.5})
33print(i, np.mean(np.argmax(teY, axis=1) ==
34sess.run(predict_op, feed_dict={X: teX,
35p_keep_input: 1.0,
36p_keep_hidden: 1.0})))

從結果看到,第二次就達到了96%以上的正確率。後來就一直在98.4%左右遊蕩。僅僅是ReLU和Dropout,就把準確率從95%提升到了98%以上。

卷積神經網絡出場


真正的深度學習利器CNN,卷積神經網絡出場。這次的模型比起前面幾個無腦型的,的確是複雜一些。涉及到卷積層和池化層。這個是需要我們後面詳細講一講了。

1import tensorflow as tf
2import numpy as np
3from tensorflow.examples.tutorials.mnist import input_data
4batch_size = 128
5test_size = 256
6def init_weights(shape):
7 return tf.Variable(tf.random_normal(shape, stddev=0.01))
8def model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden):
9 l1a = tf.nn.relu(tf.nn.conv2d(X, w,                       
10  strides=[1, 1, 1, 1], padding='SAME'))
11 l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1],              
12  strides=[1, 2, 2, 1], padding='SAME')
13 l1 = tf.nn.dropout(l1, p_keep_conv)
14  l2a = tf.nn.relu(tf.nn.conv2d(l1, w2,                     
15    strides=[1, 1, 1, 1], padding='SAME'))
16 l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1],              
17    strides=[1, 2, 2, 1], padding='SAME')
18 l2 = tf.nn.dropout(l2, p_keep_conv)
19 l3a = tf.nn.relu(tf.nn.conv2d(l2, w3,                     
20    strides=[1, 1, 1, 1], padding='SAME'))
21 l3 = tf.nn.max_pool(l3a, ksize=[1, 2, 2, 1],              
22    strides=[1, 2, 2, 1], padding='SAME')
23 l3 = tf.reshape(l3, [-1, w4.get_shape().as_list()[0]])    
24 l3 = tf.nn.dropout(l3, p_keep_conv)
25 l4 = tf.nn.relu(tf.matmul(l3, w4))
26 l4 = tf.nn.dropout(l4, p_keep_hidden)
27    pyx = tf.matmul(l4, w_o)
28    return pyx
29mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
30trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
31trX = trX.reshape(-1, 28, 28, 1)  
32teX = teX.reshape(-1, 28, 28, 1)  
33X = tf.placeholder("float", [None, 28, 28, 1])
34Y = tf.placeholder("float", [None, 10])
35w = init_weights([3, 3, 1, 32])       
36w2 = init_weights([3, 3, 32, 64])     
37w3 = init_weights([3, 3, 64, 128])    
38w4 = init_weights([128 * 4 * 4, 625]) 
39w_o = init_weights([625, 10])         
40p_keep_conv = tf.placeholder("float")
41p_keep_hidden = tf.placeholder("float")
42py_x = model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden)
43cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))
44train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
45predict_op = tf.argmax(py_x, 1)
46with tf.Session() as sess:
47    
48tf.global_variables_initializer().run()
49for i in range(100):
50training_batch = zip(range(0, len(trX), batch_size),
51range(batch_size, len(trX)+1, batch_size))
52for start, end in training_batch:
53sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],
54p_keep_conv: 0.8, p_keep_hidden: 0.5})
55test_indices = np.arange(len(teX)) 
56np.random.shuffle(test_indices)
57test_indices = test_indices[0:test_size]
58print(i, np.mean(np.argmax(teY[test_indices], axis=1) ==
59sess.run(predict_op, feed_dict={X: teX[test_indices],
60p_keep_conv: 1.0,
61p_keep_hidden: 1.0})))

我們看下這次的運行數據:

10 0.95703125
21 0.9921875
32 0.9921875
43 0.98046875
54 0.97265625
65 0.98828125
76 0.99609375

在第6輪的時候,就跑出了99.6%的高分值,比ReLU和Dropout的一個隱藏層的神經網絡的98.4%大大提高。因為難度是越到後面越困難。 


在第16輪的時候,竟然跑出了100%的正確率:

17 0.99609375
28 0.99609375
39 0.98828125
410 0.98828125
511 0.9921875
612 0.98046875
713 0.99609375
814 0.9921875
915 0.99609375
1016 1.0

綜上,藉助Tensorflow和機器學習工具,我們只有幾十行代碼,就解決了手寫識別這樣級別的問題,而且準確度可以達到如此程度。

作者博客連結:

https://blog.csdn.net/lusing/article/details/79965160

-END-

長按二維碼

擁有專屬於你的個性化機器人!

相關焦點

  • Tensorflow官方語音識別入門教程 | 附Google新語音指令數據集
    語音識別教程Google還配合這個數據集,推出了一份TensorFlow教程,教你訓練一個簡單的語音識別網絡,能識別10個詞,就像是語音識別領域的MNIST(手寫數字識別數據集)。雖然這份教程和數據集都比真實場景簡化了太多,但能幫用戶建立起對語音識別技術的基本理解,很適合初學者使用。
  • 【官方教程】TensorFlow在圖像識別中的應用
    一系列的模型不斷展現了性能的提升,每次都刷新了業界的最好成績:QuocNet, AlexNet, Inception(GoogLeNet), BN-Inception-v2。谷歌的以及其它的研究員已經發表了論文解釋這些模型,但是那些結果仍然很難被重現。我們正在準備發布代碼,在最新的模型Inception-v3 上運行圖像識別任務。
  • 教程 |TensorFlow.js速成課程 - 神經網絡機器學習 - 手寫識別
    在本文中,作者將帶領大家使用 TensorFlow.js 和 MNIST 數據集在前端 Web 開發中訓練一個手寫數字分類模型,並把手寫數字的預測結果在前端頁面中展現出來。在第一部分 TensorFlow.js 速成課程 - 網絡機器學習 - 入門我們已經介紹了以下主題:在這一部分中,我們將更進一步探討另一個用例:識別手寫數字。
  • TensorFlow與中文手寫漢字識別
    Train,Validation到Inference,是一個比較基本的Example, 從一個基本的任務學習如果在TensorFlow下做高效地圖像讀取,基本的圖像處理,整個項目很簡單,但其中有一些trick,在實際項目當中有很大的好處, 比如絕對不要一次讀入所有的 的數據到內存(儘管在Mnist這類級別的例子上經常出現)…最開始看到是這篇blog裡面的TensorFlow練習22: 手寫漢字識別
  • tensorflow安裝教程
    建立成功進入tf2.0環境conda activate tf2.0安裝tensorflow2.0 pip install tensorflow==2.0.0-beta1下載的東西挺多,多等一會,最後成功如下命令行運行python,執行import
  • TensorFlow 與中文手寫漢字識別
    Train,Validation到Inference,是一個比較基本的Example, 從一個基本的任務學習如果在TensorFlow下做高效地圖像讀取,基本的圖像處理,整個項目很簡單,但其中有一些trick,在實際項目當中有很大的好處, 比如絕對不要一次讀入所有的 的數據到內存(儘管在Mnist這類級別的例子上經常出現)…最開始看到是這篇blog裡面的TensorFlow練習22: 手寫漢字識別
  • TensorFlow圖像分類教程
    在這個由兩部分組成的系列中,我將講述如何快速的創建一個應用於圖像識別的卷積神經網絡。TensorFlow計算步驟是並行的,可對其配置進行逐幀視頻分析,也可對其擴展進行時間感知視頻分析。本系列文章直接切入關鍵的部分,只需要對命令行和Python有最基本的了解,就可以在家快速地創建一些令你激動不已的項目。
  • 圖像識別 | 從手寫字識別項目入門Tensorflow
    圖像處理是深度學習裡面的一個重要的應用,深度學習的研究者使用的最熱門的框架就要屬Tensorflow了,因此我們藉由深度學習圖像處理中最基本也是最簡單的手寫字體識別項目,帶大家入門深度學習圖像處理,了解如何使用Tensorflow搭建神經網絡。
  • 100天搞定機器學習|day39 Tensorflow Keras手寫數字識別
    1、安裝庫tensorflow有些教程會推薦安裝nightly,它適用於在一個全新的環境下進行TensorFlow的安裝,默認會把需要依賴的庫也一起裝上。我使用的是anaconda,本文我們安裝的是純淨版的tensorflow,非常簡單,只需打開Prompt:
  • TensorFlow 2.0 中文手寫字識別(漢字OCR)
    數據集處理挑戰更大,相比於mnist和fasionmnist來說,漢字手寫字體識別數據集非常少,而且僅有的數據集數據預處理難度非常大,非常不直觀,但是,千萬別嚇到,相信你看完本教程一定會收貨滿滿!漢字識別更考驗選手的建模能力,還在分類花?分類貓和狗?隨便搭建的幾層在搜索空間巨大的漢字手寫識別裡根本不work!你現在是不是想用很深的網絡躍躍欲試?
  • 使用Python+Tensorflow的CNN技術快速識別驗證碼
    一開始學習tensorflow是盲目的,不知如何下手,網上的資料都比較單一,為了回報社會,讓大家少走彎路,我將詳細介紹整個過程。本教程所需要的完整材料,我都會放在這裡。限於個人水平,如有錯誤請指出!接下來我將介紹如何使用Python+Tensorflow的CNN技術快速識別驗證碼。在此之前,介紹我們用到的工具:1.
  • TensorFlow 安裝教程
    在極客學院有關tensorflow的教程中,提到了這樣幾種安裝方式:Pip, Docker, Virtualenv, Anaconda 或 源碼編譯的方法安裝 TensorFlow。在這裡,我強烈推薦大家使用Anaconda的方式安裝!因為採用這種方式安裝的時候,相當於將所有的底層依賴細節全部已經打包給封裝好了!
  • Python人工智慧 | 七.TensorFlow實現分類學習及MNIST手寫體識別案例
    文章目錄:一.什麼是分類學習1.Classification2.MNIST二.tensorflow實現MNIST分類三.總結代碼下載地址(歡迎大家關注點讚):學Python近八年,認識了很多大佬和朋友,感恩。
  • Tensorflow 全網最全學習資料匯總之Tensorflow 的入門與安裝【2】
    最終以一個手寫數字識別的實例將這些點串起來進行了具體說明。2.《TensorFlow學習筆記1:入門》連結:http://www.jeyzhang.com/tensorflow-learning-notes.html本文與上一篇的行文思路基本一致,首先概括了TensorFlow的特性,然後介紹了graph、session、variable 等基本概念的含義,以具體代碼的形式針對每個概念給出了進一步的解釋。
  • 一句代碼發布你的TensorFlow模型,簡明TensorFlow Serving上手教程
    一句代碼保存TensorFlow模型# coding=utf-8import tensorflow as tf# 模型版本號model_version = 1# 定義模型x = tf.placeholder(tf.float32, shape=[None, 4], name="x")
  • Tensorflow之 CNN卷積神經網絡的MNIST手寫數字識別
    如果你尚未了解,請查看MNIST For ML Beginners(https://www.tensorflow.org/get_started/mnist/beginners)。在學習教程之前,請確保已經安裝Install TensorFlow(https://www.tensorflow.org/install/)。
  • 詳解與實戰TensorFlow MNIST手寫體數字識別(softmax and cnn)
    MNIST 手寫體數字介紹MNIST圖像數據集使用形如【28,28】的二姐數組來表示每個手寫體數字,數組中的每個元素對應一個像素點,即每張圖像大小固定為28X28像素。但這些圖像並非每一張都代表有效的手寫體數字,其中絕大部分都是如下的噪聲圖:
  • 一文看懂CNN、RNN等7種範例(TensorFlow教程)
    這些網絡用於圖像分類、目標檢測、視頻動作識別以及任何在結構上具有一定空間不變性的數據 (如語音音頻)。TensorFlow 教程:請參閱我們的深度學習基礎教程的第 2 部分,了解用於對 MNIST 數據集中的手寫數字進行分類的一個 CNN 示例。
  • TensorFlow極速入門
    熱衷於深度學習技術的探索,對新事物有著強烈的好奇心。一、前言目前,深度學習已經廣泛應用於各個領域,比如圖像識別,圖形定位與檢測,語音識別,機器翻譯等等,對於這個神奇的領域,很多童鞋想要一探究竟,這裡拋磚引玉的簡單介紹下最火的深度學習開源框架 tensorflow。
  • tensorflow極速入門
    一、前言目前,深度學習已經廣泛應用於各個領域,比如圖像識別,圖形定位與檢測,語音識別,機器翻譯等等,對於這個神奇的領域,很多童鞋想要一探究竟,這裡拋磚引玉的簡單介紹下最火的深度學習開源框架 tensorflow。本教程不是 cookbook,所以不會將所有的東西都事無巨細的講到,所有的示例都將使用 python。那麼本篇教程會講到什麼?