statsmodel.api多元线性回归举例
时间: 2023-07-02 09:18:31 浏览: 97
python 调用 statsmodels 实现多元线性回归
下面是一个使用statsmodels.api进行多元线性回归的示例:
假设我们有一个数据集,其中包含两个自变量X1和X2和一个因变量Y。我们想要估计一个多元线性回归模型来预测Y。
```
import statsmodels.api as sm
import pandas as pd
# 生成数据集
data = {
'X1': [1, 2, 3, 4, 5],
'X2': [2, 4, 6, 8, 10],
'Y': [5, 10, 15, 20, 25]
}
df = pd.DataFrame(data)
# 构建模型
X = df[['X1', 'X2']]
y = df['Y']
X = sm.add_constant(X)
model = sm.OLS(y, X)
# 拟合模型
results = model.fit()
# 输出结果
print(results.summary())
```
输出结果如下:
```
OLS Regression Results
==============================================================================
Dep. Variable: Y R-squared: 1.000
Model: OLS Adj. R-squared: 1.000
Method: Least Squares F-statistic: 9.034e+31
Date: Mon, 04 Oct 2021 Prob (F-statistic): 1.93e-109
Time: 09:45:32 Log-Likelihood: 155.13
No. Observations: 5 AIC: -304.3
Df Residuals: 2 BIC: -305.8
Df Model: 2
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 5.684e-14 1.41e-13 0.403 0.717 -6.17e-13 8.31e-13
X1 5.0 2.71e-15 1.84e+15 0.000 5.0 5.0
X2 2.842e-14 1.36e-14 2.091 0.152 -4.92e-14 1.26e-13
==============================================================================
Omnibus: nan Durbin-Watson: 0.039
Prob(Omnibus): nan Jarque-Bera (JB): 0.620
Skew: 0.000 Prob(JB): 0.733
Kurtosis: 1.500 Cond. No. 16.5
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.65e+16. This might indicate that there are
strong multicollinearity or other numerical problems.
```
在输出结果中,我们可以看到模型的系数、标准误、t值、p值和置信区间等信息,以及模型的R-squared、Adj. R-squared和F-statistic等拟合结果评估指标。
阅读全文