现在位置: 首页 > PyTorch 教程 > 正文

PyTorch torch.add 函数


Pytorch torch 参考手册 Pytorch torch 参考手册

torch.add 是 PyTorch 中用于执行逐元素加法的函数。它将两个张量或一个张量和一个标量相加。

这是最基础的数学运算之一,在深度学习中的各种计算场景都会用到。

函数定义

torch.add(input, other, alpha=1, out=None)

参数:

  • input (Tensor): 第一个输入张量。
  • other (Tensor 或 float): 第二个输入张量或标量。
  • alpha (float, 可选): 缩放因子,other 会乘以这个值后再加到 input 上,默认为 1。
  • out (Tensor, 可选): 输出张量。

返回值:

  • torch.Tensor: 返回相加后的张量。

使用示例

示例 1: 两个张量相加

实例

import torch

# 创建两个张量
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])

# 相加
c = torch.add(a, b)

print(c)

输出结果为:

tensor([5, 7, 9])

示例 2: 张量加标量

实例

import torch

# 创建张量
a = torch.tensor([1, 2, 3])

# 加上标量
b = torch.add(a, 10)

print(b)

输出结果为:

tensor([11, 12, 13])

示例 3: 使用 alpha 参数

实例

import torch

# 创建两个张量
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([1.0, 2.0, 3.0])

# 计算 a + 2 * b
c = torch.add(a, b, alpha=2)

print(c)

输出结果为:

tensor([3., 6., 9.])

alpha 参数在实现某些算法时很有用,例如计算 input + alpha * other

示例 4: 广播机制

实例

import torch

# 不同形状的张量相加(广播)
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
b = torch.tensor([1, 2, 3])

c = torch.add(a, b)

print(c)

输出结果为:

tensor([[2, 4, 6],
        [5, 7, 9])

PyTorch 支持广播机制,可以将不同形状的张量进行运算。


使用加号运算符

除了使用 torch.add() 函数,还可以直接使用 + 运算符,两者效果相同:

实例

import torch

a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])

# 两种方式等价
c1 = torch.add(a, b)
c2 = a + b

print(c1)
print(c2)
print(torch.equal(c1, c2))

Pytorch torch 参考手册 Pytorch torch 参考手册