【问题标题】:6th degree curve fitting with numpy/scipy使用 numpy/scipy 进行 6 度曲线拟合
【发布时间】:2012-04-25 22:56:35
【问题描述】:

我对使用 6 次多项式插值非线性数据有一个非常具体的要求。我见过 numpy/scipy 例程 (scipy.interpolate.InterpolatedUnivariateSpline) 只允许插值达到 5 度。

即使没有直接的函数可以做到这一点,有没有办法在 Python 中复制 Excel 的 LINEST 线性回归算法? LINEST 允许 6 度曲线拟合,但我不想将 Excel 用于任何事情,因为此计算是更大 Python 脚本的一部分。

任何帮助将不胜感激!

【问题讨论】:

    标签: python numpy scipy curve-fitting linear-regression


    【解决方案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()
    

    这应该会给你类似的东西:

    【讨论】:

    • 您可以使用yfit = _polynomial(xx, *coeff),还请注意,对于 0 度多项式,p0 的长度至少应为 1。
    【解决方案2】:

    【讨论】:

    • 我不敢相信我以前没有想到这一点!谢谢:)
    • +1 我不敢相信我写了一个不必要的复杂示例,而不是记住polyfit 例程!
    猜你喜欢
    • 2013-10-10
    • 1970-01-01
    • 2015-09-14
    • 2020-03-19
    • 1970-01-01
    • 2017-04-21
    • 2017-04-07
    • 2017-09-15
    • 2018-11-20
    相关资源
    最近更新 更多