天天看点

statsmodels 最小二乘法 线性回归

最近使用到了ols做​​线性​​回归,记录一下使用方法

首先是​​statsmodels​​,根据官网介绍,这是python里一个用于estimate statistical models 和 explore statistical data 的模块,经常做数据分析的小伙伴应该都不陌生

​​statsmodels​​ is a Python module that provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests, and statistical data exploration. An extensive list of result statistics are available for each estimator. The results are tested against existing statistical packages to ensure that they are correct. 

然后是ols的方法,悉大的tutor给到了api 和 formula.api 两种建模方法,感觉直接用formula更省事些,毕竟自己做老容易忘记加intercept  >-<

方法一:statsmodels.api 做​​最小二乘法​​,需要自己添加intercept截距项

方法二:statsmodels.formula.api 通过自定formula和dataframe生成模型,无需添加截距项

方法一:statsmodels.api 做最小二乘法,需要自己添加intercept截距项

1. 生成数据

2. 调用 statsmodels.api

import statsmodels.api as sm      

3. 拟合模型

    3.1  新增截距项

     3.2 OLS拟合,注意OLS要大写

方法二:statsmodels.formula.api 通过自定formula和dataframe生成模型,无需添加截距项

1. 生成数据

2. 调用 statsmodels.formula.api

3. 拟合模型

    3.1 明确要拟合的公式

     3.2 OLS拟合

4. 输出拟合结果,检验R-square, coefficient是否显著 etc.

print(results.summary())      
statsmodels 最小二乘法 线性回归