【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)]
]
相关推荐
MARS_AI_18 分钟前
人工智能外呼系统:重构智能交互的全维度进化
人工智能·自然语言处理·重构·交互·语音识别·信息与通信
赵青临的辉34 分钟前
基础数学:线性代数与概率论在AI中的应用
人工智能·线性代数·概率论
HORSE RUNNING WILD37 分钟前
解决 PicGo 上传 GitHub图床及Marp中Github图片编译常见难题指南
css·python·github
小众AI1 小时前
Void: Cursor 的开源平替
人工智能·ai编程
资深の小白1 小时前
一个基于 Spring Boot 的实现,用于代理百度 AI 的 OCR 接口
人工智能·spring boot·百度
二川bro1 小时前
从AlphaGo到ChatGPT:AI技术如何一步步改变世界?
人工智能·chatgpt
ElenaYu1 小时前
mac安装cast
python·macos·cast
码农新猿类1 小时前
帧差法识别
人工智能·opencv·计算机视觉
Dxy12393102161 小时前
python如何设置excel单元格边框样式
开发语言·python·excel
cdut_suye1 小时前
【Linux系统】从 C 语言文件操作到系统调用的核心原理
java·linux·数据结构·c++·人工智能·机器学习·云计算