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)
  • 结果

 

二、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.]}))
  • 结果 

猜你喜欢

转载自blog.csdn.net/gaoyu1253401563/article/details/86004375
今日推荐