def run(self, fetches, feed_dict=None, options=None, run_metadata=None):
"""Runs operations and evaluates tensors in `fetches`.
This method runs one "step" of TensorFlow computation, by
running the necessary graph fragment to execute every `Operation`
and evaluate every `Tensor` in `fetches`, substituting the values in
这是 session.py 中 run() 方法的代码片段。有人可以用推荐系统中的使用示例更好地解释这一点吗?
最佳答案
为了能够在不同的问题集上运行相同的模型,我们需要占位符和提要字典。
TensorFlow 中的占位符类似于变量,您可以使用 tf.placeholder
声明它。您不必提供初始值,您可以在运行时使用 session.run
内的 feed_dict
参数指定它
%tensorflow_version 1.x
import tensorflow as tf
#Setup placeholder using tf.placeholder
x = tf.placeholder(tf.int32, shape=[3],name='x')
'''It is of type integer and it has shape 3 meaning it is a 1D vector with 3 elements in it
we name it x. just create another placeholder y with same dimension'''
y = tf.placeholder(tf.int32, shape=[3],name='y')
sum_x = tf.reduce_sum(x,name="sum_x")
prod_y = tf.reduce_prod(y,name="prod_y")
with tf.Session() as sess:
print ("sum_x: ", sess.run(sum_x, feed_dict={x: [100,200,300]}))
print ("prod_y: ", sess.run(prod_y, feed_dict={y: [1,2,3]}))
输出:
sum_x: 600
prod_y: 6
我们将 fetches
和 feed_dict
传递到每个 session.run
命令中。 Fetches 参数指示我们要计算的内容
,feed 字典指定该计算的占位符值
。
W = tf.constant([10,100], name='const_W')
x = tf.placeholder(tf.int32, name='x')
b = tf.placeholder(tf.int32, name='b')
#tf.multiply is simple multiplication
Wx = tf.multiply(W,x, name="Wx")
#tf.add is simple addition
y = tf.add(Wx, b, name='y')
with tf.Session() as sess:
'''All the code which require a session is writer here
here Wx is the fetches parameter. Fetches refers to the node of the graph we want to compute
feed_dict is used to pass the values for the placeholders '''
print( "Intermediate result Wx:", sess.run(Wx, feed_dict={x:[3,33]}))
print( "Final results y:",sess.run(y, feed_dict={Wx:[5,5], b:[9,99]}))
输出:
Intermediate result Wx: [30 3300]
Final results y: [14 104]
关于python - Tensorflow 的 session 运行 feed_dict 方法的示例或解释?它有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60126143/