TensorFlow Constants
As the name speaks for itself, Constants are used as constants. They create a node that takes value and it does not change. You can simply create a constant tensor using tf.constant. It accepts the five arguments:
tf.constant(value, dtype=None, shape=None, name='Const', verify_shape=False)
Now let’s take a look at a very simple example.
Example 1:
Let’s create two constants and add them together. Constant tensors can simply be defined with a value:
# create Graph a= tf.constant(2) b= tf.constant() c = x + y # launch the graph in a session with tf.Session() as sess: print(sess.run(c))
In the above figure, we created 3 tensors with “Python-names” a, b, and c. As we didn’t define any “TensorFlow-name” for them, but TensorFlow assigns some default names to them which are observed in the graph: const and const_1 for the input constants and add for the output of the addition operation.
We can easily modify it and define custom names as shown below:
# create graph a = tf.constant(2, name='A') b = tf.constant(3, name='B') c = tf.add(a, b, name='Sum') # launch the graph in a session with tf.Session() as sess: print(sess.run(c))
This time the graph is created with the required tensor names:
Fig2. generated graph (Left) and variables (Right) with the modified names
Constants can also be defined with different types (integer, float, etc.) and shapes (vectors, matrices, etc.). The next example has one constant with type 32bit float and another constant with shape 2X2.
Example 2:
s = tf.constant(2.3, name='scalar', dtype=tf.float32) m = tf.constant([[1, 2], [3, 4]], name='matrix') # launch the graph in a session with tf.Session() as sess: print(sess.run(s)) print(sess.run(m))
[[1 2]][3 4]]
