簡體   English   中英

如何在numpy中創建一個n維網格來評估任意n的函數?

[英]How can I create an n-dimensional grid in numpy to evaluate a function for arbitrary n?

我正在嘗試創建一個簡單的數值積分函數來說明蒙特卡羅積分在高維度中的好處。 我想要這樣的東西:

def quad_int(f, mins, maxs, numPoints=100):
    '''
    Use the naive (Riemann sum) method to numerically integrate f on a box 
    defined by the mins and maxs.

    INPUTS:
    f         - A function handle. Should accept a 1-D NumPy array 
        as input.
    mins      - A 1-D NumPy array of the minimum bounds on integration.
    maxs      - A 1-D NumPy array of the maximum bounds on integration.
    numPoints - An integer specifying the number of points to sample in 
        the Riemann-sum method. Defaults to 100.
    '''
    n = len(mins)

    # Create a grid of evenly spaced points to evaluate f on
    # Evaluate f at each point in the grid; sum all these values up
    dV = np.prod((maxs-mins/numPoints))
    # Multiply the sum by dV to get the approximate integral

我知道我的dV會導致數值穩定性問題,但是現在我遇到的問題是創建域名。 如果維度的數量是固定的,那么只需使用np.meshgrid就可以了:

# We don't want the last value since we are using left-hand Riemann sums
x = np.linspace(mins[0],maxs[0],numPoints)[:-1]
y = np.linspace(mins[1],maxs[1],numPoints)[:-1]
z = np.linspace(mins[2],maxs[2],numPoints)[:-1]

X, Y, Z = np.meshgrid(x,y,z)
tot = 0
for index, x in np.ndenumerate(X):
    tot += f(x, Y[index], Z[index])

是否有類似於np.meshgrid可以為任意維度執行此操作,也許接受一個數組元組? 或者還有其他方法可以在更高的維度上完成黎曼總和嗎? 我已經考慮過以遞歸方式進行,但無法弄清楚它是如何工作的。

您可以使用列表meshgrid來生成所有的linspaces ,然后使用*將該列表傳遞給meshgrid (將列表轉換為參數元組)。

XXX = np.meshgrid(*[np.linspace(i,j,numPoints)[:-1] for i,j in zip(mins,maxs)])

XXX現在是n數組的列表(每個n維)。

我正在使用直接的Python列表和參數操作。

np.lib.index_tricks具有其他可能np.lib.index_tricks索引和網格生成函數和類。 值得一讀,看看事情是如何完成的。


在索引未知維度的數組時,在各種numpy函數中使用的巧妙技巧是構造為所需索引的列表。 它可以包括slice(None) ,你會通常看到: 然后將其轉換為元組並使用它。

In [606]: index=[2,3]
In [607]: [slice(None)]+index
Out[607]: [slice(None, None, None), 2, 3]
In [609]: Y[tuple([slice(None)]+index)]
Out[609]: array([ 0. ,  0.5,  1. ,  1.5])
In [611]: Y[:,2,3]
Out[611]: array([ 0. ,  0.5,  1. ,  1.5])

他們使用一個列表,他們需要更改元素。 並不總是需要轉換為元組

index=[slice(None)]*3
index[1]=0
Y[index] # same as Y[:,0,:]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM