【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)]
]
相关推荐
geovindu几秒前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
HyperAI超神经2 分钟前
活动预告|智源/TileRT/腾讯/华为/智元创新同台,共探 AI 编译的多层级协同优化
人工智能·ai 编译器·腾讯·具身智能·矩阵乘法·算子优化·华为昇腾
在水一缸6 分钟前
GLM 5.2 发布:当长上下文与智能体走向深度融合
人工智能·大模型·智能体·智谱ai·长上下文·glm-5.2
小妖同学学AI12 分钟前
AI编程 AI Ping+Cline搭建自己的编程助手!
人工智能·ai编程
星马梦缘18 分钟前
机器学习与模式识别 第十四章 神经网络中的反向传播 考点压缩
人工智能·机器学习·微分·反向传播
love530love21 分钟前
WorkBuddy + 本地 ComfyUI MCP:免订阅费的自建方案
人工智能·windows·mcp·comfy cloud
无心水26 分钟前
【全域智能营销实战】2、Spring AI 模块化架构深度解读:从 1.0 到 2.0 的演进与最佳实践
人工智能·spring·架构·harness·顶尖架构师·全域智能营销·harmess
tryCbest33 分钟前
Python 文件操作
服务器·python