Understanding Constant and Variable in TensorFlow 2.x
CONSTANT
tf.constant is immutable value it means these value will not change in future when code is run for example you defined a bias that is not changing throughout the code execution
Note : by default constant take dtype as int
Let's see how to declare constant in tensorflow
a = tf.constant(value, dtype=None, shape=None)
dtype is your data type you can define it by tf.int32 , tf.float32
shape is your data /matrix shape
Defining 1D array in tensorflow
import tensorflow as tf
a = tf.constant([1,2,3,4] , dtype = tf.int32)
print(a)
#print(a) give output like this
tf.Tensor([1 2 3 4], shape=(4,), dtype=int32)
tf.Tensor([1 2 3 4], shape=(4,), dtype=int32)
print(a.numpy())
#print(a.numpy()) give output like this
[1,2,3,4]
Defining 2D array in Tensorflow
import tensorflow as tf
a = tf.constant([[1,2,3],[4,5,6]],dtype = tf.float32)
print(a.numpy())
output =
[[1. 2. 3.]
[4. 5. 6.]]
notice there are decimal after every number in output in this case the reason is that we define the variable data type as float
Defining Shape in Tensorflow
import tensorflow as tf
a = tf.constant(0,shape=(2,3))
print(a.numpy())
output:
[[0 0 0]
[0 0 0]]
if you want to know dtype or shape of your constant just type
print(a.shape) #note here a is my constant name
print(a.dtype)
VARIABLE
Variable is mutable in tensorflow it means its value can be change in future while executing the code.
Example : weights defining in neural network they will change as our code execute till they didn't get optimum value
Defining 1D array in tensorflow
import tensorflow as tf
a = tf.Variable([1,2,3,4] , dtype = tf.int32)
print(a)
#print(a) give output like this
tf.Tensor([1 2 3 4], shape=(4,), dtype=int32)
tf.Tensor([1 2 3 4], shape=(4,), dtype=int32)
print(a.numpy())
#print(a.numpy()) give output like this
[1,2,3,4]
Defining 2D array in Tensorflow
import tensorflow as tf
a = tf.Variable([[1,2,3],[4,5,6]],dtype = tf.float32)
print(a.numpy())
output =
[[1. 2. 3.]
[4. 5. 6.]]
notice there are decimal after every number in output in this case the reason is that we define the variable data type as float
Defining Shape in Tensorflow
import tensorflow as tf
a = tf.Variable(0,shape=(2,3))
print(a.numpy())
output:
[[0 0 0]
[0 0 0]]
if you want to know dtype or shape of your constant just type
print(a.shape) #note here a is my Variable name
print(a.dtype)
we are going to learn more about variable modification addition in later on articles
0 Comments
if you are not getting it then ask i am glad to help