簡體   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