Python | Creating tensors using different functions in Tensorflow
Last Updated :
21 Nov, 2018
Tensorflow is an open-source machine learning framework that is used for complex numerical computation. It was developed by the Google Brain team in Google. Tensorflow can train and run deep neural networks that can be used to develop several AI applications.
What is a Tensor?
A
tensor can be described as a n-dimensional numerical array. A tensor can be called a generalized matrix. It could be a 0-D matrix (a single number), 1-D matrix (a vector), 2-D matrix or any higher dimensional structure. A tensor is identified by three parameters viz., rank, shape and size. The number of dimensions of the tensor is said to be its rank. The number of columns and rows that the tensor has, is said to be its shape. And, the data type assigned to the tensor's elements is said to be its type.
Importance of Tensor in Tensorflow:
A tensor can be called as the central data type of Tensorflow. It is because tensors are the fundamental components of computation inside the Tensorflow framework. As the name suggests, Tensorflow is a framework that involves defining and running computations involving tensors.
Let's discuss all the different ways to create tensors in Tensorflow.
Method #1: Creating tensor using the
constant()
function.
The most popular function for creating tensors in Tensorflow is the
constant()
function. We need to give values or list of values as argument for creating tensor. If the values given are of type integer, then
int32 is the default data type. And if the values given are of floating type, then
float32
is the default data type.
Python3 1==
# Program to create tensor
# using the constant() function
import tensorflow as tf
t1 = tf.constant([1, 2, 3])
t2 = tf.constant([[1.1, 2.2, 3.3], [4, 5, 6]])
t3 = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
t4 = tf.constant(["String_one", "String_two", "String_three"])
t5 = tf.constant([1.2, 2.3, 3.4], tf.float16, [3], 'N3', False)
sess = tf.Session()
print(t1)
print(sess.run(t1))
print("\n")
print(t2)
print(sess.run(t2))
print("\n")
print(t3)
print(sess.run(t3))
print("\n")
print(t4)
print(sess.run(t4))
print("\n")
print(t5)
print(sess.run(t5))
Output:

