如何在 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)输出结果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程序显示了如何将2D张量除以1D张量。
# 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程序显示了如何将2D张量除以2D张量。
# 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]])