【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)]
]
相关推荐
xqqxqxxq1 小时前
AI Agent学习:主动工具发现(李博杰《深入理解 AI Agent》4.8观后总结)
人工智能·学习
海上彼尚2 小时前
Cursor 模型的强度实测排行
前端·人工智能·后端
ai小陈2 小时前
PyTorch Profiler性能分析实战:定位GPU训练中的慢算子
人工智能·深度学习·机器学习·ai·性能优化·gpu算力
罗西的思考2 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 ---(1)--- 总体
人工智能·算法·机器学习
冬奇Lab2 小时前
DeepSeek Harness 系列(02):万物皆插件——Cordis 核心设计深度解读
人工智能·deepseek
老金带你玩AI2 小时前
image 2.5刷屏了:有人拿它做广告,有人已经做出了动画
人工智能
FII工业富联科技服务2 小时前
GPT-6 Astra发布,Agent的竞争开始从“会调用工具”走向“完成完整工作”
大数据·人工智能·gpt·架构·机器人·制造
Mr数据杨2 小时前
议会事务多标签文本分类实战 从 Open Data St Gallen 看推荐排序建模
人工智能·数据分析·kaggle竞赛
梦想的颜色2 小时前
【AI速览】2026年 9月 GPT‑6 Astra 深度解析:Agent 时代的前沿旗舰,能力、成本、落地痛点与选型判断
人工智能·openai·agent·astra·vibecoding·大模型测评·gpt6
YCOSA20252 小时前
系统工具使用检测.exe (仅供娱乐)
python·microsoft