Skip to content

ENH: add GLMInfluence - #4732

Merged
josef-pkt merged 16 commits into
statsmodels:masterfrom
josef-pkt:influence_glm_wls
Jun 21, 2018
Merged

josef-pkt merged 16 commits into
statsmodels:masterfrom
josef-pkt:influence_glm_wls

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Jun 9, 2018 •

Copy link
Copy Markdown
Member

see #4268 and #4257

just getting started to figure out what the structure should be and if we can reuse code from OLSInfluence.

Note: SAS logistic has two differences in an example printout, compared to OLSInfluence, My results agree if I correct for different definitions.

  • dfbeta: SAS prints out "dfbetas" standardized by dividing by bse
  • cooks distance: SAS "C" = k_vars * "my_cooksd", OLDInfluence divides by k_vars

short cuts, not working yet.
OLSInfluence external standardization and some other methods use explicit LOOO loops.
I faked them or skipped them for now, summary_frame has fewer columns than in OLSInfluence.
We should use only one step approximations by default.

@josef-pkt josef-pkt added this to the 0.10 milestone Jun 9, 2018
@josef-pkt

Copy link
Copy Markdown
Member Author

aside: It would be faster to write GLMInfluence by just translating formulas to code, but I'd like to figure out the generic pattern, so it will be easier to extend.
e.g. some of these expressions just look like a score test statistic for an observation dummy as added variable.
Additionally, I would like to get the leave-one-out and the local influence function approaches.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging 9f20b51 into 9913b6a - view on LGTM.com

new alerts:

  • 1 for Missing call to __init__ during object initialization

Comment posted by LGTM.com

@josef-pkt

Copy link
Copy Markdown
Member Author

The idea for keeping and fixing a LOOO loop is that we want to check the computation for selected observations, e.g. if we have influential or outlier candidates from the one-step approximation.
But there shouldn't be a reason to use the LOOO loop on all observations.

@josef-pkt

josef-pkt commented Jun 10, 2018 •

Copy link
Copy Markdown
Member Author

all red, I forget to revert a change mse_resid -> scale, that I ha d tried out for consistency between OLS and GLM, but it didn't work (at least in my simple tries) see #4733

test errors are in
statsmodels/stats/tests/test_diagnostic.py
statsmodels/graphics/tests/test_regressionplots.py

The problem is in recreating models and getting results in the explicit LOOO loop.

@josef-pkt

Copy link
Copy Markdown
Member Author

There are some things that are specific to GLM that needs a model specific subclass, mainly related to deviance.
e.g. SAS has separate delta_chisquare and delta_deviance in LOGISTIC, while Cooks D is derived as delta loglike. SAS LOGISTIC has cooks d (without k_vars normalization) as "confidence interval displacement" with "C" and "Cbar" as short cut names.
(I only have one printed table, so I don't know other numbers that SAS might provide.)

@josef-pkt

josef-pkt commented Jun 10, 2018 •

Copy link
Copy Markdown
Member Author

a quick try: MLE Newton updating versus IRLS based dparams

explicit LOOO, results for res_m0, res_m3
observation 0 has small effect
observation 3 has large effect

one Newton step underestimates changes (values in db and db_oim)
IRLS (one Fisher step) based dfbeta are closer to actual change in params but also underestimate effect of influential observation. (Some reference mentioned that behavior.)

>>> res.params.values
array([-2.87542171,  4.56167528,  5.17932402])
>>> res_m0.params.values
array([-2.85447069,  4.52741088,  5.07764814])
>>> res_m3.params.values
array([-5.20630743,  7.45498052,  8.46776565])

>>> (res.params - res_m0.params).values
array([-0.02095102,  0.03426439,  0.10167588])

>>> (res.params - res_m3.params).values
array([ 2.33088572, -2.89330524, -3.28844163])

db[:5]
array([[-0.01971875,  0.03215933,  0.09408063],
       [-0.01689695,  0.02647911,  0.0465373 ],
       [-0.06094644,  0.1138461 ,  0.10319132],
       [ 1.29470879, -1.56139189, -1.73365981],
       [-0.0971353 ,  0.22936964,  0.09606848]])

>>> db_oim[:5]
array([[-0.01971875,  0.03215933,  0.09408063],
       [-0.01689695,  0.02647911,  0.0465373 ],
       [-0.06094644,  0.1138461 ,  0.10319132],
       [ 1.29470879, -1.56139189, -1.73365981],
       [-0.0971353 ,  0.22936964,  0.09606848]])

>>> infl.dfbetas[:5]
array([[-0.02173285,  0.03544414,  0.1036902 ],
       [-0.0176544 ,  0.0276661 ,  0.04862345],
       [-0.06491749,  0.1212639 ,  0.1099149 ],
       [ 1.41768538, -1.7096991 , -1.89832971],
       [-0.10986189,  0.25942146,  0.10865529]])

results_sas[:5, 6:9] * res.bse.values
array([[-0.02179309,  0.03547323,  0.10368564],
       [-0.01769863,  0.02775366,  0.04867257],
       [-0.06498303,  0.12130741,  0.10983964],
       [ 1.41773949, -1.70969924, -1.89841691],
       [-0.10989   ,  0.25934053,  0.10872073]])

@josef-pkt
josef-pkt force-pushed the influence_glm_wls branch from 9f20b51 to e0e4040 Compare June 12, 2018 17:46
@josef-pkt

Copy link
Copy Markdown
Member Author

amended first commit with undoing mse_resid -> scale change that failed

unit tests against SAS, but I'm using different definitions, inherited from OLSInfluence, and don't have Cbar yet.

    assert_allclose(infl.dfbetas, results_sas[:, 5:8] * res.bse.values, atol=1e-4)
    assert_allclose(infl.cooks_distance[0] * k_vars, results_sas[:, 8], atol=6e-5)
    assert_allclose(infl.hat_matrix_diag, results_sas[:, 4], atol=6e-5)

    c_bar = infl.cooks_distance[0] * k_vars * (1 - infl.hat_matrix_diag)
    assert_allclose(c_bar, results_sas[:, 9], atol=6e-5)

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging e0e4040 into 3c2ea25 - view on LGTM.com

new alerts:

  • 1 for Missing call to __init__ during object initialization

Comment posted by LGTM.com

@coveralls

coveralls commented Jun 12, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.01%) to 83.538% when pulling d8dcabe on josef-pkt:influence_glm_wls into c6f5f67 on statsmodels:master.

@codecov-io

codecov-io commented Jun 12, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #4732 into master will increase coverage by 0.04%.
The diff coverage is 90.99%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4732      +/-   ##
==========================================
+ Coverage   81.01%   81.05%   +0.04%     
==========================================
  Files         578      579       +1     
  Lines       89103    89489     +386     
  Branches     9942     9967      +25     
==========================================
+ Hits        72183    72536     +353     
- Misses      14657    14681      +24     
- Partials     2263     2272       +9
Impacted Files Coverage Δ
statsmodels/stats/tests/test_diagnostic.py 91.83% <100%> (+0.06%) ⬆️
statsmodels/graphics/_regressionplots_doc.py 100% <100%> (ø) ⬆️
statsmodels/graphics/regressionplots.py 81.25% <100%> (+1.01%) ⬆️
statsmodels/stats/outliers_influence.py 81.53% <84%> (+1.73%) ⬆️
statsmodels/genmod/generalized_linear_model.py 90.7% <96.55%> (+0.33%) ⬆️
statsmodels/stats/tests/test_influence.py 97.46% <97.46%> (ø)
statsmodels/stats/descriptivestats.py 24.13% <0%> (ø) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update c6f5f67...d8dcabe. Read the comment docs.

@josef-pkt

Copy link
Copy Markdown
Member Author

all green,
computation look fine against SAS

R reports dffit and and cov_ratio (?) for glm, which I can add to the unit tests (inherited from OLSInfluence)
https://rdrr.io/r/stats/influence.measures.html
e.g. for William's binomial example

> imI <- influence.measures(glmI)
>  imI 
Influence measures of
         glm(formula = cbind(yi, mi - yi) ~ xi, family = binomial) :

    dfb.1_  dfb.xi  dffit cov.r cook.d   hat inf
1 -0.81080  0.7561 -0.815 0.801 0.2522 0.259    
2 -0.47926  0.4205 -0.500 2.427 0.2611 0.370    
3  1.29804 -0.9219  1.739 0.246 1.2899 0.354   *
4  0.00388 -0.0727 -0.246 3.357 0.0845 0.389   *
5  0.29253 -0.3982 -0.511 5.213 0.3636 0.628   *

The more difficult part is to come up with an API and inheritance structure, and specifically which variants of the influence measures to add as attributes and to cache, e.g. standardized dfbeta, variants of cooks distance.

right now I should be able to get

  • OLS
  • GLM and the corresponding classes in discrete; Logit, Poisson for the canonical case, Probit for non-canonical link and Gaussian for scale handling.
  • WLS ? should be trivial but no test case yet, i.e. does Stata or R have it?

