函数原型
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