outline
`安裝環(huán)境
`tensorflow原理簡述
`定義網(wǎng)絡(luò)結(jié)構(gòu)、啟動網(wǎng)絡(luò)計算
`使用Variable定義模型參數(shù),如何訓(xùn)練模型
`如何測試
只是自己的簡要概括,最好對神經(jīng)網(wǎng)絡(luò)、機器學(xué)習(xí)略有了解。tensorflow的中文文檔新手入門真的做的還不錯,建議大家結(jié)合理論,碼一碼代碼,上手很快的。
`安裝環(huán)境
ubuntu 16.04,pycharm IDE、python 2.7
pycharm有教育賬戶的,學(xué)生可以免費使用。IDE集成了terminal、python console,還能調(diào)試,真的好用。另外集成了virtual environment,可以切換使用python2.7、python3.x,有興趣的可以了解一下
#note
使用virtual environment的方法
file-new project-選擇解釋器的邊上有個設(shè)置可以創(chuàng)建虛擬環(huán)境,選擇相應(yīng)的解釋器就能創(chuàng)建,另外在這個project中的terminal會默認使用這個虛擬環(huán)境,形如:
(tensorflow) ceo1207@ceo1207:
安裝tensorflow
pip install https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl
另外裝jupyter(就是常說的python notebook)體驗也很好,可以像python console中一樣交互式的編程,還能保存代碼
apt-get install python-dev
python -m pip install jupyter
使用時,輸入 jupyter notebook 即可在瀏覽器中使用python
`tensorflow原理簡述
(看不懂不要緊,看完下面的再來看一遍就會了)網(wǎng)絡(luò)結(jié)構(gòu)使用Graph表示,Graph由operation(節(jié)點)組成,op接受輸入產(chǎn)生輸出,輸入輸出使用張量(tensor)表示,所以這個框架叫tensorflow,張量數(shù)據(jù)的流動的意思。
定義graph不會產(chǎn)生計算,真正的計算使用Session(會話)驅(qū)動,可以使用會話傳入數(shù)據(jù),獲取輸入以及訓(xùn)練和測試網(wǎng)絡(luò)。
#note:計算優(yōu)化
為了用python實現(xiàn)高效的數(shù)值計算,我們通常會使用函數(shù)庫,比如NumPy,會把類似矩陣乘法這樣的復(fù)雜運算使用其他外部語言實現(xiàn)。不幸的是,從外部計算切換回Python的每一個操作,仍然是一個很大的開銷。如果你用GPU來進行外部計算,這樣的開銷會更大。用分布式的計算方式,也會花費更多的資源用來傳輸數(shù)據(jù)。
TensorFlow也把復(fù)雜的計算放在python之外完成,但是為了避免前面說的那些開銷,它做了進一步完善。Tensorflow不單獨地運行單一的復(fù)雜計算,而是讓我們可以先用圖描述一系列可交互的計算操作,然后全部一起在Python之外運行。
`定義網(wǎng)絡(luò)結(jié)構(gòu)、啟動網(wǎng)絡(luò)計算
graph定義網(wǎng)絡(luò)結(jié)構(gòu),添加節(jié)點(計算單元)。但是graph只是定義結(jié)構(gòu)和數(shù)據(jù),真正的計算需要會話啟動。
節(jié)點構(gòu)造器,接收輸入tensor,返回op的輸出。最簡單的是常量節(jié)點,可以作為整個網(wǎng)絡(luò)的輸入。也可以是一些計算操作,比如矩陣相加、相乘。直接上代碼,看看就明白了。
import numpy as np
import tensorflow as tf
# define input, create operation, result(tensor) return
input1 = tf.constant(3)
input2 = tf.constant(2)
input3 = tf.constant(5)
# define operations
add = tf.add(input3,input2)
mul = tf.mul(input1,add)
with tf.Session() as sess:
? ? # use the default graph
? ? result = sess.run([mul,add])
? ? print result
輸入也可以使用占位符,用于在會話時,靈活的添加自定義的輸入。
import numpy as np
import tensorflow as tf
input1 = tf.placeholder(tf.types.float32)
input2 = tf.placeholder(tf.types.float32)
mul = tf.mul(input1, input2)
data1 = [1,2,3]
data2 = [2,4,6]
with tf.Session() as sess:
? ? print sess.run([mul], feed_dict={input1:data1,input2:data2})
關(guān)于數(shù)據(jù)的fetch和feed,上面兩段代碼都用到了其實。
Fetch,使用run獲取
with tf.Session():
? result = sess.run([mul, intermed])
? print result
需要獲取的多個 tensor 值,在 op 的一次運行中一起獲得(而不是逐個去獲取 tensor)
feed,在會話中插入數(shù)據(jù),使用placeholder
import numpy as np
import tensorflow as tf
input1 = tf.placeholder(tf.types.float32)
input2 = tf.placeholder(tf.types.float32)
mul = tf.mul(input1, input2)
data1 = [1,2,3]
data2 = [2,4,6]
with tf.Session() as sess:
? ? print sess.run([mul], feed_dict={input1:data1,input2:data2})
`使用Variable定義模型參數(shù)、如何訓(xùn)練模型
到這一步,請你確保具備以下能力,給你具體的公式和輸入,可以使用tensorflow,控制數(shù)據(jù)的輸入,利用會話驅(qū)動運算獲得最后的輸出,甚至是任意中間步驟的結(jié)果。
但是常用的神經(jīng)網(wǎng)絡(luò)、機器學(xué)習(xí)的模型都是有模型參數(shù)的,模型參數(shù)是需要訓(xùn)練的。參數(shù)如何輸入?當(dāng)然我們可以把它們當(dāng)做是另外的輸入(使用占位符),但TensorFlow有一個更好的方法來表示它們:Variable。
Variable你可以理解為一個可變的tensor,事后,框架會根據(jù)你設(shè)置的訓(xùn)練方法自動更新他的值。
#note:
模型的多種輸入:常量、占位符、Variable
有了可變的tensor(Variable),如何訓(xùn)練他們?
看懂下面的部分,先了解一下什么是softmax regression
如下,regression解決的是分類問題,對于多分類問題,使用softmax層得到歸一化的多分類的概率分布。
概率分布:(這個詞,其實不容易解釋)多分類問題下,一個隨機事件,在各個分類上的概率分布,就是所謂的概率分布。概率分布的特點,各個分類的概率之和為1.

好吧,不了解你就硬著頭皮往下看吧,沒什么關(guān)系。
首先定義優(yōu)化的目標(biāo),即確定loss function。
多分類問題采用交叉熵作為loss,形如:
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
再確定優(yōu)化的方法,可以使用常用的梯度下降方法
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
設(shè)置步長為0.01,優(yōu)化目標(biāo)是cross_entropy
好了,可以看mnist的實戰(zhàn)代碼了,可以在tensorflow github上看,這里貼一下
"""A very simple MNIST classifier.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/beginners
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
FLAGS = None
def main(_):
? # Import data
? mnist = input_data.read_data_sets(FLAGS.data_dir)
? # Create the model
? x = tf.placeholder(tf.float32, [None, 784])
? W = tf.Variable(tf.zeros([784, 10]))
? b = tf.Variable(tf.zeros([10]))
? y = tf.matmul(x, W) + b
? # Define loss and optimizer
? y_ = tf.placeholder(tf.int64, [None])
? # The raw formulation of cross-entropy,
? #
? #? tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
? #? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? reduction_indices=[1]))
? #
? # can be numerically unstable.
? #
? # So here we use tf.losses.sparse_softmax_cross_entropy on the raw
? # outputs of 'y', and then average across the batch.
? cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=y_, logits=y)
? train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
? sess = tf.InteractiveSession()
? tf.global_variables_initializer().run()
? # Train
? for _ in range(1000):
? ? batch_xs, batch_ys = mnist.train.next_batch(100)
? ? sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
? # Test trained model
? correct_prediction = tf.equal(tf.argmax(y, 1), y_)
? accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
? print(sess.run(
? ? ? accuracy, feed_dict={
? ? ? ? ? x: mnist.test.images,
? ? ? ? ? y_: mnist.test.labels
? ? ? }))
if __name__ == '__main__':
? parser = argparse.ArgumentParser()
? parser.add_argument(
? ? ? '--data_dir',
? ? ? type=str,
? ? ? default='/tmp/tensorflow/mnist/input_data',
? ? ? help='Directory for storing input data')
? FLAGS, unparsed = parser.parse_known_args()
? tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
`如何測試
最后說一下如何測試,其實上面的代碼以及中文文檔里已經(jīng)說的蠻好了。
好吧,下一篇,深入mnist(讀作m-nist),明兒見