tensorflow Placeholders Basics of Placeholders


Example

Placeholders allow you to feed values into a tensorflow graph. Aditionally They allow you to specify constraints regarding the dimensions and data type of the values being fed in. As such they are useful when creating a neural network to feed new training examples.

The following example declares a placeholder for a 3 by 4 tensor with elements that are (or can be typecasted to) 32 bit floats.

a = tf.placeholder(tf.float32, shape=[3,4], name='a')

Placeholders will not contain any values on their own, so it is important to feed them with values when running a session otherwise you will get an error message. This can be done using the feed_dict argument when calling session.run(), eg:

# run the graph up to node b, feeding the placeholder `a` with values in my_array 
session.run(b, feed_dict={a: my_array})

Here is a simple example showing the entire process of declaring and feeding a placeholer.

import tensorflow as tf
import numpy as np

# Build a graph
graph = tf.Graph()
with graph.as_default():
    # declare a placeholder that is 3 by 4 of type float32
    a = tf.placeholder(tf.float32, shape=(3, 4), name='a')
    
    # Perform some operation on the placeholder
    b = a * 2
    
# Create an array to be fed to `a`
input_array = np.ones((3,4))

# Create a session, and run the graph
with tf.Session(graph=graph) as session:
    # run the session up to node b, feeding an array of values into a
    output = session.run(b, feed_dict={a: input_array})
    print(output)

The placeholder takes a 3 by 4 array of ones, and that tensor is then multiplied by 2 at node b, wich then returns and prints out the following:

[[ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]]