A Brief about tensors in TensorFlow

In this tutorial, we will gain an understanding of what exactly is tensor in the TensorFlow Python deep learning module. Here you are going to learn, how can we create tensors, get information from tensors, manipulate tensors, etc!?

Introduction

You have probably heard of TensorFlow if you know about machine learning & deep learning. It has become a universal norm and one of the most common instruments for machine learning and deep learning professionals.

TensorFlow is an open-source library for creating machine learning models. It is a great platform for anyone interested in working with machine learning and practical skills.

That means if you want to work in ML and AI industry, you have to be comfortable with this tool.

Why TensorFlow?

TensorFlow is an open-source end-to-end machine learning platform. It has a broad, pliable ecosystem of tools, libraries, and community resources that allow inquisitors to push the current state of the ML and developers to easily produce and use powerful ML applications.

What is Tensor?

Tensors are multidimensional arrays. Tensors are like a Numpy array in Python.

  • It could be a number themselves (using tensors to represent house sale price)
  • Can be an image (using tensors to represent pixel of image)
  • Could be a text (using tensor to represent a text).

scalar tensor-  0 dimension.

vector tensor – which has more than 0 dimension

matrix tensor – has greater than 1 dimension

tensor- n-dimension

Import TensorFlow Library

Check TensorFlow version

# Import TensorFlow
import tensorflow as tf
print(tf.__version__)

Output

2.4.1

Let’s see how to create tensors in TensorFlow

Important keywords :

  • Type – Represent the type of data tensor hold like integers, floating-point, etc.
  • Shape – Represent the shape of tensors like (2,2) means 2 rows and 2 columns.
  • N-dim – Represent the dimension of tensor.

1. tf.constant()

Create a constant tensor from the tensor object.

  • Scalar Tensor- 0 dimension
# Lets Create a scalar (with 0 dimension)
scalars = tf.constant(123)
scalars

Output

<tf.Tensor: shape=(), dtype=int32, numpy=123>

Now check the dimension of scalar

# Check the  dimensions of scalar a tensor 
scalars.ndim
0
  • Vector Tensor

Let’s Create a vector (greater than 0 dimensions)

vector = tf.constant([10, 10])
vector

Output

<tf.Tensor: shape=(2,), dtype=int32, numpy=array([10, 10], dtype=int32)>
  • Matrix tensor

Let’s Create a matrix (greater than 1 dimension)

matrix = tf.constant([[10, 7],
                      [7, 10]])
matrix

Output

<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[10,  7],
       [ 7, 10]], dtype=int32)>

The output shows that the matrix tensor follows the shape of (2,2) with datatype=int32.

Check the dimension of the matrix

matrix.ndim
2

As you can see that the matrix has 2 dimensions.

  • Tensor –    n-dimensional
# How about a tensor? (greater than 2 dimensions, although, all of the above items(sclar,matrix,vetcor) are also tensors)
tensor = tf.constant([[[71, 72, 73], [74, 75, 76]], [[77, 78, 79], [80, 81, 82]], [[83, 84, 85], [86, 87, 98]]]) 
tensor

Output

<tf.Tensor: shape=(3, 2, 3), dtype=int32, numpy=
array([[[71, 72, 73],
        [74, 75, 76]],

       [[77, 78, 79],
        [80, 81, 82]],

       [[83, 84, 85],
        [86, 87, 98]]])

Check Dimensions of tensor

tensor.ndim

3

The output shows that the tensor has 3 dimensions.

2. tf.ones()

Let’s see how to create tensors of all ones.

# Creating  tensor of all ones
tf.ones(shape=(3, 4))

Output

<tf.Tensor: shape=(3, 4), dtype=float32, numpy=
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]], dtype=float32)>

As you can see that tensors of 3 rows and 4 columns are created with all ones.

3. tf.zeros()

Let’s see how to create tensors for all zeros

# Make a tensor of all zeros
tf.zeros(shape=(3, 4))

Output

<tf.Tensor: shape=(3, 4), dtype=float32, numpy=
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]], dtype=float32)>

As you can see that tensors of 3 rows and 4 columns are created with zeros.

4. tf. random.Generator()

Random tensors ​​are the tensor of some arbitrary size that contains random numbers.

Let’s see how to make random tensors.

# Creating two random (but the identical) tensors
random_t1 = tf.random.Generator.from_seed(78) # set the seed for repeatability
random_t1 = random_t1.normal(shape=(3, 2)) # create tensor from a normal distribution 
random_t2 = tf.random.Generator.from_seed(78)
random_t2 = random_t2.normal(shape=(3, 2))

# Are they equal?
random_t1, random_t2, random_t1 == random_t2

Output

(<tf.Tensor: shape=(3, 2), dtype=float32, numpy=
 array([[-1.4084325 , -1.8613014 ],
        [ 1.0928144 , -0.29996362],
        [-0.7382552 ,  1.2053189 ]], dtype=float32)>,
 <tf.Tensor: shape=(3, 2), dtype=float32, numpy=
 array([[ 0.69211644,  0.84215707],
        [-0.06378496,  0.92800784],
        [-0.6039789 , -0.1766927 ]], dtype=float32)>,
 <tf.Tensor: shape=(3, 2), dtype=bool, numpy=
 array([[ True,  True],
        [ True,  True],
        [ True,  True]])>)

Explanation: First we create 2 random tensors then check whether the two tensors are equal or not if equal return True otherwise False.

Basic Tensor Operations

  • Add

Let’s apply the addition operation in tensors.

# You can add values to a tensor using the addition operator
tensor = tf.constant([[10, 7], [3, 10]])
tensor + 10

Output

<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[20, 17],
       [13, 20]])>

The above output is like :10+10=20 |   7+10=17  | 3+10=13 |  10+10=20

  • Subtract

Let’s perform the subtraction in tensors.

# Subtraction
tensor - 10

Output

<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 0, -3],
       [-7,  0]])>

The above output is like : 10-10=0  | 7-10=-3 | 3-10=-7 | 10-10=0

  • Multiply

Let’s apply the multiplication operation in tensors.

# Use the tensorflow function equivalent of the '*' (multiply) operator
tf.multiply(tensor, 10)

Output

<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[100,  70],
       [ 30,  40]], dtype=int32)>

The above output is like : 10*10=100 | 7*10=70 | 3*10=30 | 4*10=40

Leave a Reply

Your email address will not be published.