繁体   English   中英

如何在 python 中创建多维网格

[英]How to create a multi-dimensional grid in python

我见过类似的问题,但没有一个需要 output 形状数组的格式(numpoints, dim)

这是我对dim=2的简单示例

import numpy as np

bounds = [0.5, 0.5]
n = [10,10]
dim = 2
x = np.linspace(-bounds[0], bounds[0], n[0])
y = np.linspace(-bounds[1], bounds[1], n[1])
X, Y = np.meshgrid(x, y)

s = X.shape
data = np.zeros((n[0]*n[1],dim)) 

# convert mesh into point vector for which the model can be evaluated
c = 0
for i in range(s[0]):
    for j in range(s[1]):
        data[c,0] = X[i,j]
        data[c,1] = Y[i,j]
        c = c+1;
plt.scatter(data[:,0], data[:,1])

在此处输入图像描述

是否有更快/更好的方法来执行此操作,以便以这种方式排列数据? 我想要一种适用于任何dim的通用方法。

编辑:建议的答案不起作用。

我设法用这个 function 解决了我的问题,它对于任何dim都足够通用:

def get_grid_of_points(n, *args):
    ls = [np.linspace(-i,i,n) for i in args]
    mesh_ls = np.meshgrid(*ls)
    all_mesh = [np.reshape(x, [-1]) for x in mesh_ls]
    grid_points = np.stack(all_mesh, axis=1)
    return grid_points

get_grid_of_points(10, 0.5, 0.5)

在此处输入图像描述

是的,这可以用矢量化

axis_coords = np.meshgrid(x, y, indexing='xy')
data = np.hstack([c.reshape(-1, 1) for c in axis_coords])

c.reshape(-1, 1)只是将c从 ( HxW(H*W)x1 ) 重塑,以便可以水平堆叠。

注意 - 如果您希望推广到更多的暗淡,您可能想要切换到indexing='ij'所以它按 (row, column, dim2, dim3, ...) 而不是 (column, row, dim2, dim3 , ...) 因为在 numpy 中,行被认为是第 0 维,列被认为是第 1 维。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM