如何在PyTorch中对张量进行逐元素除法?


在PyTorch中对两个张量进行逐元素除法,可以使用**torch.div()**方法。它将第一个输入张量的每个元素除以第二个张量的对应元素。我们也可以用一个标量除以一个张量。可以使用相同或不同维度的张量相除。最终张量的维度将与维度较高的张量相同。如果我们用一个一维张量除以一个二维张量,那么最终张量将是一个二维张量。

步骤

  • 导入所需的库。在以下所有Python示例中,所需的Python库是**torch**。确保你已经安装了它。

  • 定义两个或多个PyTorch张量并打印它们。如果要将张量除以标量,请定义一个标量。

  • 使用**torch.div()**将张量除以另一个张量或标量,并将值赋给一个新的变量。使用此方法除以张量不会对原始张量进行任何更改。

  • 打印最终张量。

示例1

# Python program to perform element-wise division # import the required library import torch # Create a tensor t = torch.Tensor([2, 3, 5, 9]) print("Original Tensor t:\n", t) # Divide a tensor by a scalar 4 v = torch.div(t, 4) print("Element-wise division result:\n", v) # Same result can also be obtained as below t1 = torch.Tensor([4]) w = torch.div(t, t1) print("Element-wise division result:\n", w) # other way to do above operation t2 = torch.Tensor([4,4,4,4]) x = torch.div(t, t2) print("Element-wise division result:\n", x)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Original Tensor t:
   tensor([2., 3., 5., 9.])
Element-wise division result:
   tensor([0.5000, 0.7500, 1.2500, 2.2500])
Element-wise division result:
   tensor([0.5000, 0.7500, 1.2500, 2.2500])
Element-wise division result:
   tensor([0.5000, 0.7500, 1.2500, 2.2500])

示例2

下面的Python程序演示了如何将一个二维张量除以一个一维张量。

# import the required library import torch # Create a 2D tensor T1 = torch.Tensor([[3,2],[7,5]]) # Create a 1-D tensor T2 = torch.Tensor([10, 8]) print("T1:\n", T1) print("T2:\n", T2) # Divide 2-D tensor by 1-D tensor v = torch.div(T1, T2) print("Element-wise division result:\n", v)

输出

T1:
tensor([[3., 2.],
         [7., 5.]])
T2:
tensor([10., 8.])
Element-wise division result:
tensor([[0.3000, 0.2500],
         [0.7000, 0.6250]])

示例3

下面的Python程序演示了如何将一个一维张量除以一个二维张量。

# Python program to dive a 1D tensor by a 2D tensor # import the required library import torch # Create a 2D tensor T1 = torch.Tensor([[8,7],[4,5]]) # Create a 1-D tensor T2 = torch.Tensor([10, 5]) print("T1:\n", T1) print("T2:\n", T2) # Divide 1-D tensor by 2-D tensor v = torch.div(T2, T1) print("Division 1D tensor by 2D tensor result:\n", v)

输出

T1:
tensor([[8., 7.],
         [4., 5.]])
T2:
tensor([10., 5.])
Division 1D tensor by 2D tensor result:
tensor([[1.2500, 0.7143],
         [2.5000, 1.0000]])

您可以注意到最终张量是一个二维张量。

示例4

下面的Python程序演示了如何将一个二维张量除以一个二维张量。

# import necessary library import torch # Create two 2-D tensors T1 = torch.Tensor([[8,7],[3,4]]) T2 = torch.Tensor([[0,3],[4,9]]) # Print the above tensors print("T1:\n", T1) print("T2:\n", T2) # Divide T1 by T2 v = torch.div(T1,T2) print("Element-wise division result:\n", v)

输出

T1:
tensor([[8., 7.],
         [3., 4.]])
T2:
tensor([[0., 3.],
         [4., 9.]])
Element-wise division result:
tensor([[ inf, 2.3333],
         [0.7500, 0.4444]])

更新于:2021年11月6日

5K+ 浏览量

启动您的职业生涯

完成课程获得认证

开始
广告