Open In App

Placeholders in Tensorflow

A placeholder is a variable in Tensorflow to which data will be assigned sometime later on. It enables us to create processes or operations without the requirement for data. Data is fed into the placeholder as the session starts, and the session is run. We can feed in data into tensorflow graphs using placeholders. 

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



Parameters:

  • dtype: the datatype of the elements in the tensor that will be fed.
  • shape : by default None. The tensor’s shape that will be fed , it is an optional parameter. One can feed a tensor of any shape if the shape isn’t specified.
  • name: by default None. The operation’s name , optional parameter.

Returns:



A Tensor that can be used to feed a value but cannot be evaluated directly.

Example 1: 




# importing packages
import tensorflow.compat.v1 as tf
  
# disabling eager mode
tf.compat.v1.disable_eager_execution()
  
# creating a placeholder
a = tf.placeholder(tf.float32, None)
  
# creating an operation
b = a + 10
  
# creating a session
with tf.Session() as session:
    
    # feeding data in the placeholder
    operation_res = session.run(b, feed_dict={a: [10, 20, 30, 40]})
    print("after executing the operation: " + str(operation_res))

Output:

after executing the operation: [20. 30. 40. 50.]

Explanation:

Example 2:




# importing packages
import tensorflow.compat.v1 as tf
  
# disabling eager mode
tf.compat.v1.disable_eager_execution()
  
# creating a tensorflow graph
graph = tf.Graph()
with graph.as_default():
    
    # creating a placeholder
    a = tf.placeholder(tf.float64, shape=(3, 3), name='tensor1')
      
    # creating an operation
    b = a ** 2
  
# array1 will be fed into 'a'
array1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  
# Creating a session, and running the graph
with tf.Session(graph=graph) as session:
      
    # run the session until it reaches node b,
    # then input an array of values into a
    operation_res = session.run(b, feed_dict={a: array1})
    print("after executing the operation: ")
    print(operation_res)

Output:

after executing the operation: 
[[ 1.  4.  9.]
 [16. 25. 36.]
 [49. 64. 81.]]

Article Tags :