目录
  • 一、用法:
  • 二、代码示例:

一、用法:

torch.gather 算子用于返回给定索引/下标的 Tensor 元素,在 pytorch 官网文档中的定义如下:

torch.gather( input, dim, index, *, sparse_grad=False, out=None) → Tensor

其用法等价于:

input.gather( dim, index, *, sparse_grad=False, out=None) → Tensor

其中,input 是目标 Tensor ,即被搜索的 Tensor ;dim 是搜索维度(也是 Tensor ),index 是索引。

返回值类型:Tensor

二、代码示例:

概念看不懂没关系,一看代码便知用法。

a = torch.tensor([1, 5, 3, 6, 8])
b = torch.tensor([3])    # 索引为3
c = a.gather(0, b)    # 输出a中第0维索引是3的元素:6
# 等价于 c=torch.gather(a,0,b)
print(c)     # tensor([6])
a = torch.tensor([[1.3, 2, 3, 4.5, 5],
                  [2.0, 3, 0.3, 4.1, 2],
                  [6, 7, 8, 9, 2],
                  [10, 5, 0, 6, 8]])
b = torch.tensor([[1],
                  [2],
                  [3],
                  [4]])
c = torch.gather(a, 1, b)    # 输出a中第1维索引分别是1,2,3,4的元素:2,0.3,9,8
print(c)      # tensor([[2.0000],[0.3000],[9.0000],[8.0000]])

以上就是pytorch人工智能之torch.gather算子用法示例的详细内容,更多关于pytorch算子torch.gather的资料请关注其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。