index_select

paddle.fluid.layers.index_select(input, index, dim=0)[source]

Returns a new tensor which indexes the input tensor along dimension dim using the entries in index which is a Tensor. The returned tensor has the same number of dimensions as the original input tensor. The dim-th dimension has the same size as the length of index; other dimensions have the same size as in the input tensor.

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

  • index (Variable) – The 1-D tensor containing the indices to index.

  • dim (int) – The dimension in which we index.

Returns

A Tensor with same data type as input.

Return type

Variable

Examples

System Message: ERROR/3 (/usr/local/lib/python2.7/dist-packages/paddle/fluid/layers/nn.py:docstring of paddle.fluid.layers.index_select, 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

    data = np.array([[1.0, 2.0, 3.0, 4.0],
                     [5.0, 6.0, 7.0, 8.0],
                     [9.0, 10.0, 11.0, 12.0]])
    data_index = np.array([0, 1, 1]).astype('int32')

    with fluid.dygraph.guard():
        x = fluid.dygraph.to_variable(data)
        index = fluid.dygraph.to_variable(data_index)
        out_z1 = fluid.layers.index_select(x, index)
        print(out_z1.numpy())
        #[[1. 2. 3. 4.]
        # [5. 6. 7. 8.]
        # [5. 6. 7. 8.]]
        out_z2 = fluid.layers.index_select(x, index, dim=1)
        print(out_z2.numpy())
        #[[ 1.  2.  2.]
        # [ 5.  6.  6.]
        # [ 9. 10. 10.]]