[英]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
的通用方法。
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.