如何在 PyTorch 中對張量執行元素級加法?
我們可以使用 **torch.add()** 在 PyTorch 中對張量執行元素級加法。它將張量的對應元素相加。我們可以將標量或張量新增到另一個張量。我們可以新增具有相同或不同維度的張量。最終張量的維度將與更高維度張量的維度相同。
步驟
匯入所需的庫。在以下所有 Python 示例中,所需的 Python 庫是 **torch**。確保您已安裝它。
定義兩個或多個 PyTorch 張量並列印它們。如果要新增標量,請定義它。
使用 **torch.add()** 將兩個或多個張量相加,並將值賦給一個新變數。您還可以將標量新增到張量中。使用此方法新增張量不會對原始張量進行任何更改。
列印最終張量。
示例 1
以下 Python 程式演示瞭如何將標量新增到張量中。我們看到了三種執行相同任務的不同方法。
# 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.]])
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP