Pytorch向量操作(一): torch.meshgrid

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
'''
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值