Skip to content

diagnostic: link test - nonlinearity test for many model  #1479

Open

Description

@josef-pkt

see Stata 'r.pdf' manual

estimate y with exog_test = (fittedvalues, fittedvalues**2)
reject correct specification if fittedvalues**2 is significant

there might be something similar for OLS already, but Stata's link test works for discrete models, e.g. after Logit.
For example for Logit we have to run a Logit(endog, exog_test).fit(...) again.
(do we have all information to run model and fit with the same options again?)

if rejected: either some missing non-linearities in the explanatory variables or incorrectly specified link function

edit don't use fittedvalues, use predict(linear=True), fittedvalues should be refactored to return the transformed, expected mean or estimated mean function E(y|x).

Activity

  1. jseabold commented on Mar 15, 2014

    @jseabold
    Member

    You should be able to re-run all models with results.mle_settings, if we need to. I found one example in tsa recently where it wasn't correctly attached, but it's fixed now. If it's not there, it's a bug.

  2. josef-pkt commented on Mar 15, 2014

    @josef-pkt
    MemberAuthor

    we need also the extra args or kwds for the Model.__init__ to write generic code.
    eg. Poisson init_extra_args = ['offset', 'exposure'] or weights and sigma in WLS, GLS.
    and more in GLM, RLM.

    my_results.model.__class__.__init__(endog, exog, **init_extra_kwds)
    instead of checking the model class and conditional
    if isinstance(my_results.model, sm.Poisson): ...

    might be needed also for pairs bootstrap and for multiple imputation

  3. added this to the 0.10 milestone on Jun 4, 2017
  4. josef-pkt commented on Jun 7, 2018

    @josef-pkt
    MemberAuthor

    bump for 0.10
    this is now a two linear using score_test, after #4716
    https://gist.github.com/josef-pkt/f20abdbd360c2e549f73e98844f5d2c4

    parking a reference
    Ramalho, Esmeralda A., and Joaquim J. S. Ramalho. 2012. “Alternative Versions of the RESET Test for Binary Response Index Models: A Comparative Study*.” Oxford Bulletin of Economics and Statistics 74 (1): 107–30. https://doi.org/10.1111/j.1468-0084.2011.00654.x.

    This article includes several LM test for misspecification in binary models implemented as variable addition LM tests using artificial regression following Davidson MacKinnon and Wooldridge.
    I have those separately in diagnostics_other, but we can directly use the score_test that uses the hessian and not a OPG approximation.
    They have a table about the exog_extra that need to be added for the different tests.
    For most of them there should be an analogue for other GLM families, with some differences, e.g. heteroscedasticity in binary models is the same as a non-linear misspecification, while in non-binary models we can separate nonlinearity from heteroscedasticity.
    (I don't remember a reference right now for the general GLM case.)

    about the API: I would like a GLMResults method like score_test_diagnostic that combines several test implemented as variable addition score tests, i.e. constructs the exog_extra and delegates to score_test.
    To have this attached to the Results class, we would need to have a version that computes the same tests for most models. Only RESET test might be possible to get started.
    Or we list in the docstring the tests that are available for each family.
    Otherwise, I will start a statsmodels.stats.diagnostics_glm with standalone functions that can be added later, and be reused in discrete.

    One issue, my guess is that we want to separate mean tests (i.e. variable addition to the mean function) from other specification tests, e.g. on second moments, heteroscedasticity/dispersion and correlation. Those require a different "endog", e.g. squared (pearson) residuals.

    name for option is unclear
    results.score_test_diagnostic(test="reset", **kwds)
    or "kind" instead of "test"
    and kwds would have two parts, keywords for the construction of exog_extra, e.g. order in RESET test, and keywords for the score_test, e.g. "cov_type" and "observed"
    If we use **kwds, then we need to separate them internally. Or we use test_kwds requiring a dict.

  5. josef-pkt commented on Jun 7, 2018

    @josef-pkt
    MemberAuthor

    related article by mostly the same authors.
    I just saw it next to the other article, but AFAIR I didn't read this one.

    Ramalho, Esmeralda A., Joaquim J. S. Ramalho, and José M. R. Murteira. 2014. “A Generalized Goodness-of-Functional Form Test for Binary and Fractional Regression Models.” The Manchester School 82 (4): 488–507. https://doi.org/10.1111/manc.12032.

  6. josef-pkt commented on Jun 7, 2018

    @josef-pkt
    MemberAuthor

    another reference found in my pile of glm diagnostic papers

    Canary, Jana D., Leigh Blizzard, Ronald P. Barry, David W. Hosmer, and Stephen J. Quinn. 2016. “Summary Goodness-of-Fit Statistics for Binary Generalized Linear Models with Noncanonical Link Functions.” Biometrical Journal 58 (3): 674–90. https://doi.org/10.1002/bimj.201400079.

    Based on my notes when I read this, it just adds group dummies to the added variable test, where groups are defined by binning exog or predicted values. It might be a bit more complicated than that.
    According to my notes, Tsiatis takes the full EIM in the score test, the other two tests take short cuts and are not full score_tests, i.e. ignore some correlation.

    My guess is that this now takes 5 lines to implement as score test.

    Aside about binary models: If nonlinearity and heteroscedasticity are the same/indistinguishable in binary models, then what happens if we use cov_type='HC0' in the score test?
    (I guess we might still have interpretation in terms of specific functional forms.)

  7. modified the milestones: 0.10, 0.11 on Dec 3, 2018
  8. stevenlis commented on Feb 20, 2019

    @stevenlis

    According to the Stata doc on page 3, a linktest for a OLS is just :

    regress [endog] on the prediction and the prediction squared

    Example for SM:

    import pandas as pd
    import seaborn as sns
    import statsmodels.formula.api as smf
    # loading dataset
    df = sns.load_dataset('tips')
    # regression
    formula = 'tip ~ total_bill + size'
    results = smf.ols(formula, data=df).fit()
    # getting prediction and prediction squared
    df['_hat'] = results.predict()
    df['_hatsq'] = results.predict()**2
    # link test
    formula = 'tip ~ _hat + _hatsq'
    link_test = smf.ols(formula, data=df).fit()
    link_test.summary()
    OLS Regression Results                            
    ==============================================================================
    Dep. Variable:                    tip   R-squared:                       0.468
    Model:                            OLS   Adj. R-squared:                  0.464
    Method:                 Least Squares   F-statistic:                     106.0
    Date:                Wed, 20 Feb 2019   Prob (F-statistic):           9.35e-34
    Time:                        15:26:14   Log-Likelihood:                -347.95
    No. Observations:                 244   AIC:                             701.9
    Df Residuals:                     241   BIC:                             712.4
    Df Model:                           2                                         
    Covariance Type:            nonrobust                                         
    ==============================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
    ------------------------------------------------------------------------------
    Intercept      0.1571      0.650      0.242      0.809      -1.122       1.437
    _hat           0.9011      0.392      2.301      0.022       0.130       1.673
    _hatsq         0.0141      0.055      0.256      0.798      -0.094       0.122
    ==============================================================================
    Omnibus:                       23.336   Durbin-Watson:                   2.107
    Prob(Omnibus):                  0.000   Jarque-Bera (JB):               42.122
    Skew:                           0.527   Prob(JB):                     7.13e-10
    Kurtosis:                       4.741   Cond. No.                         144.
    ==============================================================================
    
    Warnings:
    [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
    

    From Stata:

    // regression
    qui reg tip total_bill siz
    // link test
    linktest
    
          Source |       SS           df       MS      Number of obs   =       244
    -------------+----------------------------------   F(2, 241)       =    106.01
           Model |  217.726133         2  108.863067   Prob > F        =    0.0000
        Residual |  247.486344       241  1.02691429   R-squared       =    0.4680
    -------------+----------------------------------   Adj R-squared   =    0.4636
           Total |  465.212477       243  1.91445464   Root MSE        =    1.0134
    
    ------------------------------------------------------------------------------
             tip |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
    -------------+----------------------------------------------------------------
            _hat |   .9011381   .3917015     2.30   0.022     .1295426    1.672734
          _hatsq |   .0141033    .055013     0.26   0.798    -.0942643    .1224709
           _cons |   .1570506   .6495479     0.24   0.809    -1.122465    1.436567
    ------------------------------------------------------------------------------
    
    
  9. mina1987 commented on Apr 9, 2019

    @mina1987

    see Stata 'r.pdf' manual

    estimate y with exog_test = (fittedvalues, fittedvalues**2)
    reject correct specification if fittedvalues**2 is significant

    there might be something similar for OLS already, but Stata's link test works for discrete models, e.g. after Logit.
    For example for Logit we have to run a Logit(endog, exog_test).fit(...) again.
    (do we have all information to run model and fit with the same options again?)

    if rejected: either some missing non-linearities in the explanatory variables or incorrectly specified link function

    edit don't use fittedvalues, use predict(linear=True), fittedvalues should be refactored to return the transformed, expected mean or estimated mean function E(y|x).

    I am trying to contribute to this issue but having trouble figuring out what needs to be done. Is it about a linktest for GLM that takes model as an argument?

  10. josef-pkt commented on Apr 9, 2019

    @josef-pkt
    MemberAuthor

    look at https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/outliers_influence.py#L102

    Essentially we need the same thing for other models than OLS.
    The call to OLS needs to be replace by a GLM model. The extra keywords that the user used when creating the model like offset, exposure and weights in the GLM case are available in the _init_kwds attribute. There should be some examples for the creation of a new GLM model in the statsmodels source, but I don't remember where.

  11. modified the milestones: 0.11, josef on Oct 5, 2019
  12. josef-pkt commented on Oct 30, 2023

    @josef-pkt
    MemberAuthor

    bouncing around topics

    based on the canary et al article, tsiatis is a proper CMT, score_test for variable addition of dummy variables for bins of predictions or regressors, i.e. score_obs + added variable score_obs,
    (note we can do it now also with robust cov)

    related issues for reset test, e.g. #3690

    Canary, Jana D., Leigh Blizzard, Ronald P. Barry, David W. Hosmer, and Stephen J. Quinn. “A Comparison of the Hosmer–Lemeshow, Pigeon–Heyse, and Tsiatis Goodness-of-Fit Tests for Binary Logistic Regression under Two Grouping Methods.” Communications in Statistics - Simulation and Computation 46, no. 3 (March 16, 2017): 1871–94. https://doi.org/10.1080/03610918.2015.1017583.

    TSIATIS, ANASTASIOS A. “A Note on a Goodness-of-Fit Test for the Logistic Regression Model.” Biometrika 67, no. 1 (January 1, 1980): 250–51. https://doi.org/10.1093/biomet/67.1.250.

  13. josef-pkt commented on Dec 23, 2023

    @josef-pkt
    MemberAuthor

    issue #9103 rainbow test with mahalanobis central observations

    same idea can be applied to reset or variable addition test, i.e. break variable addition into 3 sets lower tail, center, upper tail observation based on mahalanobis distance of exog and we could compare with the same break based on ordering by fitted values.

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