In this article, we are going to see how to perform element-wise addition on tensors in PyTorch in Python. We can perform element-wise addition using torch.add() function.
This function also allows us to perform addition on the same or different dimensions of tensors. If tensors are different in dimensions so it will return the higher dimension tensor.
Syntax: torch.add(inp, c, out=None)
Parameters:
- inp: This is input tensor.
- c: The value that is to be added to every element of tensor.
- out: This is optional parameter and it is the output tensor.
Return: returns a new modified tensor..
Example 1: The following program is to perform addition on two single dimension tensors.
Python3
import torch
tens_1 = torch.Tensor([ 10 , 20 , 30 , 40 , 50 ])
tens_2 = torch.Tensor([ 1 , 2 , 3 , 4 , 5 ])
print ( "\nFirst Tensor \n" , tens_1)
print ( "\nsecond Tensor \n" , tens_2)
tens = torch.add(tens_1, tens_2)
print ( "\n After Element-wise Addition\n" , tens)
|
Output:

Example 2: The following program is to perform elements-wise addition on 2D tensors.
Python3
import torch
tens_1 = torch.Tensor([[ 1 , 2 ], [ 3 , 4 ]])
tens_2 = torch.Tensor([[ 10 , 20 ], [ 20 , 40 ]])
print ( "First Tensor \n" , tens_1)
print ( "second Tensor \n" , tens_2)
tens = torch.add(tens_1, tens_2)
print ( "\n After Element-wise Addition\n" , tens)
|
Output:

Example 3: The following program is to shows how to perform elements-wise addition on two different dimension tensors.
Python3
import torch
tens_1 = torch.Tensor([ 1 , 2 ])
tens_2 = torch.Tensor([[ 10 , 20 ], [ 20 , 40 ]])
print ( "\nFirst Tensor \n" , tens_1)
print ( "\nsecond Tensor \n" , tens_2)
tens = torch.add(tens_1, tens_2)
print ( "\n After Element-wise Addition\n" , tens)
|
Output:

Example 4: The following program is to know how to add a scalar quantity to a tensor.
Python3
import torch
tens_1 = torch.Tensor([ 1 , 2 , 3 , 4 ])
tens_2 = torch.Tensor([[ 10 , 20 ], [ 30 , 40 ]])
print ( "\nFirst Tensor \n" , tens_1)
print ( "second Tensor \n" , tens_2)
t1 = torch.add(tens_1, 10 )
print ( "\n After adding scalar quantity to 1D tensor: \n" , t1)
t2 = torch.add(tens_2, 20 )
print ( "\n After adding scalar quantity to 2D tensor: \n" , t2)
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Feb, 2022
Like Article
Save Article