【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)]
]
相关推荐
cxr8282 分钟前
高分子复合材料 AI 逆向设计合—— 认知基座与理论框架
人工智能·材料逆向设计合成
落叶无情4 分钟前
第二章 ICEF核心知识解读 第二节 ICEF:从“规律驱动提示“到“世界规律认知操作系统“的范式跃迁
人工智能
逻辑君5 分钟前
Foresight研究报告【20260014】
人工智能·深度学习
FserSuN6 分钟前
Machine Learning Specialization - Week 1, 9-20学习总结
人工智能·学习·机器学习
cxr8286 分钟前
高分子复合材料 AI 逆向设计合——核心生成引擎与物理约束架构
人工智能·架构·材料逆向合成
jiayong238 分钟前
AI架构师面试问题与解答 - 机器学习基础篇
人工智能·机器学习
ZhengEnCi9 分钟前
09aba-将离散的 token ID 映射为连续的稠密向量
人工智能
YOLO数据集集合17 分钟前
低空林业巡检数据集|生态监测树木识别|深度学习树种分类数据集
人工智能·深度学习·yolo·目标检测·分类·无人机
weixin_4684668519 分钟前
机器学习之决策树新手实战指南
人工智能·python·算法·决策树·机器学习·ai
cesske21 分钟前
机器学习模型评估指标|准确率、召回率、F1详解
人工智能·深度学习·机器学习·模型评估·召回率·准确率