Skip to content
Related Articles

Related Articles

What’s the difference between tf.placeholder and tf.Variable?

Improve Article
Save Article
  • Last Updated : 30 Aug, 2022
Improve Article
Save Article

In this article, we are going to see the difference between tf.placeholder and tf.Variable.


As the name suggests, it is an empty place. It is an empty variable to which the training data is fed later. The tf.placeholder allows us to create the structure first which is setting up of computational graphs and then feeding the data into it. It allows us to put the data during runtime. As the session starts, we feed the data into the placeholders.

Syntax: tf.compat.v1.placeholder(dtype, shape=None, name=None) 

  • dtype is the datatype of the input
  • shape is the tensor shape. However, it is an optional parameter.
  • name is the operation name

Let us elaborate with the help of an example


# import packages
import tensorflow.compat.v1 as tf 
# disable eager mode
# create empty placeholder
a = tf.placeholder(tf.float32, name='a')  
b = tf.placeholder(tf.float32, name='b')  
# create third node and perform subtraction
c = tf.subtract(a, b, name='c')  
sess = tf.Session()
# run session, feed_dict={a: 1, b: 8})  



In the above code, we created two placeholders and create a third node ‘c’ to perform the subtraction. Finally, we use to perform the operation.


tf.Variable is a state that holds an initial value. The values are nothing but tensors. The variables can be added to the computational graph by calling the constructors. Whenever a variable is created, it is always initialized. They basically hold weights and biases during the session execution.



Let us elaborate with the help of an example


# import packages
import tensorflow as tf
# create variables
tensor1 = tf.Variable([3, 4])
tensor2 = tf.Variable([2, 3])


Tensor("sub:0", shape=(2,), dtype=int32)

In the above code, we create two tensor variables and initialize them with two lists. Then we perform subtraction of two tensors and get the result.

Difference between tf.placeholder and tf.Variable

tf.placeholder tf.Variable
It is an empty variable in which data is fed at a later part of the code.  The variable once declared must be initialized with an initial value at the time of declaration.
Placeholders are bound inside expressions. Variables are used to hold the value of weights and biases.
The values are specific and are not changed during the execution of the program.  The values are changed during the execution of the program.
It is used to handle external data. It is used to store the values that will be required throughout the program.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!