[英]Constrained regression python with variables as constraints
我正在嘗試使用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])
代碼的一部分。
有人有想法嗎? 謝謝!
使用字符串格式:
x = int(SectorWgt.iloc[0])
y = int(SectorWgt.iloc[1])
results = model.fit_constrained('SIZE*{}+VQMadj*{}'.format(x, y))
如果使用的是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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.