mindspore.ops.gather_elements

View Source On Gitee
mindspore.ops.gather_elements(input, dim, index)[source]

Gathers elements along an axis specified by dim.

For a 3-D tensor, the output is:

output[i][j][k] = x[index[i][j][k]][j][k]  # if dim == 0

output[i][j][k] = x[i][index[i][j][k]][k]  # if dim == 1

output[i][j][k] = x[i][j][index[i][j][k]]  # if dim == 2

input and index have the same length of dimensions, and all dimensions except dim have the same size. If dim = i, input is an n-D tensor with shape \((z_0, z_1, ..., z_i, ..., z_{n-1})\), the index must be an n-D tensor with shape \((z_0, z_1, ..., y, ..., z_{n-1})\) where y>=1 and the output will have the same shape with index.

Parameters
  • input (Tensor) – The input tensor.

  • dim (int) – The axis along which to index. It must be int32 or int64. The value range is [-input.ndim, input.ndim).

  • index (Tensor) – The indices of elements to gather. It can be one of the following data types: int32, int64. The value range of each index element is [-input.shape(dim), input.shape(dim)).

Returns

Tensor, has the same shape as index tensor, the shape of tensor is \((z_0, z_1, ..., y, ..., z_{n-1})\), and has the same data type with input.

Raises
  • TypeError – If dtype of dim or index is neither int32 nor int64.

  • ValueError – If length of shape of input is not equal to length of shape of index.

  • ValueError – If the size of the dimension except dim is not equal between input and index.

  • ValueError – If the value of dim is not in the expected range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> import mindspore
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.int32)
>>> index = Tensor(np.array([[0, 0], [1, 0]]), mindspore.int32)
>>> dim = 1
>>> output = mindspore.ops.gather_elements(x, dim, index)
>>> print(output)
[[1 1]
 [4 3]]