【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)]
]
相关推荐
葡萄星球1 分钟前
OpenClaw通过多agent创建数字分身方法
人工智能·ai
水木流年追梦2 分钟前
大模型入门-DPO 直接偏好优化
人工智能·学习·算法·机器学习·正则表达式
寻道模式4 分钟前
【时间之外】私有化部署AI的3个优点和3个缺点
大数据·人工智能·ollama·私有化·genericagent
郑寿昌7 分钟前
2026脑机接口与大模型融合架构解析
大数据·人工智能·架构
这是谁的博客?7 分钟前
AI 领域精选新闻(2026-05-24)
人工智能·ai·大模型·agent·ai安全
万少7 分钟前
万少的 Claude Code 入门教程
前端·人工智能·后端
SP FA8 分钟前
深度强化学习与控制(二):无模型强化学习
人工智能·强化学习·dqn
蓦然回首却已人去楼空9 分钟前
深度学习进阶:自然语言处理|4.2.3 QA|交叉熵、激活函数与 y − t:一套数学框架的三个侧面
人工智能·深度学习·自然语言处理
malog_10 分钟前
Milvus向量数据库:AI时代的搜索革命
数据库·人工智能·后端·milvus
alphaTao13 分钟前
LeetCode 每日一题 2026/5/18-2026/5/24
python·leetcode