【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)]
]
相关推荐
飞哥数智坊5 小时前
分享被迫变直播:AI·Spring养虾记就这样上线了
人工智能
Mr_Lucifer8 小时前
「一句话」生成”小红书“式金句海报(CodeFlicker + quote-poster-generator)
人工智能·aigc·visual studio code
冬奇Lab9 小时前
OpenClaw 深度解析(五):模型与提供商系统
人工智能·开源·源码阅读
冬奇Lab9 小时前
一天一个开源项目(第42篇):OpenFang - 用 Rust 构建的 Agent 操作系统,16 层安全与 7 个自主 Hands
人工智能·rust·开源
IT_陈寒9 小时前
SpringBoot性能飙升200%?这5个隐藏配置你必须知道!
前端·人工智能·后端
yiyu07169 小时前
3分钟搞懂深度学习AI:反向传播:链式法则的归责游戏
人工智能·深度学习
机器之心10 小时前
OpenClaw绝配!GPT-5.4问世,AI能力开始大一统,就是太贵
人工智能·openai
机器之心10 小时前
海外华人15人团队打造,统一理解与生成的图像模型,超越Nano banana登顶图像编辑
人工智能·openai
用户5527960260510 小时前
在老版本 HPC 系统上运行 Antigravity(反重力)
人工智能