torch.meshgrid()

torch.meshgrid()解剖


先展现一个实例:

y, x = torch.meshgrid(h, w, indexing='ij')

这里h和w分别是长度为2473和2915的向量;
经过index设为 ‘ij’ 的meshgrid方法后,输出了x和y;
输出的x和y的格式都是{Tensor:(2473,2915)}。


这其中发生了什么呢?先从functional包中找pytorch的解释。

r"""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. See below for a plotting example.

        Given :math:`N` 1D tensors :math:`T_0 \ldots T_{N-1}` as
        inputs with corresponding sizes :math:`S_0 \ldots S_{N-1}`,
        this creates :math:`N` N-dimensional tensors :math:`G_0 \ldots
        G_{N-1}`, each with shape :math:`(S_0, ..., S_{N-1})` where
        the output :math:`G_i` is constructed by expanding :math:`T_i`
        to the result shape.

看起来乱七八糟?好了不扯了。说人话就是:
给定 n 个一维张量 x_1, x_2, …, x_n,每个张量的长度为 s_1, s_2, …, s_n,那么 “torch.meshgrid(x_1, x_2, …, x_n) ”返回一个元组 (y_1, y_2, …, y_n),其中 y_i 的形状为 (s_1, s_2, …, s_n),代表第 i 个维度上的坐标网格。


直接看作用:

坐标网格?这个有什么用呢?
假如,咱们有一个藏宝图中宝箱的x坐标集合以及y坐标集合,那咱们就可以利用这个方法组合出所有宝箱标号的格网。写出来就是:

x = torch.tensor([10, 20, 30])	#宝箱的x坐标集合
y = torch.tensor([1, 3, 5, 7, 9])	#宝箱的y坐标集合
#z = torch.tensor([500, 1000])

a, b = torch.meshgrid(x, y, indexing='xy')
print(a)
print(b)
#print(c)

>>>
tensor([[10, 20, 30],
        [10, 20, 30],
        [10, 20, 30],
        [10, 20, 30],
        [10, 20, 30]])
tensor([[1, 1, 1],
        [3, 3, 3],
        [5, 5, 5],
        [7, 7, 7],
        [9, 9, 9]])

可以想象到吗?返回的矩阵结合了xy的形状,就好像在藏宝图上画了一个基于宝箱位置的格网。每个元组分别依照坐标代表的那一条进行赋值。


如果你好奇那个indexing怎么是’xy’了?这个其实很简单,如果改成之前的’ij’,就是把输出结果进行转置,就这个区别。


那如果把注释掉的维度加上呢?结果如下:

tensor([[[10, 10, 10, 10, 10],
         [10, 10, 10, 10, 10]],

        [[20, 20, 20, 20, 20],
         [20, 20, 20, 20, 20]],

        [[30, 30, 30, 30, 30],
         [30, 30, 30, 30, 30]]])
tensor([[[1, 3, 5, 7, 9],
         [1, 3, 5, 7, 9]],

        [[1, 3, 5, 7, 9],
         [1, 3, 5, 7, 9]],

        [[1, 3, 5, 7, 9],
         [1, 3, 5, 7, 9]]])
tensor([[[ 500,  500,  500,  500,  500],
         [1000, 1000, 1000, 1000, 1000]],

        [[ 500,  500,  500,  500,  500],
         [1000, 1000, 1000, 1000, 1000]],

        [[ 500,  500,  500,  500,  500],
         [1000, 1000, 1000, 1000, 1000]]])

Process finished with exit code 0

能想象到吗?
想象之前的宝箱数据多了高度坐标。然后3个返回的格网张量。


meshgrid方法常常不会直接作为一个独立的方法单独使用。可能配合进入目标检测中锚框的生成过程中。利用meshgrid方法平铺所有像素的坐标,在此基础上进行锚框边缘的描述!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值