【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)]
]
相关推荐
AI工具测评家1 分钟前
AI检测器是怎么判断论文由AI生成的?从文本概率、语言规律到检测模型一次讲清
人工智能·aigc·降重·ai检测·查重·降ai·快降重
abnH_7 分钟前
精度焦虑与预算博弈:高性价比DD马达如何守住自动化产线的“底线精度”?
人工智能·机器人·自动化·制造
星栈15 分钟前
决定 Agent 交付下限的「操作系统」:Harness 六层架构拆解
人工智能·架构·agent
AI多Agent协作实战派15 分钟前
AI多Agent协作系统实战(五十):AI自己修配置,把模型名改错了
人工智能
A153625518 分钟前
WMS 智能仓情系统推荐:如何实现仓库全局可视与数字化管控
运维·数据库·人工智能
Data_Journal31 分钟前
如何使用 Python 抓取 Google Flights:分步指南
大数据·开发语言·数据库·python·scrapy
码视野33 分钟前
基于 Vue3 + Element Plus 的【基于物联网的智慧居家养老健康关怀与紧急医疗呼叫系统】设计与实现(附完整源码与PRD)
人工智能·物联网·vue3
月亮和九磅十五便士38 分钟前
朝闻 AI|2026-08-25
人工智能
LazzyE44 分钟前
初读 Miles:RL 后训练,难在采样和训练之间
人工智能