从2D数组创建矢量化numpy.meshgrid,以创建3D网格

时间:2019-03-27 13:48:47

标签: python numpy vectorization

是否可以向量化np.meshgrid的创建?

#Example of normal np.meshgrid

x = [1.22749725, 2.40009184, 1.48602747, 2.83286752, 2.37426951]
y = [1.23816021, 1.69811451, 2.08692546, 2.13706377, 1.60298873]
gridrez=10

X,Y = np.meshgrid(np.linspace(min(x), max(x), endpoint=True, num=gridrez), 
                  np.linspace(min(y), max(y), endpoint=True, num=gridrez))
# X.shape = 10x10
# Y.shape = 10x10

我想复制此功能,但不是x,y是1x5数组,而是1000x5数组,结果X,Y将是1000x10x10。注意,我发现了一种矢量化np.linspace的方法,所以不必担心。假设我们有两个(1000x10)数组,并想创建一个1000x10x10的网格。当我输入答案时,我得到的是(10000,10000)网格,而不是1000x10x10

1 个答案:

答案 0 :(得分:1)

这里是一个使用vectorized-linspace : create_ranges-

# https://stackoverflow.com/a/40624614/ @Divakar
def create_ranges(start, stop, N, endpoint=True):
    if endpoint==1:
        divisor = N-1
    else:
        divisor = N
    steps = (1.0/divisor) * (stop - start)
    return steps[:,None]*np.arange(N) + start[:,None]

def linspace_nd(x,y,gridrez):
    a1 = create_ranges(x.min(1), x.max(1), N=gridrez, endpoint=True)
    a2 = create_ranges(y.min(1), y.max(1), N=gridrez, endpoint=True)
    out_shp = a1.shape + (a2.shape[1],)
    Xout = np.broadcast_to(a1[:,None,:], out_shp)
    Yout = np.broadcast_to(a2[:,:,None], out_shp)
    return Xout, Yout

linspace_nd的最终输出将是进入矢量化linspace输出的3D网格视图,因此将节省内存,因此也具有良好的性能。

或者,如果您需要具有自己的内存空间而不是视图的输出,则可以使用np.repeat进行复制-

Xout = np.repeat(a1[:,None,:],a2.shape[1],axis=1)
Yout = np.repeat(a2[:,:,None],a1.shape[1],axis=2)

使用views创建此类数组的时间-

In [406]: np.random.seed(0)
     ...: x = np.random.rand(1000,5)
     ...: y = np.random.rand(1000,5)

In [408]: %timeit linspace_nd(x,y,gridrez=10)
1000 loops, best of 3: 221 µs per loop