OLS拟合特殊场景触发ValueError:exog非1/2维,如何返回指定结果?
解决方法
原代码报错的核心原因是:当因变量y全为NaN时,missing="drop"会删除所有观测样本,导致自变量矩阵exog变成空数组,OLS模型无法完成拟合,从而抛出ValueError: exog is not 1d or 2d异常。
要实现该场景下返回array([[nan., nan.]])的需求,可采用以下两种方案:
方案一:手动预处理缺失值
提前过滤含缺失值的样本,判断剩余有效样本量,再决定返回结果或正常拟合:
import numpy as np import statsmodels.api as sm y = np.array([np.nan]) exog = sm.add_constant(np.array([[1]]), has_constant="add") # 合并因变量与自变量,筛选无缺失值的行 combined_data = np.column_stack([y, exog]) valid_indices = ~np.isnan(combined_data).any(axis=1) filtered_y = y[valid_indices] filtered_exog = exog[valid_indices] if len(filtered_y) == 0: result_params = np.array([[np.nan, np.nan]]) else: model = sm.OLS(filtered_y, filtered_exog).fit() result_params = model.params.reshape(1, -1) print(result_params)
方案二:捕获特定异常
用try-except包裹拟合流程,仅针对目标异常返回指定结果:
import numpy as np import statsmodels.api as sm y = np.array([np.nan]) exog = sm.add_constant(np.array([[1]]), has_constant="add") try: result_params = sm.OLS(y, exog, missing="drop").fit().params.reshape(1, -1) except ValueError as e: # 仅处理"exog is not 1d or 2d"这个特定异常 if "exog is not 1d or 2d" in str(e): result_params = np.array([[np.nan, np.nan]]) else: # 其他ValueError情况重新抛出,不掩盖问题 raise print(result_params)
两种方案均可实现需求:当所有样本因缺失被删除时返回含两个NaN的二维数组;正常场景下则返回OLS拟合的参数。
内容的提问来源于stack exchange,提问作者lebesgue
相关产品推荐
相关产品推荐

