Understanding Constant in TensorFlow in Python

As constants in any source code, are the actual values that are fixed, the TensorFlow constants are the same. The values assigned to a TensorFlow constant cannot be changed in the future.

We use TensorFlow constants, where we need non-changing value, such as datasets in our Machine Learning.

To define TensorFlow constant, we use…

tf.constant(value, dtype=None, shape=Name, name='Constant')

tf.constant() function is used to create constant in TensorFlow. Here, it will always create host/CPU tensor.

This constant value is stored in tensor, on which the further actions will be performed.

The Arguments for TensorFlow Constant are:

  • Value : A constant value or list. This value is the constant value that is passed to the function.
  • Dtype : It is the data type of the element. dtype is passed to the specify the datatype of the value which is passed as constant. If dtype is not mentioned, then it concludes the type from value, by default.
  • Shape : It is optional dimensions given to the value.
  • Name : Another optional attribute which assigns name for the tensor, which contains the constant value.
  • Verify_shape : It is a boolean value that helps enabling of verification of the shape of values.

 

Let’s look at one simple and short example to understand this better,

import tensorflow as tf
Constant = tf.constant([1,2,3,4,5])

As you can see, in the above code we have passed a list as our constant value.

This will return a constant tensor.

Let’s see one more example with output…

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

a = tf.constant(20, name='a')
b = tf.Variable(a + 5, name='b')

model = tf.global_variables_initializer() 

with tf.Session() as session:
    session.run(model)
    print(session.run(b))

Now, in the above example, we used a constant value to add them to a TensorFlow variable. As we didn’t mention any data type, it will assume that it’s an integer, according to the value we described.

The output of the above code will be:

25

The session we run will return the variable along with the constant value.

To understand how TensorFlow Variables work, refer to the link below:

Assigning a value to a TensorFlow variable in Python

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *