【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)]
]
相关推荐
limenga1026 分钟前
奇异值分解(SVD):深度理解神经网络的内在结构
人工智能·深度学习·神经网络·机器学习
双向337 分钟前
为什么Doubao-Seed-Code成为我的主力编程助手?实测与深度解析
人工智能
秋邱12 分钟前
【机器学习】深入解析线性回归模型
人工智能·机器学习·线性回归
天下无敌笨笨熊15 分钟前
ES作为向量库研究
大数据·python·elasticsearch
数字游名Tomda16 分钟前
腾讯开源最新视频生成模型:仅8.3B,元宝已接入
人工智能·开源·开源软件
一点一木18 分钟前
国内首款原生视觉编程模型实测:Doubao-Seed-Code 前端 Agent 从零完成像素画编辑器
前端·人工智能·agent
数据知道24 分钟前
FastAPI项目:从零到一搭建一个网站导航系统
python·mysql·fastapi·python web·python项目
●VON43 分钟前
人工智能、机器学习与深度学习:从概念到实践
人工智能·深度学习·机器学习
程序员爱钓鱼1 小时前
Python 编程实战 · 进阶与职业发展:数据分析与 AI(Pandas、NumPy、Scikit-learn)
后端·python·trae
软件开发技术深度爱好者1 小时前
Python库/包/模块管理工具
开发语言·python