nonzero

paddle. nonzero ( x, as_tuple=False, *, out=None ) [源代码]

返回输入 x 中非零元素的坐标。如果输入 xn 维,共包含 z 个非零元素,当 as_tuple = False 时, 返回结果是一个 shape 等于 [z x n]Tensor,第 i 行代表输入中第 i 个非零元素的坐标;当 as_tuple = True 时, 返回结果是由 n 个大小为 z1-D Tensor 构成的元组,第 i1-D Tensor 记录输入的非零元素在第 i 维的坐标。

备注

别名支持: 参数名 input 可替代 x ,如 nonzero(input=tensor_x) 等价于 nonzero(x=tensor_x)

参数

  • x (Tensor)– 输入的 Tensor。别名: input

  • as_tuple (bool,可选) - 返回格式。是否以 1-D Tensor 构成的元组格式返回。

关键字参数

  • out (Tensor,可选) - 输出 Tensor。默认值为 None。

返回

  • Tensor or tuple(1-D Tensor),数据类型为 INT64

代码示例

>>> import paddle >>> x1 = paddle.to_tensor([[1.0, 0.0, 0.0], ...  [0.0, 2.0, 0.0], ...  [0.0, 0.0, 3.0]]) >>> x2 = paddle.to_tensor([0.0, 1.0, 0.0, 3.0]) >>> out_z1 = paddle.nonzero(x1) >>> print(out_z1) Tensor(shape=[3, 2], dtype=int64, place=Place(cpu), stop_gradient=True, [[0, 0],  [1, 1],  [2, 2]]) >>> out_z1_tuple = paddle.nonzero(x1, as_tuple=True) >>> for out in out_z1_tuple: ...  print(out) Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True, [0, 1, 2]) Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True, [0, 1, 2]) >>> out_z2 = paddle.nonzero(x2) >>> print(out_z2) Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True, [[1],  [3]]) >>> out_z2_tuple = paddle.nonzero(x2, as_tuple=True) >>> for out in out_z2_tuple: ...  print(out) Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True, [1, 3])