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

使用smf.quantreg()出现ValueError的原因及解决方法

问题描述

我正在处理名为test的数据框,数据如下:

y                intercept      x
0   -1.6168468132687293 1           NA
1   1.5500031232431757  1           NA
2   1.5952617833602785  1           1.5500031232431757
3   1.1390724309357498  1           1.5952617833602785
4   0.9950311340335872  1           1.1390724309357498
5   0.7095780139613861  1           0.9950311340335872
6   0.5962529862944801  1           0.7095780139613861
7   0.6555353674581792  1           0.5962529862944801
8   1.0008751093886736  1           0.6555353674581792
9   1.2648319050758074  1           1.0008751093886736

尝试使用smf.quantreg()函数执行分位数回归,代码如下:

import statsmodels.formula.api as smf
Output_pre = smf.quantreg('y ~ intercept + x', test , missing = 'drop')
Output = Output_pre.fit(q=0.25)

等价的statsmodels.ols()函数可正常运行,但smf.quantreg()却报错:

ValueError: operands could not be broadcast together with shapes (3,) (2,) 
错误原因与解决方法

原因

公式接口里显式加入了intercept列,而statsmodels的公式接口默认会自动添加截距项,最终导致设计矩阵出现重复的截距列:

  • 手动加入的全1intercept列
  • 公式默认生成的全1截距项
    加上自变量x后设计矩阵共3列,但分位数回归的拟合逻辑未处理这种共线性情况,触发维度不兼容的报错。
    ols()能正常运行是因为它会自动识别并丢弃重复的共线性列,规避了维度问题。

解决方法

有两种修正方式:

  1. 移除公式中的intercept,依赖接口自动生成截距:
Output_pre = smf.quantreg('y ~ x', test, missing='drop')
Output = Output_pre.fit(q=0.25)
  1. 保留手动intercept列,同时禁用接口的自动截距生成(公式末尾加-1):
Output_pre = smf.quantreg('y ~ intercept + x -1', test, missing='drop')
Output = Output_pre.fit(q=0.25)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:55:30