【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)]
]
相关推荐
码云骑士几秒前
06-Python装饰器从入门到源码(上)-闭包与自由变量
开发语言·python
码农小白AI2 分钟前
AI报告审核通审Agent版+IACheck:地方标准DB团体标准T企业标准Q智能查新
人工智能
小小龙学IT3 分钟前
Composio:开源AI智能体工具集成平台深度解析
人工智能·开源
happyprince5 分钟前
10_verl-Rollout模块详解
人工智能·架构·强化学习
某昆real5 分钟前
从零构建轻量级推理引擎 OInfer(四):卷积算子的 OpenCL 实现
人工智能
某昆real7 分钟前
从零构建轻量级推理引擎 OInfer(二):ONNX 模型解析与计算图构建
人工智能
码云骑士9 分钟前
10-Python运行时内存模型-栈帧-堆-引用计数-GC分代回收的全景图
开发语言·python
分布式存储与RustFS10 分钟前
对标MinIO!RustFS新一代AI分布式对象存储开源能力前瞻
人工智能·分布式·开源·分布式对象存储·rustfs·minio平替·s3 table
云烟成雨TD13 分钟前
Agent Scope Java 2.x 系列【9】接入高德 MCP 服务
java·人工智能·agent