gpt4 book ai didi

Python interp1d 与 UnivariateSpline

转载 作者:太空狗 更新时间:2023-10-29 17:54:34 26 4
gpt4 key购买 nike

我正在尝试将一些 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 vals 不是等间距的,虽然我不确定为什么这很重要。

最佳答案

我刚遇到同样的问题。

简答

使用InterpolatedUnivariateSpline相反:

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

长答案

UnivariateSpline是“适合给定数据点集的一维平滑样条”,而 InterpolatedUnivariateSpline是“给定数据点集的一维插值样条”。前者使数据平滑,而后者是一种更传统的插值方法,并重现了 interp1d 的预期结果。 .下图说明了差异。

Comparison of interpolation functions

重现该图的代码如下所示。

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()

关于Python interp1d 与 UnivariateSpline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6216881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com