Ama*_*nda 2 python interpolation numpy scipy
我正在尝试了解该功能的工作原理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)
Run Code Online (Sandbox Code Playgroud)
这给出了一个错误:
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
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?
您对所要求的网格结构做出了错误的假设interpn
ValueError: The points in dimension 0 must be 1-dimensional
这条消息有点晦涩,它引用了网格的元素,并告诉您它们必须是一维的,或者换句话说,您必须使用 来调用interpn而不是(gx, gy)作为第一个参数(x, y)。
scipy.interpolate.interpn((x, y), v, sample_at)
Run Code Online (Sandbox Code Playgroud)
但是您的代码中还有另一个错误的假设,因为如果您使用上面的调用以及您的定义sample_at,您将得到不同的错误
ValueError: The requested sample points xi have dimension 10, but this RegularGridInterpolator has dimension 2
希望有一个更清晰的含义:如果您的网格有两个维度(x和y,即),您interpn必须插值的所有点也必须是二维的......换句话说,在您的示例中,最后一个维度网格必须是2
将它们放在一起(sample_at在本例中我将使用 5 行 x 3 列的二维点的位置矩阵)我们有
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.]])
Run Code Online (Sandbox Code Playgroud)
PS:阅读源代码1,里面的注释比错误信息好得多......
(1) 对我来说源代码位于
~/lib/miniconda3/lib/python3.7/site-packages/scipy/interpolate/interpolate.py
Run Code Online (Sandbox Code Playgroud)