gpt4 book ai didi

python - 在样条拟合的一维数据中找到拐点

转载 作者:太空狗 更新时间:2023-10-30 01:16:04 24 4
gpt4 key购买 nike

我有一些一维数据并用样条拟合它。然后我想在其中找到拐点(忽略鞍点)。现在,我正在通过对 splev 生成的许多值使用 scipy.signal.argrelmin(和 argrelmax)来搜索其一阶推导的极值。

import scipy.interpolate
import scipy.optimize
import scipy.signal
import numpy as np
import matplotlib.pyplot as plt
import operator

y = [-1, 5, 6, 4, 2, 5, 8, 5, 1]
x = np.arange(0, len(y))
tck = scipy.interpolate.splrep(x, y, s=0)

print 'roots', scipy.interpolate.sproot(tck)
# output:
# [0.11381478]

xnew = np.arange(0, len(y), 0.01)
ynew = scipy.interpolate.splev(xnew, tck, der=0)

ynew_deriv = scipy.interpolate.splev(xnew, tck, der=1)

min_idxs = scipy.signal.argrelmin(ynew_deriv)
max_idxs = scipy.signal.argrelmax(ynew_deriv)
mins = zip(xnew[min_idxs].tolist(), ynew_deriv[min_idxs].tolist())
maxs = zip(xnew[max_idxs].tolist(), ynew_deriv[max_idxs].tolist())
inflection_points = sorted(mins + maxs, key=operator.itemgetter(0))

print 'inflection_points', inflection_points
# output:
# [(3.13, -2.9822449358974357),
# (5.03, 4.3817785256410255)
# (7.13, -4.867132628205128)]

plt.legend(['data','Cubic Spline', '1st deriv'])
plt.plot(x, y, 'o',
xnew, ynew, '-',
xnew, ynew_deriv, '-')
plt.show()

但这感觉非常错误。我想有可能在不产生那么多值(value)的情况下找到我正在寻找的东西。类似于 sproot 但可能适用于二阶推导的东西?

最佳答案

derivative of a B-spline is also a B-spline .因此,您可以先将样条曲线拟合到您的数据,然后使用导数公式构造导数样条曲线的系数,最后使用样条曲线求根来获得导数样条曲线的根。这些就是原始曲线的最大值/最小值。

这是执行此操作的代码:https://gist.github.com/pv/5504366

系数的相关计算是:

t, c, k = scipys_spline_representation
# Compute the denominator in the differentiation formula.
dt = t[k+1:-1] - t[1:-k-1]
# Compute the new coefficients
d = (c[1:-1-k] - c[:-2-k]) * k / dt
# Adjust knots
t2 = t[1:-1]
# Pad coefficient array to same size as knots (FITPACK convention)
d = np.r_[d, [0]*k]
# Done, a new spline
new_spline_repr = t2, d, k-1

Finding inflection points of a curve via derivative splines

关于python - 在样条拟合的一维数据中找到拐点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16323139/

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