我刚碰到同样的问题。
简短的回答
使用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()
它肯定快得多,这就是为什么我要使用它,但它给出了与MatLab非常不同的数字,所以我被迫进入了较慢的interp1d函数。 – 2011-06-02 16:43:54