前言:
tensorflow中有很多基本概念要理解,最好的方法是去官網跟著教程一步一步看,這裡還有一些翻譯的版本,對照著看有助於理解:tensorflow1.0 文檔翻譯 本文:
一,構建並執行計算圖的必要過程
1,graph(圖計算):詳見tf.Graph類
使用tensorflow訓練神經網路包括兩部分:構建計算圖和運行計算圖。
首先來講構建圖,一個計算圖包含了一組操作(operation objects,也叫節點)和一些tensor objects(節點之間傳遞的資料單元)。系統會預設構建一個計算圖,這也是mnist入門案例上來就可以定義節點的原因。不過我們在寫代碼的時候,應該將構建計算圖的代碼寫在一個with塊中
myGraph = tf.Graph()with myGraph.as_default(): # Define operations and tensors in `myGraph `.(在下面定義op和tensor) c = tf.constant(30.0)
2,operations(圖節點):詳見tf.Operation類
op是計算圖中的節點,它能接收tensor作為輸入,並能產生tensor作為輸出。op的建立方式有兩種,一種是調用了計算操作,比如mnist例子中的tf.matmul(),tf.nn.conv2d(),tf.nn.max_pool()函數等,這些函數名就是op。另一種方法是調用Graph.create_op()方法往圖裡加op。常用第一種方法。op在構建圖的階段不會執行,在運行圖階段才執行。
3,tensor(向量):詳見tf.Tensor類
tensor就是op計算的輸入/輸出結果。同樣的,tensor在構建圖時並不持有值,而是在運行時持有數值。tensor作為op的輸入/輸出在graph中傳遞,從而使得tensorflow能執行代表著大規模計算的計算圖,也正是Tensorflow得名的原因(向量流動)。常量和變數都是tensor。舉例如下,a,b,c,d就是tensor,它們可以作為op的輸出值,也可以作為op的輸入值。
# Build a dataflow graph.a = tf.constant([[1.0, 2.0], [3.0, 4.0]])b = tf.constant([[1.0, 1.0], [0.0, 1.0]])c = tf.matmul(c, d)d = tf.Variable([1.0, 2.0])
4,session(會話):詳見tf.Session類
前面3步我們已經構建完了一個計算圖,現在需要執行這個計算圖。session就是執行計算圖的類。 tensor的執行要通過sess.run(tensor)來執行。session對象封裝了op執行和tensor傳遞的環境。session對象開啟後會持有資源,所以用完後要記得關閉,通常寫到一個with塊裡面。綜合1234,我們寫一個例子。
myGraph = tf.Graph()with myGraph.as_default(): # Build a graph. a = tf.constant(5.0) b = tf.constant(6.0) c = a * b# Using the context manager.with tf.Session() as sess: print(sess.run(c))
二, Tensor相關的屬性和方法
1,tensor的屬性,常用的有下面這些:
dtype:tensor中元素的類型(tf.int32, tf.float32等)
graph:tensor所屬的計算圖(返回Graph類對象的地址)
name:tensor的字串名字,若定義tensor的時候取了名字,則輸出你取的名字。若你自己沒有取,系統會按規則幫你給tensor取名字,規則如下:若tensor是常量,則第一個tensor取名“Const”,第二個tensor取名“Const_1”,第三個tensor取名“Const_2”,以此類推。若tensor是變數,則第一個tensor取名“Variable”,第二個tensor取名“Variable_1”,第三個tensor取名“Variable_2”,以此類推。這個知識點在save/restore模型的時候會用到。
op:產生改tensor的op名。會列出該op的詳細資料。
shape:tensor的形狀。
舉例說明(tensor的屬性可直接列印,不需要放進sess.run()裡面):
# encoding=utf-8import tensorflow as tfgraph = tf.Graph()with graph.as_default(): x= tf.constant([[1.,2.,3.,4.],[5.,6.,7.,8.]],dtype=tf.float32) x1= tf.constant([[1.,2.,3.,4.],[5.,6.,7.,8.]],dtype=tf.float32) x2= tf.constant([[1.,2.,3.,4.],[5.,6.,7.,8.]],dtype=tf.float32) y= tf.Variable([[0.,0.,-2.,1.],[-1,-2,-2,-3]]) y1= tf.Variable([[0.,0.,-2.,1.],[-1,-2,-2,-3]]) y2= tf.Variable([[0.,0.,-2.,1.],[-1,-2,-2,-3]]) y3= y1+y2# shape:tensor的形狀# size:tensor元素個數# rank:tensor的維度with tf.Session(graph=graph) as sess: print(x.shape) print(x.dtype) print(x.graph) print(x.name) print(x1.name) print(x2.name) print(y.name) print(y1.name) print(y2.name) print(y3.shape)
2,tensor的方法
–get_shape():得到tensor的shape,效果跟shape屬性一樣。
–eval(feed_dict=None, session=None):執行tensor的方法,調用這個方法將執行該tensor所需輸入的所有op。eval()方法要在session中調用。tensor.eval()效果與sess.run(tensor)相同,官網原文是這樣說的:t.eval() is a shortcut for calling tf.get_default_session().run(t)。至少我沒看出這兩個的區別。