mindspore.ops.sum

查看源文件
mindspore.ops.sum(input, dim=None, keepdim=False, *, dtype=None)[源代码]

计算tensor在指定维度上元素的和。

说明

Tensor类型的 dim 仅用作兼容旧版本,不推荐使用。

参数:
  • input (Tensor) - 输入tensor。

  • dim (Union[None, int, tuple(int), list(int), Tensor]) - 求和的维度,默认 None

  • keepdim (bool) - 输出tensor是否保留维度,默认 False

说明

如果 dimNone ,对tensor中的所有元素求和; 如果 dim 为tuple, list或Tensor,将对 dim 中所有维度求和。

关键字参数:
返回:

Tensor

支持平台:

Ascend GPU CPU

样例:

>>> import mindspore
>>> x = mindspore.tensor([[[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]],
...                      [[4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5], [6, 6, 6, 6, 6, 6]],
...                      [[7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8], [9, 9, 9, 9, 9, 9]]], mindspore.float32)
>>> out = mindspore.ops.sum(input=x)
>>> print(out)
270.0
>>> out = mindspore.ops.sum(input=x, dim=1)
>>> print(out)
[[ 6.  6.  6.  6.  6.  6.]
 [15. 15. 15. 15. 15. 15.]
 [24. 24. 24. 24. 24. 24.]]
>>> out = mindspore.ops.sum(input=x, dim=2)
>>> print(out)
[[ 6. 12. 18.]
 [24. 30. 36.]
 [42. 48. 54.]]
>>> out = mindspore.ops.sum(input=x, dim=[1, 2])
>>> print(out)
[ 36.  90. 144.]
>>> out = mindspore.ops.sum(input=x, dim=2, keepdim=True)
>>> print(out)
[[[ 6.]
 [12.]
 [18.]]
[[24.]
 [30.]
 [36.]]
[[42.]
 [48.]
 [54.]]]
>>> print(out.ndim)
3