scipy.interp2d警告和离网大错误

Tob*_*ias 5 python interpolation numpy scipy

我正在尝试对二维函数进行插值,并且通过scipy.interpolate.interp2d遇到了我认为怪异的行为。我不明白问题是什么,我很乐意提供帮助或提示。

import numpy as np
from scipy.interpolate import interp2d

x = np.arange(10)
y = np.arange(20)
xx, yy = np.meshgrid(x, y, indexing = 'ij')
val = xx + yy
f = interp2d(xx, yy, val, kind = 'linear')
Run Code Online (Sandbox Code Playgroud)

运行此代码时,出现以下警告:

scipy / interpolate / fitpack.py:981:RuntimeWarning:由于B样条系数的数量已经超过数据点m的数量,因此无法添加更多的结。可能的原因:s或m太小。(fp> s)kx,ky = 1,1 nx,ny = 18,15 m = 200 fp = 0.000000 s = 0.000000
warnings.warn(RuntimeWarning(_iermess2 [ierm] [0] + _mess))

我不明白为什么interp2d告诉我它应该进行线性插值,为什么会使用任何样条曲线。当我继续并在网格上评估f时,一切都很好:

>>> f(1,1)
array([ 2.])
Run Code Online (Sandbox Code Playgroud)

当我脱离网格对其进行评估时,即使该函数显然是线性的,也会出现很大的错误。

>>> f(1.1,1)
array([ 2.44361975])
Run Code Online (Sandbox Code Playgroud)

我有点困惑,我不确定是什么问题。有人遇到过类似的问题吗?我以前使用过matlab,这几乎是我在那做1:1的方式,但是也许我做错了。

当我使用矩形网格(即y = np.arange(10))时,一切都可以正常工作,但这不是我所需要的。当我使用三次插值而不是线性插值时,误差变小(由于函数是线性的,所以也没有太大意义),但误差仍然很大。

Tob*_*ias 3

我尝试了一些方法,并设法使用 scipy.LinearNDInterpolator 获得(某种)我想要的东西。但是,我必须将网格转换为点和值列表。由于我的程序的其余部分以网格格式存储坐标和值,这有点烦人,所以如果可能的话,我仍然想让原始代码正常工作。

import numpy as np
import itertools
from scipy.interpolate import LinearNDInterpolator

x = np.arange(10)
y = np.arange(20)
coords = list(itertools.product(x,y))
val = [sum(c) for c in coords]
f = LinearNDInterpolator(coords, val)

>>>f(1,1)
array(2.0)

>>> f(1.1,1)
array(2.1)
Run Code Online (Sandbox Code Playgroud)