【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)]
]
相关推荐
IJCAST12 分钟前
IJCAST最新一期已经发布
人工智能·深度学习·神经网络
又幸福了哥33 分钟前
Python入门到高级(知识点七)
python
熊野君1 小时前
附录与 Codex 实操手册
开发语言·人工智能·产品经理
又幸福了哥1 小时前
Python入门到高级(知识点六)
python
维克兜率天1 小时前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
Zaimmm1 小时前
AI医学研究工具助力肝癌术后急性脑梗早期护理实践研究|证元芳 2026
人工智能
木卫四科技1 小时前
AgentAntibody:Prompt 注入防御开始“长记忆”,LLM Agent 如何构建自进化免疫系统?
人工智能·prompt·智能体安全
Djvu6771 小时前
让 Codex / Claude Code / Hermes 共享同一个搜索+抓取工具:一份 SKILL.md 走天下的取舍
人工智能
chunmiao30321 小时前
OpenAI 官宣断供 Cursor,AI 编程迎来第一次模型断供
人工智能·深度学习
pnoker1 小时前
IoT DC3 AI 能力:Agentic Center 的设计与边界
java·人工智能·物联网·大模型·spring ai