dgl.sparse.SparseMatrix.sum

SparseMatrix.sum(dim: Optional[int] = None)

Computes the sum of non-zero values of the input sparse matrix along the given dimension dim.

Parameters
  • input (SparseMatrix) – The input sparse matrix

  • dim (int, optional) –

    The dimension to reduce, must be either 0 (by rows) or 1 (by columns) or None (on both rows and columns simultaneously)

    If dim is None, it reduces both the rows and the columns in the sparse matrix, producing a tensor of shape input.val.shape[1:]. Otherwise, it reduces on the row (dim=0) or column (dim=1) dimension, producing a tensor of shape (input.shape[1],) + input.val.shape[1:] or (input.shape[0],) + input.val.shape[1:].

Returns

Reduced tensor

Return type

torch.Tensor

Examples

Case1: scalar-valued sparse matrix

>>> indices = torch.tensor([[0, 1, 1], [0, 0, 2]])
>>> val = torch.tensor([1, 1, 2])
>>> A = dglsp.spmatrix(indices, val, shape=(4, 3))
>>> dglsp.sum(A)
tensor(4)
>>> dglsp.sum(A, 0)
tensor([2, 0, 2])
>>> dglsp.sum(A, 1)
tensor([1, 3, 0, 0])

Case2: vector-valued sparse matrix

>>> indices = torch.tensor([[0, 1, 1], [0, 0, 2]])
>>> val = torch.tensor([[1, 2], [2, 1], [2, 2]])
>>> A = dglsp.spmatrix(indices, val, shape=(4, 3))
>>> dglsp.sum(A)
tensor([5, 5])
>>> dglsp.sum(A, 0)
tensor([[3, 3],
        [0, 0],
        [2, 2]])