【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)]
]
相关推荐
Python私教几秒前
Godot 4 CharacterBody2D 角色移动:输入、碰撞与八方向控制实战
人工智能·游戏引擎·godot·gdscript·游戏开发
圣光SG1 分钟前
Java操作题练习(二)
java·开发语言·python
m0_617493942 分钟前
Python OpenCV 分水岭算法(Watershed)详解与实战
python·opencv·算法
海带紫菜菠萝汤2 分钟前
企业批量PDF翻译方案:从选型到部署的完整指南
人工智能·算法·pdf
Sammyyyyy3 分钟前
如何利用本地技术栈构建 0 成本 AI SaaS 雏形
开发语言·人工智能·python·ai·servbay
炎火星3 分钟前
电商运营做直播实时切片,有哪些 AI 工具可以选择
人工智能
LuminWave4 分钟前
资本扎堆灵巧手赛道,数据基建成为规模化落地关键变量
大数据·人工智能·具身智能·灵巧手·tof相机
林小卫很行7 分钟前
WorkBuddy 入门2:下载、安装、认识主界面
人工智能·云计算·腾讯云·知识管理·obsidian
AAIshangyanxiu8 分钟前
Python 机器学习与深度学习气象水文海洋全域应用技术体系:地学时空数据 AI 建模、数值模式后处理、气象海洋水文智能预测与数据处理
人工智能·python·机器学习·水文气象·气象预测·气象海洋
CoderLiu12 分钟前
Agent 工程的下一层:为什么「把流程写成图」还不够,还需要 Graph Engineering
前端·人工智能·后端