首页 > 解决方案 > statsmodels glm fit_constrained '无法识别的令牌'

问题描述

尝试使用带有约束的 statsmodels.glm 并且无法获得(我认为应该是)一个简单的工作要求......

import numpy as np
import pandas as pd
from statsmodels.tools import add_constant
from statsmodels.formula.api import glm

test = np.array([[10,29,30],[32,26,23],[34,39,46]])
exog = add_constant(test)
y = np.array([11,23,27])

formula = 'y ~ x + q'
formula_df = formula_df = pd.DataFrame({'y' : y,'x':test[:,0],'q':test[:,1],'r':test[:,2],'int':exog[:,3]})

glmm = glm(formula=formula,data=formula_df)

glmm_results = glmm.fit_constrained(constraints='q = 0')
print(glmm_results.summary())

来自适合约束的文档:

The constraints are of the form R params = q where R is the constraint_matrix and q is the vector of constraint_values.

The estimation creates a new model with transformed design matrix, exog, and converts the results back to the original parameterization.

Parameters

    constraintsformula 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

但是,如果我尝试通过将约束更改为来简单地确保 q > 0:

glm_results = glmm.fit_constrained(constraints='q > 0')

然后我得到一个无法识别的令牌错误

PatsyError: unrecognized token in constraint
    q > 0
      ^

我也试过'>>'。除了我在上面复制/粘贴的内容之外,我找不到太多关于 statsmodels 和编写约束的文档。我怎样才能让它工作?

另一个问题是如何以 q,R 格式(x = 0、x<0、x>0、a<x<b)编写 4 种最简单类型的系数约束?

标签: pythonstatsmodels

解决方案


推荐阅读