python - Tensorflow 的 session 运行 feed_dict 方法的示例或解释?它有什么作用?

标签 python python-3.x tensorflow dictionary tensorboard

 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

我们将 fetchesfeed_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/

相关文章:

python - OpenCV 错误:(-215:断言失败)函数 'CvtHelper' 中的 VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth)

python - 按键连接数据框 - 重复数据作为新列

python - 为什么我可以重新分配 dict.update 但不能重新分配 dict.__setitem__

python - 尝试访问命令行变量时出现 Pytest KeyError

python - Tensorflow 安装和导入正确,但在尝试使用时抛出异常

machine-learning - 如何在神经网络的输出中执行诸如国际象棋走棋合法性之类的规则?

python - 使用图像序列作为时间分布式 conv2d 的输入

python - 运行 python 脚本时出错 - 语法无效

python - 通过在 Python 中的字典列表中搜索另一个值来返回一个值

python - Tensorflow 的 Between-graph replication 是数据并行的一个例子吗?