python - 如何在 numpy 中创建一个 n 维网格来评估任意 n 的函数?

标签 python arrays numpy numerical-integration

我正在尝试创建一个朴素的数值积分函数来说明高维度蒙特卡洛积分的好处。我想要这样的东西:

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 的东西可以对任意维度执行此操作,也许可以接受数组元组?还是有其他方法可以在更高维度上进行黎曼求和?我考虑过以递归方式执行此操作,但无法弄清楚它是如何工作的。

最佳答案

您可以使用列表理解生成所有 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 具有其他可能有用的索引和网格生成函数和类。值得一读,只是为了看看事情是如何完成的。


在对未知维度的数组进行索引时,在各种 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,:]

关于python - 如何在 numpy 中创建一个 n 维网格来评估任意 n 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28825219/

相关文章:

python - 在GAE环境中使用YAML

python - 从 Python 中的资源加载 txt 文件

python - 非零值的 Numpy 总和运行长度

python - Tensorflow: tf.train.Feature 错误 'expected one of: bytes'

pandas - 如何从频率表创建箱线图

python - Google AppEngine Python 3.7 上的自定义库

Python字符串拆分

python - 你如何评估 Python 中数组的某个部分?

C : static array

c - 访问二维数组中元素的精确语法 - 通过指针?