torch.add()를 사용할 수 있습니다. PyTorch에서 텐서에 대한 요소별 추가를 수행합니다. 텐서의 해당 요소를 추가합니다. 스칼라나 텐서를 다른 텐서에 추가할 수 있습니다. 차원이 같거나 다른 텐서를 추가할 수 있습니다. 최종 텐서의 차원은 더 높은 차원의 텐서의 차원과 동일합니다.
단계
-
필요한 라이브러리를 가져옵니다. 다음 모든 Python 예제에서 필수 Python 라이브러리는 torch입니다. . 이미 설치했는지 확인하십시오.
-
둘 이상의 PyTorch 텐서를 정의하고 인쇄하십시오. 스칼라 수량을 추가하려면 정의하십시오.
-
torch.add()를 사용하여 둘 이상의 텐서를 추가합니다. 값을 새 변수에 할당합니다. 텐서에 스칼라 수량을 추가할 수도 있습니다. 이 방법을 사용하여 텐서를 추가해도 원래 텐서는 변경되지 않습니다.
-
최종 텐서를 인쇄합니다.
예시 1
다음 Python 프로그램은 스칼라 수량을 atensor에 추가하는 방법을 보여줍니다. 동일한 작업을 수행하는 세 가지 다른 방법이 있습니다.
# Python program to perform element-wise Addition
# import the required library
import torch
# Create a tensor
t = torch.Tensor([1,2,3,2])
print("Original Tensor t:\n", t)
# Add a scalar value to a tensor
v = torch.add(t, 10)
print("Element-wise addition result:\n", v)
# Same operation can also be done as below
t1 = torch.Tensor([10])
w = torch.add(t, t1)
print("Element-wise addition result:\n", w)
# Other way to perform the above operation
t2 = torch.Tensor([10,10,10,10])
x = torch.add(t, t2)
print("Element-wise addition result:\n", x) 출력
Original Tensor t: tensor([1., 2., 3., 2.]) Element-wise addition result: tensor([11., 12., 13., 12.]) Element-wise addition result: tensor([11., 12., 13., 12.]) Element-wise addition result: tensor([11., 12., 13., 12.])
예시 2
다음 Python 프로그램은 1D 및 2D 텐서를 추가하는 방법을 보여줍니다.
# Import the library
import torch
# Create a 2-D tensor
T1 = torch.Tensor([[1,2],[4,5]])
# Create a 1-D tensor
T2 = torch.Tensor([10]) # also t2 = torch.Tensor([10,10])
print("T1:\n", T1)
print("T2:\n", T2)
# Add 1-D tensor to 2-D tensor
v = torch.add(T1, T2)
print("Element-wise addition result:\n", v) 출력
T1: tensor([[1., 2.], [4., 5.]]) T2: tensor([10.]) Element-wise addition result: tensor([[11., 12.], [14., 15.]])
예시 3
다음 프로그램은 2D 텐서를 추가하는 방법을 보여줍니다.
# Import the library
import torch
# create two 2-D tensors
T1 = torch.Tensor([[1,2],[3,4]])
T2 = torch.Tensor([[0,3],[4,1]])
print("T1:\n", T1)
print("T2:\n", T2)
# Add the above two 2-D tensors
v = torch.add(T1,T2)
print("Element-wise addition result:\n", v) 출력
T1: tensor([[1., 2.], [3., 4.]]) T2: tensor([[0., 3.], [4., 1.]]) Element-wise addition result: tensor([[1., 5.], [7., 5.]])