【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)]
]
相关推荐
小艾.pino14 分钟前
MiniMax M3顶住新一代多模态大模型的架构与实战
人工智能·架构
DO_Community18 分钟前
GPT 6 Astra 已上线 DigitalOcean AI 推理云:AGI 时代的计算机操作模型来了
人工智能·gpt·agi
字节跳动视频云技术团队26 分钟前
火山引擎 AI MediaKit X 懂车帝,探索汽车内容智能创作新方式
人工智能·音视频开发
MindUp31 分钟前
大模型技术在股票分析场景的应用与工具调研
人工智能·金融
tuanxiang33 分钟前
在线AI检测接口误判问题排查与绕过实践
人工智能
linweidong37 分钟前
中科闻歌Java面试题及参考答案
java·python·大模型·提示词·ai agent·mcp·rag原理
suaizai_41 分钟前
AI进化:从“回答问题”到“完成任务”
人工智能
小玮看世界1 小时前
[Python]OD算法在OD实际运用转化参考清单
开发语言·python·算法
广凌股份(广凌科技)1 小时前
2026年高校采购管理系统选型指南 | 5款软件深度测评
大数据·人工智能
加密社1 小时前
GPT-6 Astra 100 Studies | 100个AI生成的HTML5视觉作品集
人工智能·gpt