如何在 PyTorch 中对张量执行元素乘法?
torch.mul()方法用于在PyTorch中对张量执行逐元素乘法。它将张量的相应元素相乘。我们可以将两个或更多张量相乘。我们还可以将标量和张量相乘。具有相同或不同维度的张量也可以相乘。最终张量的维度将与高维张量的维度相同。张量上的元素乘法也称为Hadamard乘积。
脚步
导入所需的库。在以下所有Python示例中,所需的Python库是torch。确保您已经安装了它。
定义两个或多个PyTorch张量并打印它们。如果您想乘以一个标量,请定义它。
使用将两个或更多张量相乘并将值分配给新变量。您还可以将标量和张量相乘。使用这种方法乘以张量不会对原始张量产生任何变化。torch.mul()
打印最终张量。
示例1
以下程序显示了如何将标量与张量相乘。使用张量代替标量也可以获得相同的结果。
# Python program to perform element--wise multiplication # import the required library import torch # Create a tensor t = torch.Tensor([2.05, 2.03, 3.8, 2.29]) print("Original Tensor t:\n", t) # Multiply a scalar value to a tensor v = torch.mul(t, 7) print("Element-wise multiplication result:\n", v) # Same result can also be obtained as below t1 = torch.Tensor([7]) w = torch.mul(t, t1) print("Element-wise multiplication result:\n", w) # other way to do above operation t2 = torch.Tensor([7,7,7,7]) x = torch.mul(t, t2) print("Element-wise multiplication result:\n", x)输出结果
Original Tensor t: tensor([2.0500, 2.0300, 3.8000, 2.2900]) Element-wise multiplication result: tensor([14.3500, 14.2100, 26.6000, 16.0300]) Element-wise multiplication result: tensor([14.3500, 14.2100, 26.6000, 16.0300]) Element-wise multiplication result: tensor([14.3500, 14.2100, 26.6000, 16.0300])
示例2
以下Python程序显示了如何将2D张量与1D张量相乘。
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) # Multiply 1-D tensor with 2-D tensor v = torch.mul(T1, T2) # v = torch.mul(T2,T1) print("Element-wise multiplication result:\n", v)输出结果
T1: tensor([[3., 2.], [7., 5.]]) T2: tensor([10., 8.]) Element-wise multiplication result: tensor([[30., 16.], [70., 40.]])
示例3
以下Python程序显示了如何将两个2D张量相乘。
import torch # create two 2-D tensors T1 = torch.Tensor([[8,7],[3,4]]) T2 = torch.Tensor([[0,3],[4,9]]) print("T1:\n", T1) print("T2:\n", T2) # Multiply above two 2-D tensors v = torch.mul(T1,T2) print("Element-wise subtraction result:\n", v)输出结果
T1: tensor([[8., 7.], [3., 4.]]) T2: tensor([[0., 3.], [4., 9.]]) Element-wise subtraction result: tensor([[ 0., 21.], [12., 36.]])