Tensorflow快餐教程(1) - 30行代码搞定手写识别
摘要:?Tensorflow入門(mén)教程1
去年買(mǎi)了幾本講tensorflow的書(shū),結(jié)果今年看的時(shí)候發(fā)現(xiàn)有些樣例代碼所用的API已經(jīng)過(guò)時(shí)了。看來(lái)自己維護(hù)一個(gè)保持更新的Tensorflow的教程還是有意義的。這是寫(xiě)這一系列的初心。
快餐教程系列希望能夠盡可能降低門(mén)檻,少講,講透。
為了讓大家在一開(kāi)始就看到一個(gè)美好的場(chǎng)景,而不是停留在漫長(zhǎng)的基礎(chǔ)知識(shí)積累上,參考網(wǎng)上的一些教程,我們直接一開(kāi)始就直接展示用tensorflow實(shí)現(xiàn)MNIST手寫(xiě)識(shí)別的例子。然后基礎(chǔ)知識(shí)我們?cè)俾v。
Tensorflow安裝速成教程
由于Python是跨平臺(tái)的語(yǔ)言,所以在各系統(tǒng)上安裝tensorflow都是一件相對(duì)比較容易的事情。GPU加速的事情我們后面再說(shuō)。
Linux平臺(tái)安裝tensorflow
我們以Ubuntu 16.04版為例,首先安裝python3和pip3。pip是python的包管理工具。
sudo apt install python3 sudo apt install python3-pip然后就可以通過(guò)pip3來(lái)安裝tensorflow:
pip3 install tensorflow --upgradeMacOS安裝tensorflow
建議使用Homebrew來(lái)安裝python。
brew install python3安裝python3之后,還是通過(guò)pip3來(lái)安裝tensorflow.
pip3 install tensorflow --upgradeWindows平臺(tái)安裝Tensorflow
Windows平臺(tái)上建議通過(guò)Anaconda來(lái)安裝tensorflow,下載地址在:https://www.anaconda.com/download/#windows
然后打開(kāi)Anaconda Prompt,輸入:
conda create -n tensorflow pip activate tensorflow pip install --ignore-installed --upgrade tensorflow這樣就安裝好了Tensorflow。
我們迅速來(lái)個(gè)例子試下好不好用:
import tensorflow as tf a = tf.constant(1) b = tf.constant(2)c = a * bsess = tf.Session()print(sess.run(c))輸出結(jié)果為2.?
Tensorflow顧名思義,是一些Tensor張量的流組成的運(yùn)算。
運(yùn)算需要一個(gè)Session來(lái)運(yùn)行。如果print(c)的話,會(huì)得到
就是說(shuō)這是一個(gè)乘法運(yùn)算的Tensor,需要通過(guò)Session.run()來(lái)執(zhí)行。
入門(mén)捷徑:線性回歸
我們首先看一個(gè)最簡(jiǎn)單的機(jī)器學(xué)習(xí)模型,線性回歸的例子。
線性回歸的模型就是一個(gè)矩陣乘法:
然后我們通過(guò)調(diào)用Tensorflow計(jì)算梯度下降的函數(shù)tf.train.GradientDescentOptimizer來(lái)實(shí)現(xiàn)優(yōu)化。
我們看下這個(gè)例子代碼,只有30多行,邏輯還是很清晰的。例子來(lái)自github上大牛的工作:https://github.com/nlintz/TensorFlow-Tutorials,不是我的原創(chuàng)。
最終會(huì)得到一個(gè)接近2的值,比如我這次運(yùn)行的值為1.9183811
多種方式搞定手寫(xiě)識(shí)別
線性回歸不過(guò)癮,我們直接一步到位,開(kāi)始進(jìn)行手寫(xiě)識(shí)別。
我們采用深度學(xué)習(xí)三巨頭之一的Yann Lecun教授的MNIST數(shù)據(jù)為例。如上圖所示,MNIST的數(shù)據(jù)是28x28的圖像,并且標(biāo)記了它的值應(yīng)該是什么。
線性模型:logistic回歸
我們首先不管三七二十一,就用線性模型來(lái)做分類。
算上注釋和空行,一共加起來(lái)30行左右,我們就可以解決手寫(xiě)識(shí)別這么困難的問(wèn)題啦!請(qǐng)看代碼:
經(jīng)過(guò)100輪的訓(xùn)練,我們的準(zhǔn)確率是92.36%。
無(wú)腦的淺層神經(jīng)網(wǎng)絡(luò)
用了最簡(jiǎn)單的線性模型,我們換成經(jīng)典的神經(jīng)網(wǎng)絡(luò)來(lái)實(shí)現(xiàn)這個(gè)功能。神經(jīng)網(wǎng)絡(luò)的圖如下圖所示。
我們還是不管三七二十一,建立一個(gè)隱藏層,用最傳統(tǒng)的sigmoid函數(shù)做激活函數(shù)。其核心邏輯還是矩陣乘法,這里面沒(méi)有任何技巧。
h = tf.nn.sigmoid(tf.matmul(X, w_h)) return tf.matmul(h, w_o)完整代碼如下,仍然是40多行,不長(zhǎng):
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data# 所有連接隨機(jī)生成權(quán)值 def init_weights(shape):return tf.Variable(tf.random_normal(shape, stddev=0.01))def model(X, w_h, w_o):h = tf.nn.sigmoid(tf.matmul(X, w_h)) return tf.matmul(h, w_o) mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labelsX = tf.placeholder("float", [None, 784]) Y = tf.placeholder("float", [None, 10])w_h = init_weights([784, 625]) w_o = init_weights([625, 10])py_x = model(X, w_h, w_o)cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) # 計(jì)算誤差損失 train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) # construct an optimizer predict_op = tf.argmax(py_x, 1)with tf.Session() as sess:tf.global_variables_initializer().run()for i in range(100):for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})print(i, np.mean(np.argmax(teY, axis=1) ==sess.run(predict_op, feed_dict={X: teX})))第一輪運(yùn)行,我這次的準(zhǔn)確率只有69.11%?,第二次就提升到了82.29%。最終結(jié)果是95.41%,比Logistic回歸的強(qiáng)!
請(qǐng)注意我們模型的核心那兩行代碼,完全就是無(wú)腦地全連接做了一個(gè)隱藏層而己,這其中沒(méi)有任何的技術(shù)。完全是靠神經(jīng)網(wǎng)絡(luò)的模型能力。
深度學(xué)習(xí)時(shí)代的方案 - ReLU和Dropout顯神通
上一個(gè)技術(shù)含量有點(diǎn)低,現(xiàn)在是深度學(xué)習(xí)的時(shí)代了,我們有很多進(jìn)步。比如我們知道要將sigmoid函數(shù)換成ReLU函數(shù)。我們還知道要做Dropout了。于是我們還是一個(gè)隱藏層,寫(xiě)個(gè)更現(xiàn)代一點(diǎn)的模型吧:
X = tf.nn.dropout(X, p_keep_input)h = tf.nn.relu(tf.matmul(X, w_h))h = tf.nn.dropout(h, p_keep_hidden)h2 = tf.nn.relu(tf.matmul(h, w_h2))h2 = tf.nn.dropout(h2, p_keep_hidden)return tf.matmul(h2, w_o)除了ReLU和dropout這兩個(gè)技巧,我們?nèi)匀恢挥幸粋€(gè)隱藏層,表達(dá)能力沒(méi)有太大的增強(qiáng)。并不能算是深度學(xué)習(xí)。
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_datadef init_weights(shape):return tf.Variable(tf.random_normal(shape, stddev=0.01))def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden): X = tf.nn.dropout(X, p_keep_input)h = tf.nn.relu(tf.matmul(X, w_h))h = tf.nn.dropout(h, p_keep_hidden)h2 = tf.nn.relu(tf.matmul(h, w_h2))h2 = tf.nn.dropout(h2, p_keep_hidden)return tf.matmul(h2, w_o)mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labelsX = tf.placeholder("float", [None, 784]) Y = tf.placeholder("float", [None, 10])w_h = init_weights([784, 625]) w_h2 = init_weights([625, 625]) w_o = init_weights([625, 10])p_keep_input = tf.placeholder("float") p_keep_hidden = tf.placeholder("float") py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden)cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) predict_op = tf.argmax(py_x, 1)with tf.Session() as sess:# you need to initialize all variablestf.global_variables_initializer().run()for i in range(100):for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],p_keep_input: 0.8, p_keep_hidden: 0.5})print(i, np.mean(np.argmax(teY, axis=1) ==sess.run(predict_op, feed_dict={X: teX,p_keep_input: 1.0,p_keep_hidden: 1.0})))從結(jié)果看到,第二次就達(dá)到了96%以上的正確率。后來(lái)就一直在98.4%左右游蕩。僅僅是ReLU和Dropout,就把準(zhǔn)確率從95%提升到了98%以上。
卷積神經(jīng)網(wǎng)絡(luò)出場(chǎng)
真正的深度學(xué)習(xí)利器CNN,卷積神經(jīng)網(wǎng)絡(luò)出場(chǎng)。這次的模型比起前面幾個(gè)無(wú)腦型的,的確是復(fù)雜一些。涉及到卷積層和池化層。這個(gè)是需要我們后面詳細(xì)講一講了。
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_databatch_size = 128 test_size = 256def init_weights(shape):return tf.Variable(tf.random_normal(shape, stddev=0.01))def model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden):l1a = tf.nn.relu(tf.nn.conv2d(X, w, # l1a shape=(?, 28, 28, 32)strides=[1, 1, 1, 1], padding='SAME'))l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1], # l1 shape=(?, 14, 14, 32)strides=[1, 2, 2, 1], padding='SAME')l1 = tf.nn.dropout(l1, p_keep_conv)l2a = tf.nn.relu(tf.nn.conv2d(l1, w2, # l2a shape=(?, 14, 14, 64)strides=[1, 1, 1, 1], padding='SAME'))l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1], # l2 shape=(?, 7, 7, 64)strides=[1, 2, 2, 1], padding='SAME')l2 = tf.nn.dropout(l2, p_keep_conv)l3a = tf.nn.relu(tf.nn.conv2d(l2, w3, # l3a shape=(?, 7, 7, 128)strides=[1, 1, 1, 1], padding='SAME'))l3 = tf.nn.max_pool(l3a, ksize=[1, 2, 2, 1], # l3 shape=(?, 4, 4, 128)strides=[1, 2, 2, 1], padding='SAME')l3 = tf.reshape(l3, [-1, w4.get_shape().as_list()[0]]) # reshape to (?, 2048)l3 = tf.nn.dropout(l3, p_keep_conv)l4 = tf.nn.relu(tf.matmul(l3, w4))l4 = tf.nn.dropout(l4, p_keep_hidden)pyx = tf.matmul(l4, w_o)return pyxmnist = input_data.read_data_sets("MNIST_data/", one_hot=True) trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels trX = trX.reshape(-1, 28, 28, 1) # 28x28x1 input img teX = teX.reshape(-1, 28, 28, 1) # 28x28x1 input imgX = tf.placeholder("float", [None, 28, 28, 1]) Y = tf.placeholder("float", [None, 10])w = init_weights([3, 3, 1, 32]) # 3x3x1 conv, 32 outputs w2 = init_weights([3, 3, 32, 64]) # 3x3x32 conv, 64 outputs w3 = init_weights([3, 3, 64, 128]) # 3x3x32 conv, 128 outputs w4 = init_weights([128 * 4 * 4, 625]) # FC 128 * 4 * 4 inputs, 625 outputs w_o = init_weights([625, 10]) # FC 625 inputs, 10 outputs (labels)p_keep_conv = tf.placeholder("float") p_keep_hidden = tf.placeholder("float") py_x = model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden)cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) predict_op = tf.argmax(py_x, 1)with tf.Session() as sess:# you need to initialize all variablestf.global_variables_initializer().run()for i in range(100):training_batch = zip(range(0, len(trX), batch_size),range(batch_size, len(trX)+1, batch_size))for start, end in training_batch:sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],p_keep_conv: 0.8, p_keep_hidden: 0.5})test_indices = np.arange(len(teX)) # Get A Test Batchnp.random.shuffle(test_indices)test_indices = test_indices[0:test_size]print(i, np.mean(np.argmax(teY[test_indices], axis=1) ==sess.run(predict_op, feed_dict={X: teX[test_indices],p_keep_conv: 1.0,p_keep_hidden: 1.0})))我們看下這次的運(yùn)行數(shù)據(jù):
0 0.95703125 1 0.9921875 2 0.9921875 3 0.98046875 4 0.97265625 5 0.98828125 6 0.99609375在第6輪的時(shí)候,就跑出了99.6%的高分值,比ReLU和Dropout的一個(gè)隱藏層的神經(jīng)網(wǎng)絡(luò)的98.4%大大提高。因?yàn)殡y度是越到后面越困難。
在第16輪的時(shí)候,竟然跑出了100%的正確率:
綜上,借助Tensorflow和機(jī)器學(xué)習(xí)工具,我們只有幾十行代碼,就解決了手寫(xiě)識(shí)別這樣級(jí)別的問(wèn)題,而且準(zhǔn)確度可以達(dá)到如此程度。
本文作者:lusing
原文鏈接
總結(jié)
以上是生活随笔為你收集整理的Tensorflow快餐教程(1) - 30行代码搞定手写识别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 用深度学习解决Bongard问题
- 下一篇: 【 CDN 最佳实践】CDN 命中率优化