Hon*_*zaB 253 python numpy mesh multidimensional-array numpy-ndarray
有人可以向我解释meshgrid
Numpy功能的目的是什么?我知道它会为绘图创建某种坐标网格,但我无法真正看到它的直接好处.
我正在学习Sebastian Raschka的"Python机器学习",他正在使用它来绘制决策边界.请参见此处的输入11 .
我也从官方文档中尝试过这段代码,但是,输出对我来说并没有多大意义.
x = np.arange(-5, 5, 1)
y = np.arange(-5, 5, 1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)
Run Code Online (Sandbox Code Playgroud)
如果可能的话,请向我展示很多现实世界的例子.
Sue*_*ver 336
目的meshgrid
是从x值数组和y值数组中创建一个矩形网格.
因此,例如,如果我们想要创建一个网格,我们在x和y方向的0到4之间的每个整数值上都有一个点.要创建矩形网格,我们需要每个点x
和y
点的组合.
这将是25分,对吧?因此,如果我们想为所有这些点创建一个x和y数组,我们可以执行以下操作.
x[0,0] = 0 y[0,0] = 0
x[0,1] = 1 y[0,1] = 0
x[0,2] = 2 y[0,2] = 0
x[0,3] = 3 y[0,3] = 0
x[0,4] = 4 y[0,4] = 0
x[1,0] = 0 y[1,0] = 1
x[1,1] = 1 y[1,1] = 1
...
x[4,3] = 3 y[4,3] = 4
x[4,4] = 4 y[4,4] = 4
Run Code Online (Sandbox Code Playgroud)
这将导致以下x
和y
矩阵,使得每个矩阵中的对应元素的配对给出网格中的点的x和y坐标.
x = 0 1 2 3 4 y = 0 0 0 0 0
0 1 2 3 4 1 1 1 1 1
0 1 2 3 4 2 2 2 2 2
0 1 2 3 4 3 3 3 3 3
0 1 2 3 4 4 4 4 4 4
Run Code Online (Sandbox Code Playgroud)
然后我们可以绘制这些来验证它们是网格:
plt.plot(x,y, marker='.', color='k', linestyle='none')
Run Code Online (Sandbox Code Playgroud)
显然,这变得非常乏味,特别是对于大范围x
和y
.相反,meshgrid
实际上可以为我们生成这个:我们必须指定的是唯一x
和y
值.
xvalues = np.array([0, 1, 2, 3, 4]);
yvalues = np.array([0, 1, 2, 3, 4]);
Run Code Online (Sandbox Code Playgroud)
现在,当我们打电话时meshgrid
,我们会自动获得之前的输出.
xx, yy = np.meshgrid(xvalues, yvalues)
plt.plot(xx, yy, marker='.', color='k', linestyle='none')
Run Code Online (Sandbox Code Playgroud)
创建这些矩形网格对于许多任务都很有用.在您在您的文章所提供的例子,它是简单地品尝函数(的方式sin(x**2 + y**2) / (x**2 + y**2)
)在范围值的x
和y
.
由于此功能已在矩形网格上采样,因此该功能现在可以显示为"图像".
此外,结果现在可以传递给期望矩形网格上的数据的函数(即contourf
)
Hai*_*han 195
由Microsoft Excelle提供:
MSe*_*ert 40
实际上np.meshgrid
文档中已经提到了目的:
从坐标向量返回坐标矩阵.
在给定一维坐标数组x1,x2,...,xn的情况下,使ND坐标数组用于ND网格上的ND标量/矢量场的矢量化评估.
所以它的主要目的是创建一个坐标矩阵.
你可能只是问自己:
你需要使用Python/NumPy坐标矩阵的原因是坐标与值之间没有直接的关系,除非你的坐标从零开始并且是纯正整数.然后你可以使用数组的索引作为索引.但是,如果不是这种情况,您需要在数据旁边存储坐标.这就是网格进来的地方.
假设您的数据是:
1 2 1
2 5 2
1 2 1
Run Code Online (Sandbox Code Playgroud)
但是,每个值代表水平2公里宽的区域和垂直3公里.假设您的原点位于左上角,并且您需要表示可以使用的距离的数组:
import numpy as np
h, v = np.meshgrid(np.arange(3)*3, np.arange(3)*2)
Run Code Online (Sandbox Code Playgroud)
在哪里x
:
0 2 4
0 2 4
0 2 4
Run Code Online (Sandbox Code Playgroud)
和h:
0 0 0
3 3 3
6 6 6
Run Code Online (Sandbox Code Playgroud)
所以,如果你有两个指标,比方说y
与meshgrid
(这就是为什么的返回值xx
通常是xs
或x
,而不是h
在这种情况下,我选择np.meshgrid
了水平!),那么你可以得到该点的x坐标,在Y点和坐标使用以下值的价值:
h[x, y] # horizontal coordinate
v[x, y] # vertical coordinate
data[x, y] # value
Run Code Online (Sandbox Code Playgroud)
这样可以更容易地跟踪坐标,并且(更重要的是)您可以将它们传递给需要知道坐标的函数.
然而,np.mgrid
它本身并不经常直接使用,大多数人只是使用类似物体之一np.ogrid
或np.mgrid
.这里sparse=False
代表np.ogrid
和sparse=True
的sparse
情况下(我指的是np.meshgrid
的说法np.meshgrid
).请注意,之间存在差异显著
np.ogrid
和np.mgrid
和matplotlib.pyplot.imshow
:前两个返回的值(如果有两个或更多)是相反的.通常这没关系,但你应该根据上下文给出有意义的变量名.例如,在2D网格的情况下,并np.meshgrid
是有意义的名字的第一个返回的项目x
y
,第二个np.mgrid
,而它周围的其他方式np.ogrid
和np.ogrid
.
np.meshgrid
和稀疏的网格>>> import numpy as np
>>> yy, xx = np.ogrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]])
>>> yy
array([[-5],
[-4],
[-3],
[-2],
[-1],
[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5]])
Run Code Online (Sandbox Code Playgroud)
正如已经说过的yy, xx
那样xx, yy
,与之相比,输出是相反的,这就是为什么我将它解压缩而不是np.mgrid
:
>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6), sparse=True)
>>> xx
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]])
>>> yy
array([[-5],
[-4],
[-3],
[-2],
[-1],
[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5]])
Run Code Online (Sandbox Code Playgroud)
这看起来像坐标,特别是2D图的x和y线.
可视化:
yy, xx = np.ogrid[-5:6, -5:6]
plt.figure()
plt.title('ogrid (sparse meshgrid)')
plt.grid()
plt.xticks(xx.ravel())
plt.yticks(yy.ravel())
plt.scatter(xx, np.zeros_like(xx), color="blue", marker="*")
plt.scatter(np.zeros_like(yy), yy, color="red", marker="x")
Run Code Online (Sandbox Code Playgroud)
np.meshgrid
和密集/充实的网格>>> yy, xx = np.mgrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
[-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
[-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
[-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]])
Run Code Online (Sandbox Code Playgroud)
这同样适用于:与以下相比,输出反转ogrid
:
>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6))
>>> xx
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
[-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
[-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
[-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]])
Run Code Online (Sandbox Code Playgroud)
与xx
这些数组不同,包含-5 <= xx <= 5的全部 yy
和np.arange
坐标; -5 <= yy <= 5格.
yy, xx = np.mgrid[-5:6, -5:6]
plt.figure()
plt.title('mgrid (dense meshgrid)')
plt.grid()
plt.xticks(xx[0])
plt.yticks(yy[:, 0])
plt.scatter(xx, yy, color="red", marker="x")
Run Code Online (Sandbox Code Playgroud)
它不仅限于2D,这些函数适用于任意维度(嗯,Python中函数的最大参数数量和NumPy允许的最大维数):
>>> x1, x2, x3, x4 = np.ogrid[:3, 1:4, 2:5, 3:6]
>>> for i, x in enumerate([x1, x2, x3, x4]):
... print('x{}'.format(i+1))
... print(repr(x))
x1
array([[[[0]]],
[[[1]]],
[[[2]]]])
x2
array([[[[1]],
[[2]],
[[3]]]])
x3
array([[[[2],
[3],
[4]]]])
x4
array([[[[3, 4, 5]]]])
>>> # equivalent meshgrid output, note how the first two arguments are reversed and the unpacking
>>> x2, x1, x3, x4 = np.meshgrid(np.arange(1,4), np.arange(3), np.arange(2, 5), np.arange(3, 6), sparse=True)
>>> for i, x in enumerate([x1, x2, x3, x4]):
... print('x{}'.format(i+1))
... print(repr(x))
# Identical output so it's omitted here.
Run Code Online (Sandbox Code Playgroud)
即使这些也适用于1D,有两个(更常见的)1D网格创建功能:
除了stop
和step
参数之外,它还支持mgrid
参数(甚至表示步骤数的复杂步骤):
>>> x1, x2 = np.mgrid[1:10:2, 1:10:4j]
>>> x1 # The dimension with the explicit step width of 2
array([[1., 1., 1., 1.],
[3., 3., 3., 3.],
[5., 5., 5., 5.],
[7., 7., 7., 7.],
[9., 9., 9., 9.]])
>>> x2 # The dimension with the "number of steps"
array([[ 1., 4., 7., 10.],
[ 1., 4., 7., 10.],
[ 1., 4., 7., 10.],
[ 1., 4., 7., 10.],
[ 1., 4., 7., 10.]])
Run Code Online (Sandbox Code Playgroud)
您特别询问了目的,实际上如果您需要坐标系,这些网格非常有用.
例如,如果您有一个NumPy函数来计算二维距离:
def distance_2d(x_point, y_point, x, y):
return np.hypot(x-x_point, y-y_point)
Run Code Online (Sandbox Code Playgroud)
你想知道每个点的距离:
>>> ys, xs = np.ogrid[-5:5, -5:5]
>>> distances = distance_2d(1, 2, xs, ys) # distance to point (1, 2)
>>> distances
array([[9.21954446, 8.60232527, 8.06225775, 7.61577311, 7.28010989,
7.07106781, 7. , 7.07106781, 7.28010989, 7.61577311],
[8.48528137, 7.81024968, 7.21110255, 6.70820393, 6.32455532,
6.08276253, 6. , 6.08276253, 6.32455532, 6.70820393],
[7.81024968, 7.07106781, 6.40312424, 5.83095189, 5.38516481,
5.09901951, 5. , 5.09901951, 5.38516481, 5.83095189],
[7.21110255, 6.40312424, 5.65685425, 5. , 4.47213595,
4.12310563, 4. , 4.12310563, 4.47213595, 5. ],
[6.70820393, 5.83095189, 5. , 4.24264069, 3.60555128,
3.16227766, 3. , 3.16227766, 3.60555128, 4.24264069],
[6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
2.23606798, 2. , 2.23606798, 2.82842712, 3.60555128],
[6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
1.41421356, 1. , 1.41421356, 2.23606798, 3.16227766],
[6. , 5. , 4. , 3. , 2. ,
1. , 0. , 1. , 2. , 3. ],
[6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
1.41421356, 1. , 1.41421356, 2.23606798, 3.16227766],
[6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
2.23606798, 2. , 2.23606798, 2.82842712, 3.60555128]])
Run Code Online (Sandbox Code Playgroud)
如果在密集网格而不是开放网格中传递,则输出将是相同的.NumPys广播使其成为可能!
让我们看看结果:
plt.figure()
plt.title('distance to point (1, 2)')
plt.imshow(distances, origin='lower', interpolation="none")
plt.xticks(np.arange(xs.shape[1]), xs.ravel()) # need to set the ticks manually
plt.yticks(np.arange(ys.shape[0]), ys.ravel())
plt.colorbar()
Run Code Online (Sandbox Code Playgroud)
这也是当NumPys ogrid
和imshow
变得非常方便,因为它可以让你轻松更改网格的分辨率:
ys, xs = np.ogrid[-5:5:200j, -5:5:200j]
# otherwise same code as above
Run Code Online (Sandbox Code Playgroud)
但是,由于x
不支持y
和x
输入,必须手动更改刻度.如果接受y
和matplotlib.pyplot.contour
坐标会很方便,对吗?
使用NumPy编写与网格自然对应的函数很容易.此外,NumPy,SciPy,MatPlotLib中有几个函数可以让你传入网格.
我喜欢图像所以让我们探索density
:
ys, xs = np.mgrid[-5:5:200j, -5:5:200j]
density = np.sin(ys)-np.cos(xs)
plt.figure()
plt.contour(xs, ys, density)
Run Code Online (Sandbox Code Playgroud)
请注意坐标是如何正确设置的!如果你刚刚通过,那就不会是这种情况scipy.interpolate.interp2d
.
或者使用astropy模型给出另一个有趣的例子(这次我不关心坐标,我只是用它们来创建一些网格):
from astropy.modeling import models
z = np.zeros((100, 100))
y, x = np.mgrid[0:100, 0:100]
for _ in range(10):
g2d = models.Gaussian2D(amplitude=100,
x_mean=np.random.randint(0, 100),
y_mean=np.random.randint(0, 100),
x_stddev=3,
y_stddev=3)
z += g2d(x, y)
a2d = models.AiryDisk2D(amplitude=70,
x_0=np.random.randint(0, 100),
y_0=np.random.randint(0, 100),
radius=5)
z += a2d(x, y)
Run Code Online (Sandbox Code Playgroud)
虽然这只是"看起来"与Scipy等功能模型和拟合(例如scipy.interpolate.griddata
,
np.mgrid
甚至显示示例使用np.meshgrid
)相关的几个功能需要网格.其中大多数使用开放式网格和密集网格,但有些只能与其中一个一起使用.
MSe*_*ert 34
假设你有一个功能:
def sinus2d(x, y):
return np.sin(x) + np.sin(y)
Run Code Online (Sandbox Code Playgroud)
例如,您希望在0到2*pi的范围内看到它的样子.你会怎么做?有np.meshgrid
进来:
xx, yy = np.meshgrid(np.linspace(0,2*np.pi,100), np.linspace(0,2*np.pi,100))
z = sinus2d(xx, yy) # Create the image on this grid
Run Code Online (Sandbox Code Playgroud)
这样的情节看起来像:
import matplotlib.pyplot as plt
plt.imshow(z, origin='lower', interpolation='none')
plt.show()
Run Code Online (Sandbox Code Playgroud)
所以np.meshgrid
只是一个方便.原则上可以通过以下方式完成:
z2 = sinus2d(np.linspace(0,2*np.pi,100)[:,None], np.linspace(0,2*np.pi,100)[None,:])
Run Code Online (Sandbox Code Playgroud)
但是你需要知道你的尺寸(假设你有两个......)和正确的广播.np.meshgrid
为你做所有这些.
netgrid也允许您删除坐标和数据,例如,如果您想要插值但排除某些值:
condition = z>0.6
z_new = z[condition] # This will make your array 1D
Run Code Online (Sandbox Code Playgroud)
那你现在怎么做插值?您可以提供x
和y
插入函数,scipy.interpolate.interp2d
因此您需要一种方法来知道哪些坐标被删除:
x_new = xx[condition]
y_new = yy[condition]
Run Code Online (Sandbox Code Playgroud)
然后你仍然可以使用"正确"坐标进行插值(尝试不使用meshgrid,你会有很多额外的代码):
from scipy.interpolate import interp2d
interpolated = interp2(x_new, y_new, z_new)
Run Code Online (Sandbox Code Playgroud)
并且原始的meshgrid允许您再次在原始网格上进行插值:
interpolated_grid = interpolated(xx, yy)
Run Code Online (Sandbox Code Playgroud)
这些只是我用过的一些例子,meshgrid
可能还有很多.
简答
目的meshgrid
是通过 C NumPy 库中的矢量化操作来帮助替换 Python 循环(慢解释代码)。
借用本站。
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
Run Code Online (Sandbox Code Playgroud)
meshgrid
用于创建 -4 和 +4 之间的坐标对,在每个方向 X 和 Y 上以 0.25 为增量。然后使用每对坐标从中找到 R 和 Z。这种准备坐标“网格”的方法经常用于绘制 3D 表面或着色 2D 表面。
详细信息:Python for 循环 vs NumPy 向量运算
举一个更简单的例子,假设我们有两个值序列,
a = [2,7,9,20]
b = [1,6,7,9] ?
Run Code Online (Sandbox Code Playgroud)
我们想对每对可能的值执行一个操作,一个取自第一个列表,一个取自第二个列表。我们还想存储结果。例如,假设我们想要获得每个可能对的值的总和。
缓慢而费力的方法
c = []
for i in range(len(b)):
row = []
for j in range(len(a)):
row.append (a[j] + b[i])
c.append (row)
print (c)
Run Code Online (Sandbox Code Playgroud)
结果:
[[3, 8, 10, 21],
[8, 13, 15, 26],
[9, 14, 16, 27],
[11, 16, 18, 29]]
Run Code Online (Sandbox Code Playgroud)
Python 是解释性的,这些循环执行起来相对较慢。
快速简便的方法
meshgrid
旨在从代码中删除循环。它返回两个数组(下面的 i 和 j),它们可以组合起来扫描所有现有的对,如下所示:
i,j = np.meshgrid (a,b)
c = i + j
print (c)
Run Code Online (Sandbox Code Playgroud)
结果:
[[ 3 8 10 21]
[ 8 13 15 26]
[ 9 14 16 27]
[11 16 18 29]]
Run Code Online (Sandbox Code Playgroud)
引擎盖下的网格
准备的两个数组meshgrid
是:
(array([[ 2, 7, 9, 20],
[ 2, 7, 9, 20],
[ 2, 7, 9, 20],
[ 2, 7, 9, 20]]),
array([[1, 1, 1, 1],
[6, 6, 6, 6],
[7, 7, 7, 7],
[9, 9, 9, 9]]))
Run Code Online (Sandbox Code Playgroud)
这些数组是通过重复提供的值创建的。一个包含相同行中的值,另一个包含相同列中的其他值。行数和列数由另一个序列中的元素数决定。
meshgrid
因此,由创建的两个数组对于向量操作是形状兼容的。想象一下页面顶部代码中的 x 和 y 序列具有不同数量的元素,X 和 Y 结果数组无论如何都将是形状兼容的,不需要任何广播。
起源
numpy.meshgrid
来自MATLAB,就像许多其他NumPy函数一样。所以你也可以从 MATLAB 中学习例子,看看meshgrid
在使用中,3D 绘图的代码在 MATLAB 中看起来是一样的。
小智 5
meshgrid 有助于从两个阵列的所有点对的两个一维阵列创建矩形网格。
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])
Run Code Online (Sandbox Code Playgroud)
现在,如果您已经定义了一个函数 f(x,y) 并且您想将此函数应用于数组 'x' 和 'y' 中所有可能的点组合,那么您可以这样做:
f(*np.meshgrid(x, y))
Run Code Online (Sandbox Code Playgroud)
比方说,如果你的函数只产生两个元素的乘积,那么这就是如何实现笛卡尔积,有效地用于大型数组。
从这里引用
给定可能的 x 值 ,xs
(将它们视为绘图 x 轴上的刻度线)和可能的 y 值 ,ys
生成meshgrid
相应的一组 (x, y) 网格点——类似于set((x, y) for x in xs for y in yx)
。例如,如果xs=[1,2,3]
和ys=[4,5,6]
,我们将得到坐标集{(1,4), (2,4), (3,4), (1,5), (2,5), (3,5), (1,6), (2,6), (3,6)}
。
但是,返回的表示形式meshgrid
与上面的表达式有两个不同之处:
首先,meshgrid
在 2d 数组中布置网格点:行对应于不同的 y 值,列对应于不同的 x 值——如 中所示list(list((x, y) for x in xs) for y in ys)
,这将给出以下数组:
[[(1,4), (2,4), (3,4)],
[(1,5), (2,5), (3,5)],
[(1,6), (2,6), (3,6)]]
Run Code Online (Sandbox Code Playgroud)
其次,meshgrid
分别返回 x 和 y 坐标(即在两个不同的 numpy 2d 数组中):
xcoords, ycoords = (
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]),
array([[4, 4, 4],
[5, 5, 5],
[6, 6, 6]]))
# same thing using np.meshgrid:
xcoords, ycoords = np.meshgrid([1,2,3], [4,5,6])
# same thing without meshgrid:
xcoords = np.array([xs] * len(ys)
ycoords = np.array([ys] * len(xs)).T
Run Code Online (Sandbox Code Playgroud)
注意,np.meshgrid
还可以生成更高维度的网格。给定 xs、ys 和 zs,您将返回 xcoords、ycoords、zcoords 作为 3d 数组。meshgrid
还支持维度的逆序以及结果的稀疏表示。
为什么我们想要这种形式的输出?
在网格上的每个点应用一个函数:
一个动机是像 (+, -, *, /, **) 这样的二元运算符作为元素运算在 numpy 数组中被重载。这意味着如果我有一个def f(x, y): return (x - y) ** 2
适用于两个标量的函数,我还可以将其应用于两个 numpy 数组以获得元素结果数组:例如f(xcoords, ycoords)
或f(*np.meshgrid(xs, ys))
在上面的示例中给出以下内容:
array([[ 9, 4, 1],
[16, 9, 4],
[25, 16, 9]])
Run Code Online (Sandbox Code Playgroud)
高维外积:我不确定这有多有效,但您可以通过这种方式获得高维外积:np.prod(np.meshgrid([1,2,3], [1,2], [1,2,3,4]), axis=0)
。
matplotlib 中的等高线图:meshgrid
我在研究使用matplotlib 绘制等高线图以绘制决策边界时遇到过。为此,您可以使用 生成网格meshgrid
,评估每个网格点处的函数(例如,如上所示),然后将 xcoords、ycoords 和计算出的 f 值(即 zcoords)传递到轮廓函数中。