sum

paddle.sparse. sum ( x, axis=None, dtype=None, keepdim=False, name=None ) [source]

Computes the sum of sparse tensor elements over the given dimension, requiring x to be a SparseCooTensor or SparseCsrTensor.

Parameters
  • x (Tensor) – An N-D Tensor, the data type is bool, float16, float32, float64, int32 or int64.

  • axis (int|list|tuple, optional) – The dimensions along which the sum is performed. If None, sum all elements of x and 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 x unless keepdim is true, default value is False.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Results of summation operation on the specified axis of input Tensor x. if x.dtype=’bool’ or x.dtype=’int32’, it’s data type is ‘int64’, otherwise it’s data type is the same as x.

Return type

Tensor

Examples

>>> import paddle

>>> dense_x = paddle.to_tensor([[-2., 0.], [1., 2.]])
>>> sparse_x = dense_x.to_sparse_coo(1)
>>> out1 = paddle.sparse.sum(sparse_x)
>>> out1
Tensor(shape=[1], dtype=paddle.float32, place=Place(cpu), stop_gradient=True,
    indices=[0],
    values=1.)
>>> out2 = paddle.sparse.sum(sparse_x, axis=0)
>>> out2
Tensor(shape=[1, 2], dtype=paddle.float32, place=Place(cpu), stop_gradient=True,
    indices=[[0]],
    values=[[-1.,  2.]])
>>> out3 = paddle.sparse.sum(sparse_x, axis=-1)
>>> out3
Tensor(shape=[2], dtype=paddle.float32, place=Place(cpu), stop_gradient=True,
    indices=[[0, 1]],
    values=[-2.,  3.])
>>> out4 = paddle.sparse.sum(sparse_x, axis=1, keepdim=True)
>>> out4
Tensor(shape=[2, 1], dtype=paddle.float32, place=Place(cpu), stop_gradient=True,
    indices=[[0, 1]],
    values=[[-2.],
            [ 3.]])