Instagram
youtube
Facebook
Twitter

Basic Operations on Tensors

Tensors are used to hold complex data in deep learning and machine learning models. They are the basis of many libraries including Tensorflow and Pytorch.

We can perform various operations on tensors, including addition, subtraction, multiplication, division, and reshaping etc.

In this tutorial, we will learn about how to perform basic operations on tensors. Some common operations are:

1. Addition - we can add two or more tensors in tensorflow using “tf.add” function.

import tensorflow as tf
a = tf.constant([2,2,2])
b = tf.constant([1,1,1])
c = tf.add(a,b)
print(c)

Output - 

tf.Tensor([3 3 3], shape=(3,), dtype=int32)

 

2. Subtraction  - we can subtract one tensor from other in tensorflow using “tf.subtract” function.

import tensorflow as tf
a = tf.constant([2,2,2])
b = tf.constant([1,1,1])
c = tf.subtract(a,b)
print(c)

Output - 

tf.Tensor([1 1 1], shape=(3,), dtype=int32)

 

3. Multiplication  - we can perform multiplication on two or more tensors in tensorflow using “tf.multiply” function.

import tensorflow as tf
a = tf.constant([2,2,2])
b = tf.constant([1,1,1])
c = tf.multiply(a,b)
print(c)

Output - 

tf.Tensor([2 2 2], shape=(3,), dtype=int32)

 

4. Division  - we can perform Division on two tensors in tensorflow using “tf.divide” function.

import tensorflow as tf
a = tf.constant([2,2,2])
b = tf.constant([1,1,1])
c = tf.divide(a,b)
print(c)

Output - 

tf.Tensor([2. 2. 2.], shape=(3,), dtype=float64)

 

5. Reshaping  - we can reshape a tensor using tf.reshape() function.

import tensorflow as tf
a = tf.constant([2,2,2,5,6,8])
b = tf.reshape(a, [2,3])
print(b)

Output - 

tf.Tensor(
[[2 2 2]
 [5 6 8]], shape=(2, 3), dtype=int32)

 

6. Matrix Multiplication  - we can perform matrix multiplication between two tensors using the tf.matmul() function.

a = tf.constant([[2,2],[2,2]])
b = tf.constant([[2,3],[4,5]])
c = tf.matmul(a,b)
print(c)

Output - 

tf.Tensor(
[[12 16]
 [12 16]], shape=(2, 2), dtype=int32)