tf.Session.run()函数参数fetches和feed_dict解析

函数原型

run(
    fetches,
    feed_dict=None,
    options=None,
    run_metadata=None
)

参数说明

  • fetches:单个图元素,图元素列表或字典,字典元素其值是图元素或图元素列表。
  • feed_dict:将图元素映射到值的字典。

返回值
如果fetches是单个图元素则返回单个值,如果fetches是列表则返回值列表,如果fetches是字典则返回具有相同键的字典。
举例:

1. fetches举例

   a = tf.constant([10, 20])
   b = tf.constant([1.0, 2.0])
   # 'fetches' 是单个的图元素
   v = session.run(a)       # v is the numpy array [10, 20]
  
   # 'fetches' 是一个图元素列表
   """
   		v is a Python list with 2 numpy arrays: 
   		the 1-D array [10, 20] and the 1-D array [1.0, 2.0]
   """
   v = session.run([a, b])
   
   # 'fetches' can be arbitrary lists, tuples, namedtuple, dicts:
   MyData = collections.namedtuple('MyData', ['a', 'b'])
   v = session.run({'k1': MyData(a, b), 'k2': [b, a]})
   # v is a dict with
   # v['k1'] is a MyData namedtuple with 'a' (the numpy array [10, 20]) and
   # 'b' (the numpy array [1.0, 2.0])
   # v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array
   # [10, 20].

2. feed_dict举例

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:
    # 变量运行前必须做初始化操作
    sess.run(tf.global_variables_initializer())
    print(sess.run(y, feed_dict={x:[[0.7, 0.5]]}))

在运行程序的时候我们用feed_dict的方式把具体的值提供给placeholder,达到了给graph提供input的目的。 placeholder有点像在定义函数的时候用到的参数。我们在写函数内部代码的时候,虽然用到了参数,但并不知道参数所代表的值。只有在调用函数的时候,我们才把具体的值传递给参数,而在TF中正是通过feed_dict来实现传值的。

参考:https://blog.csdn.net/qq_36666115/article/details/80017305

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值