评价此页

torch.sum#

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

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

参数

input (Tensor) – 输入张量。

关键字参数

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

注意

如果您需要结果为特定张量类型,请使用 dtype 参数。否则,结果类型可能会自动提升(例如,从 torch.int32 提升到 torch.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

返回给定维度 diminput 张量每行的和。如果 dim 是一个维度列表,则将所有这些维度进行规约。

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

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

  • dim (inttuple of ints, optional) – 要规约的维度或维度。如果为 None,则规约所有维度。

  • keepdim (bool, optional) – 输出张量是否保留 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.])