【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)]
]
相关推荐
q_35488851532 分钟前
交通数据分析项目:python地铁数据可视化分析系统 Flask框架 爬虫 数据分析 轨道数据 地铁数据分析 大数据 (源码)✅
人工智能·爬虫·python·机器学习·信息可视化·数据分析·flask
物联网软硬件开发-轨物科技1 小时前
【轨物方案】新能源的下半场:构筑光伏场站全生命周期智慧运维新范式
大数据·人工智能·物联网
2501_936146041 小时前
【目标检测】钙钛矿晶体YOLO11-GhostDynamicConv模型改进与实现_1
人工智能·目标检测·计算机视觉
Deepoch1 小时前
Deepoc具身模型:电厂巡检机械狗的智能核心
人工智能·科技·机器狗·具身模型·deepoc·机械狗·巡检机械狗
好奇龙猫6 小时前
【人工智能学习-AI入试相关题目练习-第七次】
人工智能·学习
Mao.O8 小时前
开源项目“AI思维圆桌”的介绍和对于当前AI编程的思考
人工智能
jake don8 小时前
AI 深度学习路线
人工智能·深度学习
信创天地9 小时前
信创场景软件兼容性测试实战:适配国产软硬件生态,破解运行故障难题
人工智能·开源·dubbo·运维开发·risc-v
幻云20109 小时前
Python深度学习:从筑基到登仙
前端·javascript·vue.js·人工智能·python
bst@微胖子9 小时前
LlamaIndex之核心概念及部署以及入门案例
pytorch·深度学习·机器学习