mindspore.ops.sum
- mindspore.ops.sum(input, dim=None, keepdim=False, *, dtype=None)[source]
Calculate sum of tensor elements over a given dim.
Note
The dim with tensor type is only used for compatibility with older versions and is not recommended.
- Parameters
input (Tensor) – The input tensor.
dim (Union[None, int, tuple(int), list(int), Tensor]) – Dimensions along which the sum is calculated. Default
None
.keepdim (bool) – Whether the output tensor has dim retained or not. If
True
, keep these reduced dimensions and the length is 1. IfFalse
, will not keep these dimensions. DefaultFalse
.
Note
If dim is
None
, sum is calculated on all the elements of the input tensor.If dim is a tuple or list of ints or tensor, sum is calculated on all dimensions specified in dim .
- Keyword Arguments
dtype (
mindspore.dtype
, optional) – The data type returned.- Returns
Tensor
- Supported Platforms:
Ascend
GPU
CPU
Examples
>>> 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