Tensorflow官方文档---起步 MNIST示例
Tensorflow
?使用圖 (graph) 來表示計算任務.
? 在被稱之為 會話 (Session) 的上下文 (context) 中執行圖.
? 使用 tensor 表示數據.
? 通過 變量 (Variable) 維護狀態.
? 使用 feed 和 fetch 可以為任意的操作(arbitrary operation) 賦值或者從其中獲取數據
綜述
節點通常代表數學運算,邊表示節點之間的某種聯系,它負責傳輸多維數據(Tensors)。
概念描述
Tensor
Tensor的意思是張量,可以理解為tensorflow中矩陣的表示形式。Tensor的生成方式有很多種,最簡單的就如
import tensorflow as tf # 在下面所有代碼中,都去掉了這一行,默認已經導入 a = tf.zeros(shape=[1,2])不過要注意,因為在訓練開始前,所有的數據都是抽象的概念,也就是說,此時a只是表示這應該是個1*5的零矩陣,而沒有實際賦值,也沒有分配空間,所以如果此時print,就會出現如下情況:
print(a) #===>Tensor("zeros:0", shape=(1, 2), dtype=float32)只有在訓練過程開始后,才能獲得a的實際值
sess = tf.InteractiveSession() print(sess.run(a)) #===>[[ 0. 0.]]更詳細的Tensor 的理解見你真的懂TensorFlow嗎?Tensor是神馬?為什么還會Flow?
Variable
故名思議,是變量的意思。一般用來表示圖中的各計算參數,包括矩陣,向量等。
變量 Variable,是維護圖執行過程中的狀態信息的. 需要它來保持和更新參數值,是需要動態調整的。
一個 變量 代表著TensorFlow計算圖中的一個值,能夠在計算過程中使用,甚至進行修改.
例如,我要表示上圖中的模型,那表達式就是
(relu是一種激活函數,具體可見這里)這里W和b是我要用來訓練的參數,那么此時這兩個值就可以用Variable來表示。Variable的初始函數有很多其他選項,這里先不提,只輸入一個Tensor也是可以的
W = tf.Variable(tf.zeros(shape=[1,2]))注意,此時W一樣是一個抽象的概念,而且與Tensor不同,Variable必須初始化以后才有具體的值。
tensor = tf.zeros(shape=[1,2]) variable = tf.Variable(tensor) sess = tf.InteractiveSession() # print(sess.run(variable)) # 會報錯 sess.run(tf.initialize_all_variables()) # 對variable進行初始化 print(sess.run(variable)) #===>[[ 0. 0.]]tf.initialize_all_variables,是預先對變量初始化,Tensorflow 的變量必須先初始化,然后才有值!而常值張量是不需要的
placeholder
又叫占位符,同樣是一個抽象的概念。用于表示輸入輸出數據的格式。告訴系統:這里有一個值/向量/矩陣,現在我沒法給你具體數值,不過我正式運行的時候會補上的!例如上式中的x和y。因為沒有具體數值,所以只要指定尺寸即可
x = tf.placeholder(tf.float32,[1, 5],name='input') y = tf.placeholder(tf.float32,[None, 5],name='input')上面有兩種形式,第一種x,表示輸入是一個[1,5]的橫向量。
而第二種形式,表示輸入是一個[?,5]的矩陣。那么什么情況下會這么用呢?就是需要輸入一批[1,5]的數據的時候。比如我有一批共10個數據,那我可以表示成[10,5]的矩陣。如果是一批5個,那就是[5,5]的矩陣。tensorflow會自動進行批處理
Session
session,也就是會話。session是抽象模型的實現者。為什么之前的代碼多處要用到session?因為模型是抽象的嘛,只有實現了模型以后,才能夠得到具體的值。同樣,具體的參數訓練,預測,甚至變量的實際值查詢,都要用到session
# 啟動默認圖. sess = tf.Session() # 調用 sess 的 'run()' 方法, 傳入 'product' 作為該方法的參數, # 觸發了圖中三個 op (兩個常量 op 和一個矩陣乘法 op), # 向方法表明, 我們希望取回矩陣乘法 op 的輸出. result = sess.run(product)# 返回值 'result' 是一個 numpy `ndarray` 對象. print result # ==> [[ 12.]]# 任務完成, 需要關閉會話以釋放資源。 sess.close()Session 對象在使用完后需要關閉以釋放資源. 除了顯式調用 close 外, 也可以使用 “with” 代碼塊 來自動完成關閉動作.
with tf.Session() as sess: result = sess.run([product]) print result交互式使用
在 Python API 中,使用一個會話 Session 來 啟動圖, 并調用 Session.run() 方法執行操作.
為了便于在 IPython 等交互環境使用 TensorFlow,需要用 InteractiveSession 代替 Session 類, 使用 Tensor.eval() 和 Operation.run() 方法代替 Session.run()。
使用更加方便的 InteractiveSession 類。通過它,你可以更加靈活地構建你的代碼。它能讓你在運行
圖的時候,插入一些計算圖,這些計算圖是由某些操作(operations)構成的。這對于工作在交互式環境中的人們來說非常便利,比如使用IPython。如果你沒有使用 InteractiveSession ,那么你需要在啟動session之前構建整個計算圖,然后啟動該計算圖。
計算 ‘x’ 減去 ‘a’:
# 進入一個交互式 TensorFlow 會話. import tensorflow as tf sess = tf.InteractiveSession()x = tf.Variable([1.0, 2.0]) a = tf.constant([3.0, 3.0])# 使用初始化器 initializer op 的 run() 方法初始化 'x' x.initializer.run()# 增加一個減法 sub op, 從 'x' 減去 'a'. 運行減法 op, 輸出結果 sub = tf.sub(x, a) print sub.eval() # ==> [-2. -1.]Tensorflow 調用GPU
with tf.Session() as sess: with tf.device("/gpu:1"): matrix1 = tf.constant([[3., 3.]]) matrix2 = tf.constant([[2.],[2.]]) product = tf.matmul(matrix1, matrix2) ...設備用字符串進行標識. 目前支持的設備包括:
? “/cpu:0” : 機器的 CPU.
? “/gpu:0” : 機器的第一個 GPU, 如果有的話.
? “/gpu:1” : 機器的第二個 GPU, 以此類推.
計算圖
tensorflow的運行流程主要有2步,分別是構造模型和訓練
TensorFlow 程序通常被組織成一個構建階段和一個執行階段. 在構建階段, op 的執行步驟 被描述成一個圖. 在執行階段, 使用會話執行執行圖中的 op.
模型構建
這里我們使用官方tutorial中的mnist數據集的分類代碼,公式可以寫作
z=Wx+ba=softmax(z)那么該模型的代碼描述為
# 建立抽象模型 x = tf.placeholder(tf.float32, [None, 784]) # 輸入占位符,None 表示其值大小不定,在這里作為第一個維度值,用以指代batch的大小,意即 x 的數量不定。 y = tf.placeholder(tf.float32, [None, 10]) # 輸出占位符(預期輸出) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) a = tf.nn.softmax(tf.matmul(x, W) + b) # a表示模型的實際輸出 # 定義損失函數和訓練方法 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(a), reduction_indices=[1])) # 損失函數為交叉熵#tf.reduce_sum 把minibatch里的每張圖片的交叉熵值都加起來了。我們計算的交叉熵是指整個minibatch 的。optimizer = tf.train.GradientDescentOptimizer(0.5) # 梯度下降法,學習速率為0.5 train = optimizer.minimize(cross_entropy) # 訓練目標:最小化損失函數可以看到這樣以來,模型中的所有元素(圖結構,損失函數,下降方法和訓練目標)都已經包括在train里面。我們可以把train叫做訓練模型。那么我們還需要測試模型
correct_prediction = tf.equal(tf.argmax(a, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))上述兩行代碼,tf.argmax表示找到最大值的位置(也就是預測的分類和實際的分類),然后看看他們是否一致,是就返回true,不是就返回false,這樣得到一個boolean數組。tf.cast將boolean數組轉成int數組,最后求平均值,得到分類的準確率.
實際訓練
有了訓練模型和測試模型以后,我們就可以開始進行實際的訓練了
sess = tf.InteractiveSession() # 建立交互式會話 tf.initialize_all_variables().run() # 所有變量初始化 for i in range(1000):batch_xs, batch_ys = mnist.train.next_batch(100) # 獲得一批100個數據train.run({x: batch_xs, y: batch_ys}) # 給訓練模型提供輸入和輸出 print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))可以看到,在模型搭建完以后,我們只要為模型提供輸入和輸出,模型就能夠自己進行訓練和測試了。中間的求導,求梯度,反向傳播等等繁雜的事情,tensorflow都會幫你自動完成。
示例代碼
實際操作中,還包括了獲取數據的代碼
"""A very simple MNIST classifier. See extensive documentation at http://tensorflow.org/tutorials/mnist/beginners/index.md """ from __future__ import absolute_import from __future__ import division from __future__ import print_function# Import data from tensorflow.examples.tutorials.mnist import input_dataimport tensorflow as tfflags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data') # 把數據放在/tmp/data文件夾中mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) # 讀取數據集 #標簽數據是"one-hot vectors"。 一個one-hot向量除了某一位的數字是1以外其余各維度數字都是0。# 建立抽象模型 x = tf.placeholder(tf.float32, [None, 784]) # 占位符, #進行模型計算,a是預測,y 是實際 y = tf.placeholder(tf.float32, [None, 10]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) a = tf.nn.softmax(tf.matmul(x, W) + b)------------------------- #輸入圖像28X28(這個數組展開成一個向量,長度是 28x28 = 784。如何展開這個數組(數字間的順序)不重要,只要保持各個圖片采用相同的方式展開,展平圖片的數字數組會丟失圖片的二維結構信息。) #標簽數據是"one-hot vectors"。 一個one-hot向量除了某一位的數字是1以外其余各維度數字都是0。 ------------------------------------# 定義損失函數和訓練方法 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(a), reduction_indices=[1])) # 損失函數為交叉熵 optimizer = tf.train.GradientDescentOptimizer(0.5) # 梯度下降法,學習速率為0.5 train = optimizer.minimize(cross_entropy) # 訓練目標:最小化損失函數#成本函數是“交叉熵”(cross-entropy)。交叉熵產生于信息論里面的信息壓縮編碼技術,但是它后來演變成為從博弈論到機器學習等其他領域里的重要技術手段.比較粗糙的理解是,交叉熵是用來衡量我們的預測用于描述真相的低效性. -------------------------- # Test trained model correct_prediction = tf.equal(tf.argmax(a, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))#tf.argmax 是一個非常有用的函數,它能給出某個tensor對象在某一維上的其數據最大值所在的索引值。由于標簽向量是由0,1組成,因此最大值1所在的索引位置就是類別標簽,比如 tf.argmax(y,1) 返回的是模型對于任一輸入x預測到的標簽值 #tf.equal 來檢測我們的預測是否真實標簽匹配 --------------------- # Train sess = tf.InteractiveSession() # 建立交互式會話 tf.initialize_all_variables().run() for i in range(1000):batch_xs, batch_ys = mnist.train.next_batch(100)train.run({x: batch_xs, y: batch_ys}) print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})) #執行結果 Extracting /tmp/data/train-images-idx3-ubyte.gz Extracting /tmp/data/train-labels-idx1-ubyte.gz Extracting /tmp/data/t10k-images-idx3-ubyte.gz Extracting /tmp/data/t10k-labels-idx1-ubyte.gz WARNING:tensorflow:From <ipython-input-16-30d57c355fc3>:39: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02. Instructions for updating: Use `tf.global_variables_initializer` instead. 0.9144得到的分類準確率在91%左右
使用變量實現一個簡單的計數器
# -創建一個變量, 初始化為標量 0. 初始化定義初值 state = tf.Variable(0, name="counter")# 創建一個 op, 其作用是使 state 增加 1 one = tf.constant(1) new_value = tf.add(state, one) update = tf.assign(state, new_value)# 啟動圖后, 變量必須先經過`初始化` (init) op 初始化, # 才真正通過Tensorflow的initialize_all_variables對這些變量賦初值 init_op = tf.initialize_all_variables()# 啟動默認圖, 運行 op with tf.Session() as sess:# 運行 'init' opsess.run(init_op)# 打印 'state' 的初始值# 取回操作的輸出內容, 可以在使用 Session 對象的 run() 調用 執行圖時, # 傳入一些 tensor, 這些 tensor 會幫助你取回結果. # 此處只取回了單個節點 state,# 也可以在運行一次 op 時一起取回多個 tensor: # result = sess.run([mul, intermed])print sess.run(state)# 運行 op, 更新 'state', 并打印 'state'for _ in range(3):sess.run(update)print sess.run(state)# 輸出:# 0 # 1 # 2 # 3
過程就是:建圖->啟動圖->運行取值
Deep MNIST for Experts
見腳本
input_data.py
執行結果
step 0, train_accuracy 0.22 step 100, train_accuracy 0.84 step 200, train_accuracy 0.92 step 300, train_accuracy 0.9 step 400, train_accuracy 0.96 step 500, train_accuracy 0.9 step 600, train_accuracy 1 step 700, train_accuracy 0.96 step 800, train_accuracy 0.92 step 900, train_accuracy 0.98 step 1000, train_accuracy 0.94 step 1100, train_accuracy 0.9 step 1200, train_accuracy 0.96 step 1300, train_accuracy 0.98 step 1400, train_accuracy 0.96 step 1500, train_accuracy 0.98 step 1600, train_accuracy 0.96 step 1700, train_accuracy 1 step 1800, train_accuracy 1 step 1900, train_accuracy 0.98 step 2000, train_accuracy 0.98 step 2100, train_accuracy 0.98 step 2200, train_accuracy 1 step 2300, train_accuracy 0.96 step 2400, train_accuracy 1 step 2500, train_accuracy 0.98 step 2600, train_accuracy 0.98 step 2700, train_accuracy 0.98 step 2800, train_accuracy 0.98 step 2900, train_accuracy 0.96 step 3000, train_accuracy 1 step 3100, train_accuracy 1 step 3200, train_accuracy 0.98 step 3300, train_accuracy 1 step 3400, train_accuracy 0.98 step 3500, train_accuracy 0.96 step 3600, train_accuracy 0.98 step 3700, train_accuracy 0.96 step 3800, train_accuracy 1 step 3900, train_accuracy 1 step 4000, train_accuracy 1 step 4100, train_accuracy 1 step 4200, train_accuracy 0.98 step 4300, train_accuracy 1 step 4400, train_accuracy 1 step 4500, train_accuracy 0.96 step 4600, train_accuracy 1 step 4700, train_accuracy 0.96 step 4800, train_accuracy 0.98 step 4900, train_accuracy 1 step 5000, train_accuracy 1 step 5100, train_accuracy 1 step 5200, train_accuracy 1 step 5300, train_accuracy 0.98 step 5400, train_accuracy 0.98 step 5500, train_accuracy 1 step 5600, train_accuracy 1 step 5700, train_accuracy 0.98 step 5800, train_accuracy 0.98 step 5900, train_accuracy 1 step 6000, train_accuracy 0.98 step 6100, train_accuracy 1 step 6200, train_accuracy 0.98 step 6300, train_accuracy 0.98 step 6400, train_accuracy 1 step 6500, train_accuracy 0.98 step 6600, train_accuracy 0.98 step 6700, train_accuracy 1 step 6800, train_accuracy 1 step 6900, train_accuracy 1 step 7000, train_accuracy 0.98 step 7100, train_accuracy 1 step 7200, train_accuracy 0.96 step 7300, train_accuracy 0.98 step 7400, train_accuracy 0.96 step 7500, train_accuracy 1 step 7600, train_accuracy 1 step 7700, train_accuracy 1 step 7800, train_accuracy 1 step 7900, train_accuracy 1 step 8000, train_accuracy 0.98 step 8100, train_accuracy 1 step 8200, train_accuracy 1 step 8300, train_accuracy 1 step 8400, train_accuracy 0.98 step 8500, train_accuracy 0.94 step 8600, train_accuracy 1 step 8700, train_accuracy 1 step 8800, train_accuracy 1 step 8900, train_accuracy 1 step 9000, train_accuracy 0.98 step 9100, train_accuracy 1 step 9200, train_accuracy 0.98 step 9300, train_accuracy 1 step 9400, train_accuracy 1 step 9500, train_accuracy 1 step 9600, train_accuracy 1 step 9700, train_accuracy 1 step 9800, train_accuracy 1 step 9900, train_accuracy 0.98 step 10000, train_accuracy 1 step 10100, train_accuracy 0.98 step 10200, train_accuracy 1 step 10300, train_accuracy 1 step 10400, train_accuracy 1 step 10500, train_accuracy 1 step 10600, train_accuracy 1 step 10700, train_accuracy 1 step 10800, train_accuracy 1 step 10900, train_accuracy 1 step 11000, train_accuracy 1 step 11100, train_accuracy 1 step 11200, train_accuracy 1 step 11300, train_accuracy 1 step 11400, train_accuracy 0.98 step 11500, train_accuracy 1 step 11600, train_accuracy 1 step 11700, train_accuracy 1 step 11800, train_accuracy 0.98 step 11900, train_accuracy 1 step 12000, train_accuracy 1 step 12100, train_accuracy 1 step 12200, train_accuracy 0.98 step 12300, train_accuracy 1 step 12400, train_accuracy 1 step 12500, train_accuracy 1 step 12600, train_accuracy 1 step 12700, train_accuracy 1 step 12800, train_accuracy 1 step 12900, train_accuracy 1 step 13000, train_accuracy 0.98 step 13100, train_accuracy 1 step 13200, train_accuracy 1 step 13300, train_accuracy 0.98 step 13400, train_accuracy 1 step 13500, train_accuracy 1 step 13600, train_accuracy 1 step 13700, train_accuracy 1 step 13800, train_accuracy 1 step 13900, train_accuracy 1 step 14000, train_accuracy 1 step 14100, train_accuracy 1 step 14200, train_accuracy 1 step 14300, train_accuracy 0.98 step 14400, train_accuracy 1 step 14500, train_accuracy 1 step 14600, train_accuracy 1 step 14700, train_accuracy 1 step 14800, train_accuracy 1 step 14900, train_accuracy 1 step 15000, train_accuracy 1 step 15100, train_accuracy 0.98 step 15200, train_accuracy 1 step 15300, train_accuracy 1 step 15400, train_accuracy 1 step 15500, train_accuracy 1 step 15600, train_accuracy 0.98 step 15700, train_accuracy 1 step 15800, train_accuracy 1 step 15900, train_accuracy 1 step 16000, train_accuracy 1 step 16100, train_accuracy 1 step 16200, train_accuracy 1 step 16300, train_accuracy 0.98 step 16400, train_accuracy 1 step 16500, train_accuracy 1 step 16600, train_accuracy 1 step 16700, train_accuracy 1 step 16800, train_accuracy 1 step 16900, train_accuracy 1 step 17000, train_accuracy 1 step 17100, train_accuracy 1 step 17200, train_accuracy 1 step 17300, train_accuracy 1 step 17400, train_accuracy 1 step 17500, train_accuracy 1 step 17600, train_accuracy 1 step 17700, train_accuracy 1 step 17800, train_accuracy 1 step 17900, train_accuracy 1 step 18000, train_accuracy 1 step 18100, train_accuracy 1 step 18200, train_accuracy 1 step 18300, train_accuracy 0.98 step 18400, train_accuracy 1 step 18500, train_accuracy 1 step 18600, train_accuracy 1 step 18700, train_accuracy 1 step 18800, train_accuracy 1 step 18900, train_accuracy 1 step 19000, train_accuracy 1 step 19100, train_accuracy 1 step 19200, train_accuracy 0.98 step 19300, train_accuracy 1 step 19400, train_accuracy 1 step 19500, train_accuracy 1 step 19600, train_accuracy 1 step 19700, train_accuracy 1 step 19800, train_accuracy 1 step 19900, train_accuracy 1 test accuracy 0.9938 running time is 252.157 s參考文獻
tensorflow筆記:流程,概念和簡單代碼注釋
tensorflow筆記:流程,概念和簡單代碼注釋
TensorFlow 入門
TensorFlow 訓練 MNIST 數據(二)
MNIST機器學習入門
MNIST For ML Beginners
深入MNIST
Deep MNIST for Experts
tensorflow/tensorflow/examples/tutorials/mnist/
Tensorflow英文文檔
2·MNIST機器學習入門
3·深入MNIST
總結
以上是生活随笔為你收集整理的Tensorflow官方文档---起步 MNIST示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 权益、年费、额度三方面分析:中银京东联名
- 下一篇: 申请中银京东联名卡要哪些条件?如何申请?