【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)]
]
相关推荐
程序员小八7771 分钟前
Java 快速转 Go
java·python·golang
熊猫钓鱼>_>19 分钟前
鸿蒙ArkUI全手势操作实战指南:6大基础手势从原理到落地避坑
人工智能·深度学习·华为·架构·harmonyos·arkui·tapgesture
职场的momo24 分钟前
11个后端与AI岗位同时开放:Java、网关、推理优化怎么匹配
java·开发语言·人工智能
微石科技29 分钟前
社区卫生中心慢病管理怎么做?宁波微石科技智慧医康系统:一个平台管住趋势、随访、患者
大数据·人工智能·科技
AI模型调用笔记31 分钟前
GPT-5.4 8月31日退出 Codex?先分清 ChatGPT 登录与 API Key,再迁移 Terra/Luna
人工智能·gpt·chatgpt·ai编程
Henry-SAP1 小时前
AI与机器人信息新闻
人工智能·云原生·sap·erp
天远数科1 小时前
零信任架构实战:基于天远二手车VIN估值构建自动化汽车数据网关
人工智能·架构·自动化·汽车
AI码农小姐姐1 小时前
小说导入AI漫剧赚钱教程:知漫剧批量生成与选型
人工智能
hh9501 小时前
Agent Plan x DeepSeek Harness — Token 预算管理与成本追踪体系技术
人工智能·学习·adg·火山引擎·adg成都社区
梦想的旅途21 小时前
Python实现企业微信文本消息发送
开发语言·python·企业微信