【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)]
]
相关推荐
李昊哲小课3 分钟前
销售数据可视化分析项目
python·信息可视化·数据分析·matplotlib·数据可视化·seaborn
isNotNullX12 分钟前
实时数仓和离线数仓还分不清楚?看完就懂了
大数据·数据库·数据仓库·人工智能·数据分析
烛阴14 分钟前
带参数的Python装饰器原来这么简单,5分钟彻底掌握!
前端·python
Liudef0621 分钟前
大语言模型的极限:知识、推理与创造力的边界探析
人工智能·语言模型·自然语言处理
潮湿的心情28 分钟前
亚洲牧原:活跃行业交流,延伸公益版图,市场拓展再结硕果
大数据·人工智能
平和男人杨争争29 分钟前
机器学习14——线性回归
人工智能·机器学习·线性回归
一个天蝎座 白勺 程序猿41 分钟前
飞算JavaAI进阶:重塑Java开发范式的AI革命
java·开发语言·人工智能
全干engineer44 分钟前
Flask 入门教程:用 Python 快速搭建你的第一个 Web 应用
后端·python·flask·web
nightunderblackcat1 小时前
新手向:Python网络编程,搭建简易HTTP服务器
网络·python·http
李昊哲小课1 小时前
pandas销售数据分析
人工智能·python·数据挖掘·数据分析·pandas