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生成模型,无需添加截距项


  
  1. import pandas as pd
  2. import numpy as np

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

1. 生成数据


  
  1. data = pd.DataFrame({ 'Salary':np.random.rand( 1000)* 100000,
  2. 'Catologs':np.random.randint( 1, 20,size= 1000),
  3. 'Children':np.random.randint( 0, 3,size= 1000),
  4. 'AmountSpent':np.random.rand( 1000)* 10000})
  5. data.head()

2. 调用 statsmodels.api

import statsmodels.api as sm
  

3. 拟合模型

    3.1  新增截距项


  
  1. # 原有x,y
  2. x = data[[ 'Salary', 'Catologs', 'Children']] # 注意是[[ ]]
  3. y = data[ 'AmountSpent']
  4. # 新增截距项
  5. x_with_intercept = sm.add_constant(x, prepend= True)

     3.2 OLS拟合,注意OLS要大写


  
  1. # 拟合模型
  2. model = sm.OLS(y, x_with_intercept) # OLS 要大写,函数里因变量在前面
  3. results = model.fit()

 

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

1. 生成数据


  
  1. # 生成数据
  2. data = pd.DataFrame({ 'Salary':np.random.rand( 1000)* 100000,
  3. 'Catologs':np.random.randint( 1, 20,size= 1000),
  4. 'Children':np.random.randint( 0, 3,size= 1000),
  5. 'AmountSpent':np.random.rand( 1000)* 10000})
  6. data.head()

2. 调用 statsmodels.formula.api


  
  1. # 直接调用formula,无需手动增加截距项
  2. import statsmodels.formula.api as smf

3. 拟合模型

    3.1 明确要拟合的公式


  
  1. # formula,"因变量 ~ 自变量1 + 自变量2 + ... + 自变量n"
  2. formula = "AmountSpent ~ Salary + Catologs + Children"

     3.2 OLS拟合


  
  1. model = smf.ols(formula, data)
  2. results = model.fit()

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

print(results.summary())
  

PS:随机生成的数据果然挺随机的,这结果等于做了个寂寞

 

posted @ 2022-11-21 18:53  TwcatL_tree  阅读(38)  评论(1编辑  收藏  举报