使用scipy查找样条曲线的平滑度

问题描述 投票:3回答:1

请考虑以下示例:

import numpy as np
import math
import matplotlib.pyplot as plt
from scipy import interpolate
xs = np.linspace(1,10,500)
ys = [0.92 * x ** 2.3 + 0.0132 * x ** 4 + 0.0743 * (x - 9) ** 3 - 4 * (x -3) ** 2 + 80 * math.sin(math.sin(x)) + 10 * math.sin(x*5) + 1.2* np.random.normal(-4,4,1) for x in xs]
ys[200] = ys[200] + 130
ys[201] = ys[201] + 135
ys[202] = ys[202] + 129
ys[203] = ys[203] + 128
ys[204] = ys[204] + 131
ys[205] = ys[205] + 130
ys[206] = ys[206] + 129
ys[207] = ys[207] + 129
ys[208] = ys[208] + 128
ys[209] = ys[209] + 130

如果我在这一点上绘制xsys,它会产生一个很好的图:a oisy dataset for testing

现在我使用scipy.interpolate.splrep来拟合这个数据的样条曲线。我使用了两个不同的样条线来拟合数据的两个不同部分:

tck = interpolate.splrep(xs[0:199], ys[0:199], s = 1000)
ynew2 = interpolate.splev(xs[0:199], tck, der = 0)

并且:

tck = interpolate.splrep(xs[210:500], ys[210:500], s = 9000)
ynew3 = interpolate.splev(xs[210:500], tck, der = 0)

然后我们有:Sample spline fit of the same data as above

现在我想以编程方式检测拟合的质量。拟合既不应该太直 - 即保留特征,也不应该“过度检测”作为特征的嘈杂变化。

我计划使用馈送到ANN的峰值计数器。

但是,在这一点上,我的问题是:

  • scipy / numpy是否具有内置函数,我可以在splrep的输出中输入,它将计算最小值或最大值以及任何特定间隔的最大值/最小值的密度?

注意: 我知道R**2值,我正在寻找另一种检测功能保存的措施。

python numpy scipy curve-fitting spline
1个回答
1
投票

SciPy没有找到三次样条曲线临界点的方法。最接近我们有sproot找到立方样条的根。为了使这在这里有用,我们必须拟合阶数为4的样条,以便导数是三次样条。这就是我在下面所做的

from scipy.interpolate import splrep, splev, splder, sproot

tck1 = splrep(xs[0:199], ys[0:199], k=4, s=1000)
tck2 = splrep(xs[210:500], ys[210:500], k=4, s=9000)
roots1 = sproot(splder(tck1), 1000)     # 1000 is an upper bound for the number of roots
roots2 = sproot(splder(tck2), 1000)

x1 = np.linspace(xs[0], xs[198], 1000)     # plot both splines
plt.plot(x1, splev(x1, tck1))
x2 = np.linspace(xs[210], xs[499], 1000)
plt.plot(x2, splev(x2, tck2))             

plt.plot(roots1, splev(roots1, tck1), 'ro')        # plot their max/min points
plt.plot(roots2, splev(roots2, tck2), 'ro') 
plt.show()

critical points

差异很明显。

您还可以在任何特定时间间隔内找到根数,例如[3,4]:

np.where((3 <= roots1) & (roots1 <= 4))[0].size    # 29

或者相当于,np.sum((3 <= roots1) & (roots1 <= 4))

© www.soinside.com 2019 - 2024. All rights reserved.