gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:05:24 24 4
gpt4 key购买 nike

我目前正在使用

在 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)

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

最佳答案

我仍然不确定您运行的是哪种模型(发布 Minimal, Complete, and Verifiable example 肯定会有帮助),但以下内容应该适用于 GLM。来自docs ,我们有,

constraints (formula expression or tuple) – If it is a tuple, then the constraint needs to be given by two arrays (constraint_matrix, constraint_value), i.e. (R, q). Otherwise, the constraints can be given as strings or list of strings. see t_test for details.

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

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 是否必须符合文档。

关于python - 具有多个约束的 Python 中的约束回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51270715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com