如何在 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