Skip to content

OLS 回归

普通最小二乘线性回归。

核心代码

py
    def _fit_standard_regression(self, df: pd.DataFrame) -> Any:
        """
        执行标准回归(OLS、Logit、Probit)

        参数:
            df: 清洗后的数据框

        返回:
            statsmodels 拟合结果
        """
        regressors = [var for var in self.x_vars if var != self.y_var]
        formula = build_patsy_formula(self.y_var, regressors)

        if self.method == 'ols':
            try:
                model = smf.ols(formula, data=df)
            except ValueError as exc:
                if 'negative dimensions are not allowed' in str(exc).lower():
                    raise ValueError(
                        _('所选变量联合删除缺失值后没有可用于 OLS 回归的有效样本,')
                        + _('请检查变量缺失情况或减少所选变量。')
                    ) from exc
                raise

            # 配置标准误
            if self.se_options.get('type') == 'robust':
                self.result = model.fit(cov_type='HC1')
            elif self.se_options.get('type') == 'cluster':
                c_var = self.se_options.get('cluster_var')
                self.result = model.fit(
                    cov_type='cluster',
                    cov_kwds={'groups': df[c_var]}
                )
            else:
                self.result = model.fit()

            self.model_stats = {
                'N': int(self.result.nobs),
                'R2': self.result.rsquared,
                'Adj-R2': self.result.rsquared_adj,
                'F': self.result.fvalue,
                'AIC': self.result.aic
            }

        elif self.method == 'logit':
            model = smf.logit(formula, data=df)
            self.result = model.fit(disp=0)

            # 计算边际效应(如果需要)
            if self.margeff_options.get('compute', False):
                try:
                    at_option = self.margeff_options.get('at', 'overall')
                    self.marginal_effects_result = self.result.get_margeff(at=at_option)
                except Exception as e:
                    warnings.warn(f"边际效应计算失败: {str(e)}", UserWarning)
                    self.marginal_effects_result = None

            self.model_stats = {
                'N': int(self.result.nobs),
                'Pseudo-R2': self.result.prsquared,
                'AIC': self.result.aic,
                'LL': self.result.llf
            }

        elif self.method == 'probit':
            model = smf.probit(formula, data=df)
            self.result = model.fit(disp=0)

            # 计算边际效应(如果需要)
            if self.margeff_options.get('compute', False):
                try:
                    at_option = self.margeff_options.get('at', 'overall')
                    self.marginal_effects_result = self.result.get_margeff(at=at_option)
                except Exception as e:
                    warnings.warn(f"边际效应计算失败: {str(e)}", UserWarning)
                    self.marginal_effects_result = None

            self.model_stats = {
                'N': int(self.result.nobs),
                'Pseudo-R2': self.result.prsquared,
                'AIC': self.result.aic,
                'LL': self.result.llf
            }

        return self.result

Released under the AGPL-3.0 License.