【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)]
]
相关推荐
德林恩宝1 分钟前
搜索 Agent 的两条路——训练一个,还是工程搭一个
人工智能·大模型·llm·agent
在所不辞兄1 分钟前
【零基础学智能仿真-58】Foam-Agent协作与知识检索
人工智能·深度学习·神经网络·机器学习·有限元·仿真计算
cc_瀚海知行2 分钟前
工具调用 6|助手什么时候该停下来?
java·服务器·前端·人工智能·python·ai
Martina_03213 分钟前
AI生成3D模型UV岛太碎,重绘贴图全是接缝?用6步重整UV并保留原材质
图像处理·人工智能·3d·自然语言处理·贴图·uv·游戏策划
youdexiang16 分钟前
Android录音APP微信语音导入机制详解
人工智能·语音识别
溪语流沙17 分钟前
【Web全栈进阶】Nginx反向代理 + HTTPS:正式上线
前端·vue.js·python·nginx·https·fastapi
悟天特斯19 分钟前
楼宇自控的“协同优化“:从设备控制到系统级节能与舒适平衡
人工智能·物联网
全栈弄潮儿24 分钟前
Python实战第11期:面向对象编程基础
后端·python·编程语言
叫我啊腻29 分钟前
Nano Banana 2.1 深度测评:升级了哪些,和 GPT Image 2.5 怎么选?
人工智能
johnsong29 分钟前
AI前沿日报 2026-10-21:开源AI全面反击
人工智能·开源