Tensorflow 4: Placeholders

Expanding from my previous post. .  All my code can be found on github (4_Placeholders.ipynb)

Placeholders

Placeholders are variables that we assign the value to at Runtime.  They are used as the way to input data to our graph.

Lets start with a really basic example:

#created graph
import tensorflow as tf

a = tf.placeholder("int16",None)
b = a + 2

We define ‘a‘ as our placeholder and assign it a type of ‘int16‘.  A full list of datatypes can be found here.  The ‘None‘ indicates the shape of the input.

Then we define b to equal ‘a + 2

#Define a dictionary to replace the value of 'a' with
inputs={a:[10,20,30]}

with tf.Session() as session:
    print(session.run(b,feed_dict=inputs))

Ee define a dictionary for a to be the values [10,20,30] called inputs.

We then execute the graph asking to find the value of b.

Feed_Dict

Notice session.run(b) now has an additional argument called feed_dict that is assigned to the dictionary inputs.

feed_dict means feed dictionary which is a dictionary of values that we feed into the data graph. These values are fed in one at a time.

This is the same as running the data graph with:

  • a = 10….. then
  • a= 20….. then
  • a = 30

 

So when we run our graph we get the following output

 

More Advanced

feed_dict can also pass multiple values at once

a = tf.placeholder(dtype=tf.int16,shape=None,name="A_input")
b = tf.placeholder(dtype=tf.int16,shape=None,name="A_input")

c = a + b

#Define a dictionary to replace the value of 'a' with
inputs={a:[10,20,30],b:[20,20,20]}

with tf.Session() as sess:
    print(sess.run(c,feed_dict=inputs))

Which produces