【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)]
]
相关推荐
陈年老古董19 分钟前
PyTorch食物图像分类实战:从数据集制作到CNN模型训练全流程详解
pytorch·深度学习·学习·机器学习·分类·cnn
飞哥数智坊29 分钟前
TraeCode 180积分帮我做了一套系统,全程我感觉自己有点多余
人工智能·ai编程
AI人工智能集结号30 分钟前
GEO优化公司怎么选?从检测、诊断到执行判断服务是否完整
人工智能
酒旅Agent开发实战31 分钟前
开发者如何选择API和MCP
人工智能·大模型·酒店预订·ai agent·mcp
持敬chijing35 分钟前
Python-数据类型-列表
开发语言·python·青少年编程
人民广场吃泡面1 小时前
什么是AI Agent?它又能给前端带来哪些效率提升?
前端·人工智能
沈管家AI数字员工1 小时前
自研 AI 智能体 vs 采购数字员工平台:成本、风险与周期的真实对比
人工智能
集成电路芯片封装设备1 小时前
除氧型真空共晶设备技术详解:从原理到应用
人工智能
武汉星际互动1 小时前
咨询量大、时段受限、口语化难识别,政务AI数字人如何承接大厅导办?
人工智能·政务
2601_962301011 小时前
Python环境搭建及PyCharm破解使用技巧
python·pycharm·环境搭建·避坑技巧·破解使用