【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)]
]
相关推荐
日日大王学编程14 分钟前
AI Agent 技术发展历程、演进逻辑与技术范式综述
人工智能·python
春涧草茶27 分钟前
慢就是快16-1协程
开发语言·前端·python
Yuzhiyuxia1 小时前
【AI Agent面试系列】上下文管理1
人工智能·面试·职场和发展
5233AI开发笔记1 小时前
API 返回 429:先区分限速、并发和配额,再决定是否重试
python
databook1 小时前
经常听到的透视表是干什么的?
python·数据分析·pandas
王中阳Go1 小时前
预算给够了,时间花错了地方:三跳链路给了 27 秒,实际只用掉 9 秒
人工智能·后端·性能优化
方方洛1 小时前
ray教程-25-附录E-端到端实战案例
人工智能·分布式·机器学习
火山引擎开发者社区1 小时前
上万个 Agent 在线不乱跑,云沙箱给 Agent 造了间“独立办公室”
人工智能
神鹰手哥_起飞版1 小时前
一句话生成带品牌 logo 的架构图:方舟 Seed 2.1 负责听懂,代码负责画准
人工智能
老马识码1 小时前
WorkBuddy 的连接器是怎么统一到 MCP 的
人工智能