【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)]
]
相关推荐
njsgcs2 小时前
什么是能干的ai
人工智能
开发者小天2 小时前
python中使用jupyter notebook 绘制正态分布直方图 密度图 小提琴图 模仿企鹅喙长分布图
开发语言·python·jupyter
大傻^2 小时前
Python机器学习实战:用机器学习进行情感分析 核心知识点总结
开发语言·python·机器学习
圣心2 小时前
Visual Studio Code 中的 AI 智能操作
ide·人工智能·vscode
weixin_440401692 小时前
Python数据分析-数据可视化(柱状图bar【双轴柱状图、动态柱状图】)
python·信息可视化·数据分析
longvoyage2 小时前
MindSpore社区活动:零样本图像分割推理任务
人工智能·python·深度学习
乐迪信息2 小时前
乐迪信息:AI防爆摄像头实时监测港口船舶倾斜安全状态
人工智能·安全
清水白石0082 小时前
模板方法模式全解析:用抽象基类定义算法骨架,让子类优雅填充细节
数据库·python·算法·模板方法模式
山顶望月川2 小时前
实测MiniMax-Hailuo-02:当“开工大吉“变成“无字天书“,国产AI视频模型的能与之不能
人工智能·音视频
CV@CV2 小时前
具身智能平台设计实战|基于ROS+边缘计算,从搭建到部署
人工智能·边缘计算·具身智能