【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)]
]
相关推荐
IT_陈寒3 分钟前
用了Proxy才发现以前的JavaScript白写了
前端·人工智能·后端
甲维斯27 分钟前
Claude Opus5手搓“NewAPI Plus”首轮成果!
人工智能
程序猿DD32 分钟前
分享两个我每天都在用的 Skill,拖进豆包就能跑,限时领 30 天会员
人工智能
阿里云大数据AI技术1 小时前
Agentic Search 2.0:从单轮对话迈向企业级 AI 搜索自动驾驶Agent
人工智能·elasticsearch·agent
东风破_1 小时前
从 messages 数组到 Memory:大模型到底是怎么“记住”上一轮对话的?
人工智能
AEI1 小时前
四年间大模型的演进历程
人工智能·面试·程序员
狂师2 小时前
阿里开源:skill-up,一款Agent Skill 评测工具!
人工智能·开源·agent
武子康2 小时前
同一套 Agent Runtime,为什么 Web、Headless 和 Python SDK 仍然不是同一个产品
人工智能·llm·agent
天天代码码天天2 小时前
一个纯 C 的 OCR Runtime,又向前走了一步:lw.PPOCR.C preview.5 发布
人工智能
程序员cxuan2 小时前
Claude 官方的学习教程,太强了。
人工智能·后端·程序员