Calculate confidence band of least-square fit

后端 未结 2 947
悲&欢浪女
悲&欢浪女 2021-02-04 17:22

I got a question that I fight around for days with now.

How do I calculate the (95%) confidence band of a fit?

Fitt

2条回答
  •  心在旅途
    2021-02-04 17:52

    You can achieve this easily using StatsModels module.

    Also see this example and this answer.

    Here is an answer for your question:

    import numpy as np
    from matplotlib import pyplot as plt
    
    import statsmodels.api as sm
    from statsmodels.stats.outliers_influence import summary_table
    
    x = np.linspace(0,10)
    y = 3*np.random.randn(50) + x
    X = sm.add_constant(x)
    res = sm.OLS(y, X).fit()
    
    st, data, ss2 = summary_table(res, alpha=0.05)
    fittedvalues = data[:,2]
    predict_mean_se  = data[:,3]
    predict_mean_ci_low, predict_mean_ci_upp = data[:,4:6].T
    predict_ci_low, predict_ci_upp = data[:,6:8].T
    
    fig, ax = plt.subplots(figsize=(8,6))
    ax.plot(x, y, 'o', label="data")
    ax.plot(X, fittedvalues, 'r-', label='OLS')
    ax.plot(X, predict_ci_low, 'b--')
    ax.plot(X, predict_ci_upp, 'b--')
    ax.plot(X, predict_mean_ci_low, 'g--')
    ax.plot(X, predict_mean_ci_upp, 'g--')
    ax.legend(loc='best');
    plt.show()
    

    Example

提交回复
热议问题