Skip to content

BUG: GLM score_test singular matrix #4798

Open

Description

@josef-pkt

edit this looks more like a problem for score and profile likelihood confidence intervals with a link function that does not satisfy domain constraints.

I got an example where scoretest raises with singular matrix in np.linalg.solve
This is using #4716, and a score confidence interval example.

Maybe I need to use pinv instead of solve.

0.23119 -71.3544794856 [ 0.05000118]
Traceback (most recent call last):
  File "E:\Josef_new\scripts\score_confint_naive.py", line 55, in <module>
    low = optimize.brentq(diff_scoretest, wald_ci[0]*2, wald_ci[0]*0.5, xtol=1e-5)
  File "...\WinPython-64bit-3.4.4.5Qt5\python-3.4.4.amd64\lib\site-packages\scipy\optimize\zeros.py", line 442, in brentq
    r = _zeros._brentq(f,a,b,xtol,rtol,maxiter,args,full_output,disp)
  File "E:\Josef_new\scripts\score_confint_naive.py", line 41, in diff_scoretest
    pvalue = resc.score_test()[1]
  File "E...\statsmodels_py34_pr\statsmodels\genmod\generalized_linear_model.py", line 1671, in score_test
    observed=observed)
  File "...\statsmodels_py34_pr\statsmodels\base\_parameter_inference.py", line 249, in score_test
    chi2stat = score.dot(np.linalg.solve(cov_score_test, score[:, None]))
  File "...\WinPython-64bit-3.4.4.5Qt5\python-3.4.4.amd64\lib\site-packages\numpy\linalg\linalg.py", line 384, in solve
    r = gufunc(a, b, signature=signature, extobj=extobj)
  File "...\WinPython-64bit-3.4.4.5Qt5\python-3.4.4.amd64\lib\site-packages\numpy\linalg\linalg.py", line 90, in _raise_linalgerror_singular
    raise LinAlgError("Singular matrix")
numpy.linalg.linalg.LinAlgError: Singular matrix

example is during score confidence interval search
2-sample proportion, second exog is indicator with 11 of 100 obs in group 0

>>> y.tolist()
[1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1]

>>> x[:,1].tolist()
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

