欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python meshgrid_torch.meshgrid()和np.meshgrid()的区别

发布时间:2024/1/23 python 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python meshgrid_torch.meshgrid()和np.meshgrid()的区别 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

np.meshgrid()函数常用于生成二维网格,比如图像的坐标点。

pytorch中也有一个类似的函数torch.meshgrid(),功能也类似,但是两者的用法有区别,使用时需要注意(刚踩坑,因此记录一下。。。)

比如我要生成一张图像(h=6, w=10)的xy坐标点,看下两者的实现方式:

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()函数的区别,就不用文字总结了,自己体会哈哈哈。

超强干货来袭 云风专访:近40年码龄,通宵达旦的技术人生

总结

以上是生活随笔为你收集整理的python meshgrid_torch.meshgrid()和np.meshgrid()的区别的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。