scipy的splrep行为 [英] Behavior of scipy's splrep
问题描述
我有一组数据点,想用样条函数近似它们. 我使用了两个不同的功能:
I have a set of data points and would like to approximate them with a spline function. I used two different functions:
-
来自scipy的
- splrep
- 和我在此处找到的三次样条函数.
- splrep from scipy
- and a cubic spline function that I found here.
结果类似于此.
代码如下:
from matplotlib.pyplot import *
from numpy import *
from scipy import interpolate
#----------------------------------------------
s = arange(257)/256.0
z = s[::-1]
b = transpose(array((z*z*z,
3*z*z*s,
3*z*s*s,
s*s*s)))
def cubicspline(c,t):
return dot(b[t],c)
#----------------------------------------------
A = array([
[ -126.041 , 246.867004],
[ -113.745003, 92.083 ],
[ 208.518997, -183.796997],
[ 278.859009, -190.552994]])
a1 = A[:,0]
a2 = A[:,1]
cs = reshape(A, (-1, 4, 2))
X = []
Y = []
#spline with cubicspline()
for (x,y) in [cubicspline(c,16*t) for c in cs for t in arange(17)]:
X.append(x)
Y.append(y)
# spline with splrep
tck = interpolate.splrep( a1, a2)
xnew = np.arange( min(a1), max(a1), 5)
ynew = interpolate.splev(xnew, tck)
plot(a1, a2, "--ob", ms = 9, label = "points")
plot(X, Y, "r", lw=2, label = "cubicspline")
plot(xnew, ynew, "g", lw=2, label = "splrep")
legend(); savefig("image.png"); show()
您可能会看到 splrep 的结果远远不能令人满意. 有人可以解释这种现象以及如何从 splrep 获得合理的近似值吗?
As you may see the results of splrep are far from being satisfying. Can someone please explain this behavior and how to get reasonable approximation from splrep?
推荐答案
您需要定义满意"的含义.显然,三次样条曲线不会通过这些点进行插值,而splrep
结果确实会进行插值(从这个意义上来说,这是完全令人满意的).还要注意,三次样条线"实际上只是一个多项式,而不是样条线(具有断点的多项式).
You need to define what you mean by "satisfying". Clearly, your cubic spline is not interpolating through the points, whereas the splrep
result does (and is perfectly satisfactory in that sense). Note also that your 'cubicspline' is actually just a single polynomial rather than a spline (which are polynomials with breakpoints).
您需要明确地告诉splrep
样条曲线不需要经过点-传递非零的s
平滑参数.如何正确选择此选项,请参见以下问题:
scipy.interpolate.UnivariateSpline不管参数如何都无法平滑
You need to explicitly tell splrep
that the spline doesn't need to go through the points --- pass in a nonzero s
smoothing parameter. How to choose this properly, see this question:
scipy.interpolate.UnivariateSpline not smoothing regardless of parameters
这篇关于scipy的splrep行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!