Skip to content

ENH: LM-test for heteroscedasticity in binary response models Logit, Probit #2730

Open

Description

@josef-pkt

I'm not sure what the status here is, I just found an older script of mine with a function

def het_binary(results, exog_var, method='all'):
    '''Lagrange Multiplier (score) test for heterogeneity in binary models

    Test a homoscedastic model against a variance function for the latent
    variable of the form exp(Z gamma) where the `exog_var` Z are the
    explanatory variables for the heteroscedasticity.

which (unfortunately) has 4 or 5 different versions, and I don't know of any reference numbers.
(based on Greene, Wooldridge, and maybe Davidson-MacKinnon

http://www.statalist.org/forums/forum/general-stata-discussion/general/5564-heteroskedasticity-test-for-logit-and-logistic-models
http://www.stata.com/manuals13/rhetprobit.pdf

related to issues and PR on score/LM and conditional moment tests


two blog articles for R
http://www.r-bloggers.com/the-problem-with-testing-for-heteroskedasticity-in-probit-models/
https://diffuseprior.wordpress.com/2012/11/19/the-heteroskedastic-probit-model/

Shazam for LM test Davidson-MacKinnon with Shazam output (useful for unit test)
http://www.econometrics.com/intro/logit3.htm
data: http://www.econometrics.com/intro/school.htm

another blog article in favor of LM test
http://davegiles.blogspot.ca/2011/05/gripe-of-day.html
but he has things mostly in "unreadable" Eviews workfiles http://web.uvic.ca/~dgiles/downloads/binary_choice/index.html

Activity

  1. josef-pkt commented on Apr 20, 2016

    @josef-pkt
    MemberAuthor

    just another idea based on double exponential model (GLM with GLM-Gamma dispersion estimation):

    instead of using OLS for estimation of the LM test, use GLM-Gamma and test coefficients.
    some discussion and example on GLM-Gamma for variance/dispersion function estimation is in Tweedie PR #2872

  2. josef-pkt commented on May 23, 2017

    @josef-pkt
    MemberAuthor

    Stata nonlinear test has an example to test for unequal variance between male and female by testing the assumption that all coefficients for female and male are proportional to each other. (Ref ?)

  3. josef-pkt commented on May 23, 2017

    @josef-pkt
    MemberAuthor

    attaching the full script file as reference, (so I don't have to look for it again)
    "local_scripts\local_scripts\try_logit_lm_test.py"
    2013-11-18, used with Python 2.7.1, updated to work with Python 3

    result of hetbinary (no idea now what it the versions are)

    >>> print(np.asarray(list(map(np.ravel, rr))).reshape(-1, 2))
    [[ 3.93289759  0.04735029]
     [ 1.68421593  0.19436519]
     [ 3.93289759  0.04735029]
     [ 1.97727831  0.15967742]
     [ 1.97727831  0.15967742]
     [ 1.26654174  0.26041645]]
    

    '''Specification test for heteroscedasticity after Logit or binary models
    
    see Greene and Wooldridge
    see also log file
    
    Author: Josef Perktold
    original file in "local_scripts\local_scripts\try_logit_lm_test.py"  2013-11-18
    updated for Python 3
    '''
    
    
    import numpy as np
    from scipy import stats
    import statsmodels.api as sm
    
    # Load data from Spector and Mazzeo (1980). Examples follow Greene's
    # Econometric Analysis Ch. 21 (5th Edition).
    spector_data = sm.datasets.spector.load()
    spector_data.exog = sm.add_constant(spector_data.exog, prepend=False)
    
    # Inspect the data:
    spector_data.exog[:5, :]
    spector_data.endog[:5]
    
    # Linear Probability Model (OLS)
    #-------------------------------
    lpm_mod = sm.OLS(spector_data.endog, spector_data.exog)
    lpm_res = lpm_mod.fit()
    print(lpm_res.params[:-1])
    
    #Logit Model
    #-----------
    logit_mod = sm.Logit(spector_data.endog, spector_data.exog)
    logit_res = logit_mod.fit()
    print(logit_res.params)
    
    
    def het_binary(results, exog_var, method='all'):
        '''Lagrange Multiplier (score) test for heterogeneity in binary models
    
        Test a homoscedastic model against a variance function for the latent
        variable of the form exp(Z gamma) where the `exog_var` Z are the
        explanatory variables for the heteroscedasticity.
        
    
        Parameters
        ----------
        results : Logit or Probit results instance
            the restricted model with assumed homoscedasticity
            This would also work for GLM, but that does not have the same
            methods and attributes.
        exog_var : ndarray
            explanatory variables for the variance function, see Notes.
            exog_var should not include a constant.
        method : string or list
            Which method(s) of the test to use.
            TODO: Currently 'all' are always returned
            
    
        Returns
        -------
        lm_stat : float
            Lagrange multiplier statistic, distributed as chisquare
        p_value : float
            p-value for the Lagrange multiplier test. If p_value is below a threshold
            often 0.05, then we can reject the Null hypothesis of homoscedasticity
            at that size.
        more asymptotically equivalent results
    
        Notes
        -----
        A binary model has a variance that is completely specified by the mean.
        The variance of the observed variable cannot be misspecified separately from
        the mean. Misspecification in the variance function of the underlying latent
        variable is equivalent to a misspecification of the functional form.
        The alternative hypothesis for the variance of the latent variable
        is `exp(Z gamma)`, which implies a mean function ::
    
           `exp(Z gamma) * X beta` instead of just `X beta`.
    
        References
        ----------
        Greene 5th edt
        Wooldridge 2nd edt
    
        '''
        
        res = results
        z = exog_var
        if z.ndim == 1:
            z = z[:, None]
    
        xb = res.predict(linear=True)
    
        orthvar = np.column_stack((res.model.exog, -xb[:,None] * z))
        scores = res.resid_generalized[:, None] * orthvar
    
        score_sum = scores.sum(0)
        
        # version 1: uses OPG variance, based on Greene
        # I cannot get directly the Hessian from the results to replace OPG
        cov = np.dot(scores.T, scores)
        cov_inv = np.linalg.pinv(cov)
        lm_stat = np.dot(score_sum, np.dot(cov_inv, score_sum[:,None]))
        
        pvalue = stats.chi2.sf(lm_stat, z.shape[1])
    
        # version 2: just a different way of calculating version 1
        res_olslm2 = sm.OLS(np.ones(len(scores)), scores).fit()
        lm_stat2 = res.nobs * (1 - res_olslm2.ssr / res_olslm2.uncentered_tss)
        pvalue2 = stats.chi2.sf(lm_stat2, z.shape[1])
    
        # description in Greene is a bit vague, this might be something different
    ##    # version 2 #Logit only, doesn't match so well with version 1? Greene 5th 
    ##    res_olslm = sm.OLS(res.model.endog - res.model.endog.mean(), orthvar).fit()
    ##    lm_stat3 = res.nobs * (1 - res_olslm.ssr / res_olslm.uncentered_tss)
    ##    pvalue3 = stats.chi2.sf(lm_stat3, z.shape[1])
    
    
        # version based on Wooldridge 2010, section 15.5.3
        pdfi = res.model.pdf(xb)
        ex = pdfi[:, None] * orthvar
        fitted_prob = res.predict()
        res_wlslm = sm.WLS(res.model.endog - fitted_prob, ex,
                           weights=1. / (fitted_prob * (1 - fitted_prob))).fit()
        #lm_statr = res.nobs * (1 - res_wlslm.ssr / res_wlslm.uncentered_tss)
        lm_statr = res.nobs * res_wlslm.rsquared  # rsquared looks correct
        pvaluer = stats.chi2.sf(lm_statr, z.shape[1])
    
        # cross check with OLS with weighted variables
        std = np.sqrt(fitted_prob * (1 - fitted_prob))
        # endog in the following is just resid_pearson
        res_olslm4 = sm.OLS((res.model.endog - fitted_prob) / std, ex / std[:,None]).fit()
        lm_stat4 = res.nobs * (1 - res_olslm4.ssr / res_olslm4.uncentered_tss)
        pvalue4 = stats.chi2.sf(lm_stat4, z.shape[1])
    
        # augmented variable test with Wald test
        model_class = res.model.__class__
        start_params = np.concatenate((res.params, [0]))
        res_aug = model_class(res.model.endog, orthvar).fit(start_params=start_params)
        R = np.zeros((1, len(res_aug.params)))
        R = np.eye(len(res_aug.params))[-z.shape[1]:]
        tres_wald = res_aug.wald_test(R)
        #tres_wald.statistic, tres_wald.pvalue
    
    
        # version 1b: with Hessian instead of OPG, based on Greene 
        # not sure if this is correct
        # this is based on Hessian with new parameters
        cov_inv = res_aug.cov_params()  
        # get Hessian under Null
        params_null = np.concatenate((res.params, [0] * z.shape[1]))
        cov_inv = -np.linalg.pinv(res_aug.model.hessian(params_null))
        lm_stat5 = np.dot(score_sum, np.dot(cov_inv, score_sum[:,None]))
        pvalue5 = stats.chi2.sf(lm_stat5, z.shape[1])
    
        
        return (lm_stat, pvalue, lm_stat5, pvalue5, lm_stat2, pvalue2,
                lm_statr, pvaluer, lm_stat4, pvalue4,
                tres_wald.statistic, tres_wald.pvalue)
        
    
    
    res = logit_res
    
    z = spector_data.exog[:,2:3]
    
    xb = res.predict(linear=True)
    
    orthvar = np.column_stack((res.model.exog, -xb[:,None] * z))
    
    scores = res.resid_generalized[:, None] * orthvar
    
    score_sum = scores.sum(0)
    cov = np.dot(scores.T, scores)
    lm_stat = np.dot(score_sum, np.dot(cov, score_sum[:,None]))
    from scipy import stats
    pvalue = stats.chi2.sf(lm_stat, z.shape[1])
    print(lm_stat, pvalue)
    print("het_binary(res, z)")
    print(het_binary(res, z))
    
    res_olslm = sm.OLS(res.model.endog - res.model.endog.mean(), orthvar).fit()
    print(res_olslm.rsquared)
    print(1 - res_olslm.ssr/res_olslm.uncentered_tss)
    
    
    # example LR test for splitting on binary explanatory variable
    mask = np.squeeze(z == 0)#[:,None]
    cols = np.arange(4) != 2
    ex = spector_data.exog[:, cols]
    #res0 = sm.Logit(spector_data.endog[~mask], spector_data.exog[~mask[:,None], cols]).fit()
    #res1 = sm.Logit(spector_data.endog[mask], spector_data.exog[mask[:,None], cols]).fit()
    res0 = sm.Logit(spector_data.endog[~mask], ex[~mask, :]).fit()
    res1 = sm.Logit(spector_data.endog[mask], ex[mask, :]).fit()
    
    
    exog_interact = np.column_stack((ex * (1-z), ex * z))
    res_i = sm.Logit(spector_data.endog, exog_interact).fit()
    
    print(res.params)
    print(res0.params)
    print(res1.params)
    print(res_i.params[:3])
    print(res_i.params[3:])
    # same as compare_lr which is not available yet for LikelihoodModels
    LR = -2 * (res.llf - res_i.llf)
    LR_pvalue = stats.chi2.sf(LR, len(res_i.params) - len(res.params))
    print('LR test for split')
    print(LR, LR_pvalue)
    
    #Wald test for testing that binary explanatory variable has no effect
    # Note: we only have interaction effect not the linear effect
    R = np.column_stack((np.eye(3), -np.eye(3)))
    print('Wald test for equality of coefficients in split')
    print(res_i.f_test(R))
    
    print('\nhet_binary')
    rr = het_binary(res, z)
    print(np.asarray(list(map(np.ravel, rr))).reshape(-1, 2))
    
    
  4. josef-pkt commented on Dec 3, 2018

    @josef-pkt
    MemberAuthor

    related reference (just found by chance again, I don't remember)

    looks good, some functions to be implemented, most likely directly generalized to all binary response models.

    Yatchew, Adonis, and Zvi Griliches. 1985. “Specification Error in Probit Models.” The Review of Economics and Statistics 67 (1): 134–39. https://doi.org/10.2307/1928444.

  5. added this to the 0.11 milestone on Dec 3, 2018
  6. modified the milestones: 0.11, josef on Oct 5, 2019
  7. josef-pkt commented on Jan 2, 2020

    @josef-pkt
    MemberAuthor

    related issue: omitted variable bias in Logit even if explanatory variables are uncorrelated
    https://stats.stackexchange.com/questions/113766/omitted-variable-bias-in-logistic-regression-vs-omitted-variable-bias-in-ordina

    quick read: omitted variable produces unobserved heterogeneity which also affects the mean parameter interpretation, ie. attentuation bias compared to including uncorrelated omitted variable.

    This might come back to that heteroscedasticity is observationally equivalent to misspecified mean function. I didn't check the details now.
    Can we provide specification tests based on this, e.g. if we have candidate explanatory variables of omitted mean variables or heteroscedasticity?

  8. josef-pkt commented on Oct 16, 2022

    @josef-pkt
    MemberAuthor

    bump

    orthvar = np.column_stack((res.model.exog, -xb[:,None] * z))

    I can derive this as a variable addition test using first order taylor series expansion of the nonlinearity.

    with current status of statsmodels we can implement this using variable addition score_test in GLM and discrete,
    or use a variable addition wald test tres_wald) in above experimental code.
    in analogy to reset test, i.e. here we interact linpred with other explanatory variables (that might explain heteroscedasticity of latent variable) instead of using polynomial of linpred as in standard reset test.

    see also #2179 (comment)

  9. modified the milestones: josef, 0.15 on Oct 16, 2022
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