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

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

存在 大小 operation hold 而是 表示 意思 占位符 不同

安裝好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的時候,需要你給出的值類型與占位符定義的類型相同。

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