1. 程式人生 > >Tensorflow入門----佔位符、常量和Session

Tensorflow入門----佔位符、常量和Session

安裝好TensorFlow之後,開一個python環境,就可以開始執行和使用TensorFlow了。

先給一個例項,

#先匯入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!”呢,這個看起來很麻煩,是嗎?其實不是的
1.Tensor是什麼?
在 TensorFlow 中,資料不是以整數,浮點數或者字串形式存在的,而是被封裝在一個叫做 tensor 的物件中。Tensor是張量的意思,張量包含了0到任意維度的量,其中,0維的叫做常數,1維的叫做向量,二維叫做矩陣,多維度的就直接叫張量量。在 hello_constant = tf.constant(‘Hello World!’) 程式碼中,hello_constant是一個 0 維度的字串 tensor,tensors 還有很多不同大小:

# 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.Session是Tensorflow中的一個重要概念
Tensorflow中的所有計算都構建在一張計算圖中,這是一種對數學運算過程的視覺化方法。就像剛才的程式碼:

with tf.Session() as sess:
    output = sess.run(hello_constant)

這裡寫圖片描述
這個session就是負責讓這個圖運算起來,session的主要任務就是負責分配GPU或者CPU的。

3.tf.placeholder()
前面程式碼中出現了tf.constant(‘Hello World!’),這個tf.constant是用來定義常量的,其值是不變的,但是如果你需要用到一個變數怎麼辦呢?

這個時候就需要用到tf.placeholder() 和 feed_dict了。
先給程式碼

x = tf.placeholder(tf.string)

with tf.Session() as sess:
    output = sess.run(x, feed_dict={x: 'Hello World'})

tf.placeholder表示一個佔位符,至於是什麼型別,看自己定義了,這裡定義的是tf.string型別,然後呢,在session開始run以前,也就死這個圖開始計算以前,就使用feed_dict將對應的值傳入x,也就是這個佔位符。
同樣的feed_dict可以設定多個tensor

x = tf.placeholder(tf.string)
y = tf.placeholder(tf.int32)
z = tf.placeholder(tf.float32)

with tf.Session() as sess:
    output = sess.run(x, feed_dict={x: 'Test String', y: 123, z: 45.67})

但是需要注意的是,使用feed_dict設定tensor的時候,需要你給出的值型別與佔位符定義的型別相同。