作者簡介:劉子瑛,阿里巴巴作業系統框架專家;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-
長按二維碼
擁有專屬於你的個性化機器人!