torch.meshgrid函数
在此记录下torch.meshgrid的用法,该函数常常用于生成二维的网格:
1
2
3
4
5
6
7
8
9
10
11
|
>>> x = torch.tensor([ 1 , 2 , 3 ]) >>> y = torch.tensor([ 4 , 5 , 6 ]) >>> grid_x, grid_y = torch.meshgrid(x, y) >>> grid_x tensor([[ 1 , 1 , 1 ], [ 2 , 2 , 2 ], [ 3 , 3 , 3 ]]) >>> grid_y tensor([[ 4 , 5 , 6 ], [ 4 , 5 , 6 ], [ 4 , 5 , 6 ]]) |
另一个例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
>>> import torch >>> h = 6 >>> w = 10 >>> ys,xs = torch.meshgrid(torch.arange(h), torch.arange(w)) >>> xs.shape torch.Size([ 6 , 10 ]) >>> ys.shape torch.Size([ 6 , 10 ]) >>> xs tensor([[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ], [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ], [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ], [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ], [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ], [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]]) >>> ys tensor([[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ], [ 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 ], [ 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 ], [ 4 , 4 , 4 , 4 , 4 , 4 , 4 , 4 , 4 , 4 ], [ 5 , 5 , 5 , 5 , 5 , 5 , 5 , 5 , 5 , 5 ]]) >>> xys = torch.stack([xs, ys], dim = - 1 ) >>> xys.shape torch.Size([ 6 , 10 , 2 ]) |
需要注意的点:
1. torch.meshgrid函数的输入是若干个(N个)一维Tensor或者若干个标量。
2. torch.meshgrid函数的输出有N个,每个输出都是N维的。
3. torch.meshgrid函数的每个输出tensor的shape都为(d1,d2,d3...dN)(d1,d2,d3...dN),其中didi为第i个输入向量的长度。
4. torch.meshgrid函数的每个输出有什么不同?答:为该输出对应输入向量在其他维度舒展开的结果。
5. torch的meshgrid实现和numpy的meshgrid实现有所不同,后者“可能”能够更直接地获取我们需要的东西,而torch的meshgrid调用后可能还需要做一个转置。
本文来自博客园,作者:海_纳百川,转载请注明原文链接:https://www.cnblogs.com/chentiao/p/16683675.html,如有侵权联系删除
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异