![]() |
In this article, we will understand how to perform element-wise division of two tensors in PyTorch. To perform the element-wise division of tensors, we can apply the torch.div() method. It takes two tensors (dividend and divisor) as the inputs and returns a new tensor with the element-wise division result. We can use the below syntax to compute the element-wise division-
Example: Inputs: tensor([10., 25., 30.]) tensor([2., -5., 10.]) Output: tensor([5., -5., 3.]) Inputs: tensor([3., 0., 23.]) tensor([2., -5., 0.]) Output: tensor([1.5, -0., inf]) Let’s understand how the element-wise division of tensors works with the help of some Python examples. Example 1:In the example below, we perform the element-wise division of two 1-D tensors using the PyTorch method torch.div(). Python3
Output: Tensor A: tensor([ 0.0312, 0.3401, 0.1645, -1.0781]) Tensor B: tensor([-1.8584, 0.5706, -0.8994, 2.2492]) Element-wise Division Output: tensor([-0.0168, 0.5960, -0.1829, -0.4793]) Example 2:In the example below, we perform the element-wise division of a 2D tensor by a 2D tensor using the PyTorch method torch.div(). We also apply different rounding modes. Python3
Output: Tensor a: tensor([[-1.8665, 0.6341, 0.8920], [-0.1712, 0.3949, 1.9414], [-1.2088, -1.0375, -1.3087], [ 0.9161, -0.2972, 1.5289]]) Tensor b: tensor([[-0.2187, 0.5252, -0.5840], [ 1.5293, -0.4514, 1.8490], [-0.7269, -0.1561, -0.0629], [-0.5379, -0.9751, 0.6541]]) Element-wise Division: Result: tensor([[ 8.5345, 1.2073, -1.5274], [-0.1119, -0.8748, 1.0500], [ 1.6630, 6.6464, 20.8060], [-1.7031, 0.3048, 2.3374]]) Result with rounding_mode='trunc': tensor([[ 8., 1., -1.], [-0., -0., 1.], [ 1., 6., 20.], [-1., 0., 2.]]) Result with rounding_mode='floor': tensor([[ 8., 1., -2.], [-1., -1., 1.], [ 1., 6., 20.], [-2., 0., 2.]]) Example 3:In the below example, we perform the element-wise division of a 3-D tensor by a 1-D tensor using the PyTorch method torch.div(). Python3
Output: Tensor a : tensor([[[-0.7549, 1.8301], [-0.5545, 1.3180]], [[ 0.1159, 0.8394], [ 0.0452, -1.2860]], [[ 0.3850, -0.9654], [-1.5530, -0.8627]]]) Tensor b : tensor([-1.2378, 0.2153]) Elementwise Division Output : tensor([[[ 0.6098, 8.5011], [ 0.4480, 6.1226]], [[-0.0937, 3.8991], [-0.0365, -5.9739]], [[-0.3110, -4.4844], [ 1.2546, -4.0074]]]) |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 8 |