mask_as

paddle.sparse. mask_as ( x, mask, name=None ) [源代码]

使用稀疏张量 mask 的索引过滤输入的稠密张量 x,并生成相应格式的稀疏张量。输入的 xmask 必须具有相同的形状,且返回的稀疏张量具有与 mask 相同的索引,即使对应的索引中存在 值。

参数

  • x (DenseTensor) - 输入的 DenseTensor。数据类型为 float32,float64,int32,int64,complex64,complex128,int8,int16,float16。

  • mask (SparseTensor) - 输入的稀疏张量,可以为 SparseCooTensor、SparseCsrTensor。当其为 SparseCsrTensor 时,应该是 2D 或 3D 的形式。

  • name (str,可选) - 具体用法请参见 Name,一般无需设置,默认值为 None。

返回

SparseTensor: 其稀疏格式、dtype、shape 均与 mask 相同。

代码示例

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

>>> # csr sparse tensor
>>> crows = [0, 2, 3, 5]
>>> cols = [1, 3, 2, 0, 1]
>>> values = [1., 2., 3., 4., 5.]
>>> dense_shape = [3, 4]
>>> csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape)
>>> paddle.seed(2024)
>>> x = paddle.rand(dense_shape).astype(csr.dtype)
>>> out = paddle.sparse.mask_as(x, 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])

>>> # coo sparse tensor
>>> 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)
>>> paddle.seed(2024)
>>> x = paddle.rand(dense_shape).astype(coo.dtype)
>>> out = paddle.sparse.mask_as(x, 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])

使用本API的教程文档