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

Published January 02, 2022

In neural network programming, tensors are frequently used to perform element-by-element operations. In this post, I'll illustrate how to add tensors in PyTorch element-by-tensor.

The torch.add() method is used  for element-by-element addition of tensors. The corresponding tensor elements are then added. A scalar or tensor can be appended to another tensor in various ways. There is no limit to how many tensors we can add. The final tensor's dimension will match the higher-dimensional tensor's.

 

Element-wise addition on tensors in PyTorch

Simply follow the simple steps below to perform element-wise addition on tensors:

Step 1: As a first step, import the torch library to ensure it is already installed.

 Step 2: Next, you'll need to generate and print a number of PyTorch tensors. Add a scalar quantity by first defining it.

Step 3: Apply two or more tensors with the torch. Using the add() method, assign the value to a new variable. The tensor can also have a scalar quantity added to it. Adding tensors in this manner has no effect on the tensors.

Step 4: The final step in the process involves printing the final tensor.

 

Example

The Python code below demonstrates how to add a scalar value to a tensor

import torch

a = torch.Tensor([[4,5],[6,7]])

b = torch.Tensor([11])

print("Tensor1:\n", a)

print("Tensor2:\n", b)

c = torch.add(T1, T2)

print("Result:\n", c)

 

 

Output:

Tensor1:

tensor([[4., 5.],

         [6., 7.]])

Tensor2:

tensor([11.])

Result:

tensor([[15., 16.],

         [17., 18.]])

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

362 Views