正确使用scipy.interpolate.RegularGridInterp

2024-03-29 08:31:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点被documentation for scipy.interpolate.RegularGridInterpolator搞糊涂了。

例如,我有一个函数f:R^3=>;R,它在单位立方体的顶点上采样。我想插值以便在多维数据集中找到值。

import numpy as np

# Grid points / sample locations
X = np.array([[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1,1.]])

# Function values at the grid points
F = np.random.rand(8)

现在,RegularGridInterpolator接受一个points参数和一个values参数。

points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) The points defining the regular grid in n dimensions.

values : array_like, shape (m1, ..., mn, ...) The data on the regular grid in n dimensions.

我将此解释为能够这样调用:

import scipy.interpolate as irp

rgi = irp.RegularGridInterpolator(X, F)

但是,当我这样做时,会出现以下错误:

ValueError: There are 8 point arrays, but values has 1 dimensions

我在文件里误解了什么?


Tags: oftheimport参数asnpscipyarray
2条回答

你的回答更好,你完全可以接受。我只是添加这个作为一个“替代”的方式来编写它。

import numpy as np
import scipy.interpolate as spint

RGI = spint.RegularGridInterpolator

x = np.linspace(0, 1, 3) #  or  0.5*np.arange(3.) works too

# populate the 3D array of values (re-using x because lazy)
X, Y, Z = np.meshgrid(x, x, x, indexing='ij')
vals = np.sin(X) + np.cos(Y) + np.tan(Z)

# make the interpolator, (list of 1D axes, values at all points)
rgi = RGI(points=[x, x, x], values=vals)  # can also be [x]*3 or (x,)*3

tst = (0.47, 0.49, 0.53)

print rgi(tst)
print np.sin(tst[0]) + np.cos(tst[1]) + np.tan(tst[2])

返回:

1.93765972087
1.92113615659

好吧,当我回答自己的问题时,我觉得很傻,但是我在原始库的文档中发现了我的错误:

https://github.com/JohannesBuchner/regulargrid

points应该是一个数组列表,指定点沿每个轴的间距。

例如,要采用上述单位立方体,我应该设置:

pts = ( np.array([0,1.]), )*3

或者,如果我有沿最后一个轴以更高分辨率采样的数据,我可以设置:

pts = ( np.array([0,1.]), np.array([0,1.]), np.array([0,0.5,1.]) )

最后,values的形状必须与由points隐式布置的网格相对应。例如

val_size = map(lambda q: q.shape[0], pts)
vals = np.zeros( val_size )

# make an arbitrary function to test:
func = lambda pt: (pt**2).sum()

# collect func's values at grid pts
for i in range(pts[0].shape[0]):
    for j in range(pts[1].shape[0]):
        for k in range(pts[2].shape[0]):
            vals[i,j,k] = func(np.array([pts[0][i], pts[1][j], pts[2][k]]))

所以最后

rgi = irp.RegularGridInterpolator(points=pts, values=vals)

按需运行和执行。

相关问题 更多 >