【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)]
]
相关推荐
shangjian00721 分钟前
Python基础-With关键字
python
xuxianliang44 分钟前
第154章 “神谕”的低语(AI)
人工智能·程序员创富
geneculture1 小时前
人机互助新时代超级个体(OPC)的学术述评——基于人文学科与数理学科的双重视域
大数据·人工智能·哲学与科学统一性·信息融智学·融智时代(杂志)
KG_LLM图谱增强大模型1 小时前
给具身智能装上图谱大模型大脑,7B小模型超越72B大模型!层次化知识图谱让复杂机器人规划能力暴增17%,能耗大幅降低
人工智能·机器人·知识图谱
2401_836235861 小时前
名片识别产品:技术要点与应用场景深度解析
人工智能·科技·深度学习·ocr
zchxzl1 小时前
亲测2026京津冀可靠广告展会
大数据·人工智能·python
人工智能AI技术1 小时前
Stable Diffusion 3.0实战:用Colab免费训练你的专属AI绘画模型
人工智能·ai作画
龙山云仓2 小时前
No159:AI中国故事-对话娄敬——戍策长安与AI远见:草根智慧与国都定鼎
人工智能·深度学习·机器学习
qq_390369532 小时前
豆包2.0(Doubao-Seed-2.0)和千问Qwen3.5发布,与Gemini 3 Pro比如何
人工智能
时72 小时前
Python 项目环境隔离配置指南:pyenv + venv 组合使用
python