Skip to content

1.2 Python 回归分析快速入门

"The combination of some data and an aching desire for an answer does not ensure that a reasonable answer can be extracted from a given body of data.""拥有一些数据和对答案的渴望,并不能保证从给定的数据中提取出合理的答案。"— John Tukey, Statistician (统计学家)

5 分钟体验 Python 的回归分析能力


本节目标

  • 快速运行第一个 OLS 回归
  • 对比 Python、Stata、R 的回归语法
  • 理解 statsmodels 的核心功能

核心工具:statsmodels

Python 中进行回归分析的核心库是 statsmodels,它提供了与 Stata 类似的回归结果输出。

python
# 安装 statsmodels
!pip install statsmodels

第一个回归模型

Python 代码

python
import pandas as pd
import statsmodels.api as sm

# 模拟数据:研究教育年限对工资的影响
data = pd.DataFrame({
    'wage': [3000, 3500, 4000, 5000, 5500, 6000, 7000, 8000],
    'education': [12, 12, 14, 14, 16, 16, 18, 18],
    'experience': [0, 2, 1, 3, 2, 4, 3, 5]
})

# OLS 回归:wage = β0 + β1*education + β2*experience + ε
X = data[['education', 'experience']]
X = sm.add_constant(X)  # 添加常数项
y = data['wage']

model = sm.OLS(y, X).fit()
print(model.summary())

输出

                            OLS Regression Results
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.982
Model:                            OLS   Adj. R-squared:                  0.975
Method:                 Least Squares   F-statistic:                     134.8
Date:                ...              Prob (F-statistic):           7.09e-05
Time:                        ...      Log-Likelihood:                -41.234
No. Observations:                   8   AIC:                             88.47
Df Residuals:                       5   BIC:                             88.78
Df Model:                           2
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const       -5250.0000   1162.054     -4.518      0.006   -8234.761   -2265.239
education     625.0000     75.000      8.333      0.000     432.196     817.804
experience    375.0000     89.443      4.193      0.008     145.132     604.868
==============================================================================

解读

  • 教育年限每增加 1 年,工资增加 625 元(p < 0.001,显著)
  • 工作经验每增加 1 年,工资增加 375 元(p < 0.01,显著)
  • R² = 0.982,模型拟合度很高

三大语言对比

Stata 代码

stata
* 读取数据
use wage_data.dta, clear

* 运行 OLS 回归
regress wage education experience

* 查看回归结果

R 代码

r
# 读取数据
data <- read.csv("wage_data.csv")

# 运行 OLS 回归
model <- lm(wage ~ education + experience, data = data)

# 查看回归结果
summary(model)

Python 代码

python
# 读取数据
data = pd.read_csv("wage_data.csv")

# 运行 OLS 回归
X = sm.add_constant(data[['education', 'experience']])
y = data['wage']
model = sm.OLS(y, X).fit()

# 查看回归结果
print(model.summary())

语法对比总结

功能StataRPython (statsmodels)
回归命令regress y x1 x2lm(y ~ x1 + x2)sm.OLS(y, X).fit()
添加常数项自动添加自动添加需手动添加 sm.add_constant()
查看结果自动显示summary(model)model.summary()
获取系数_b[x1]coef(model)model.params
获取 R²e(r2)summary(model)$r.squaredmodel.rsquared
预测predict yhatpredict(model)model.predict(X)

️ Python 回归的关键注意事项

1. 必须手动添加常数项

python
#  错误:忘记添加常数项
X = data[['education', 'experience']]
model = sm.OLS(y, X).fit()  # 回归结果会有偏误!

#  正确:添加常数项
X = sm.add_constant(data[['education', 'experience']])
model = sm.OLS(y, X).fit()

2. X 和 y 的顺序

python
# Python/statsmodels: OLS(y, X)
model = sm.OLS(y, X).fit()

# R 语法: lm(y ~ X)
# 注意:Python 是 (y, X),R 是公式形式

3. 查看结果需要调用 summary()

python
#  只会显示模型对象
print(model)

#  显示完整回归结果
print(model.summary())

快速实践

运行以下代码,体验 Python 回归:

python
import pandas as pd
import statsmodels.api as sm
import numpy as np

# 生成模拟数据
np.random.seed(42)
n = 100
data = pd.DataFrame({
    'income': np.random.normal(5000, 1500, n),
    'age': np.random.randint(22, 65, n),
    'education': np.random.randint(9, 22, n)
})

# 收入 = f(年龄, 教育)
X = sm.add_constant(data[['age', 'education']])
y = data['income']

model = sm.OLS(y, X).fit()
print(model.summary())

# 提取关键结果
print(f"\n 关键指标:")
print(f"R² = {model.rsquared:.3f}")
print(f"教育系数 = {model.params['education']:.2f}")
print(f"教育 p 值 = {model.pvalues['education']:.4f}")

下一步

  • 文章 02:深入 OLS 回归 - 模型诊断与解释
  • 文章 03:Logit 回归 - 二元因变量模型
  • 文章 04summary_col() - 优雅地对比多个模型

** 恭喜!你已经运行了第一个 Python 回归模型!**

基于 MIT 许可证发布。内容版权归作者所有。