30

我想创建一个与网格相对应的点列表。因此,如果我想创建从(0, 0)到的区域网格,(1, 1)它将包含点(0, 0)(0, 1)和。(1, 0)(1, 0)

我知道这可以通过以下代码完成:

g = np.meshgrid([0,1],[0,1])
np.append(g[0].reshape(-1,1),g[1].reshape(-1,1),axis=1)

产生结果:

array([[0, 0],
       [1, 0],
       [0, 1],
       [1, 1]])

我的问题是双重的:

  1. 有没有更好的方法来做到这一点?
  2. 有没有办法将其推广到更高的维度?
4

5 回答 5

54

我刚刚注意到 numpy 中的文档提供了一种更快的方法来执行此操作:

X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([X.ravel(), Y.ravel()])

使用链接的 meshgrid2 函数并将“ravel”映射到生成的网格,这可以很容易地推广到更多维度。

g = meshgrid2(x, y, z)
positions = np.vstack(map(np.ravel, g))

对于每个轴上有 1000 个刻度的 3D 数组,结果比 zip 方法快大约 35 倍。

来源:http ://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html#scipy.stats.gaussian_kde

要比较这两种方法,请考虑以下代码部分:

创建有助于创建网格的众所周知的刻度线。

In [23]: import numpy as np

In [34]: from numpy import asarray

In [35]: x = np.random.rand(100,1)

In [36]: y = np.random.rand(100,1)

In [37]: z = np.random.rand(100,1)

为网格网格定义 mgilson 链接到的函数:

In [38]: def meshgrid2(*arrs):
   ....:     arrs = tuple(reversed(arrs))
   ....:     lens = map(len, arrs)
   ....:     dim = len(arrs)
   ....:     sz = 1
   ....:     for s in lens:
   ....:        sz *= s
   ....:     ans = []
   ....:     for i, arr in enumerate(arrs):
   ....:         slc = [1]*dim
   ....:         slc[i] = lens[i]
   ....:         arr2 = asarray(arr).reshape(slc)
   ....:         for j, sz in enumerate(lens):
   ....:             if j != i:
   ....:                 arr2 = arr2.repeat(sz, axis=j)
   ....:         ans.append(arr2)
   ....:     return tuple(ans)

创建网格并为这两个函数计时。

In [39]: g = meshgrid2(x, y, z)

In [40]: %timeit pos = np.vstack(map(np.ravel, g)).T
100 loops, best of 3: 7.26 ms per loop

In [41]: %timeit zip(*(x.flat for x in g))
1 loops, best of 3: 264 ms per loop
于 2012-10-15T08:11:37.917 回答
17

您的网格点总是不可或缺的吗?如果是这样,你可以使用numpy.ndindex

print list(np.ndindex(2,2))

更高维度:

print list(np.ndindex(2,2,2))

不幸的是,这不符合 OP 的要求,因为不满足积分假设(从 0 开始)。只有在其他人正在寻找那些假设正确的相同事物时,我才会留下这个答案。


另一种方法是zip

g = np.meshgrid([0,1],[0,1])
zip(*(x.flat for x in g))

这部分可以很好地缩放到任意尺寸。不幸的是,np.meshgrid不能很好地扩展到多个维度,因此需要解决该部分,或者(假设它有效),您可以使用这个SO 答案来创建自己的 ndmeshgrid 函数。

于 2012-10-12T17:48:06.223 回答
5

另一种方法是:

np.indices((2,2)).T.reshape(-1,2)

这可以推广到更高的维度,例如:

In [60]: np.indices((2,2,2)).T.reshape(-1,3)
Out[60]:
array([[0, 0, 0],
       [1, 0, 0],
       [0, 1, 0],
       [1, 1, 0],
       [0, 0, 1],
       [1, 0, 1],
       [0, 1, 1],
       [1, 1, 1]])
于 2014-02-26T14:25:45.880 回答
1

一个简单的 3D 示例(我猜可以扩展到 N 维,但要注意最终维度和 RAM 使用情况):

import numpy as np

ndim = 3
xmin = 0.
ymin = 0.
zmin = 0.
length_x = 1000.
length_y = 1000.
length_z = 50.
step_x = 1.
step_y = 1.
step_z = 1.

x = np.arange(xmin, length_x, step_x)
y = np.arange(ymin, length_y, step_y)
z = np.arange(zmin, length_z, step_z)
%timeit xyz = np.array(np.meshgrid(x, y, z)).T.reshape(-1, ndim)

在:2.76 s ± 185 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

产生:

In [2]: xyx
Out[2]: 
array([[  0.,   0.,   0.],
       [  0.,   1.,   0.],
       [  0.,   2.,   0.],
       ...,
       [999., 997.,  49.],
       [999., 998.,  49.],
       [999., 999.,  49.]])

In [4]: xyz.shape
Out[4]: (50000000, 3)

Python3.6.9
麻木:1.19.5

于 2021-07-08T10:46:41.867 回答
1

我正在使用以下内容将网格网格转换为 MX 2 数组。还将向量列表更改为迭代器可以使其非常快。

import numpy as np

# Without iterators
x_vecs = [np.linspace(0,1,1000), np.linspace(0,1,1000)]

%timeit np.reshape(np.meshgrid(*x_vecs),(2,-1)).T
6.85 ms ± 93.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# With iterators
x_vecs = iter([np.linspace(0,1,1000), np.linspace(0,1,1000)])

%timeit np.reshape(np.meshgrid(*x_vecs),(2,-1)).T
5.78 µs ± 172 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

对于使用生成器的 ND 阵列

vec_dim = 3
res = 100

# Without iterators
x_vecs = [np.linspace(0,1,res) for i in range(vec_dim)]

>>> %timeit np.reshape(np.meshgrid(*x_vecs),(vec_dim,-1)).T
11 ms ± 124 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# With iterators
x_vecs = (np.linspace(0,1,res) for i in range(vec_dim))

>>> %timeit np.reshape(np.meshgrid(*x_vecs),(vec_dim,-1)).T
5.54 µs ± 32.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
于 2021-08-28T02:09:53.277 回答