為了使用TensorFlow你需要理解一下幾個方面:TensorFlow是如何
- 把運(yùn)算表示為圖
- 在 Session 的語境下執(zhí)行圖
- 把數(shù)據(jù)用多維向量表示
- 用 Variable 維護(hù)狀態(tài)
- 使用feed和fetch把數(shù)據(jù)放進(jìn)和取出任意的算子
概述
TensorFlow把運(yùn)算表示為圖。圖的節(jié)點(diǎn)是ops(operations)。一個op可以對零個或者多個tensor進(jìn)行運(yùn)算,產(chǎn)生零個或多個tensor。在TensorFlow的語境下,tensor就是一個多維向量。
一個TensorFlow 圖就是一個對運(yùn)算的描述。運(yùn)算開始之前你必須把圖在一個Session中 啟動。Session會把圖放在Devices上面,比如CPU、GPU,然后提供方法來進(jìn)行計算。在Python中這些方法會返回 numpy 的 ndarray,在C/C++中則會返回tensorflow:Tensor類型的實例。
計算流圖
TensorFlow程序一般分為構(gòu)建階段和執(zhí)行階段。在構(gòu)建階段,你可以把圖組合起來,比如神經(jīng)網(wǎng)絡(luò)圖模型。在執(zhí)行階段則用Session在執(zhí)行一系列的ops,比如訓(xùn)練神經(jīng)網(wǎng)絡(luò)的運(yùn)算。
TensorFlow的圖可以用Python、C或者C++來寫,但是Python會簡單一點(diǎn),因為有許多輔助函數(shù)可以使用。
-
構(gòu)建圖
首先從不需要任何輸入的算子開始,比如 Constant 。把輸出結(jié)果傳遞給其他需要輸入的算子。
TF的Python提供了默認(rèn)的圖,可以在大多數(shù)場景下使用。import tensorflow as tf # Create a Constant op that produces a 1x2 matrix. The op is # added as a node to the default graph. # # The value returned by the constructor represents the output # of the Constant op. matrix1 = tf.constant([[3., 3.]]) # Create another Constant that produces a 2x1 matrix. matrix2 = tf.constant([[2.],[2.]]) # Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs. # The returned value, 'product', represents the result of the matrix # multiplication. product = tf.matmul(matrix1, matrix2) -
在Session中啟動圖
# Launch the default graph. sess = tf.Session() # To run the matmul op we call the session 'run()' method, passing 'product' # which represents the output of the matmul op. This indicates to the call # that we want to get the output of the matmul op back. # # All inputs needed by the op are run automatically by the session. They # typically are run in parallel. # # The call 'run(product)' thus causes the execution of three ops in the # graph: the two constants and matmul. # # The output of the matmul is returned in 'result' as a numpy `ndarray` object. result = sess.run(product) print(result) # ==> [[ 12.]] # Close the Session when we're done. sess.close()你可以使用with語句
with tf.Session() as sess: result = sess.run([product]) print(result)通常呢你不需要告訴TF你需要哪個設(shè)備進(jìn)行運(yùn)算,但是如果你有多個GPU的話你就可以指定TF用哪個設(shè)備進(jìn)行運(yùn)算了。比如
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) ...
你可以使用以下字符串來表示設(shè)備:
- "/cpu:0" : 設(shè)備的CPU。
- "/gpu:0" : 設(shè)備的第一塊GPU。
- "/gpu:1" : 設(shè)備的第二塊GPU。
你也可以在分布式集群中運(yùn)行TensorFlow:
with tf.Session("grpc://example.org:2222") as sess:
Calls to sess.run(...) will be executed on the cluster.
...
指定的機(jī)器將會成為你的master,并調(diào)動集群中的其他機(jī)器進(jìn)行運(yùn)算。
或者用```tf.device()```語句來指定worker。
with tf.device("/job:ps/task:0"):
weights = tf.Variable(...)
biases = tf.Variable(...)
### 交互使用
在iPython等交互式的Python環(huán)境中,你可以用```InteractiveSession```類,用```Tensor.eval()```,```Operation.run()```等方法。
Enter an interactive TensorFlow Session.
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])
Initialize 'x' using the run() method of its initializer op.
x.initializer.run()
Add an op to subtract 'a' from 'x'. Run it and print the result
sub = tf.sub(x, a)
print(sub.eval())
==> [-2. -1.]
Close the Session when we're done.
sess.close()
### Tensor
TensorFlow程序使用Tensor來表示所有的數(shù)據(jù)。只有Tensor可以在Operation之間傳遞。你可以把Tensor看作是一個多維數(shù)組。Tensor有靜態(tài)類型、秩以及形狀。
### Variable
Variable 維護(hù)執(zhí)行過程中圖的狀態(tài)。
Create a Variable, that will be initialized to the scalar value 0.
state = tf.Variable(0, name="counter")
Create an Op to add one to state.
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)
Variables must be initialized by running an init Op after having
launched the graph. We first have to add the init Op to the graph.
init_op = tf.global_variables_initializer()
Launch the graph and run the ops.
with tf.Session() as sess:
Run the 'init' op
sess.run(init_op)
Print the initial value of 'state'
print(sess.run(state))
Run the op that updates 'state' and print 'state'.
for _ in range(3):
sess.run(update)
print(sess.run(state))
output:
0
1
2
3
通常你可以把一個統(tǒng)計模型中的參數(shù)表達(dá)為Variable。比如,把神經(jīng)網(wǎng)絡(luò)的權(quán)重表達(dá)為Variable中的tensor。訓(xùn)練過程中你通過不斷地運(yùn)行圖來更新這個tensor。
### Fetches
你可以通過運(yùn)行Session的```run()```方法來獲取tensor的值。比如
input1 = tf.constant([3.0])
input2 = tf.constant([2.0])
input3 = tf.constant([5.0])
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)
with tf.Session() as sess:
result = sess.run([mul, intermed])
print(result)
output:
[array([ 21.], dtype=float32), array([ 7.], dtype=float32)]
所有需要的op都會被運(yùn)行一遍。
### Feeds
Feeds用tensor的值暫時取代了一個op的輸出。你可以把feed的數(shù)據(jù)作為參數(shù)傳進(jìn)```run()```函數(shù)。feed數(shù)據(jù)僅會應(yīng)用于當(dāng)前的 ```run()```。你可以指定```tf.placeholder()```來創(chuàng)建要feed的op。
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)
with tf.Session() as sess:
print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))
output:
[array([ 14.], dtype=float32)]