【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工具集:Git提交时使用AI进行CodeReview如何在前端应用构建NPM包
前端·人工智能·git·npm·codeview
Stick_ZYZ3 分钟前
从 Prompt 到 Context Engineering:Agent 真正稳定的关键
大数据·人工智能·算法·ai·prompt
shiyuankeyan3 分钟前
【AICsE 2026 Workshop 1 征稿】面向健康监测的多模态生物传感器——三位顶尖学者领衔,聚焦可穿戴医疗与边缘AI前沿
人工智能
码农小旋风4 分钟前
Codex中文网 | Codex CLI 中文指南
运维·服务器·ide·人工智能·chatgpt·claude
数学建模导师6 分钟前
2026第八届中青杯ABC题赛题分析【配套解题思路+代码】
大数据·人工智能·数学建模
ZHW_AI课题组7 分钟前
使用Stable Diffusion v1.5文本引导与无分类器引导(CFG)算法实现条件生成图片
人工智能·python·算法·机器学习·stable diffusion
tedcloud1237 分钟前
Dolt部署教程:打造可追踪数据变更的数据库环境
服务器·数据库·人工智能·学习·自动化·powerpoint
盼小辉丶8 分钟前
OpenCV-Python实战(25)——基于深度传感器与凸性分析打造实时手势识别系统
人工智能·python·opencv·计算机视觉
庖丁AI9 分钟前
PDF解析工具怎么选?OCR、表格提取和结构化输出有什么区别
人工智能·pdf·ocr
娟宝宝萌萌哒11 分钟前
Agent 应用工程架构:模块、挑战与传统工程迁移
人工智能·架构