# How to perform element-wise addition on tensors in PyTorch?

We can use torch.add() to perform element-wise addition on tensors in PyTorch. It adds the corresponding elements of the tensors. We can add a scalar or tensor to another tensor. We can add tensors with same or different dimensions. The dimension of the final tensor will be same as the dimension of the higher dimension tensor.

## Steps

• Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already installed it.

• Define two or more PyTorch tensors and print them. If you want to add a scalar quantity, define it.

• Add two or more tensors using torch.add() and assign the value to a new variable. You can also add a scalar quantity to the tensor. Adding the tensors using this method does not make any change in the original tensors.

• Print the final tensor.

## Example 1

The following Python program shows how to add a scalar quantity to a tensor. We see three different ways to perform the same task.

# Python program to perform element-wise Addition
# import the required library
import torch

# Create a tensor
t = torch.Tensor([1,2,3,2])
print("Original Tensor t:\n", t)

# Add a scalar value to a tensor

# Same operation can also be done as below
t1 = torch.Tensor()

# Other way to perform the above operation
t2 = torch.Tensor([10,10,10,10])
print("Element-wise addition result:\n", x)

## Output

Original Tensor t:
tensor([1., 2., 3., 2.])
tensor([11., 12., 13., 12.])
tensor([11., 12., 13., 12.])
tensor([11., 12., 13., 12.])

## Example 2

The following Python program shows how to add 1D and 2D tensors.

# Import the library
import torch

# Create a 2-D tensor
T1 = torch.Tensor([[1,2],[4,5]])

# Create a 1-D tensor
T2 = torch.Tensor() # also t2 = torch.Tensor([10,10])
print("T1:\n", T1)
print("T2:\n", T2)

# Add 1-D tensor to 2-D tensor
print("Element-wise addition result:\n", v)

## Output

T1:
tensor([[1., 2.],
[4., 5.]])
T2:
tensor([10.])
tensor([[11., 12.],
[14., 15.]])

## Example 3

The following program shows how to add 2D tensors.

# Import the library
import torch

# create two 2-D tensors
T1 = torch.Tensor([[1,2],[3,4]])
T2 = torch.Tensor([[0,3],[4,1]])
print("T1:\n", T1)
print("T2:\n", T2)

# Add the above two 2-D tensors
print("Element-wise addition result:\n", v)

## Output

T1:
tensor([[1., 2.],
[3., 4.]])
T2:
tensor([[0., 3.],
[4., 1.]])
[7., 5.]])