not clear yet what will become available for

  • general MLE, e.g. negative binomial, zero-inflated count models and generic mle
  • OLS-Ridge i.e TheilGLS for OLS not GLS case. At least there are formulas for it in references
  • ...

It's not clear to me what is the common denominator, i.e. what can we put into a superclass that the model specific Influence classes inherit.

Not clear either is how to handle nonrobust cov_type.

Refactoring: make delete obs i loop, _res_looo, generic and limit to provided indices. Most likely not in this PR.

@josef-pkt

Copy link
Copy Markdown
Member Author

detail: last IRLS WLS weights are one iteration step behind using hessian_factor based on final params.
Difference in example is around 1e-5 AFAIR, and I need to account for it in unit tests.
GLMInfluence uses hessian_factor for the weights and not the weights in the final irls step.

@josef-pkt

Copy link
Copy Markdown
Member Author

reusing regressionplots

this works for GLM now, without changes

>>> import statsmodels.graphics.regressionplots as inflplot
>>> inflplot.influence_plot(res)

this doesn't, and needs resid options:

>>> inflplot.plot_leverage_resid2(res)
  File "...\statsmodels\graphics\regressionplots.py", line 849, in plot_leverage_resid2
    resid = zscore(results.resid)
  File "...\statsmodels\base\wrapper.py", line 35, in __getattribute__
    obj = getattr(results, attr)
AttributeError: 'GLMResults' object has no attribute 'resid'

@josef-pkt

Copy link
Copy Markdown
Member Author

I finally read Cook and Weisberg chapter 5 on "other problems", i.e. not linear regression.
It has the MLE version similar to the newer articles, and a section on GLM and a section on nonlinear least squares.
In the GLM section they make the link to the MLE version which sound to be equivalent, but they don't produce the same numbers in my experimental computation. My only guess is that there is a approximation at the one step away from the full sample MLE instead of using the approximation at the full sample MLE. (equ 5.4.4. which I didn't try to understand in detail.)

@josef-pkt

Copy link
Copy Markdown
Member Author

dfbeta in R influence.measures sounds wrong.
I'm not able to figure out what they do, and the values are far away from the explicit LOOO loop, while mine are close to those.
The example is glm Binomial counts from William's article which is in the R influence measure docstring.

one observation they use weighted residuals from the model which is resid_deviance, while I use the explicit formulas for GLM using resid_pearson.

my and R's dffits also differs but I haven't looked yet what the version inherited from OLSInfluence actually does.
computation based on standardized resid_pearson is trivial
dffits_ = self.resid_studentized_external * np.sqrt(hii / (1 - hii))
but I don't know of a way yet to verify this. The references don't mention dffits explicitly or by that name.

@josef-pkt

Copy link
Copy Markdown
Member Author

one possible naming convention
dxxx for one step approx
delta_xxx for explicit loo differences

or post fix _looo

not clear API w.r.t. options

  • set options when calling get_influence, and then use (cached) attributes, or
  • use methods in influence classes with options

also naming for scaled or studentized variants if separate attributes, e.g. dfbeta dfbetas

also should we wrap individual attributes as pandas Series?
Currently we have summary_frame with fixed columns, i.e. no choice what columns to add.
This becomes more relevant if we have several variants of each measure, and default summary_frame has only a small number.
Add row_labels as attribute, so users can wrap by themselves.
or add option return_type with numpy and pandas option, which only works for methods.
We need numpy arrays internally, given that I don't want to do any computation with pandas.

