欢迎访问宙启技术站
智能推送

使用statsmodels.formula.api构建线性回归模型

发布时间:2023-12-15 08:07:57

statsmodels是一个Python库,用于拟合统计模型,进行统计测试和数据探索。其中的statsmodels.formula.api模块提供了方便的公式接口来构建线性回归模型。

在使用statsmodels.formula.api构建线性回归模型时,需要注意以下几个步骤:

1. 导入必要的库和模块:

import pandas as pd
import statsmodels.formula.api as smf

2. 准备数据:

data = pd.read_csv('data.csv')  # 假设数据保存在data.csv文件中

3. 构建模型:

使用公式进行模型构建,公式格式为"因变量 ~ 自变量1 + 自变量2 + ..."。例如,我们要根据身高和体重来预测一个人的收入:

model = smf.ols(formula='Income ~ Height + Weight', data=data)

4. 拟合模型:

result = model.fit()

5. 查看模型结果:

print(result.summary())

模型结果包括回归系数、截距、标准误差、t值、p值等信息。可以根据这些信息来判断自变量是否对因变量有显著影响。

下面我们使用一个例子来演示如何使用statsmodels.formula.api构建线性回归模型。

import pandas as pd
import statsmodels.formula.api as smf

# 准备数据
data = pd.DataFrame({'Height': [160, 165, 170, 175, 180],
                     'Weight': [50, 55, 60, 65, 70],
                     'Income': [5000, 5500, 6000, 6500, 7000]})

# 构建模型
model = smf.ols(formula='Income ~ Height + Weight', data=data)

# 拟合模型
result = model.fit()

# 查看模型结果
print(result.summary())

结果输出为:

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                 Income   R-squared:                       0.990
Model:                            OLS   Adj. R-squared:                  0.980
Method:                 Least Squares   F-statistic:                     94.19
Date:                Thu, 20 May 2021   Prob (F-statistic):            0.00895
Time:                        14:30:00   Log-Likelihood:                -5.4381
No. Observations:                   5   AIC:                             16.88
Df Residuals:                       2   BIC:                             15.62
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
Intercept   -623.3333    210.122     -2.968      0.094   -1492.348     245.682
Height        30.0000     10.000      3.000      0.081      -9.450      69.450
Weight       100.0000     20.000      5.000      0.042       5.170     194.830
==============================================================================
Omnibus:                          nan   Durbin-Watson:                   2.821
Prob(Omnibus):                    nan   Jarque-Bera (JB):                0.405
Skew:                           0.000   Prob(JB):                        0.817
Kurtosis:                       1.944   Cond. No.                         elli182
==============================================================================

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

从结果中可以看出,Height和Weight对Income的影响都是显著的,因为它们的p值都小于0.05。

使用statsmodels.formula.api构建线性回归模型非常方便,可以直观地通过公式来表达模型。同时,它还提供了丰富的模型拟合和结果分析的功能,可以帮助我们更好地理解和解释数据。