vaibhav
vaibhav

Reputation: 158

Example or explanation for Tensorflow's session run feed_dict method ? What does it do?

 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

This is the code snippet for run() method inside session.py. Can some one explain this preferably with an example of its use in recommendation system ?

Upvotes: 2

Views: 1970

Answers (1)

user11530462
user11530462

Reputation:

For the ability to run the same model on different problem set we need placeholders and feed dictionaries.

Placeholders in TensorFlow are similar to variables and you can declare it using tf.placeholder. You don't have to provide an initial value and you can specify it at runtime with feed_dict argument inside 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]}))

Output:

sum_x:  600
prod_y:  6

We give fetches and feed_dict pass into every session.run command. Fetches parameter indicate what it we want to compute and the feed 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]}))

Output:

Intermediate result Wx: [30 3300]
Final results y: [14 104]

Upvotes: 3

Related Questions