【pytorch】torch.gather()函数

dim=0时

python 复制代码
index=[ [x1,x2,x2],
		[y1,y2,y2],
		[z1,z2,z3] ]

如果dim=0
填入方式为:
index=[ [(x1,0),(x2,1),(x3,2)]
		[(y1,0),(y2,1),(y3,2)]
		[(z1,0),(z2,1),(z3,2)] ]
python 复制代码
input = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
] # shape(3,4)
input = torch.tensor(input)
length = torch.LongTensor([
    [2,2,2,2],
    [1,1,1,1],
    [0,0,0,0],
    [0,1,2,0]
])# shape(4,4)
out = torch.gather(input, dim=0, index=length)
print(out)
python 复制代码
tensor([[9, 10, 11, 12],
        [5, 6, 7, 8],
        [1, 2, 3, 4],
        [1, 6, 11, 4]])
python 复制代码
#### dim=0后,根据new_index对input进行索引
new_index=[ [(2,0),(2,1),(2,2),(2,3)],
			[(1,0),(1,1),(1,2),(1,3)],
			[(0,0),(0,1),(0,2),(0,3)],
			[(0,0),(1,1),(2,2),(0,3)] ]
			
可以观察到第四行,行索引变为0,所以当gather函数里的index超过input的唯独时,会从0重新计数。

dim=1时

python 复制代码
input = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
] # shape(3,4)
input = torch.tensor(input)
length = torch.LongTensor([
    [2,2,2,2],
    [1,1,1,1],
    [0,1,2,0]
]) # shape(3,4)
out = torch.gather(input, dim=1, index=length)
print(out)
python 复制代码
tensor([[3, 3, 3, 3],
        [6, 6, 6, 6],
        [9, 10, 11, 9]])
python 复制代码
new_index = [
	[(0,2),(0,2),(0,2),(0,2)],
	[(1,1),(1,1),(1,1),(1,1)],
	[(2,0),(2,1),(2,2)(2,0)]
]
相关推荐
love_summer1 分钟前
深入理解Python基础:数据类型、运算符与内存机制初探
python
沙漠的浪人1 分钟前
基于多 Agent 的 Planning-Executor 架构设计
人工智能·agent
小雪_Snow2 分钟前
Python 安装教程【使用 Python install manager】
python
光锥智能4 分钟前
高通推出全套机器人技术组合,含 Dragonwing IQ10 系列处理器
人工智能
云卓SKYDROID6 分钟前
工业吊舱图像采集与增强模块解析
人工智能·数码相机·计算机视觉·无人机·高科技·云卓科技
狮子座明仔6 分钟前
EXPLAIN:用实体摘要为RAG“开外挂“,让文档问答又快又准
人工智能
星月前端6 分钟前
基于DeepSeek API的Telegram机器人
python·机器人
狮子座明仔6 分钟前
CiteFix: 通过后处理引用校正提升RAG系统准确率
人工智能·深度学习·ai·语言模型·自然语言处理
希艾席帝恩6 分钟前
数字孪生赋能水利行业转型升级的关键路径
大数据·人工智能·数字孪生·数据可视化·数字化转型
AI 智能服务9 分钟前
第2课___结构化输出与 Prompt 设计
人工智能·机器学习·prompt