【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)]
]
相关推荐
程序猿乐锅3 分钟前
什么是skills? 如何使用skills?如何创建skills?
人工智能·skills
nebula-AI3 分钟前
人工智能导论:模型与算法(未来发展与趋势)
人工智能·神经网络·算法·机器学习·量子计算·automl·类脑计算
灵机一物6 分钟前
灵机一物AI原生电商小程序、PC端(已上线)-OpenAI 模型推翻离散几何核心猜想:AI 首次证明人类错了
人工智能
Tony Bai6 分钟前
AI 编码胜率榜:Go 与 Rust 完胜 C++
人工智能
数字时代全景窗6 分钟前
从OpenClaw、Palantir、SpaceX,看颠覆式创新的四个层次(5)传统财务模型的局限
大数据·人工智能·架构·软件工程
code_pgf6 分钟前
sVLM在资源受限环境中的应用案例
人工智能·深度学习·架构
多年小白7 分钟前
复盘】2026年5月21日(周四)
大数据·人工智能·ai·金融·区块链
南屹川8 分钟前
【并发编程】Python异步编程实战:从协程到异步框架
人工智能
BU摆烂会噶8 分钟前
【LangGraph】House_Agent 实战(四):预定流程 —— 中断与人工干预
android·人工智能·python·langchain
AI玫瑰助手9 分钟前
Python运算符:比较运算符(等于不等等于大于小于)与返回值
android·开发语言·python