【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)]
]
相关推荐
未来和明天7 分钟前
领嵌4G/5GAI边缘计算盒子多路视频算力高达10.4Tops兼容Modbus、DLT645、OPC UA等多种行业协议
人工智能·5g·边缘计算
万联WANFLOW8 分钟前
Meta开源了能本地跑的agent
运维·服务器·网络·人工智能·业界资讯
Bruce_Liuxiaowei9 分钟前
安全意识培训——大模型在安全培训中的创新应用
人工智能·安全·ai·智能体
2601_9563198811 分钟前
2026年用示例、拆解和练习提升量化理解效率
人工智能·python
飞哥数智坊14 分钟前
WorkBuddy 帮我把吃灰的 ima 收藏,变成了每日知识速览
人工智能·agent
学习中.........17 分钟前
Karpathy nanoGPT 教程到底讲了什么
人工智能·算法·语言模型
ZYJCSZKJ22 分钟前
AI数字人直播系统的技术架构与多方言交互实现方案——基于广西区域商业场景的工程实践
人工智能·架构·交互
珐恩AI-人工智能29 分钟前
大模型意图召回偏差分析:GEO如何解决“有收录却不触发问答曝光”的难题
大数据·前端·人工智能·html·流量运营·geo优化
Java小白笔记35 分钟前
Windows系统免软件命令激活
java·网络·人工智能·windows·ai·ai编程
王志来1379447300835 分钟前
从分散到集成:工控服务器机箱采购如何实现“一站式”破局
运维·服务器·人工智能·python