Also, I want to add an unscaled or optionally scaled d_fitted or d_predict with linear=False/True option in analogy to dffits. (Neither R's dffits nor my inherited dffits seem to be close to delta_predict in the binomial count example. So I want to have a different name for the actual thing.)

@josef-pkt

Copy link
Copy Markdown
Member Author

cov_type for influence
get_prediction standard errors are only available for the cov_type specified in fit.
The hessian would always be available if cov_type is robust in fit, but nonrobust in influence.

simplest possibility: cov_type in influence is always the same as cov_type in fit. The users need to refit with a different cov_type to get influence with a different cov_type. That's one extra step compared to using results.get_influence(cov_type = ...).

backwards compatibility: OLSInfluence is currently completely cov_type='nonrobust'.

Do any current users actually care about this?

If the only problem is the standard error of predicted mean (fittedvalues), then it's just one line to compute it with the nonrobust cov_type.

@josef-pkt

josef-pkt commented Jun 15, 2018 •

Copy link
Copy Markdown
Member Author

I need a generic function for influence_plot, plot_leverage_resid2 and similar that takes already computed values,
i.e. scatter plot + annotation for selected indices + optional size of scatter points

do we have an index plot with annotation for selected indices?

@josef-pkt

josef-pkt commented Jun 17, 2018 •

Copy link
Copy Markdown
Member Author

another naming issue: postfix: _scaled, _standardized, _studentized

The literature has several names for resid_studentized, OLSInfluence uses resid_studentized_internal and resid_studentized_external.

I now have d_fittedvalues_studentized and d_linpred_studentized for GLMInfluence which in analogy to dffits divides by prediction standard error. However, I just realized that this is a misnomer because studentizing also means removing the mean, i.e. z-scoring in this case using model implied mean and variance.

dfbetas is dfbeta plus "scaled" by bse in the literature, i.e. it should be d_params_scaled.

aside: The distribution of resid is messy in general, because it contains endog y, which has the randomness in the response and is correlated with the estimate of beta and predict. Cook Weisberg have some discussion in chapter 5 for generalized residuals.
The distribution/standard error of predict is easy, i.e. what we have in get_prediction for GLM and linear models (or linear index models in general).

edit maybe studentized wouldn't be a misnomer, i.e. not if dfxxx/d_xxx has expected value of zero, which might be the case in many cases, but most likely not for some non-linear functions like predicted response in GLM and discrete models.

@josef-pkt

Copy link
Copy Markdown
Member Author

In my notebook for development, the main method that doesn't exist anymore in GLMInfluence is cov_ratio based on the res_looo loop.

I think it's time and a reasonable place to stop.
The basics are done, although there are still many things that can be added, but that should be easier now.

Still needs some cleanup and reviewing of docstrings.

@josef-pkt
josef-pkt force-pushed the influence_glm_wls branch from ea58cbc to 3200fb3 Compare June 20, 2018 21:06
@josef-pkt

Copy link
Copy Markdown
Member Author

My mistake, I only ran some test classes locally
summary_frame in MLE/GLMInfluence differs from the one in OLSInfluence, OLSInfluence summary_frame has more columns
amended and force pushed

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging 3200fb3 into 65312bb - view on LGTM.com

new alerts:

  • 1 for Missing call to __init__ during object initialization
  • 1 for Variable defined multiple times

Comment posted by LGTM.com

@josef-pkt

josef-pkt commented Jun 21, 2018 •

Copy link
Copy Markdown
Member Author

looking at coverage: https://coveralls.io/builds/17600536/source?filename=statsmodels%2Fstats%2Foutliers_influence.py#L190

  • the top level Mixin still has resid_studentized and cooks_distance which are not used anymore, because I moved them back into OLS and GLM Influence
  • several of the index plot options are not used in the unit tests
  • GLMInfluence uses the rewritten inherited d_fittedvalues, because I moved it to MLE but didn't keep the original GLM specific (inverse link) version. d_linpred is now not used anymore, and so not unit tested. With linear link, OLS testcase, d_linpred and d_fittedvalues will be the same.
  • GLMInfluence has sigma2_not_obsi which was used by methods that were before inherited by OLSInfluenc. No it's unused and has a non-future proof name.
  • GLMInfluence has it's own __init__ and doesn't use the inherited __init__
  • GLMInfluence has no test case for offset or exposure
  • MLEInfluence itself has full coverage (in terms of lines) except for caller provided hat_matrix_diag.
  • OLSInfluence has still auxiliary, experimental methods without test coverage, which doesn't change in this PR.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging fa2499e into 65312bb - view on LGTM.com

new alerts:

  • 1 for Variable defined multiple times

Comment posted by LGTM.com

@josef-pkt

Copy link
Copy Markdown
Member Author

another test case: Binomial count from Williams article and R docs
n_trials is the same across cases, so it's not general.

I needed to lower test precision a bit comparing GLM versus MLE, but rtol and atol are still around 1e-7 or 5e-9, cooks_distance has only rtol=5e-5. This uses the same results instance, so it's not affected by convergence tolerance in fit. (That's still much closer than what would make a meaningful difference in interpretations.)

@josef-pkt

Copy link
Copy Markdown
Member Author

BUG: LGTM finds a hardcoded external in the call to plot_influence, ignores keyword.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging 66af430 into 65312bb - view on LGTM.com

new alerts:

  • 1 for Variable defined multiple times

Comment posted by LGTM.com

@josef-pkt
josef-pkt force-pushed the influence_glm_wls branch from 66af430 to 1b128ca Compare June 21, 2018 03:16
@josef-pkt

