【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)]
]
相关推荐
人工智能AI技术8 小时前
Laya与Jev深度对比:Agent场景专用判断模型落地实战
人工智能
abigalexy8 小时前
图解AI应用架构设计
人工智能·ai·架构·系统架构·aigc
智能RPA8 小时前
金融行业智能体自动化平台对比评测报告(银行核心与监管报送场景)
人工智能·金融·自动化·agent·rpa
龍德明宇8 小时前
竞技场的设计师-龍德明宇
人工智能·大语言模型llm·负主体性·ai存在论
具身AGI8 小时前
端侧推理的工程账,全栈自研 物理AI 的最后一公里
人工智能
径硕科技JINGdigital8 小时前
出海企业想要借助统一平台接入国际主流基础模型,可选哪些云上生成式 AI 平台?
大数据·人工智能
估值探索者8 小时前
【Python量化策略实战 #04】Donchian 通道假突破太多?用 ATR 阈值过滤跑通真实突破信号
开发语言·python·接口·api接口·数据api接口·股票数据api接口
DP DPharness8 小时前
从零装通 dsh-plugin-subscriptions:三条安装路径、版本门槛与 headless 跑法
人工智能·dpharness
龙亘川8 小时前
智慧交通运输监管平台业务建模与架构解析
人工智能·架构·智慧城市·数据可视化·政务
Summer-Bright8 小时前
深度 | 谷歌Gemini 4 Argon单次输出100万Token:长输出是智能体刚需,先给防御者不给攻击者才是新玩法
人工智能·安全·ai