例7.1:验证多元线性回归的偏回归系数
代码部分
# lec04
# 计量实验3-代码部分-01
# 导入库文件
import pandas as pd
# import matplotlib.pyplot as plt
import statsmodels.api as sm
import ssl
# 禁用SSL证书校验
ssl._create_default_https_context = ssl._create_unverified_context# 导入在线数据
# 读取在线数据
df01 = pd.read_excel(r"https://cdn.seit2019.xyz/data/econometrics/exp7.1.xlsx")
# 展示数据
print("原始数据展示如下:")
print(df01, "\n")
# 简要的描述性统计
print("原始数据的主要统计指标:")
print(df01.describe(), "\n")
# 多元线性回归
# 主回归模型
y = df01["CM"]
x = df01[["PGNP", "FLR"]]
X = sm.add_constant(x) # 添加常数项
OLS_model = sm.OLS(y, X).fit() # OLS回归
print(OLS_model.summary(), "\n") # 显示OLS回归结果
dfc = pd.DataFrame(OLS_model.params).round(4) # 获取回归参数,保留小数点后4位
dfc = dfc.astype("string") # 转换格式为字符串
beta0 = dfc.iloc[0, 0] # 定义beta0
beta1 = dfc.iloc[1, 0] # 定义beta1
beta2 = dfc.iloc[2, 0] # 定义beta2
OLS_equation = "CM=" + beta0 + beta1 + "*PGNP" + beta2 + "*FLR" # 定义回归方程,格式:字符串
print("估计的回归方程为:")
print(OLS_equation)
# 辅助回归模型1
y = df01["CM"]
x = df01["FLR"]
X = sm.add_constant(x) # 添加常数项
OLS_model = sm.OLS(y, X).fit() # OLS回归
print(OLS_model.summary(), "\n") # 显示OLS回归结果
resid01 = OLS_model.resid # 生成残差
dfc = pd.DataFrame(OLS_model.params).round(4) # 获取回归参数,保留小数点后4位
dfc = dfc.astype("string") # 转换格式为字符串
beta0 = dfc.iloc[0, 0] # 定义beta0
beta1 = dfc.iloc[1, 0] # 定义beta1
AUX_equation01 = "CM=" + beta0 + beta1 + "*FLR" # 定义回归方程,格式:字符串
print("估计的回归方程为:")
print(AUX_equation01)
# 辅助回归模型2
y = df01["PGNP"]
x = df01["FLR"]
X = sm.add_constant(x) # 添加常数项
OLS_model = sm.OLS(y, X).fit() # OLS回归
print(OLS_model.summary(), "\n") # 显示OLS回归结果
resid02 = OLS_model.resid # 生成残差
dfc = pd.DataFrame(OLS_model.params).round(4) # 获取回归参数,保留小数点后4位
dfc = dfc.astype("string") # 转换格式为字符串
beta0 = dfc.iloc[0, 0] # 定义beta0
beta1 = dfc.iloc[1, 0] # 定义beta1
AUX_equation02 = "PGNP=" + beta0 + "+" + beta1 + "*FLR" # 定义回归方程,格式:字符串
print("估计的回归方程为:")
print(AUX_equation02)
# 辅助回归模型3
y = resid01
x = resid02
# X = sm.add_constant(x) # 添加常数项
OLS_model = sm.OLS(y, x).fit() # OLS回归
print(OLS_model.summary(), "\n") # 显示OLS回归结果
dfc = pd.DataFrame(OLS_model.params).round(4) # 获取回归参数,保留小数点后4位
dfc = dfc.astype("string") # 转换格式为字符串
beta1 = dfc.iloc[0, 0] # 定义beta1
AUX_equation03 = "E1=" + beta1 + "*E2" # 定义回归方程,格式:字符串
print("估计的回归方程为:")
print(AUX_equation03, "\n")
# 显示所有回归方程
print("所有回归结果展示如下:")
print("主回归方程:" + OLS_equation)
print("辅助回归方程1:" + AUX_equation01)
print("辅助回归方程2:" + AUX_equation02)
print("辅助回归方程3:" + AUX_equation03)
print("比较上述回归结果发现:主回归方程中PGNP系数与辅助回归方程3中E2系数相同。")