torch.mul() 메서드는 PyTorch의 텐서에 대해 요소별 곱셈을 수행하는 데 사용됩니다. 텐서의 해당 요소를 곱합니다. 두 개 이상의 텐서를 곱할 수 있습니다. 스칼라와 텐서를 곱할 수도 있습니다. 차원이 같거나 다른 텐서도 곱할 수 있습니다. 최종 텐서의 차원은 고차원 텐서의 차원과 동일합니다. 텐서의 요소별 곱셈은 하다마르 곱이라고도 합니다.
단계
-
필요한 라이브러리를 가져옵니다. 다음 모든 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.]])