【问题标题】:Print 'std err' value from statsmodels OLS results从 statsmodels OLS 结果中打印“std err”值
【发布时间】:2015-10-10 00:20:05
【问题描述】:

(很抱歉,http://statsmodels.sourceforge.net/ 目前已关闭,我无法访问文档)

我正在使用statsmodels 进行线性回归,基本上:

import statsmodels.api as sm
model = sm.OLS(y,x)
results = model.fit()

我知道我可以打印出完整的结果集:

print results.summary()

输出类似:

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.952
Model:                            OLS   Adj. R-squared:                  0.951
Method:                 Least Squares   F-statistic:                     972.9
Date:                Mon, 20 Jul 2015   Prob (F-statistic):           5.55e-34
Time:                        15:35:22   Log-Likelihood:                -78.843
No. Observations:                  50   AIC:                             159.7
Df Residuals:                      49   BIC:                             161.6
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1             1.0250      0.033     31.191      0.000         0.959     1.091
==============================================================================
Omnibus:                       16.396   Durbin-Watson:                   2.166
Prob(Omnibus):                  0.000   Jarque-Bera (JB):                3.480
Skew:                          -0.082   Prob(JB):                        0.175
Kurtosis:                       1.718   Cond. No.                         1.00
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

我需要一种方法来打印出coefstd err 的值。

我可以通过以下方式访问coef

print results.params

但我找不到打印出std err 的方法。

我该怎么做?

【问题讨论】:

标签: python io statsmodels


【解决方案1】:

应用here 给出的答案我使用dir() 打印results 对象的所有属性。

之后我搜索了包含std err 值的那个,结果是:

print results.bse

(不确定bse 中的b 代表什么,但我猜se 代表“标准错误”)

【讨论】:

  • b 是一个历史产物,当params 在线性模型b 中称为y = X b + u 时,应该正确地称为params_se
  • 感谢@user333700 的解释!
  • @Josef 你的意思是results.params_se。它似乎不起作用。
  • 它仍然被称为“bse”,就像答案一样。名称从未更改。
【解决方案2】:

以下函数可用于获取回归分析结果的概览。参数ols_modelstatsmodels.formula.api生成的回归模型。输出是保存回归系数、标准误差、p 值、观察次数、AIC 和调整后的 rsquared 的 pandas 数据框。标准误差保存在括号中。 ******分别代表0.001、0.01、0.1的显着性水平:

def output_regres_result(ols_model, variable_list: list):
    """
    Create a pandas dataframe saving the regression analysis result
    :param ols_model: a linear model containing the regression result.
    type: statsmodels.regression.linear_model.RegressionResultsWrapper
    :param variable_list: a list of interested variable names
    :return: a pandas dataframe saving the regression coefficient, pvalues, standard errors, aic,
    number of observations, adjusted r squared
    """
    coef_dict = ols_model.params.to_dict()  # coefficient dictionary
    pval_dict = ols_model.pvalues.to_dict()  # pvalues dictionary
    std_error_dict = ols_model.bse.to_dict()  # standard error dictionary
    num_observs = np.int(ols_model.nobs) # number of observations
    aic_val = round(ols_model.aic, 2) # aic value
    adj_rsqured = round(ols_model.rsquared_adj, 3) # adjusted rsqured
    info_index = ['Num', 'AIC', 'Adjusted R2']
    index_list = variable_list + info_index

    for variable in variable_list:
        assert variable in coef_dict, 'Something wrong with variable name!'

    coef_vals = []

    for variable in variable_list:
        std_val = std_error_dict[variable]
        coef_val = coef_dict[variable]
        p_val = pval_dict[variable]
        if p_val <= 0.01:
            coef_vals.append('{}***({})'.format(round(coef_val, 4), round(std_val, 3)))
        elif 0.01 < p_val <= 0.05:
            coef_vals.append('{}**({})'.format(round(coef_val, 4), round(std_val, 3)))
        elif 0.05 < p_val <= 0.1:
            coef_vals.append('{}*({})'.format(round(coef_val, 4), round(std_val, 3)))
        else:
            coef_vals.append('{}({})'.format(round(coef_val, 4), round(std_val, 3)))

    coef_vals.extend([num_observs, aic_val, adj_rsqured])

    result_data = pd.DataFrame()
    result_data['coef'] = coef_vals
    result_data_reindex = result_data.set_index(pd.Index(index_list))

    return result_data_reindex

【讨论】:

  • @Bright Chang,它会抛出错误:AttributeError: 'numpy.ndarray' object has no attribute 'to_dict'
【解决方案3】:

估计的统计标准误差总是等于残差均方误差的平方根。它可以使用公式 np.sqrt(results.mse_resid) 从结果中获得

【讨论】:

  • 问题是关于参数估计的标准误,而不是残差标准误。
【解决方案4】:

results.bse 提供系数的标准误差,与results.summary() 中列出的相同。

使用results.scale**.5得到回归的标准误。

也与 np.sqrt(np.sum(results.resid**2)/results.df_resid) 相同,其中 results 是您的拟合模型。

【讨论】:

    猜你喜欢
    • 2016-12-29
    • 2020-11-23
    • 2023-02-15
    • 2018-01-01
    • 2015-12-31
    • 2022-06-08
    • 2018-10-17
    • 2014-07-28
    • 2018-12-05
    相关资源
    最近更新 更多