Course Content
TensorFlow for Beginners
About Lesson

Creating a Tensor

Following is the way of creating a Tensor

Syntax:

tf.constant(value, dtype, name = "")

Arguments:

-`value`: Value of n-dimension to define the tensor.

Optional –

‘dtype’ – Define the type of data:

  • `tf.string`: String variable
  • `tf.int16`: Integer variable
  • `tf.float32`: Flot variable
  • “name”: Name of the tensor.

Optional:

By default, `Const_1:0`

 

To create a tensor of dimension 0

import tensorflow as tf  
r1 = tf.constant(1, tf.int16)   
print(r1)  
r2 = tf.constant(1, tf.int16, name = "my_scalar")   
print(r2)

 

The output of the above code will be Tensor(“Const_1:0”, shape=(), dtype=int16) Tensor(“my_scalar:0”, shape=(), dtype=int16)

 

To create a tensor with decimal or string values

import tensorflow as tf  
# Decimal  
r1_decimal = tf.constant(1.12345, tf.float32)  
print(r1_decimal)  
# String  
r1_string = tf.constant("infovistar", tf.string)  
print(r1_string)

 

The output of the above code will be Tensor(“Const_2:0”, shape=(), dtype=float32) Tensor(“Const_3:0”, shape=(), dtype=string)

 

To create a tensor of dimension 1

import tensorflow as tf  
r2_boolean = tf.constant([True, True, False], tf.bool)  
print(r2_boolean)  
## Rank 2  
r2_matrix = tf.constant([ [1, 2],  
                          [3, 4] ], tf.int16)  
print(r2_matrix)

 

The output of the above code will be Tensor(“Const_4:0”, shape=(3,), dtype=bool) Tensor(“Const_5:0”, shape=(2, 2), dtype=int16)