评价此页

torch.sum#

torch.sum(input, *, dtype=None) Tensor#

返回 input 张量中所有元素的和。

参数

input (Tensor) – 输入张量。

关键字参数

dtype (torch.dtype, 可选) – 返回张量所需的数据类型。如果指定,输入张量将在执行操作前转换为 dtype。这对于防止数据类型溢出很有用。默认值:None。

注意

如果您需要特定张量类型的结果,请使用 dtype 参数。否则,结果类型可能会自动提升(例如,从 torch.int32torch.int64)。

示例

>>> a = torch.randn(1, 3)
>>> a
tensor([[ 0.1133, -0.9567,  0.2958]])
>>> torch.sum(a)
tensor(-0.5475)
torch.sum(input, dim, keepdim=False, *, dtype=None) Tensor

返回 input 张量在给定维度 dim 中每行的和。如果 dim 是维度列表,则对所有维度进行求和。

如果 keepdimTrue,则输出张量的大小与 input 相同,除了维度 dim 处的大小为 1。否则,dim 被挤压(参见 torch.squeeze()),导致输出张量减少 1(或 len(dim))个维度。

参数
  • input (Tensor) – 输入张量。

  • dim (intint元组, 可选) – 要缩减的维度。如果为 None,则所有维度都将缩减。

  • keepdim (bool, 可选) – 输出张量是否保留 dim。默认值:False

关键字参数

dtype (torch.dtype, 可选) – 返回张量所需的数据类型。如果指定,输入张量将在执行操作前转换为 dtype。这对于防止数据类型溢出很有用。默认值:None。

示例

>>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.0569, -0.2475,  0.0737, -0.3429],
        [-0.2993,  0.9138,  0.9337, -1.6864],
        [ 0.1132,  0.7892, -0.1003,  0.5688],
        [ 0.3637, -0.9906, -0.4752, -1.5197]])
>>> torch.sum(a, 1)
tensor([-0.4598, -0.1381,  1.3708, -2.6217])
>>> b = torch.arange(4 * 5 * 6).view(4, 5, 6)
>>> torch.sum(b, (2, 1))
tensor([  435.,  1335.,  2235.,  3135.])