图解PyTorch中的torch.gather函数和 scatter 函数

前言

torch.gather在目前基于 transformer or query based 的目标检测中,在最后获取目标结果时,经常用到。

这里记录下用法,防止之后又忘了。

介绍

torch.gather

官方文档对torch.gather()的定义非常简洁

定义:从原tensor中获取指定dim和指定index的数据

看到这个核心定义,我们很容易想到gather()的基本想法其实就类似从完整数据中按索引取值般简单,比如下面从列表中按索引取值

python 复制代码
lst = [1, 2, 3, 4, 5]
value = lst[2]  # value = 3
value = lst[2:4]  # value = [3, 4]

上面的取值例子是取单个值或具有逻辑顺序序列的例子,而对于深度学习常用的批量tensor数据来说,我们的需求可能是选取其中多个且乱序的值,此时gather()就是一个很好的tool,它可以帮助我们从批量tensor中取出指定乱序索引下的数据,因此其用途如下

用途:方便从批量tensor中获取指定索引下的数据,该索引是高度自定义化的,可乱序的

示例

我们找个3x3的二维矩阵做个实验

python 复制代码
import torch

tensor_0 = torch.arange(3, 12).view(3, 3)
print(tensor_0)

输出结果

python 复制代码
tensor([[ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11]])

2.1 输入行向量index,并替换行索引(dim=0)

python 复制代码
index = torch.tensor([[2, 1, 0]])
tensor_1 = tensor_0.gather(0, index)
print(tensor_1)

输出结果

python 复制代码
tensor([[9, 7, 5]])

过程如图所示

2.2 输入行向量index,并替换列索引(dim=1)

python 复制代码
index = torch.tensor([[2, 1, 0]])
tensor_1 = tensor_0.gather(1, index)
print(tensor_1)

输出结果

python 复制代码
tensor([[5, 4, 3]])

过程如图所示

2.3 输入列向量index,并替换列索引(dim=1)

python 复制代码
index = torch.tensor([[2, 1, 0]]).t()
tensor_1 = tensor_0.gather(1, index)
print(tensor_1)

输出结果

python 复制代码
tensor([[5],
        [7],
        [9]])

过程如图所示

scatter

基本是 gather 的反过程,是将数据添加进去,

doc:https://pytorch.org/docs/stable/generated/torch.Tensor.scatter_.html#torch.Tensor.scatter_

python 复制代码
self[index[i][j][k]][j][k] = src[i][j][k]  # if dim == 0
self[i][index[i][j][k]][k] = src[i][j][k]  # if dim == 1
self[i][j][index[i][j][k]] = src[i][j][k]  # if dim == 2

example:

python 复制代码
>>> src = torch.arange(1, 11).reshape((2, 5))
>>> src
tensor([[ 1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10]])
>>> index = torch.tensor([[0, 1, 2, 0]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src)
tensor([[1, 0, 0, 4, 0],
        [0, 2, 0, 0, 0],
        [0, 0, 3, 0, 0]])
>>> index = torch.tensor([[0, 1, 2], [0, 1, 4]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src)
tensor([[1, 2, 3, 0, 0],
        [6, 7, 0, 0, 8],
        [0, 0, 0, 0, 0]])

>>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]),
...            1.23, reduce='multiply')
tensor([[2.0000, 2.0000, 2.4600, 2.0000],
        [2.0000, 2.0000, 2.0000, 2.4600]])
>>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]),
...            1.23, reduce='add')
tensor([[2.0000, 2.0000, 3.2300, 2.0000],
        [2.0000, 2.0000, 2.0000, 3.2300]])

具体过程见 gather 的就好~一摸一样,一个获取,一个填入。

相关推荐
晓风残月淡34 分钟前
JVM字节码与类的加载(二):类加载器
jvm·python·php
EasyCVR3 小时前
视频融合平台EasyCVR在智慧水利中的实战应用:构建全域感知与智能预警平台
人工智能·音视频
DisonTangor3 小时前
阿里开源Qwen3-Omni-30B-A3B三剑客——Instruct、Thinking 和 Captioner
人工智能·语言模型·开源·aigc
独孤--蝴蝶3 小时前
AI人工智能-机器学习-第一周(小白)
人工智能·机器学习
西柚小萌新3 小时前
【深入浅出PyTorch】--上采样+下采样
人工智能·pytorch·python
丁学文武3 小时前
大语言模型(LLM)是“预制菜”? 从应用到底层原理,在到中央厨房的深度解析
人工智能·语言模型·自然语言处理·大语言模型·大模型应用·预制菜
fie88894 小时前
基于MATLAB的声呐图像特征提取与显示
开发语言·人工智能
文火冰糖的硅基工坊5 小时前
[嵌入式系统-100]:常见的IoT(物联网)开发板
人工智能·物联网·架构
刘晓倩5 小时前
实战任务二:用扣子空间通过任务提示词制作精美PPT
人工智能
shut up5 小时前
LangChain - 如何使用阿里云百炼平台的Qwen-plus模型构建一个桌面文件查询AI助手 - 超详细
人工智能·python·langchain·智能体