outline
`安裝環(huán)境
`tensorflow原理簡(jiǎn)述
`定義網(wǎng)絡(luò)結(jié)構(gòu)、啟動(dòng)網(wǎng)絡(luò)計(jì)算
`使用Variable定義模型參數(shù)韭脊,如何訓(xùn)練模型
`如何測(cè)試
只是自己的簡(jiǎn)要概括漏健,最好對(duì)神經(jīng)網(wǎng)絡(luò)、機(jī)器學(xué)習(xí)略有了解吟温。tensorflow的中文文檔新手入門(mén)真的做的還不錯(cuò)幽告,建議大家結(jié)合理論汛骂,碼一碼代碼,上手很快的。
`安裝環(huán)境
ubuntu 16.04,pycharm IDE豪诲、python 2.7
pycharm有教育賬戶(hù)的,學(xué)生可以免費(fèi)使用蝶念。IDE集成了terminal、python console芋绸,還能調(diào)試媒殉,真的好用。另外集成了virtual environment摔敛,可以切換使用python2.7廷蓉、python3.x,有興趣的可以了解一下
#note
使用virtual environment的方法
file-new project-選擇解釋器的邊上有個(gè)設(shè)置可以創(chuàng)建虛擬環(huán)境马昙,選擇相應(yīng)的解釋器就能創(chuàng)建桃犬,另外在這個(gè)project中的terminal會(huì)默認(rèn)使用這個(gè)虛擬環(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(就是常說(shuō)的python notebook)體驗(yàn)也很好行楞,可以像python console中一樣交互式的編程攒暇,還能保存代碼
apt-get install python-dev
python -m pip install jupyter
使用時(shí),輸入 jupyter notebook 即可在瀏覽器中使用python
`tensorflow原理簡(jiǎn)述
(看不懂不要緊子房,看完下面的再來(lái)看一遍就會(huì)了)網(wǎng)絡(luò)結(jié)構(gòu)使用Graph表示形用,Graph由operation(節(jié)點(diǎn))組成就轧,op接受輸入產(chǎn)生輸出,輸入輸出使用張量(tensor)表示田度,所以這個(gè)框架叫tensorflow妒御,張量數(shù)據(jù)的流動(dòng)的意思。
定義graph不會(huì)產(chǎn)生計(jì)算镇饺,真正的計(jì)算使用Session(會(huì)話)驅(qū)動(dòng)乎莉,可以使用會(huì)話傳入數(shù)據(jù),獲取輸入以及訓(xùn)練和測(cè)試網(wǎng)絡(luò)兰怠。
#note:計(jì)算優(yōu)化
為了用python實(shí)現(xiàn)高效的數(shù)值計(jì)算,我們通常會(huì)使用函數(shù)庫(kù)李茫,比如NumPy揭保,會(huì)把類(lèi)似矩陣乘法這樣的復(fù)雜運(yùn)算使用其他外部語(yǔ)言實(shí)現(xiàn)。不幸的是魄宏,從外部計(jì)算切換回Python的每一個(gè)操作秸侣,仍然是一個(gè)很大的開(kāi)銷(xiāo)。如果你用GPU來(lái)進(jìn)行外部計(jì)算宠互,這樣的開(kāi)銷(xiāo)會(huì)更大味榛。用分布式的計(jì)算方式,也會(huì)花費(fèi)更多的資源用來(lái)傳輸數(shù)據(jù)予跌。
TensorFlow也把復(fù)雜的計(jì)算放在python之外完成搏色,但是為了避免前面說(shuō)的那些開(kāi)銷(xiāo),它做了進(jìn)一步完善券册。Tensorflow不單獨(dú)地運(yùn)行單一的復(fù)雜計(jì)算频轿,而是讓我們可以先用圖描述一系列可交互的計(jì)算操作,然后全部一起在Python之外運(yùn)行烁焙。
`定義網(wǎng)絡(luò)結(jié)構(gòu)航邢、啟動(dòng)網(wǎng)絡(luò)計(jì)算
graph定義網(wǎng)絡(luò)結(jié)構(gòu),添加節(jié)點(diǎn)(計(jì)算單元)骄蝇。但是graph只是定義結(jié)構(gòu)和數(shù)據(jù)膳殷,真正的計(jì)算需要會(huì)話啟動(dòng)。
節(jié)點(diǎn)構(gòu)造器九火,接收輸入tensor赚窃,返回op的輸出。最簡(jiǎn)單的是常量節(jié)點(diǎn)岔激,可以作為整個(gè)網(wǎng)絡(luò)的輸入考榨。也可以是一些計(jì)算操作,比如矩陣相加鹦倚、相乘河质。直接上代碼,看看就明白了。
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
輸入也可以使用占位符掀鹅,用于在會(huì)話時(shí)散休,靈活的添加自定義的輸入。
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乐尊,上面兩段代碼都用到了其實(shí)戚丸。
Fetch,使用run獲取
with tf.Session():
? result = sess.run([mul, intermed])
? print result
需要獲取的多個(gè) tensor 值扔嵌,在 op 的一次運(yùn)行中一起獲得(而不是逐個(gè)去獲取 tensor)
feed限府,在會(huì)話中插入數(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)練模型
到這一步胁勺,請(qǐng)你確保具備以下能力,給你具體的公式和輸入独旷,可以使用tensorflow署穗,控制數(shù)據(jù)的輸入,利用會(huì)話驅(qū)動(dòng)運(yùn)算獲得最后的輸出嵌洼,甚至是任意中間步驟的結(jié)果案疲。
但是常用的神經(jīng)網(wǎng)絡(luò)、機(jī)器學(xué)習(xí)的模型都是有模型參數(shù)的麻养,模型參數(shù)是需要訓(xùn)練的褐啡。參數(shù)如何輸入?當(dāng)然我們可以把它們當(dāng)做是另外的輸入(使用占位符)鳖昌,但TensorFlow有一個(gè)更好的方法來(lái)表示它們:Variable春贸。
Variable你可以理解為一個(gè)可變的tensor,事后遗遵,框架會(huì)根據(jù)你設(shè)置的訓(xùn)練方法自動(dòng)更新他的值萍恕。
#note:
模型的多種輸入:常量、占位符车要、Variable
有了可變的tensor(Variable)允粤,如何訓(xùn)練他們?
看懂下面的部分翼岁,先了解一下什么是softmax regression
如下类垫,regression解決的是分類(lèi)問(wèn)題,對(duì)于多分類(lèi)問(wèn)題琅坡,使用softmax層得到歸一化的多分類(lèi)的概率分布悉患。
概率分布:(這個(gè)詞,其實(shí)不容易解釋?zhuān)┒喾诸?lèi)問(wèn)題下榆俺,一個(gè)隨機(jī)事件售躁,在各個(gè)分類(lèi)上的概率分布坞淮,就是所謂的概率分布。概率分布的特點(diǎn)陪捷,各個(gè)分類(lèi)的概率之和為1.
好吧回窘,不了解你就硬著頭皮往下看吧,沒(méi)什么關(guān)系市袖。
首先定義優(yōu)化的目標(biāo)啡直,即確定loss function。
多分類(lèi)問(wèn)題采用交叉熵作為loss苍碟,形如:
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
再確定優(yōu)化的方法酒觅,可以使用常用的梯度下降方法
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
設(shè)置步長(zhǎng)為0.01,優(yōu)化目標(biāo)是cross_entropy
好了微峰,可以看mnist的實(shí)戰(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)
`如何測(cè)試
最后說(shuō)一下如何測(cè)試县忌,其實(shí)上面的代碼以及中文文檔里已經(jīng)說(shuō)的蠻好了掂榔。
好吧继效,下一篇症杏,深入mnist(讀作m-nist),明兒見(jiàn)