- placeholder —佔位符
參考莫煩PYTHON視頻P12
placeholder, 譯爲佔位符,官方說法:”TensorFlow provides a placeholder operation that must be fed with data on execution.” 即必須在執行時feed值。
placeholder 實例通常用來爲算法的實際輸入值作佔位符。
例如
Tensorflow 如果想要從外部傳入data, 那就需要用到 tf.placeholder(), 然後以這種形式傳輸數據 sess.run(***, feed_dict={input: **}).
示例:
import tensorflow as tf
#在 Tensorflow 中需要定義 placeholder 的 type ,一般爲 float32 形式
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
#mul=multiply是將input1和input2做乘法運算,並輸出爲output
ouput = tf.multiply(input1, input2)
接下來, 傳值的工作交給了 sess.run() , 需要傳入的值放在了feed_dict={} (這在python中相當於一本字典)並一一對應每一個 input. placeholder 與 feed_dict={} 是綁定在一起出現的。
with tf.Session() as sess:
print(sess.run(ouput, feed_dict={input1: [7.], input2: [2.]}))
輸出
#[14.]
- variable —變量
參考:莫煩PYTHON視頻P11
在 Tensorflow 中,定義了某字符串是變量,它纔是變量,這一點是與 Python 所不同的。
定義語法: state = tf.Variable()
import tensorflow as tf
state = tf.Variable(0, name='counter')
#定義常量one
one = tf.constant(1)
#定義加法步驟(注:此步並沒有直接計算)
new_value = tf.add(state, one)
#將state更新爲new_value
update = tf.assign(state, new_value)
如果你在 Tensorflow 中設定了變量,那麼初始化變量是最重要的!!所以定義了變量以後, 一定要定義
init = tf.initialize_all_variables() .
到這裏變量還是沒有被激活,需要再在 sess 裏,
sess.run(init)
激活 init 這一步.
#如果定義variable,就一定要initialize
#init = tf.initialize_all_variables() # tf 馬上就要廢棄這種寫法
init = tf.global_variables_initializer() # 替換成這樣就好
#使用session
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))
注意:直接 print(state) 不起作用!!
一定要把 sess 的指針指向 state 再進行 print 才能得到想要的結果!