Copy link
Copy Markdown
Member Author

LOOO:
Currently _res_looo is a cached attribute, so we cannot add options for computing only for selected indices.
One possible design is to force user to explicitly call a looo method to make the _res_looo results available.
If we keep track of indices_looo, then we can get the corresponding observation labels or pandas index, and we could add xxx_looo methods that don't cache but use _res_looo results for computation.
To avoid repeated computation users can get summary_frame_looo. However, without caching, separate methods for the individual statistics would do repeated computation. i.e. we need to pool the main computation in one method.

@josef-pkt

Copy link
Copy Markdown
Member Author

parking some initial code that is still in a test function but I will delete the unused parts.
The code is for comparing GLM Logit with discrete Logit and checks OIM versus EIM versus WLS/IRLS.

def test_influence_glm_bernoulli():

    df = data_bin
    results_sas = np.asarray(results_sas_df)

    res = Logit(df['constrict'], df[['const', 'log_rate', 'log_volumne']]).fit()
    print(res.summary())

    res = GLM(df['constrict'], df[['const', 'log_rate', 'log_volumne']],
              family=families.Binomial()).fit(attach_wls=True, atol=1e-10)
    print(res.summary())

    wexog = res.results_wls.model.wexog
    pinv_wexog = res.results_wls.model.pinv_wexog
    hat_diag = (wexog * pinv_wexog.T).sum(1)

    infl = res.get_influence(observed=False)

    mask = np.ones(len(df), np.bool_)
    mask[3] = False
    df_m3 = df[mask]
    res_m3 = GLM(df_m3['constrict'], df_m3[['const', 'log_rate', 'log_volumne']],
                 family=families.Binomial()).fit(attach_wls=True, atol=1e-10)

    mask = np.ones(len(df), np.bool_)
    mask[0] = False
    df_m0 = df[mask]
    res_m0 = GLM(df_m0['constrict'], df_m0[['const', 'log_rate', 'log_volumne']],
                 family=families.Binomial()).fit(attach_wls=True, atol=1e-10)

    hess = res.model.hessian(res.params, observed=False)
    score_obs = res.model.score_obs(res.params)
    cd = (score_obs * np.linalg.solve(-hess, score_obs.T).T).sum(1)
    db = np.linalg.solve(-hess, score_obs.T).T
    hess_oim = res.model.hessian(res.params, observed=True)
    db_oim = np.linalg.solve(-hess_oim, score_obs.T).T



    k_vars = 3
    assert_allclose(infl.dfbetas, results_sas[:, 5:8], atol=1e-4)
    assert_allclose(infl.d_params, results_sas[:, 5:8] * res.bse.values, atol=1e-4)
    assert_allclose(infl.cooks_distance[0] * k_vars, results_sas[:, 8], atol=6e-5)
    assert_allclose(infl.hat_matrix_diag, results_sas[:, 4], atol=6e-5)

    c_bar = infl.cooks_distance[0] * 3 * (1 - infl.hat_matrix_diag)
    assert_allclose(c_bar, results_sas[:, 9], atol=6e-5)

@josef-pkt

Copy link
Copy Markdown
Member Author

I also added the notebook for the GLM-Logit example. I took the example from the SAS documentation, but actually it's the main example in Pregibon 1981.

Time to stop here and merge.

One thought while working on docstrings.
I don't really like the p-values returned by cooks_distance. I kept them from OLS. But AFAIK those p-values are based on a single observation so we don't get any large sample, asymptotic results for it. Williams mentioned that point more strongly, i.e. in these/some cases it is equivalent to a score test for adding an observation dummy variable, but that parameter is based on only a single observation.
One possibility is to remove them from cooks_distance and put them in a separate attribute.

A review of this before the next release would be useful.

I'll merge when green.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging 43a59ce into 01ce369 - view on LGTM.com

new alerts:

  • 1 for Unused import

Comment posted by LGTM.com


from statsmodels.tools.sm_exceptions import (PerfectSeparationError,
DomainWarning)
from cvxopt.base import matrix

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how did this get in here? unit tests fail
That's the second time in this PR that I get an unrelated import added to a module.
I'm only editing the statsmodels source in pydev/Eclipse.

@josef-pkt
josef-pkt force-pushed the influence_glm_wls branch from 43a59ce to d8dcabe Compare June 21, 2018 20:05
@josef-pkt

Copy link
Copy Markdown
Member Author

all green, except coveralls changed how it counts.
merging

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants