【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实战派4 分钟前
ChatGPT / Realtime API / 智能体故障排查指南:语音模型、浏览器会话与权限问题全流程解决方案
人工智能·chatgpt
agicall.com6 分钟前
信电助 - 信创坐席盒 UB-B-XC 型号功能列表
人工智能·语音识别·信创电话助手·座机语音转文字·固话录音转文字
金玉满堂@bj7 分钟前
Python 后端开发 从零到就业完整教程(2026 企业级完整版)
开发语言·python
夜影风10 分钟前
Prompt提示词工程化:用LangChain把提示词从字符串变成资产
人工智能·langchain·ai agent
土星云SaturnCloud10 分钟前
防爆边缘计算+工业视频智能分析:高危场景视觉安全闭环,落地架构与场景全解
服务器·人工智能·ai·边缘计算
周末也要写八哥11 分钟前
开发者如何快速实现一个NLP模型?
人工智能·自然语言处理
iuu_star12 分钟前
跑通最简单的Vue3+Python前后端分离项目
前端·vue.js·python
大龄码农有梦想13 分钟前
AI 智能体核心组件:Tool、MCP 与 Skills 的区别、标准与协同架构
人工智能·agent·智能体·ai工具·tool·mcp·skills
The Open Group14 分钟前
AI智能体时代,如何构建数字化架构以实现持续成功
大数据·人工智能·架构
Elastic 中国社区官方博客16 分钟前
将 Logstash Pipeline 从 Azure Event Hubs 迁移到 OTel Collector Kafka Receiver
大数据·数据库·人工智能·分布式·elasticsearch·搜索引擎·kafka