我正在尝试将一些MatLab代码移植到Scipy,并且尝试了scipy.interpolate的两个不同函数interp1dUnivariateSpline。 interp1d结果与interp1d MatLab函数匹配,但是UnivariateSpline的数字不同-在某些情况下非常不同。

f = interp1d(row1,row2,kind='cubic',bounds_error=False,fill_value=numpy.max(row2))
return  f(interp)

f = UnivariateSpline(row1,row2,k=3,s=0)
return f(interp)

谁能提供任何见解?我的x值不等距,尽管我不确定为什么这很重要。

最佳答案

我只是遇到了同样的问题。

简短答案

使用InterpolatedUnivariateSpline代替:

f = InterpolatedUnivariateSpline(row1, row2)
return f(interp)

长答案

UnivariateSpline是“对给定数据点集的一维平滑样条曲线”,而InterpolatedUnivariateSpline是“对给定数据点集的一维插值样条曲线”。前者使数据平滑,而后者是更常规的插值方法,并再现interp1d的预期结果。下图说明了差异。

复制该图的代码如下所示。
import scipy.interpolate as ip

#Define independent variable
sparse = linspace(0, 2 * pi, num = 20)
dense = linspace(0, 2 * pi, num = 200)

#Define function and calculate dependent variable
f = lambda x: sin(x) + 2
fsparse = f(sparse)
fdense = f(dense)

ax = subplot(2, 1, 1)

#Plot the sparse samples and the true function
plot(sparse, fsparse, label = 'Sparse samples', linestyle = 'None', marker = 'o')
plot(dense, fdense, label = 'True function')

#Plot the different interpolation results
interpolate = ip.InterpolatedUnivariateSpline(sparse, fsparse)
plot(dense, interpolate(dense), label = 'InterpolatedUnivariateSpline', linewidth = 2)

smoothing = ip.UnivariateSpline(sparse, fsparse)
plot(dense, smoothing(dense), label = 'UnivariateSpline', color = 'k', linewidth = 2)

ip1d = ip.interp1d(sparse, fsparse, kind = 'cubic')
plot(dense, ip1d(dense), label = 'interp1d')

ylim(.9, 3.3)

legend(loc = 'upper right', frameon = False)

ylabel('f(x)')

#Plot the fractional error
subplot(2, 1, 2, sharex = ax)

plot(dense, smoothing(dense) / fdense - 1, label = 'UnivariateSpline')
plot(dense, interpolate(dense) / fdense - 1, label = 'InterpolatedUnivariateSpline')
plot(dense, ip1d(dense) / fdense - 1, label = 'interp1d')

ylabel('Fractional error')
xlabel('x')
ylim(-.1,.15)

legend(loc = 'upper left', frameon = False)

tight_layout()

10-08 04:22