You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用statsmodels add_constant无法添加常数项的问题求助

问题解决:statsmodels add_constant未生成常数项的问题

问题出在sm.add_constant的默认行为上,statsmodels 0.14.0版本中该函数默认参数has_constant='skip',会自动检测输入数组是否包含常数项,当检测逻辑误判(或数据结构触发检测规则)时,就会跳过添加常数项的步骤。

解决方法很直接,调用add_constant时显式指定has_constant='add',强制添加常数列:

import numpy as np
import statsmodels.api as sm

future_time_points = np.array([2010])
stacked_array = np.column_stack((future_time_points, future_time_points ** 2))
# 显式指定参数,强制添加常数项
array_with_constant = sm.add_constant(stacked_array, has_constant='add')

print(array_with_constant)

执行后输出会变成:

[[1.000e+00 2.010e+03 4.0401e+06]]

补充说明:如果你的输入数组可能本身包含常数项,也可以用has_constant='raise'来强制检查,避免重复添加;但你的场景里直接用'add'就能确保常数项被加入。

内容的提问来源于stack exchange,提问作者user308827

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 04:52:02