sess.run()方法

参数详解

run(fetches, feed_dict=None, options=None, run_metadata=None)
  • fetches
    可以是单个图元素(single graph element),也可以是任意嵌套的列表list,元组tuple,名称元组namedtuple,字典dict或包含图元素的OrderedDict

  • feed_dict
    可选参数 feed_dict允许调用者替换图中张量的值(the value of tensors in the graph)。

  • options
    可选的options参数需要一个RunOptions原型。 选项允许控制该特定步骤的行为(例如,打开跟踪)。

  • run_metadata
    可选的run_metadata参数需要一个RunMetadata原型。 适当时,将在那里收集此步骤的非Tensor输出。 例如,当用户在options中打开跟踪时,配置信息将被收集到此参数中并传回。

举例

  • 使用feed_dict替换图中的某个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)

这样做的好处是在某些情况下可以避免一些不必要的计算。除此之外,feed_dict还可以用来设置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:
    # 变量运行前必须做初始化操作
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print sess.run(y, feed_dict={x:[[0.7, 0.5]]})
# 运行结果
[[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]]}))

运行结果

# 运行结果
[[3.0904665]
 [1.2236414]
 [1.7270732]
 [2.2305048]]

注意:此时的a不是一个tensor,而是一个placeholder。我们定义了它的type和shape,但是并没有具体的值。在后面定义graph的代码中,placeholder看上去和普通的tensor对象一样。在运行程序的时候我们用feed_dict的方式把具体的值提供给placeholder,达到了给graph提供input的目的
placeholder有点像在定义函数的时候用到的参数。我们在写函数内部代码的时候,虽然用到了参数,但并不知道参数所代表的值。只有在调用函数的时候,我们才把具体的值传递给参数。

你可能感兴趣的:(sess.run()方法)