简体   繁体   English

如何在 python 中创建多维网格

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

I have seen similar questions but none that need the format of the output array of shape (numpoints, dim)我见过类似的问题,但没有一个需要 output 形状数组的格式(numpoints, dim)

Here is a simple example of what I have for dim=2这是我对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])

在此处输入图像描述

Is there a faster/better way of doing this so that the data are arranged in this way?是否有更快/更好的方法来执行此操作,以便以这种方式排列数据? I want a general method that could work for any dim .我想要一种适用于任何dim的通用方法。

Edit : Suggested answer does not work.编辑:建议的答案不起作用。

I managed to solve my problem with this function that is general enough for any 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)

在此处输入图像描述

Yeah, that can be vectorized with是的,这可以用矢量化

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

c.reshape(-1, 1) just reshapes c from ( HxW to (H*W)x1 ) so that it can be stacked horizontally. c.reshape(-1, 1)只是将c从 ( HxW(H*W)x1 ) 重塑,以便可以水平堆叠。

Note - if you're looking to generalize to more dims you probably want to switch to indexing='ij' so it's arranged by (row, column, dim2, dim3, ...) rather than (column, row, dim2, dim3, ...) since in numpy rows are considered the 0'th dimension and columns the 1st.注意 - 如果您希望推广到更多的暗淡,您可能想要切换到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