【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)]
]
相关推荐
Turbo正则几秒前
群论在AI中的应用概述
人工智能·算法·抽象代数
Fibocom广和通几秒前
让机器人动作更流畅!广和通实现VLA端侧推理2.6倍加速
大数据·人工智能·机器人
TanYYF7 分钟前
spring ai入门教程二
java·人工智能·spring
动恰客流统计11 分钟前
客流统计如何结合AI分析?从传统计数到智能决策的技术升级路径
数据库·人工智能·边缘计算
世界很奇妙塔20 分钟前
基因编辑产业化:从科研探索到临床应用,重构生命健康产业底层逻辑
大数据·人工智能·机器学习
取经蜗牛24 分钟前
Python 第一阶段完全指南:从零到第一个实用工具
开发语言·python
创世宇图29 分钟前
【Python工程化实战】OpenTelemetry 在 Python 中的全链路追踪落地:从埋点到可视化的完整实战指南
python·分布式链路追踪·性能监控·opentelemetry·微服务可观测性
试剂界的爱马仕31 分钟前
Anti-mouse PD-1 mAb (Clone RMP1-14) 与 Axitinib 小鼠实验使用方案整理汇总
大数据·人工智能·深度学习·学习
dreamread38 分钟前
2026带详细解读的八字排盘App怎么选:看解释层级、AI边界和复盘价值
人工智能·软件工具·传统文化
每天三杯咖啡43 分钟前
【无标题】
人工智能·技术选型·deepseek