天天看點

Tensorflow——Fetch和Feed操作

一、Fetch操作

Tensorflow中的Fetch操作是指:定義會話,調用op實作相應功能時,Fetch操作可以sess.run()多個op(同時run多個op),将多個op組成數組(或者說清單),傳入run中可以得到多個op的輸出結果。

執行個體展示

  • 定義一些常量和op
import tensorflow as tf
#Fetch的作用:會話裡執行多個op,得到它運作後的結果
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
add = tf.add(input2,input3)
mul = tf.multiply(input1, add)
           
  • 實作Fetch操作
with tf.Session() as sess:
    #會話中執行多個op,這裡的op是mul和add
    result = sess.run([mul,add])
    print(result)
           
  • 結果
Tensorflow——Fetch和Feed操作

二、Feed操作(以後會經常用到)

Feed的字面意思是喂,流入。在tensorflow中,先聲明一個或者幾個tensor,先用占位符(placeholder)給他們留幾個位置。等到後面定義會話,使用run對op進行操作時,再一其他形式,例如字典(feed_dict())的形式把op的參數值傳進去,以達到使用時在傳入參數的目的。

執行個體展示

  • 先使用占位符(placeholder)對tensor進行聲明,同時定義op
import tensorflow as tf
#Feed操作是在一開始不定義參數的具體值,在會話中運作時,再傳入具體的值
#建立占位符
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
           
  • 實作Feed操作
with tf.Session() as sess:
    #Feed的資料以字典(feed_dict)的形式傳入
    print(sess.run(output,feed_dict = {input1:[10.], input2:[2.]}))
           
  • 結果 
Tensorflow——Fetch和Feed操作