理解 scipy.interpolate 的 interpn 函数

Understanding interpn function of scipy.interpolate

我正在尝试了解函数 scipy.interpolate 的工作原理。我创建了一个小设置,但它给出了错误。这是我所做的:

import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.arange(10)
gx, gy = np.meshgrid(x,y)
v = np.ones((10,10))


sample_at = np.random.random((10,10))

interpolated = scipy.interpolate.interpn((gx, gy), v, sample_at)


print(interpolated.shape)

这给出了一个错误:

    Traceback (most recent call last):
File "test.py", line 13, in <module>
    interpolated = scipy.interpolate.interpn((gx, gy), v, sample_at)
File "/home/lib/python3.5/site-packages/scipy/interpolate/interpolate.py", line 2624, in interpn
    "1-dimensional" % i)
ValueError: The points in dimension 0 must be 1-dimensional

这里发生了什么?

您对 interpn

请求的网格结构做出了错误的假设

ValueError: The points in dimension 0 must be 1-dimensional

此消息有点晦涩,引用了网格的元素并告诉您它们必须是一维的,或者换句话说,您必须调用 interpn 而不是 (gx, gy) 作为第一个参数,但带有 (x, y).

scipy.interpolate.interpn((x, y), v, sample_at)

但是你的代码中还有另一个错误的假设,因为如果你使用上面的调用,根据你定义的 sample_at,你会得到一个不同的错误

ValueError: The requested sample points xi have dimension 10, but this RegularGridInterpolator has dimension 2

希望有更明确的含义:如果您的网格有两个维度(xy,即)您的所有观点interpn 必须插值的也必须是二维的...换句话说,在您的示例中,网格的 LAST 维度必须是 2

将它们放在一起(在此示例中,我将使用 5 行乘 3 列的二维点的位置矩阵 sample_at)我们有

In [69]: import numpy as np 
    ...: import scipy.interpolate 
    ...: import matplotlib.pyplot as plt 
    ...:  
    ...: x = np.arange(10) 
    ...: y = np.arange(10) 
    ...: v = np.ones((10,10)) 
    ...: sample_at = 8*np.random.random((30)).reshape(5, 3, 2) 
    ...:  
    ...: scipy.interpolate.interpn((x, y), v, sample_at)                                                       
Out[69]: 
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

PS: 阅读源码1,里面的注释比错误信息好多了...


(1) 对我来说,源代码位于

~/lib/miniconda3/lib/python3.7/site-packages/scipy/interpolate/interpolate.py