在scipy(python)中执行B样条拟合时,如何更改基本函数的数量?

时间:2018-07-05 16:17:42

标签: python scipy interpolation bspline

我有一组离散点(x_n,y_n),我想将它们近似/表示为B样条曲线基函数的线性组合。我需要能够手动更改该方法使用的B样条基函数的数量,并且我正在尝试使用scipy在python中实现此功能。具体来说,以下是我正在使用的一些代码:

import scipy
spl = scipy.interpolate.splrep(x, y)

但是,除非我对文档有误解或遗漏,否则似乎无法更改scipy使用的B样条基函数的数量。这似乎是由x和y的大小设置的。因此,我的具体问题是:

  1. 我可以在上面使用的“ splrep”函数中更改scipy使用的B样条基函数的数量吗?

  2. 完成上面代码中所示的变换后,如何访问线性组合的系数?我认为这些系数存储在矢量spl [1]中是否正确?

  3. 我应该使用更好的方法/工具箱吗?

在此先感谢您提供的任何帮助/指导。

2 个答案:

答案 0 :(得分:0)

是的,spl [1]是系数,spl [0]包含结向量。

但是,如果想要更好的控制,则可以操纵BSpline对象,并使用make_interp_spline或make_lsq_spline构造它们,它们接受结向量并确定要使用的b样条基础函数。

答案 1 :(得分:0)

通过提供带有t参数的结向量,可以更改B样条基函数的数量。由于存在连接number of knots = number of coefficients + degree + 1,所以结数也将定义系数的数目(==基函数的数目)。

t参数的用法不是那么直观,因为给定的结应该只是内部结。因此,例如,如果要为三次样条曲线设置7个系数,则需要给出3个内部结。在函数内部,它用xbxe填充第一个和最后一个(度+1)结(夹紧的结束条件请参见here)。 此外,如文档所述,结点应满足Schoenberg-Whitney的条件。

下面是执行此操作的示例代码:

# Input:
x = np.linspace(0,2*np.pi, 9)
y = np.sin(x)

# Your code:
spl = scipy.interpolate.splrep(x, y)
t,c,k = spl  # knots, coefficients, degree (==3 for cubic)

# Computing the inner knots and using them:
t3 = np.linspace(x[0],x[-1],5)  # five equally spaced knots in the interval
t3 = t3[1:-1]  # take only the three inner values

spl3 = scipy.interpolate.splrep(x, y, t=t3)

关于第二个问题,您是正确的,系数确实存储在spl[1]中。但是,请注意(如文档所述),最后一个(度+1)值用零填充,应该忽略。

为了评估生成的B样条曲线,可以使用函数splev或类BSpline。 下面是一些示例代码,用于评估和绘制上述样条线(如下图所示):

enter image description here

xx = np.linspace(x[0], x[-1], 101)  # sample points
yy = scipy.interpolate.splev(xx, spl) # evaluate original spline
yy3 = scipy.interpolate.splev(xx, spl3)  # evaluate new spline

plot(x,y,'b.')  # plot original interpolation points
plot(xx,yy,'r-', label='spl')
plot(xx,yy3,'g-', label='spl3')