sess.run()方法

參數(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ù)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容