【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)]
]
相关推荐
涛思数据(TDengine)2 分钟前
从_找根因_到_搭系统_:工业 AI 实战直播(十、十一期)
大数据·数据库·人工智能·时序数据库·tdengine
2601_966650418 分钟前
2026完美收官,2027赛逸展再扩容预售
人工智能
Capricorn198811 分钟前
科研引用无法溯源怎么排查?知芽 Notebook Skill 技术机制拆解
大数据·论文阅读·人工智能·笔记·论文笔记
jay神17 分钟前
一文讲清楚YOLOv26模型
人工智能·深度学习·yolo·机器学习·计算机视觉
2601_9557598825 分钟前
Claude API 容量规划与业务增长评估
大数据·人工智能
Capricorn198830 分钟前
Agent 记忆层接入后引用仍不可信?知芽 Notebook Skill 排障指南
大数据·论文阅读·人工智能·笔记·架构
Zguigo31 分钟前
【DL】RNN|序列数据|Hidden State
人工智能·rnn·深度学习
桃西西呀31 分钟前
「百年一遇」的台风,为什么我这辈子就遇了好几回?概率论把这笔账算给你看
人工智能·python·数据可视化
苏其鸿36 分钟前
Python开发入门:从环境搭建到第一个实用小项目
python
练习两年半的攻城狮39 分钟前
【RAG实战】知识库 BGE-M3 稀疏向量混合检索方案
python·fastapi·llamaindex