【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)]
]
相关推荐
中國龍在廣州几秒前
生成不遗忘,「超长时序」世界模型,北大EgoLCD长短时记忆加持
人工智能·深度学习·算法·自然语言处理·chatgpt
亓才孓6 分钟前
java中的Math.Radom拓展
开发语言·python·算法
豌豆学姐17 分钟前
Sora2 能做什么?25 秒视频生成 API 的一次接入实践
大数据·人工智能·小程序·aigc·php·开源软件
Cherry的跨界思维21 分钟前
25、AI时代的数字生存战:爬虫与反爬虫的数据争夺全面解析
人工智能·爬虫·机器学习·python爬虫·python办公自动化·python反爬虫
测试人社区-千羽26 分钟前
智能化测试:AI驱动的测试覆盖率提升方法论与实战路径
运维·人工智能·测试工具·程序人生·自动化·测试覆盖率
yongche_shi36 分钟前
第八十八篇: 设计一个配置中心
python·面试宝典·设计一个配置中心
龙腾AI白云43 分钟前
图神经网络初探(1)
人工智能
躺柒44 分钟前
读共生:4.0时代的人机关系02人机合作后
大数据·人工智能·机器人·人机交互·人机协作·人机对话
无心水1 小时前
【神经风格迁移:性能】23、边缘艺术革命:树莓派+ONNX实现本地神经风格迁移,单张<2秒
pytorch·边缘计算·树莓派·onnx·int8·神经风格迁移:性能·神经风格
itwangyang5201 小时前
AIDD药物筛选与设计详细方法
人工智能·python