【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)]
]
相关推荐
Thneonl几秒前
99.9% 置信被拒收,76% 靠两个佐证进场
人工智能·架构
Thneonl几秒前
stateless 4/6 漏判,stateful 3/5 错杀:该信谁?
人工智能·架构
百万蹄蹄向前冲1 分钟前
一张平面图把学校做成2D游戏
前端·人工智能·后端
机器之心1 分钟前
突发:Claude自主发现未知生物系统,或能编辑基因
前端·人工智能·后端
小小张说故事1 分钟前
pytest 入门指南:Python 自动化测试的标配工具
python·机器学习
用户8356290780511 分钟前
使用 Python 在 Excel 中添加和管理图片
后端·python
犀利豆1 分钟前
AI 老板五分钟挂出招聘启事,四个月后开除了第一个人
人工智能·llm·aigc
乱码三千1 分钟前
如何优雅地直连无公网 IP 的远程 GPU 服务器
linux·人工智能·程序员
墨林陌1 分钟前
AI 热点日报(2026-09-24):奥尔特曼安理会呼吁建全球AI标准,DeepSeek披露智能体沙箱平台DSec
人工智能
9i编程2 分钟前
9. 把 DDD 开源脚手架化为自己的:联调照出的问题与事件重构——租户权限、按钮样式与全局 DomainEvent 反哺 SKILL
人工智能·openai·ai编程