參數(shù)詳解
run(fetches, feed_dict=None, options=None, run_metadata=None)
fetches
可以是單個圖元素(single graph element
),也可以是任意嵌套的列表list
涤姊,元組tuple
详囤,名稱元組namedtuple
,字典dict或包含圖元素的OrderedDict
漓滔。feed_dict
可選參數(shù)feed_dict
允許調用者替換圖中張量的值(the value of tensors in the graph
)。options
可選的options
參數(shù)需要一個RunOptions
原型乖篷。 選項允許控制該特定步驟的行為(例如响驴,打開跟蹤)。run_metadata
可選的run_metadata
參數(shù)需要一個RunMetadata
原型撕蔼。 適當時豁鲤,將在那里收集此步驟的非Tensor輸出。 例如鲸沮,當用戶在options
中打開跟蹤時畅形,配置信息將被收集到此參數(shù)中并傳回。
舉例
- 使用feed_dict替換圖中的某個tensor的值
a = tf.add(2, 5)
b = tf.multiply(a, 3)
with tf.Session() as sess:
sess.run(b)
replace_dict = {a: 15}
sess.run(b, feed_dict = replace_dict)
這樣做的好處是在某些情況下可以避免一些不必要的計算诉探。除此之外,feed_dict還可以用來設置graph的輸入值
x = tf.placeholder(tf.float32, shape=(1, 2))
w1 = tf.Variable(tf.random_normal([2, 3],stddev=1,seed=1))
w2 = tf.Variable(tf.random_normal([3, 1],stddev=1,seed=1))
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
with tf.Session() as sess:
# 變量運行前必須做初始化操作
init_op = tf.global_variables_initializer()
sess.run(init_op)
print sess.run(y, feed_dict={x:[[0.7, 0.5]]})
# 運行結果
[[3.0904665]]
或者多輸入
x = tf.placeholder(tf.float32, shape=(None, 2))
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(y, feed_dict={x: [[0.7, 0.5], [0.2, 0.3], [0.3, 0.4], [0.4, 0.5]]}))
運行結果
# 運行結果
[[3.0904665]
[1.2236414]
[1.7270732]
[2.2305048]]
注意:此時的a不是一個tensor棍厌,而是一個placeholder肾胯。我們定義了它的type和shape竖席,但是并沒有具體的值。在后面定義graph的代碼中敬肚,placeholder看上去和普通的tensor對象一樣毕荐。在運行程序的時候我們用feed_dict的方式把具體的值提供給placeholder,達到了給graph提供input的目的艳馒。
placeholder有點像在定義函數(shù)的時候用到的參數(shù)憎亚。我們在寫函數(shù)內部代碼的時候,雖然用到了參數(shù)弄慰,但并不知道參數(shù)所代表的值第美。只有在調用函數(shù)的時候,我們才把具體的值傳遞給參數(shù)陆爽。