Tensorflow的会话运行feed_dict方法的例子或解释 ? 它的作用是什么?

问题描述 投票:1回答:1
 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()方法的代码片段。有谁能解释一下,最好能举个例子说明它在推荐系统中的应用?

python python-3.x tensorflow dictionary tensorboard
1个回答
0
投票

为了能够在不同的问题集上运行相同的模型,我们需要占位符和feed dictionary。

在TensorFlow中,占位符类似于变量,你可以通过使用 tf.placeholder. 你不必提供一个初始值,你可以在运行时使用 feed_dict 内的论点 session.run

%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 parameter indicate what it we want to computefeed dictionary specifies the placeholder values for that computation.

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]
© www.soinside.com 2019 - 2024. All rights reserved.