python meshgrid_torch.meshgrid()和np.meshgrid()的区别
np.meshgrid()函數(shù)常用于生成二維網(wǎng)格,比如圖像的坐標(biāo)點(diǎn)。
pytorch中也有一個(gè)類似的函數(shù)torch.meshgrid(),功能也類似,但是兩者的用法有區(qū)別,使用時(shí)需要注意(剛踩坑,因此記錄一下。。。)
比如我要生成一張圖像(h=6, w=10)的xy坐標(biāo)點(diǎn),看下兩者的實(shí)現(xiàn)方式:
np.meshgrid()
>>> import numpy as np
>>> h = 6
>>> w = 10
>>> xs, ys = np.meshgrid(np.arange(w), np.arange(h))
>>> xs.shape
(6, 10)
>>> ys.shape
(6, 10)
>>> xs
array([[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
array([[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 = np.stack([xs, ys], axis=-1)
>>> xys.shape
(6, 10, 2)
torch.meshgrid()
>>> 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])
從python交互式窗口可以清晰的看出numpy和pytorch中meshgrid()函數(shù)的區(qū)別,就不用文字總結(jié)了,自己體會(huì)哈哈哈。
超強(qiáng)干貨來(lái)襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的python meshgrid_torch.meshgrid()和np.meshgrid()的区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python cpython关系_第3篇
- 下一篇: u盘排序软件_华硕电脑u盘启动设置