torch.meshgrid(*tensors)
- tensors: 两个一维向量,如果是0维,当作1维处理
创建网格坐标
Creates grids of coordinates specified by the 1D inputs in attr:tensors.
This is helpful when you want to visualize data over some range of inputs.
返回:两个矩阵
- 第一个矩阵行相同,列是第一个向量的各个元素
- 第二个矩阵列相同,行是第二个向量的各个元素
一个直观的例子
从输出中可以看到,grid_x从左到右从上到下分别为[0,0,0,0,1,1,1,1,2,2,2,2],grid_y从左到右从上到下分别为[0,1,2,3,0,1,2,3,0,1,2,3],因此我们将每个元素分别组合,就能得到x到y的网格坐标了
x = torch.tensor([0, 1, 2])
y = torch.tensor([0, 1, 2, 3])
grid_x, grid_y = torch.meshgrid(x, y)
print("grid_x: ", grid_x)
print("grid_y: ", grid_y)
print(torch.cartesian_prod(x, y))
print(torch.equal(torch.cat(tuple(torch.dstack([grid_x, grid_y]))), torch.cartesian_prod(x, y)))
'''
grid_x:
tensor([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2]])
grid_y:
tensor([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]])
tensor([[0, 0],
[0, 1],
[0, 2],
[0, 3],
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[2, 0],
[2, 1],
[2, 2],
[2, 3]])
True
'''