繁体   English   中英

Python中具有多个约束的约束回归

[英]Constrained regression in Python with multiple constraints

我目前正在使用以下方法在Python中设置约束回归

import statsmodels.api as sm

model = sm.GLM(Y,X)    
model.fit_constrained 

'''Setting the restrictions on parameters in the form of (R, q), where R 
and q are constraints' matrix and constraints' values, respectively. As
for the restriction in the aforementioned regression model, i.e., 
c = b - 1 or b - c = 1, R = [0, 1, -1] and q = 1.'''

StatsModel提供的函数,但在尝试使用多个约束进行设置时遇到一些问题。 我有七个系数,包括一个常数。 我要进行设置,以使虚拟1和虚拟2的加权和等于零,并且虚拟3和虚拟4的加权和等于零。 要使用一个约束示例,

results = model.fit_constrained(([0, 0, 0, a, b, 0, 0], 0))

其中a和b是虚拟3和虚拟4的权重,并且是我预先定义的变量。

如果没有a和b变量,并且虚拟变量的权重相等,则可以使用以下语法

fit_constrained('Dummy1 + Dummy2, Dummy3 + Dummy4')

但是当我尝试使用类似的语法时

results = model.fit_constrained(([0, 0, 0, a, b, 0, 0], 0),([0, c, d, 0, 0, 0, 0], 0)) 

我得到错误

ValueError: shapes (2,) and (7,6) not aligned: 2 (dim 0) != 7 (dim 0)

有人有什么想法吗? 非常感谢!

我仍然不确定您正在运行哪种模型(发布最小,完整和可验证的示例肯定会有所帮助),但是以下操作对于GLM应该适用。 根据文档 ,我们有

约束公式表达式或元组 )–如果是元组,则约束必须由两个数组(constraint_matrix,constraint_value),即(R,q)给出。 否则,约束可以给出为字符串或字符串列表。 有关详细信息,请参见t_test。

这意味着函数调用应遵循以下几行:

R = [[0, 0, 0, a, b, 0, 0],
     [0, c, d, 0, 0, 0, 0]]
q = [0, 0]

results = model.fit_constrained((R, q))

这应该可以工作,但是由于我们没有您的模型,因此我不确定R * params = q必须根据文档确定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM