【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)]
]
相关推荐
iFeng的小屋6 分钟前
【2026年新版】Python根据小红书关键词爬取所有笔记数据
笔记·爬虫·python
HAREWORK_FFF7 分钟前
近几年,非技术岗转向AI岗位的现实可能性
人工智能
weixin_6687 分钟前
深度分析:多模态、全模态、VLM、ASR、TTS、STT、OCR- AI分析分享
人工智能
m0_561359677 分钟前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
LeonDL1688 分钟前
基于YOLO11深度学习的衣物识别系统【Python源码+Pyqt5界面+数据集+安装使用教程+训练代码】【附下载链接】
人工智能·python·pyqt5·yolo数据集·yolo11数据集·yolo11深度学习·衣物识别系统
犀思云12 分钟前
企业总部网络全球化扩张:利用FusionWAN NaaS 破解“网络成本瓶颈”
网络·人工智能·机器人·智能仓储·专线
傻啦嘿哟16 分钟前
Python操作PDF页面详解:删除指定页的完整方案
开发语言·python·pdf
Data_Journal17 分钟前
如何使用 Python 解析 JSON 数据
大数据·开发语言·前端·数据库·人工智能·php
陈天伟教授17 分钟前
人工智能应用- 语言理解:09.大语言模型
人工智能·语言模型·自然语言处理
serve the people20 分钟前
python环境搭建 (十三) tenacity重试库
服务器·python·php