gather_nd

paddle. gather_nd ( x, index, name=None ) [源代码]

该OP是 gather 的高维推广,并且支持多轴同时索引。 index 是一个K维度的张量,它可以认为是从 x 中取K-1维张量,每一个元素是一个切片:

gather_nd - 图1

显然, index.shape[-1] <= x.rank 并且输出张量的维度是 index.shape[:-1] + x.shape[index.shape[-1]:]

示例:

  1. 给定:
  2. x = [[[ 0, 1, 2, 3],
  3. [ 4, 5, 6, 7],
  4. [ 8, 9, 10, 11]],
  5. [[12, 13, 14, 15],
  6. [16, 17, 18, 19],
  7. [20, 21, 22, 23]]]
  8. x.shape = (2, 3, 4)
  9. - 案例 1:
  10. index = [[1]]
  11. gather_nd(x, index)
  12. = [x[1, :, :]]
  13. = [[12, 13, 14, 15],
  14. [16, 17, 18, 19],
  15. [20, 21, 22, 23]]
  16. - 案例 2:
  17. index = [[0,2]]
  18. gather_nd(x, index)
  19. = [x[0, 2, :]]
  20. = [8, 9, 10, 11]
  21. - 案例 3:
  22. index = [[1, 2, 3]]
  23. gather_nd(x, index)
  24. = [x[1, 2, 3]]
  25. = [23]

参数:

  • x (Tensor) - 输入Tensor,数据类型可以是int32,int64,float32,float64, bool。

  • index (Tensor) - 输入的索引Tensor,其数据类型int32或者int64。它的维度 index.rank 必须大于1,并且 index.shape[-1] <= x.rank

  • name (str,可选)- 具体用法请参见 Name ,一般无需设置,默认值为None。

返回:shape为index.shape[:-1] + x.shape[index.shape[-1]:]的Tensor,数据类型与 x 一致。

代码示例

  1. import paddle
  2. import numpy as np
  3. np_x = np.array([[[1, 2], [3, 4], [5, 6]],
  4. [[7, 8], [9, 10], [11, 12]]])
  5. np_index = [[0, 1]]
  6. x = paddle.to_tensor(np_x)
  7. index = paddle.to_tensor(np_index)
  8. output = paddle.gather_nd(x, index) #[[3, 4]]