【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)]
]
相关推荐
yuezhilangniao1 分钟前
【AI 编辑器开发规范 v2.1 版】—— 为 AI 时代的敏捷开发而生
人工智能·编辑器·敏捷流程
jz_ddk3 分钟前
[数学基础] 浅尝矩阵基础运算
人工智能·线性代数·ai·矩阵
AC赳赳老秦5 分钟前
新能源AI趋势:DeepSeek分析光伏/风电数据,助力2026新能源运维升级
运维·人工智能·python·安全·架构·prometheus·deepseek
向上的车轮13 分钟前
机器人未来会发展出自我意识吗?
人工智能·机器人
Elastic 中国社区官方博客14 分钟前
Elasticsearch 9.3 增加 bfloat16 向量 支持
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
冬奇Lab16 分钟前
一天一个开源项目(第27篇):Awesome AI Coding - 一站式 AI 编程资源导航
人工智能·开源·资讯
Learner__Q29 分钟前
GPT模型入门教程:从原理到实现
python·gpt
夕除33 分钟前
js--21
java·python·算法
A小码哥36 分钟前
Claude 今天发布了 Sonnet 4.6, 深度对比:sonnet vs Opus,如何选择最适合你的模型?
大数据·数据库·人工智能
破晓之翼38 分钟前
关于AI应用开发需要了解专有名词解释和实际作用
大数据·人工智能