【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)]
]
相关推荐
小玮看世界1 分钟前
[Python] str() 和 join() 的区别与实战避坑指南
前端·javascript·python
卷无止境3 分钟前
FastAPI 的 WebSocket 装了些什么
后端·python·fastapi
sali-tec4 分钟前
C# 基于OpenCv的视觉工作流-章103-空车位识别
人工智能·opencv·计算机视觉
码云骑士4 分钟前
108-vLLM推理引擎-PagedAttention-连续批处理-吞吐提升10倍
python·vllm
DeepVisionary7 分钟前
从微软砍掉Copilot的AI播客、Deep Research看AI产品“做减法“:个人版与企业版合并,超级应用呼之欲出
python·自动化
IT·侯老师8 分钟前
qq-auto-reply
python
迷迭香yy8 分钟前
大宗交易折溢价因子怎么挖掘本地化Python全流程实战
开发语言·人工智能·python
也非非也9 分钟前
DeepSeek 又开源了一个新东西——DeepSeek Harness
人工智能·开源·agi·deepseek·harness·dsh
海兰16 分钟前
【AI工具】腾讯云开源自研 AI 助手 Octop介绍及安装使用指南
人工智能·云计算·腾讯云
卷无止境17 分钟前
FastAPI 的 Request 类装了什么
后端·python