tensorflow中張量、常量、變數、佔位符
阿新 • • 發佈:2019-02-14
引言
從例項出發
#先匯入TensorFlow
import tensorflow as tf
# Create TensorFlow object called hello_constant
hello_constant = tf.constant('Hello World!')
with tf.Session() as sess:
# Run the tf.constant operation in the session
output = sess.run(hello_constant)
print(output)
有人會奇怪為什麼不直接輸出“hello world”,其實在tensorflow裡面有它自己的 一套。
正文
1.tensor
在tensorflow中,資料是被封裝在tensor物件中的。tensor是張量的意思,即包含從0到任意維度的張量。常數是0維度的張量,向量是1維度的張量,矩陣是二維度的張量,以及還有多維度的張量。
# tensor1 是一個0維的 int32 tensor tensor1 = tf.constant(1234) # tensor2 是一個1維的 int32 tensor tensor2 = tf.constant([123,456,789]) # tensor3 是一個二維的 int32 tensor tensor3 = tf.constant([ [123,456,789], [222,333,444] ])
2.tf.constant
constant函式提供在tensorflow中定義常量(不可更改的張量)的方法
如:
tensor_constant = tf.constant([1,2,3,4)
3.tf.Variable
tensorflow中的變數是通過Variable類來實現的。tensorflow中需要定義為變數的包括訓練過程中的輸入資料,輸出資料,以及控制從輸入到輸出的學習機制,即網路引數。輸入輸出資料在tf中是用placeholder佔位符來定義的,網路引數是用tf.Variable來定義的。
4.tf.placeholder
用於宣告一個張量的資料格式,告訴系統這裡會有一個這種格式的張量,但是還沒有傳入具體的值。
如:
X = tf.placeholder("float", shape=[None, 100])
上面聲明瞭一個張量X,資料型別是float,100列,行數不確定。
5.tf.Session
以上部分都是搭建一個計算圖的程式碼,在tf中,先搭建好計算圖,然後再啟動session,執行定義好的圖。
import tensorflow as tf
x = tf.placeholder("string")
with tf.Session() as sess:
output = sess.run(x, feed_dict={x : "run the map"})
print(output)
通過上面的例子我們明白瞭如何使用佔位符,首先定義x為佔位符,然後執行的時候將想要傳入的值傳給x。