【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怎么用?从智能表格落地看如何提升运营效率
大数据·人工智能·企业微信
私域实战笔记2 分钟前
如何选择企业微信SCRM?2025年3个选型参考维度
大数据·人工智能·企业微信·scrm·企业微信scrm
袁庭新6 分钟前
2025年10月总结
人工智能·aigc·coze
AI浩7 分钟前
SMamba: 基于稀疏Mamba的事件相机目标检测
人工智能·数码相机·目标检测
QTreeY1238 分钟前
yolov5/8/9/10/11/12/13+deep-oc-sort算法的目标跟踪实现
人工智能·算法·yolo·目标检测·计算机视觉·目标跟踪
IT_陈寒17 分钟前
SpringBoot 3.2新特性实战:这5个隐藏技巧让你的应用性能飙升50%
前端·人工智能·后端
aitoolhub20 分钟前
考研论文引用格式 AI 校验实操:工具合集 + 技术原理
c语言·人工智能·考研·aigc
Fnetlink132 分钟前
推动“AI+ 网络安全”深度融合与创新发展
人工智能·安全·web安全
xuehaikj39 分钟前
苹果质量检测与分类 - YOLO13结合RFCAConv实现
人工智能·数据挖掘
xuehaikj42 分钟前
芦笋嫩茎形态分类与识别_YOLO11-C3k2-MambaOut-SFSC模型实现_1
人工智能·数据挖掘