nonzero

paddle.fluid.layers.nonzero(input, as_tuple=False)[source]

Return a tensor containing the indices of all non-zero elements of the input tensor. If as_tuple is True, return a tuple of 1-D tensors, one for each dimension in input, each containing the indices (in that dimension) of all non-zero elements of input. Given a n-Dimensional input tensor with shape [x_1, x_2, …, x_n], If as_tuple is False, we can get a output tensor with shape [z, n], where z is the number of all non-zero elements in the input tensor. If as_tuple is True, we can get a 1-D tensor tuple of length n, and the shape of each 1-D tensor is [z, 1].

Parameters
  • inputs (Variable) – The input tensor variable.

  • as_tuple (bool) – Return type, Tensor or tuple of Tensor.

Returns

Variable. The data type is int64.

Examples

System Message: ERROR/3 (/usr/local/lib/python2.7/dist-packages/paddle/fluid/layers/nn.py:docstring of paddle.fluid.layers.nonzero, line 18)

Error in “code-block” directive: maximum 1 argument(s) allowed, 11 supplied.

.. 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)
        out_z1 = fluid.layers.nonzero(x1)
        print(out_z1.numpy())
        #[[0 0]
        # [1 1]
        # [2 2]]
        out_z1_tuple = fluid.layers.nonzero(x1, as_tuple=True)
        for out in out_z1_tuple:
            print(out.numpy())
        #[[0]
        # [1]
        # [2]]
        #[[0]
        # [1]
        # [2]]
        out_z2 = fluid.layers.nonzero(x2)
        print(out_z2.numpy())
        #[[1]
        # [3]]
        out_z2_tuple = fluid.layers.nonzero(x2, as_tuple=True)
        for out in out_z2_tuple:
            print(out.numpy())
        #[[1]
        # [3]]
        out_z3 = fluid.layers.nonzero(x3)
        print(out_z3.numpy())
        #[]
        out_z3_tuple = fluid.layers.nonzero(x3, as_tuple=True)
        for out in out_z3_tuple:
            print(out.numpy())
        #[]