nonzero_cn.rst 2.3 KB
Newer Older
1 2
.. _cn_api_tensor_search_nonzero:

T
tianshuo78520a 已提交
3 4
nonzero
-------------------------------
5

L
Leo Chen 已提交
6
.. py:function:: paddle.fluid.layers.nonzero(input, as_tuple=False)
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

该OP返回输入 ``input`` 中非零元素的坐标。如果输入 ``input`` 有 ``n`` 维,共包含 ``z`` 个非零元素,当 ``as_tuple = False`` 时,
返回结果是一个 ``shape`` 等于 ``[z x n]`` 的 ``Tensor`` , 第 ``i`` 行代表输入中第 ``i`` 个非零元素的坐标;当 ``as_tuple = True`` 时,
返回结果是由 ``n`` 个大小为 ``z`` 的 ``1-D Tensor`` 构成的元组,第 ``i`` 个 ``1-D Tensor`` 记录输入的非零元素在第 ``i`` 维的坐标。
        
**参数**:
    - **input** (Variable)– 输入张量。
    - **as_tuple** (bool, optinal) - 返回格式。是否以 ``1-D Tensor`` 构成的元组格式返回。

**返回**:
    - **Variable** (Tensor or tuple(1-D Tensor)),数据类型为 **INT64** 。
     
**代码示例**:

.. code-block:: python

        import paddle
        import paddle.fluid as fluid
        import numpy as np

        data1 = np.array([[1.0, 0.0, 0.0],
                            [0.0, 2.0, 0.0],
                            [0.0, 0.0, 3.0]])
        data2 = np.array([0.0, 1.0, 0.0, 3.0])
        data3 = np.array([0.0, 0.0, 0.0])
        with fluid.dygraph.guard():
            x1 = fluid.dygraph.to_variable(data1)
            x2 = fluid.dygraph.to_variable(data2)
            x3 = fluid.dygraph.to_variable(data3)
L
Leo Chen 已提交
36
            out_z1 = fluid.layers.nonzero(x1)
37 38 39 40
            print(out_z1.numpy())
            #[[0 0]
            # [1 1]
            # [2 2]]
L
Leo Chen 已提交
41
            out_z1_tuple = fluid.layers.nonzero(x1, as_tuple=True)
42 43 44 45 46 47 48 49
            for out in out_z1_tuple:
                print(out.numpy())
            #[[0]
            # [1]
            # [2]]
            #[[0]
            # [1]
            # [2]]
L
Leo Chen 已提交
50
            out_z2 = fluid.layers.nonzero(x2)
51 52 53
            print(out_z2.numpy())
            #[[1]
            # [3]]
L
Leo Chen 已提交
54
            out_z2_tuple = fluid.layers.nonzero(x2, as_tuple=True)
55 56 57 58
            for out in out_z2_tuple:
                print(out.numpy())
            #[[1]
            # [3]]
L
Leo Chen 已提交
59
            out_z3 = fluid.layers.nonzero(x3)
60 61
            print(out_z3.numpy())
            #[]
L
Leo Chen 已提交
62
            out_z3_tuple = fluid.layers.nonzero(x3, as_tuple=True)
63 64 65 66 67
            for out in out_z3_tuple:
                print(out.numpy())
            #[]