sum( x, axis=None, dtype=None, keepdim=False, name=None )
Computes the sum of tensor elements over the given dimension.
x (Tensor) – An N-D Tensor, the data type is float32, float64, int32 or int64.
axis (int|list|tuple, optional) – The dimensions along which the sum is performed. If
None, sum all elements of
xand return a Tensor with a single element, otherwise must be in the range \([-rank(x), rank(x))\). If \(axis[i] < 0\), the dimension to reduce is \(rank + axis[i]\).
dtype (str, optional) – The dtype of output Tensor. The default value is None, the dtype of output is the same as input Tensor x.
keepdim (bool, optional) – Whether to reserve the reduced dimension in the output Tensor. The result Tensor will have one fewer dimension than the
keepdimis true, default value is False.
name (str, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to Name
Results of summation operation on the specified axis of input Tensor x, it’s data type is the same as x.
- Return type
ValueError – If the data type of x is float64,
dtypecan not be float32 or int32.
ValueError – If the data type of x is int64,
dtypecan not be int32.
TypeError – The type of
axismust be int, list or tuple.
import paddle # x is a Tensor with following elements: # [[0.2, 0.3, 0.5, 0.9] # [0.1, 0.2, 0.6, 0.7]] # Each example is followed by the corresponding output tensor. x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], [0.1, 0.2, 0.6, 0.7]]) out1 = paddle.sum(x) # [3.5] out2 = paddle.sum(x, axis=0) # [0.3, 0.5, 1.1, 1.6] out3 = paddle.sum(x, axis=-1) # [1.9, 1.6] out4 = paddle.sum(x, axis=1, keepdim=True) # [[1.9], [1.6]] # y is a Tensor with shape [2, 2, 2] and elements as below: # [[[1, 2], [3, 4]], # [[5, 6], [7, 8]]] # Each example is followed by the corresponding output tensor. y = paddle.to_tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) out5 = paddle.sum(y, axis=[1, 2]) # [10, 26] out6 = paddle.sum(y, axis=[0, 1]) # [16, 20]