sparse_mask

paddle.Tensor. sparse_mask ( self: Tensor, mask: Tensor, name: str | None = None ) → Tensor

constructs a sparse tensor by extracting values from a dense source at the unique, sorted indices defined by a sparse mask.

Parameters
  • self (Tensor) – The input dense tensor (will be filtered).

  • mask (Tensor) – Sparse tensor (SparseCooTensor or SparseCsrTensor) used as mask.

  • name (str, optional) – Operation name (ignored in this implementation).

Returns

A sparse tensor with the same indices as mask, containing values from self at mask positions.

Return type

SparseTensor

Examples

>>> import paddle
>>> paddle.set_device('cpu')
>>> paddle.seed(2024)

>>> crows = [0, 2, 3, 5]
>>> cols = [1, 3, 2, 0, 1]
>>> values = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> dense_shape = [3, 4]
>>> csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape)
>>> x = paddle.rand(dense_shape)
>>> out = x.sparse_mask(csr)
>>> print(out)
Tensor(shape=[3, 4], dtype=paddle.float32, place=Place(cpu), stop_gradient=True,
crows=[0, 2, 3, 5],
cols=[1, 3, 2, 0, 1],
values=[0.23659813, 0.08467803, 0.64152628, 0.66596609, 0.90394485])

>>> paddle.seed(2024)
>>> indices = [[0, 1, 2], [1, 2, 0]]
>>> values = [1.0, 2.0, 3.0]
>>> dense_shape = [3, 3]
>>> coo = paddle.sparse.sparse_coo_tensor(indices, values, dense_shape)
>>> x = paddle.rand(dense_shape)
>>> out = x.sparse_mask(coo)
>>> print(out)
Tensor(shape=[3, 3], dtype=paddle.float32, place=Place(cpu), stop_gradient=True,
indices=[[0, 1, 2],
         [1, 2, 0]],
values=[0.23659813, 0.40340215, 0.64152628])