使用Scipy找到样条函数的平滑度

3
考虑以下示例:
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,它会产生一个漂亮的图表:一个用于测试的嘈杂数据集 现在我正在使用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)

然后我们有: 相同数据的示例样条拟合 现在,我想编程检测拟合的质量。 拟合既不应该太直 - 即保留特征,也不应该将噪音变化“过度检测”为特征。
我计划使用馈送到ANN的峰值计数器。
但是,此时我的问题是:
Scipy / numpy是否具有内置函数,可以将splrep的输出馈入其中,并在任何特定间隔处计算最小值或最大值及其密度?
注意: 我知道R ** 2值,我正在寻找另一种检测特征保存的方法。
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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接