我剛碰到同樣的問題。
簡短的回答
使用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