我尝试先使用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])
部分代码。
有谁有什么想法吗?谢谢!
发布于 2018-06-30 03:08:12
使用字符串格式:
x = int(SectorWgt.iloc[0])
y = int(SectorWgt.iloc[1])
results = model.fit_constrained('SIZE*{}+VQMadj*{}'.format(x, y))
发布于 2018-07-03 21:00:43
如果使用Python3.6或更新版本,您可以使用Python3.6或更新版本的f-strings来利用更清晰的字符串插值语法。
constraint_str = f"SIZE*{int(SectorWgt.iloc[0])}+VQMadj*{int(SectorWgt.iloc[1])}"
results = model.fit_constrained(constraint_str)
https://stackoverflow.com/questions/51106180
复制相似问题