A placeholder in TensorFlow is simply a variable whose value is to be assigned sometime in the future. Placeholders are mainly used to outline operations and build computation graphs without the need to feed data first. The data is later fed into the placeholder at runtime. In TensorFlow, placeholders shouldn’t be confused with variables as they serve different purposes and use cases.
Placeholder | Variable |
Created using | Created with the command |
No initial value is required during the declaration | Initial value must be provided |
Used to feed data into the model | Used for storing trainable model parameters such as weights (W) and biases (B) |
In a nutshell, variables are the parameters of the algorithm and placeholders are objects that allow you to feed in data of a specific type and shape into the model.
A real benefit of using placeholders is that it allows for creating a template by defining a graph without having prior knowledge of the data to be used for execution by the graph.
The syntax for defining a placeholder is as shown in the following snippet:
tf.placeholder(dtype, shape=None, name=None)
dtype
: type of value(s) to be passed into the placeholder
shape
: shape of the expected tensor(s)
name
: a name for the operation
Note: There are two optional parameters, such as shape and name.
Below is a code snippet describing the process of creating placeholders in TensorFlow.
# import TensorFlow V1import tensorflow.compat.v1 as tf# turn Off TF Version 2 behaviortf.disable_v2_behavior()# create placeholdera = tf.placeholder("float", None, name='a')# add value(s) of placeholder with 1.4b = a + 1.4# run session to execute code abovewith tf.Session() as session:# supply 5 values for the placeholderresult = session.run(b, feed_dict={a: [1, 2, 3, 4, 5]})print("The results: ",result)
Line 2: TensorFlow v1 was imported into the environment.
Line 5: The reason TensorFlow v2 features were turned off is because placeholder API was originally developed for TensorFlow v1 and is not compatible with eager execution which comes by default in TF v2.
Line 8: It shows placeholder blueprint has created.
Line 11: A simple operation which adds 1.4 to each value supplied as data for the placeholder. The expected result of the operation above after execution is 2.4, 3.4, 4.4, 5.4, and 6.4 respectively.
Line 14: Session.run
takes the operation we created and the data fed in and returns the result.
Free Resources