【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)]
]
相关推荐
sunywz5 小时前
【JVM】(4)JVM对象创建与内存分配机制深度剖析
开发语言·jvm·python
wheelmouse77885 小时前
如何设置VSCode打开文件Tab页签换行
java·python
木头程序员5 小时前
大模型边缘部署突破:动态推理技术与精度-延迟-能耗帕累托优化
大数据·人工智能·计算机视觉·自然语言处理·智能手机·数据挖掘
DX_水位流量监测5 小时前
无人机测流之雷达流速仪监测技术分析
大数据·网络·人工智能·数据分析·自动化·无人机
昨日之日20065 小时前
LTX-2 - 一键生成音视频,创作更轻松 支持50系显卡 ComfyUI工作流 一键整合包
人工智能·音视频·视频
0思必得05 小时前
[Web自动化] Selenium基础介绍
前端·python·selenium·自动化·web自动化
imbackneverdie5 小时前
Science最新文章:大型语言模型时代的科学生产
人工智能·语言模型·自然语言处理·aigc·ai写作
P-ShineBeam5 小时前
八卡A100服务器坏卡引发 CUDA initialization: cudaGetDeviceCount()异常
运维·服务器·人工智能·语言模型
真上帝的左手5 小时前
26. AI-框架工具-LangChain & LangGraph
人工智能·langchain
沛沛老爹5 小时前
Web开发者进阶AI:Agent Skills-深度迭代处理架构——从递归函数到智能决策引擎
java·开发语言·人工智能·科技·架构·企业开发·发展趋势