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

Published January 02, 2022

PyTorch is a tensor processing library that runs on GPUs. As a fully convolutional framework, PyTorch may also be used for numerical computation. This article will look at how to use PyTorch to do element-wise multiplication on tensors.   

The torch.mul() method in PyTorch is used to multiply tensors element by element. The constituents of the relevant tensor are multiplied. It is possible to multiply two or multiple tensors. Scalars and tensors can be multiplied as well. You can multiply two or more tensors with the same or different dimensions. The dimension of the resultant tensor will be the same as the dimension of the higher-dimensional tensor. 

 

How to Perform element-wise multiplication on tensors in PyTorch

Follow the simple steps below to perform element-wise multiplication on tensors:

Step 1: Import the required torch Python library.

Step 2: Create at least two tensors using PyTorch and print them out.

Step 3: define the multiplicative scalar.

Step 4: use a torch to multiply two or more tensor. Use the output of mul() and assign a new value to the variable.

Step 5: This is the last step in the process, and it involves printing the final tensor.

 

Example

import torch

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

b = torch.Tensor([[3,0],[6,7]])

print("Tensor1:\n", a)

print("Tensor2:\n", b)

v = torch.mul(a,b)

print("Element-wise Multiplication value is:\n", v)

 

 

Output:

T1:

tensor([[5., 4.],

         [2., 4.]])

T2:

tensor([[3., 0.],

         [6., 7.]])

Element-wise Multiplication value is:

tensor([[ 15., 0.],

         [12., 28.]])

 

 

Download Source code

 

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

586 Views