# megengine.functional.sum¶

sum(inp, axis=None, keepdims=False)[源代码]

Calculates the sum of tensor elements over a given axis (or axes).

Tensor

if the sum was computed over the entire tensor, a zero-dimensional tensor containing the sum; otherwise, a tensor containing the sums. The returned tensor must have a data type determined by 类型提升规则.

Special Cases

Let N equal the number of elements over which to compute the sum.

• If N is 0, the sum is 0 (i.e., the empty sum).

• If $$x_i$$ is NaN, the sum is NaN (i.e., NaN values propagate).

If the accumulator is too small, overflow occurs:

>>> x = F.ones(128, dtype="int8")
>>> F.sum(x)
Tensor(-128, dtype=int8, device=xpux:0)


The sum of an empty tensor is the neutral element 0:

>>> F.sum(Tensor([]))
Tensor(0.0, device=xpux:0)


Normal case:

>>> F.sum(Tensor([1, 2, 3]))
Tensor(6, dtype=int32, device=xpux:0)
>>> F.sum(Tensor([0.5, 1.5]))
Tensor(2.0, device=xpux:0)


Along an axis:

>>> F.sum(Tensor([[1, 2, 3], [4, 5, 6]]), axis=0)
Tensor([5 7 9], dtype=int32, device=xpux:0)
>>> F.sum(Tensor([[1, 2, 3], [4, 5, 6]]), axis=1)
Tensor([ 6 15], dtype=int32, device=xpux:0)