mindspore.Tensor.gather

mindspore.Tensor.gather(input_indices, axis)[源代码]

返回指定 axisinput_indices 的元素对应的输入Tensor切片,输入Tensor的形状是 \((x_1, x_2, ..., x_R)\)。为了方便描述,对于输入Tensor记为 input_params

Note

  1. input_indices 的值必须在 [0, input_params.shape[axis]) 的范围内,结果未定义超出范围。

  2. 当前在Ascend平台,input_params的值不能是 bool_ 类型。

参数:
  • input_indices (Tensor) - 待切片的索引张量,其形状为 \((y_1, y_2, ..., y_S)\),代表指定原始张量元素的索引,其数据类型包括:int32,int64。

  • axis (int) - 指定维度索引的轴以搜集切片。

返回:

Tensor,其中shape维度为 \(input\_params.shape[:axis] + input\_indices.shape + input\_params.shape[axis + 1:]\)

异常:
  • TypeError - 如果 axis 不是一个整数。

  • TypeError - 如果 input_indices 不是一个整数类型的Tensor。

支持平台:

Ascend GPU CPU

样例:

>>> # case1: input_indices is a Tensor with shape (5, ).
>>> input_params = Tensor(np.array([1, 2, 3, 4, 5, 6, 7]), mindspore.float32)
>>> input_indices = Tensor(np.array([0, 2, 4, 2, 6]), mindspore.int32)
>>> axis = 0
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[1. 3. 5. 3. 7.]
>>> # case2: input_indices is a Tensor with shape (2, 2). When the input_params has one dimension,
>>> # the output shape is equal to the input_indices shape.
>>> input_indices = Tensor(np.array([[0, 2], [2, 6]]), mindspore.int32)
>>> axis = 0
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[[ 1. 3.]
 [ 3. 7.]]
>>> # case3: input_indices is a Tensor with shape (2, ) and
>>> # input_params is a Tensor with shape (3, 4) and axis is 0.
>>> input_params = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]), mindspore.float32)
>>> input_indices = Tensor(np.array([0, 2]), mindspore.int32)
>>> axis = 0
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[[1.  2.  3.  4.]
 [9. 10. 11. 12.]]
>>> # case4: input_indices is a Tensor with shape (2, ) and
>>> # input_params is a Tensor with shape (3, 4) and axis is 1.
>>> input_params = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]), mindspore.float32)
>>> input_indices = Tensor(np.array([0, 2]), mindspore.int32)
>>> axis = 1
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[[1.  3.]
 [5.  7.]
 [9. 11.]]