參數(shù)詳解
run(fetches, feed_dict=None, options=None, run_metadata=None)
fetches
可以是單個(gè)圖元素(single graph element),也可以是任意嵌套的列表list,元組tuple,名稱(chēng)元組namedtuple,字典dict或包含圖元素的OrderedDict。feed_dict
可選參數(shù)feed_dict允許調(diào)用者替換圖中張量的值(the value of tensors in the graph)。options
可選的options參數(shù)需要一個(gè)RunOptions原型。 選項(xiàng)允許控制該特定步驟的行為(例如,打開(kāi)跟蹤)。run_metadata
可選的run_metadata參數(shù)需要一個(gè)RunMetadata原型。 適當(dāng)時(shí),將在那里收集此步驟的非Tensor輸出。 例如,當(dāng)用戶(hù)在options中打開(kāi)跟蹤時(shí),配置信息將被收集到此參數(shù)中并傳回。
舉例
- 使用feed_dict替換圖中的某個(gè)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)
這樣做的好處是在某些情況下可以避免一些不必要的計(jì)算。除此之外,feed_dict還可以用來(lái)設(shè)置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:
# 變量運(yùn)行前必須做初始化操作
init_op = tf.global_variables_initializer()
sess.run(init_op)
print sess.run(y, feed_dict={x:[[0.7, 0.5]]})
# 運(yùn)行結(jié)果
[[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]]}))
運(yùn)行結(jié)果
# 運(yùn)行結(jié)果
[[3.0904665]
[1.2236414]
[1.7270732]
[2.2305048]]
注意:此時(shí)的a不是一個(gè)tensor,而是一個(gè)placeholder。我們定義了它的type和shape,但是并沒(méi)有具體的值。在后面定義graph的代碼中,placeholder看上去和普通的tensor對(duì)象一樣。在運(yùn)行程序的時(shí)候我們用feed_dict的方式把具體的值提供給placeholder,達(dá)到了給graph提供input的目的。
placeholder有點(diǎn)像在定義函數(shù)的時(shí)候用到的參數(shù)。我們?cè)趯?xiě)函數(shù)內(nèi)部代碼的時(shí)候,雖然用到了參數(shù),但并不知道參數(shù)所代表的值。只有在調(diào)用函數(shù)的時(shí)候,我們才把具體的值傳遞給參數(shù)。