Activity

  1. josef-pkt commented on Jul 17, 2018

    @josef-pkt
    MemberAuthor

    current script file score_confint_naive.py

    # -*- coding: utf-8 -*-
    """
    Created on Mon Jul 16 16:13:07 2018
    
    Author: Josef Perktold
    """
    
    import numpy as np
    from scipy import optimize, stats
    from statsmodels.genmod.generalized_linear_model import GLM
    from statsmodels.genmod import families
    from statsmodels.genmod.families import links
    
    from statsmodels.tools.sm_exceptions import DomainWarning
    
    import warnings
    warnings.simplefilter('ignore', DomainWarning)
    
    
    nobs = 100
    x = np.column_stack((np.ones(nobs), np.arange(nobs) > nobs //10))
    params_prob = [0.45, 0.1]
    prob = x.dot(params_prob)
    np.random.seed(567986)
    y = np.random.binomial(np.ones(nobs, dtype=np.int32), prob)
    
    res = GLM(y, x, family=families.Binomial(links.identity())).fit()
    print(res.summary())
    print()
    print(res.predict([[1, 0], [1, 1]]))
    
    resc_upp = res.model.fit_constrained('x1=0.238245')
    print(resc_upp.score_test())
    resc_low = res.model.fit_constrained('x1=-0.16055')
    print(resc_low.score_test())
    
    llf_full = res.llf
    
    def diff_scoretest(p, alpha=0.05):
        resc = res.model.fit_constrained('x1=%f'%p)
        pvalue = resc.score_test()[1]
        print(resc.params[1], resc.llf, pvalue)
        return pvalue - alpha
        
    def diff_profilelrtest(p, alpha=0.05):
        resc = res.model.fit_constrained('x1=%f'%p)
        lrstat = -2*(resc.llf - llf_full)
        lrdf = 1
        lr_pvalue = stats.chi2.sf(lrstat, lrdf)
        return lr_pvalue - alpha
    
    wald_ci = res.conf_int()[1]
    
    upp = optimize.brentq(diff_scoretest, wald_ci[1]*0.5, wald_ci[1]*2, xtol=1e-5)
    low = optimize.brentq(diff_scoretest, wald_ci[0]*2, wald_ci[0]*0.5, xtol=1e-5)
    
    upp_lr = optimize.brentq(diff_profilelrtest, wald_ci[1]*0.5, wald_ci[1]*2, xtol=1e-5)
    low_lr = optimize.brentq(diff_profilelrtest, wald_ci[0]*2, wald_ci[0]*0.5, xtol=1e-5)
    
    print()
    print('wald confint ', *wald_ci)
    print('score confint', low, upp)
    print('LR confint   ', low_lr, upp_lr)
    
  2. josef-pkt commented on Jul 17, 2018

    @josef-pkt
    MemberAuthor

    AFAICS, the problem comes from using identity link and a Domain violation, probability outside [0, 1], in GLM-Binomial.
    The bounds for the brentq zero search don't take into account that parameters should imply probabilities in [0, 1].

    running the example with a different seed:

    -> chi2stat = score.dot(np.linalg.solve(cov_score_test, score[:, None]))
    (Pdb) cov_score_test
    array([[  2.10870011e+33,   2.10870011e+33],
           [  2.10870011e+33,   2.10870011e+33]])
    (Pdb) score
    array([ -3.02969429e+17,  -3.02969429e+17])
    

    That means, that score_test is just where it fails, but the cause is some more fundamental problem in the score confidence interval computation. With identity link wald confidence intervals do not necessarily imply predicted probabilities in [0, 1].
    Profile confint in #1791 have most likely the same problem with using wald confint as bounds for the confint search.

  3. josef-pkt commented on Jul 17, 2018

    @josef-pkt
    MemberAuthor

    parking the corrected script here
    now limits the search bounds to have valid probability, but specific to two sample case. Finding bounds will be more difficult in more general cases with more regressors. But it should not be a problem with links that respect domain.
    I changed the seed and relative nobs to try different cases. No exception, but warnings from in some cases.

    example results with equal nobs in both samples, nobs=100
    confint differ a bit more across methods with unequal sample sizes

    wald confint  -0.114915537623 0.275779883361
    score confint -0.11878383884415761 0.2796360527188463
    LR confint    -0.11511881130709012 0.2718700839756163
    
    # -*- coding: utf-8 -*-
    """
    Created on Mon Jul 16 16:13:07 2018
    
    Author: Josef Perktold
    """
    
    import numpy as np
    from scipy import optimize, stats
    from statsmodels.genmod.generalized_linear_model import GLM
    from statsmodels.genmod import families
    from statsmodels.genmod.families import links
    
    from statsmodels.tools.sm_exceptions import DomainWarning
    
    import warnings
    warnings.simplefilter('ignore', DomainWarning)
    
    
    nobs = 100
    x = np.column_stack((np.ones(nobs), np.arange(nobs) > nobs //2))
    params_prob = [0.45, 0.1]
    prob = x.dot(params_prob)
    np.random.seed(567983)
    y = np.random.binomial(np.ones(nobs, dtype=np.int32), prob)
    
    res = GLM(y, x, family=families.Binomial(links.identity())).fit()
    print(res.summary())
    print()
    print(res.predict([[1, 0], [1, 1]]))
    
    resc_upp = res.model.fit_constrained('x1=0.238245')
    print(resc_upp.score_test())
    resc_low = res.model.fit_constrained('x1=-0.16055')
    print(resc_low.score_test())
    
    llf_full = res.llf
    
    def diff_scoretest(p, alpha=0.05):
        resc = res.model.fit_constrained('x1=%f'%p)
        pvalue = resc.score_test()[1]
        print(resc.params[1], resc.llf, pvalue)
        return pvalue - alpha
        
    def diff_profilelrtest(p, alpha=0.05):
        resc = res.model.fit_constrained('x1=%f'%p)
        lrstat = -2*(resc.llf - llf_full)
        lrdf = 1
        lr_pvalue = stats.chi2.sf(lrstat, lrdf)
        print(resc.params[1], resc.llf, lr_pvalue)
        return lr_pvalue - alpha
    
    wald_ci = res.conf_int()[1]
    
    half_ci = wald_ci[1] - res.params[1]
    upp_start = min(wald_ci[1] + half_ci, 1 - res.params[0]-1e-5)
    low_start = max(wald_ci[0] - half_ci,  - res.params[0] + 1e-5)
    upp = optimize.brentq(diff_scoretest, wald_ci[1]*0.5, upp_start, xtol=1e-5)
    low = optimize.brentq(diff_scoretest, low_start, wald_ci[0]*0.5, xtol=1e-5)
    
    upp_lr = optimize.brentq(diff_profilelrtest, wald_ci[1]*0.5, upp_start, xtol=1e-5)
    low_lr = optimize.brentq(diff_profilelrtest, low_start, wald_ci[0]*0.5, xtol=1e-5)
    
    print()
    print('wald confint ', *wald_ci)
    print('score confint', low, upp)
    print('LR confint   ', low_lr, upp_lr)
    
  4. added this to the 0.15 milestone on Feb 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions