【问题标题】:Python- doing least square fitting on time series data?Python-对时间序列数据进行最小二乘拟合?
【发布时间】:2016-06-29 18:27:22
【问题描述】:

我有一个时间序列数据集 pr11(形状为 (151,)),绘制时如下图所示。请注意非常小的数字。我想通过对直线进行最小二乘拟合来找到数据的平均斜率。

我从另一个 StackExchange 页面尝试了两种不同的方法来获得答案。我尝试使用 scipy.optimize.curve_fit 如下...

len = np.arange(pr11.shape[0])

def f(x, A, B):
return A*x + B

A,B = curve_fit(f,pr11,len)[0]

但是,这给了我一个 1.0 的斜率 (A),我知道这是不对的,所以这里肯定有什么问题。 “拟合”数据最终看起来与我的原始数据完全相同。我也试过 scipy.stats...

slope, intercept, r_value, p_value, std_err = stats.linregress(len,pr11)

我这次的斜率是一个 e-08 量级的数字。问题是当我使用直线斜率*x + 截距的方程时,该数字将我的时间序列数据乘以一个非常低的值(e-15 阶)。因此,当我绘制拟合线时,这条线是水平的,根本不适合我的数据。

我怎样才能得到这个数据的拟合线?

【问题讨论】:

    标签: python scipy least-squares


    【解决方案1】:

    我喜欢使用的一个包是lmfit。安装后,您可以:

    from lmfit import minimize, Parameters, Parameter, report_fit
    import numpy as np
    
    # create data to be fitted
    x = np.arange(150)/100.
    data = 2e-6*x-5e-7 + np.random.normal(size=len(x), scale=5e-7)
    
    # define objective function: returns the array to be minimized
    def fcn2min(params, x, data):
        """ model decaying sine wave, subtract data"""
        slope = params['slope'].value
        offset = params['offset'].value
    
        model = slope * x + offset
        return model - data
    
    # create a set of Parameters
    params = Parameters()
    params.add('slope',   value= 1.,  min=0)
    params.add('offset', value= 0.)
    
    # do fit, here with leastsq model
    result = minimize(fcn2min, params, args=(x, data))
    
    # calculate final result
    final = data + result.residual
    
    # write error report
    report_fit(result.params)
    
    # [[Variables]]
    #     slope:    2.1354e-06 +/- 9.33e-08 (4.37%) (init= 1)
    #     offset:  -6.0680e-07 +/- 8.02e-08 (13.22%) (init= 0)
    # [[Correlations]] (unreported correlations are <  0.100)
    #     C(slope, offset)             = -0.865 
    
    # plot results
    import matplotlib.pyplot as plt
    plt.plot(x, data, 'k+')
    plt.plot(x, final, 'r')
    plt.show()
    

    【讨论】:

    • 谢谢,成功了!现在我会看看我是否可以为多个数据集创建一个循环,但如果不能,至少我有工作代码。
    猜你喜欢
    • 2020-10-02
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多