sess.run() method

Detailed parameter

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

Fetches
can be a single graph element, or any nested list, tuple tuple, named tuple, dictionary dict, or OrderedDict containing graph elements.

The
optional feed_dict parameter feed_dict allows the caller to replace the value of tensors in the graph.

The
optional options parameter requires a RunOptions prototype. Options allow to control the behavior of that particular step (for example, turn on tracing).

The
optional run_metadata parameter of run_metadata requires a RunMetadata prototype. When appropriate, the non-Tensor output of this step will be collected there. For example, when the user turns on tracking in options, the configuration information will be collected in this parameter and sent back.

For example

Use feed_dict to replace the value of a tensor in the graph

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)

The advantage of this is that in some cases, unnecessary calculations can be avoided. In addition, feed_dict can also be used to set the input value of 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]]

Guess you like

Origin blog.csdn.net/jiachun199/article/details/108085390