以变​​量为约束条件的约束回归Python

时间:2018-06-29 16:41:39

标签: python constraints regression

我正在尝试使用sm.GLM模型然后使用model.fit_constrained代码在Python中运行约束回归。

我要同时输入两个变量和两个虚拟变量,这是我要限制的虚拟变量。我希望两个虚拟变量系数乘以一个等于零的权重。

当我将系数乘以整数权重时,这很好用,如下所示

results = model.fit_constrained('BOATS * 1 + CARS * 0.5')

但是,我希望这些整数是变量,并且取决于我的数据比例(每个虚拟变量为1)。我已经计算了SectorWgt系列中的比例,但是无法弄清楚如何将其输入到model.fit_constrained代码中。

这是我最好的尝试

results = model.fit_constrained('SIZE*int(SectorWgt.iloc[0])+VQMadj*int(SectorWgt.iloc[1])')

但是我得到了错误

patsy.PatsyError: unrecognized token in constraint

由于

int(SectorWgt.iloc[0])

部分代码。

有人有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:0)

使用字符串格式:

x = int(SectorWgt.iloc[0])
y = int(SectorWgt.iloc[1])

results = model.fit_constrained('SIZE*{}+VQMadj*{}'.format(x, y))

答案 1 :(得分:0)

如果使用Python 3.6或更高版本,则可以使用Python的f-strings使用更清晰的字符串插值语法。

constraint_str = f"SIZE*{int(SectorWgt.iloc[0])}+VQMadj*{int(SectorWgt.iloc[1])}"
results = model.fit_constrained(constraint_str)