小编典典

用numpy / scipy拟合的6度曲线

python

对于使用6阶多项式插值非线性数据,我有一个非常具体的要求。我看过numpy / scipy例程(scipy.interpolate.InterpolatedUnivariateSpline),这些例程最多只能进行5级插值。

即使没有直接函数可以执行此操作,是否有办法在Python中复制Excel的LINEST线性回归算法?LINEST允许进行6度曲线拟合,但是我不希望将Excel用于任何东西,因为此计算是更大的Python脚本的一部分。

任何帮助,将不胜感激!


阅读 190

收藏
2020-12-20

共1个答案

小编典典

您可以使用scipy.optimize.curve_fit(在合理的情况下)使您想要的任何功能适合数据。该功能的签名是

curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw)

并使用非线性最小二乘拟合将函数拟合到f数据ydata(xdata)。在您的情况下,我会尝试类似的方法:

import numpy
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

def _polynomial(x, *p):
    """Polynomial fitting function of arbitrary degree."""
    poly = 0.
    for i, n in enumerate(p):
        poly += n * x**i
    return poly

# Define some test data:
x = numpy.linspace(0., numpy.pi)
y = numpy.cos(x) + 0.05 * numpy.random.normal(size=len(x))

# p0 is the initial guess for the fitting coefficients, set the length
# of this to be the order of the polynomial you want to fit. Here I
# have set all the initial guesses to 1., you may have a better idea of
# what values to expect based on your data.
p0 = numpy.ones(6,)

coeff, var_matrix = curve_fit(_polynomial, x, y, p0=p0)

yfit = [_polynomial(xx, *tuple(coeff)) for xx in x] # I'm sure there is a better
                                                    # way of doing this

plt.plot(x, y, label='Test data')
plt.plot(x, yfit, label='fitted data')

plt.show()
2020-12-20