mindspore.ops.gather
- mindspore.ops.gather(input_params, input_indices, axis, batch_dims=0)[源代码]
返回输入Tensor在指定 axis 上 input_indices 索引对应的元素组成的切片。
下图展示了Gather常用的计算过程:
其中,params代表输入 input_params ,indices代表要切片的索引 input_indices 。
说明
input_indices的值必须在 [0, input_param.shape[axis]) 范围内,超出该范围结果未定义。
Ascend平台上,input_params的数据类型当前不能是 bool_ 。
- 参数:
input_params (Tensor) - 原始Tensor,shape为 \((x_1, x_2, ..., x_R)\) 。
input_indices (Tensor) - 要切片的索引Tensor,shape为 \((y_1, y_2, ..., y_S)\) 。指定原始Tensor中要切片的索引。数据类型必须是int32或int64。
axis (Union(int, Tensor[int])) - 指定要切片的维度索引。它必须要大于或等于 batch_dims。若 axis 为Tensor,其size必须为1。
batch_dims (int) - 指定batch维的数量。它必须要小于或等于 input_indices 的rank。默认值:
0
。
- 返回:
Tensor,shape为 \(input\_params.shape[:axis] + input\_indices.shape[batch\_dims:] + input\_params.shape[axis + 1:]\) 。
- 异常:
TypeError - axis 不是int或Tensor。
ValueError - axis 为Tensor时,size不为1。
TypeError - input_params 不是Tensor。
TypeError - input_indices 不是int类型的Tensor。
- 支持平台:
Ascend
GPU
CPU
样例:
>>> import mindspore >>> import numpy as np >>> from mindspore import Tensor, ops >>> # 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 = ops.gather(input_params, 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 = ops.gather(input_params, 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 = ops.gather(input_params, 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, batch_dims 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, 1]), mindspore.int32) >>> axis = 1 >>> batch_dims = 1 >>> output = ops.gather(input_params, input_indices, axis, batch_dims) >>> print(output) [ 1. 7. 10.]