Here, t1 is a one-dimensional tensor and has three integer values of datatype int32. t2 is a two-dimensional tensor and it contains floating-point values of datatype float32. t3 is a three-dimensional tensor and it contains integer values of datatype int32. t4 is a one-dimensional having three strings of datatype string. In t5, we have given it a name 'N3', specified the datatype as 'float16' and given the value of shape as 3. Since the shape value of t5 is 3, we cannot pass more than 3 elements in it. Otherwise, it will throw an error.
Method #2: Creating tensor using the
zeros()
function.
The
zeros()
function is used to create tensor with all of its elements as zero. The
shape
of the tensor is the only required argument.
Python3 1==
# Program to create tensor using the zeros() function
import tensorflow as tf
zero_int = tf.zeros([3])
zero_float = tf.zeros([3], tf.int32, 'zero_float')
zero_3d = tf.zeros([3, 3, 3], tf.int8, '3d')
sess = tf.Session()
print(zero_int)
print(sess.run(zero_int))
print("\n")
print(zero_float)
print(sess.run(zero_float))
print("\n")
print(zero_3d)
print(sess.run(zero_3d))
Output:
Method #3: Creating tensor using the "ones()" function.
The
ones()
function basically does the same thing as the
zeros()
function, but the elements are one in this case instead of zero.
Python3 1==
# Program to create tensor using the ones() function
import tensorflow as tf
one_float = tf.ones([3])
one_complex = tf.ones([2, 2], tf.complex64, 'complex_ones_tensor')
one_3d = tf.ones([3, 3, 3], tf.int8, '3d')
sess = tf.Session()
print(one_float)
print(sess.run(one_float))
print("\n")
print(one_complex)
print(sess.run(one_complex))
print("\n")
print(one_3d)
print(sess.run(one_3d))
Output:
Method #4: Creating tensor using the
fill()
function.
The
fill()
function is used to create tensors with all the elements in the tensor having the same value. The value of the element is to be passed as an argument and the datatype depends upon that value passed.
Python3 1==
# Program to create tensor using the fill() function
import tensorflow as tf
fill_1d = tf.fill([3], 10)
fill_2d = tf.fill([2, 2], 6, '2d')
fill_string = tf.fill([2, 2], "str", 'fill_tensor_string')
fill_3d = tf.fill([3, 3, 3], 1.2, '3d')
sess = tf.Session()
print(fill_1d)
print(sess.run(fill_1d))
print("\n")
print(fill_2d)
print(sess.run(fill_2d))
print("\n")
print(fill_string)
print(sess.run(fill_string))
print("\n")
print(fill_3d)
print(sess.run(fill_3d))
Output:
Method #5: Creating tensors using the
linspace()
function.
The
linspace()
function is used in creating tensors in which we specify the starting value, ending value and the number of elements as arguments and the elements of the tensor changes its values based on the arguments.
Python3 1==
# Program to create tensor using the linspace() function
import tensorflow as tf
linspace_inc = tf.linspace(1.0, 10.0, 5, "linspace_inc")
linspace_dec = tf.linspace(100.0, 10.0, 20, "linspace_dec")
sess = tf.Session()
print(linspace_inc)
print(sess.run(linspace_inc))
print("\n")
print(linspace_dec)
print(sess.run(linspace_dec))
Output:
Method #6: Creating tensors using the
range()
function.
The
range()
function is almost the same as the linspace() function. The only difference is that in the range() function, we specify a value called
delta
, that is used to calculate the successive elements of the tensor, instead of the number of elements in the
linspace()
function.
Python3 1==
# Program to create tensor using the range() function
import tensorflow as tf
range_inc = tf.range(10.0, 100.0, delta = 25.5)
range_dec = tf.range(100.0, delta = 25.5, name ="range_dec")
sess = tf.Session()
print(range_inc)
print(sess.run(range_inc))
print("\n")
print(range_dec)
print(sess.run(range_dec))
Output:
Similar Reads
tensorflow.math.atan2() function in Python
TensorFlow is open-source python library designed by Google to develop Machine Learning models and deep learning  neural networks. atan2() is used to find element wise arctangent of y/x. Syntax: tf.math.atan2(y, x, name) Parameters: y: It's the input tensor. Allowed dtype for this tensor are bfloat
2 min read
Difference Between tf.Session() And tf.InteractiveSession() Functions in Python Tensorflow
In this article, we are going to see the differences between  tf.Session() and tf.InteractiveSession(). tf.Session() In TensorFlow, the computations are done using graphs. But when a graph is created, the values and computations are not defined. So a session is used to run the graph. The sessions pl
2 min read
Python - tensorflow.math.bessel_i1() function
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. bessel_i1() is function present in tensorflow math module. This function is used to find element wise first order modified Bessel function. Syntax: tensorflow.math.besse
1 min read
Graphs and Functions in TensorFlow
TensorFlow is a powerful machine learning library that allows developers to create and train models efficiently. One of the foundational concepts in TensorFlow is its computational graph system, which provides a structured way to define and execute operations. Along with graphs, TensorFlow offers tf
9 min read
Using bfloat16 with TensorFlow models in Python
In this article, we will discuss bfloat16 (Brain Floating Point 16) in Python. It is a numerical format that occupies 16 bits in memory and is used to represent floating-point numbers. It is similar to the more commonly used 32-bit single-precision float (float32) and 64-bit double-precision float (
2 min read
Python - tensorflow.identity_n()
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. identity_n() is used get a list of Tensor with same shape and content as input Tensor. Syntax: tensorflow.identity_n( input, name) Parameters: input:  It is a Tensor.na
2 min read
tf.transpose() function in TensorFlow
In TensorFlow tf.transpose() is used to rearrange the dimensions of a tensor. It works just like the transpose of a matrix where rows become columns and columns become rows. If youâre working with higher-dimensional data like 3D or 4D tensors tf.transpose() allow you to shuffle the dimensions howeve
2 min read
Random number generation using TensorFlow
In the field of Machine Learning, Random numbers generation plays an important role by providing stochasticity essential for model training, initialization, and augmentation. We have TensorFlow, a powerful open-source machine learning library, that contains tf.random module. This module helps us for
6 min read
Python - tensorflow.math.greater()
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. greater() is used to find element wise truth value of x>y. It supports broadcasting Syntax: tensorflow.math.greater( x, y, name) Parameters: x: It is a tensor. Allow
2 min read
Using the SavedModel format in Tensorflow
TensorFlow is a popular deep-learning framework that provides a variety of tools to help users build, train, and deploy machine-learning models. One of the most important aspects of deploying a machine learning model is saving and exporting it to a format that can be easily used by other programs an
4 min read