天天看點

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 最小二乘法 線性回歸