如何在Python中实现回归模型的不对称系数(Dual Beta)
实现回归分析中的不对称正负效应(双贝塔)
在回归分析框架中,我们有两个自变量x1和x2,需要针对x1>0、x1<0以及x2>0、x2<0分别设置不同的斜率,这类模型可用于计算双贝塔(Dual Beta)。
已完成普通OLS回归的代码及输出如下:
import numpy as np import statsmodels.api as sm spector_data = sm.datasets.spector.load() spector_data.exog = sm.add_constant(spector_data.exog, prepend=False) # 拟合并总结OLS模型 mod = sm.OLS(spector_data.endog, spector_data.exog) res = mod.fit() print(res.summary())
输出结果:
============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ x1 0.4639 0.162 2.864 0.008 0.132 0.796 x2 0.0105 0.019 0.539 0.594 -0.029 0.050 x3 0.3786 0.139 2.720 0.011 0.093 0.664 const -1.4980 0.524 -2.859 0.008 -2.571 -0.425 ==============================================================================
现在需要实现不对称正负效应的量化,期望输出格式如下:
============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ x1+ 0.1031 0.162 2.864 0.008 0.132 0.796 x1- 0.4639 0.162 2.864 0.008 0.132 0.796 x2+ 0.0111 0.019 0.539 0.594 -0.029 0.050 x2- 0.212 0.019 0.539 0.594 -0.029 0.050 x3 0.3786 0.139 2.720 0.011 0.093 0.664 const -1.4980 0.524 -2.859 0.008 -2.571 -0.425 ==============================================================================
实现步骤
- 构造拆分后的自变量:将
x1拆分为x1+(仅保留x1>0的部分,其余为0)和x1-(仅保留x1<0的部分,其余为0);同理拆分x2为x2+和x2-。 - 替换原数据集的自变量:用拆分后的变量替换原
x1、x2,保留x3和常数项。 - 拟合OLS模型:使用新的自变量矩阵拟合模型,输出结果会自动匹配自定义的变量名。
完整代码
import numpy as np import statsmodels.api as sm # 加载数据 spector_data = sm.datasets.spector.load() df = spector_data.exog.copy() df['y'] = spector_data.endog # 拆分自变量:生成x1、x2的正负部分 df['x1+'] = np.where(df['x1'] > 0, df['x1'], 0) df['x1-'] = np.where(df['x1'] < 0, df['x1'], 0) df['x2+'] = np.where(df['x2'] > 0, df['x2'], 0) df['x2-'] = np.where(df['x2'] < 0, df['x2'], 0) # 准备新的自变量矩阵:保留x3、常数项,替换x1、x2为拆分后的变量 exog_new = sm.add_constant(df[['x1+', 'x1-', 'x2+', 'x2-', 'x3']], prepend=False) # 拟合模型并输出结果 mod = sm.OLS(df['y'], exog_new) res = mod.fit() print(res.summary())
补充说明
- 拆分变量时,
x1=0或x2=0的样本会被同时排除在正负部分之外,若需处理这类样本,可根据业务需求调整np.where的条件(比如将0归入某一类)。 - 输出的变量名会直接显示为
x1+、x1-等,与期望格式完全匹配。
内容的提问来源于stack exchange,提问作者PeCaDe
相关产品推荐
相关产品推荐

