【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 小时前
【人工智能学习-AI入试相关题目练习-第一次】
人工智能·学习
Java后端的Ai之路3 小时前
【阿里AI大赛】-二手车价格预测使用五折交叉验证
人工智能·深度学习·机器学习·二手车价格预测·天池
wang6021252183 小时前
本地docker的解释器在pycharm进行调试
python·pycharm·fastapi
数说星榆1813 小时前
在线简单画泳道图工具 PC端无水印
大数据·论文阅读·人工智能·架构·流程图·论文笔记
过河卒_zh15667663 小时前
情感型AI被“立规矩”,AI陪伴时代进入下半场
人工智能·算法·aigc·生成式人工智能·算法备案
工业HMI实战笔记3 小时前
拯救HMI×施耐德电气|以AI重塑工业人机交互新范式
人工智能·ui·信息可视化·自动化·人机交互·交互
张彦峰ZYF3 小时前
多智能体(Multi-Agent)系统在人工智能中的应用与发展
人工智能·autogen·metagpt·multi-agent·agentscope·camel ai·agentverse
启途AI3 小时前
2026年课件制作新范式:AI PPT工具深度解析
大数据·人工智能·powerpoint·ppt
SunnyDays10113 小时前
如何使用 Python 将 ODT 转换为 PDF:完整指南
python·odt转pdf
木头程序员3 小时前
机器学习核心知识点汇总
大数据·人工智能·机器学习·kmeans·近邻算法