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 index.shape[axis] <= input.shape[axis] where axis goes through all dimensions of input except dim.

Warning

On Ascend, the behavior is unpredictable in the following cases:

  • the value of index is not in the range [-input.shape[dim], input.shape[dim]) in forward;

  • the value of index is not in the range [0, input.shape[dim]) in backward.

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 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 in input is less than size in 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]]