python interpolate.interp1d,Python interp1d与UnivariateSpline

本文讨论了从MatLab代码迁移到Scipy时遇到的插值问题,特别是使用interp1d和UnivariateSpline函数得到的不同结果,并提供了解决方案:使用InterpolatedUnivariateSpline函数。
摘要由CSDN通过智能技术生成

I'm trying to port some MatLab code over to Scipy, and I've tried two different functions from scipy.interpolate, interp1d and UnivariateSpline. The interp1d results match the interp1d MatLab function, but the UnivariateSpline numbers come out different - and in some cases very different.

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)

Could anyone offer any insight? My x vals aren't equally spaced, although I'm not sure why that would matter.

解决方案

I just ran into the same issue.

Short answer

f = InterpolatedUnivariateSpline(row1, row2)

return f(interp)

Long answer

UnivariateSpline is a 'one-dimensional smoothing spline fit to a given set of data points' whereas InterpolatedUnivariateSpline is a 'one-dimensional interpolating spline for a given set of data points'. The former smoothes the data whereas the latter is a more conventional interpolation method and reproduces the results expected from interp1d. The figure below illustrates the difference.

94794125e666514af815f651b62fe1b0.png

The code to reproduce the figure is shown below.

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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值