Skip to content

ENH: add get_influence to DiscreteResults - #7951

Merged
josef-pkt merged 6 commits into
statsmodels:mainfrom
josef-pkt:post_estimation
Dec 21, 2021
Merged

josef-pkt merged 6 commits into
statsmodels:mainfrom
josef-pkt:post_estimation

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

WIP still in design/decision stage

MLEInfluence with resid_pearson default

works for
Logit,
Poisson,
NegativeBinomialP,
GeneralizedPoisson,

other models are missing derivatives.

currently test failures because definition of MLEInfluence.resid_studentized changed, in TestInfluenceGaussianGLMMLE.test_basics

@josef-pkt

Copy link
Copy Markdown
Member Author

test failure: it looks like because GLM.resid_pearson does not divide by scale

(Pdb) infl0.resid_studentized / infl1.resid_studentized
array([13.3690284, 13.3690284, 13.3690284, 13.3690284, 13.3690284,

(Pdb) np.sqrt(infl0.results.scale)
13.369028398196098

I need to go through the details to see where the scale is missing

@josef-pkt

josef-pkt commented Dec 15, 2021 •

Copy link
Copy Markdown
Member Author

if we want to use MLEInfluence with GLM, OLS and similar that have scale as auxiliary parameter, then we need some attribute that indicates this. either something specific to scale, or something about auxiliary parameters that are not part of the main optimization and estimation.

checking discrete_model for scale:
It shouldn't have any, we only have HC but no cov_type for excess dispersion.
However, base.model.Results requires scale, so I guess we have it set to 1 by default.
MLEInfluence adds the scale as attribute already
self.scale = scale if scale is not None else results.scale
so maybe we can just use resid = resid_pearson / scale (maybe conditional on scale !=1)

Brief file search CountModel._deriv_score_obs_dendog and the Poisson method have scale argument which might be copy-paste mistake from GLM.
I guess CountModel shouldn't have the method (except as NotImplemented) because the current version is specific to Poisson.

_deriv_score_obs_dendog is missing in Probit and ZI
ZI might need numdiff. BetaModel has already a numdiff version, but using score_factor which we don't have (yet) in ZI.
I might need the new uncommitted vectorized numdiff version.
Aside: we should replace norm.cdf by our own version that allows complex numbers.

ZI _deriv_mean_dparams raise NotImplementedError
but we should be able to get analytical derivative, generically.

new score residual methods in MLEInfluence don't have unit tests, not even smoke.

open questions:
Do I need resid options in get_influence?
other options?
MLEInfluence has many keywords to override using the default results attributes.

update
I don't understand the docstring last sentence for the Return in _deriv_score_obs_dendog
The derivative of the score_obs with respect to endog. This
can is given by score_factor0[:, None] * exog where
score_factor0 is the score_factor without the residual.

copied to Logit from GLM
It might make sense in GLM and Logit (after thinking about it long enough), but is not general.
e.g. Probit score_factor is not computed based on a resid representation.
Other models like ZI models or general distributions might not have a resid representation at all.

brief explanation:
residual representation of score : g(x, theta) * (y - m(x, theta)) where g(x, theta) does not depend on y.
Then derivative of score wrt y is just g(x, theta).
I used that to copy and adjust the code from score_factor in GLM.
With canonical link g(x, theta) = x, e.g. Logit, Poisson.

general binary (cdf link), (if my derivation is correct)
deriv = f(z) / (F(z) * (1 - F(z)) * x where f, F are pdf, cdf, and z is linear predictor.

@josef-pkt

josef-pkt commented Dec 15, 2021 •

Copy link
Copy Markdown
Member Author

I'm running into problems trying to scale resid_pearson in MLEInfluenc.__init__:

        if resid is not None:
            self.resid = resid
        else:
            self.resid = getattr(results, "resid_pearson", None)
            if self.resid is not None and scale != 1:
                # GLM and similar does not divide resid_pearson by scale
                self.resid /= np.sqrt(self.scale)

GLMInfluence subclasses MLEInfluence and does not have it's own __init__
GLM scale is used in resid_studentized directly following the pattern of OLSInfluence. The justification there is that we want an option to use externally studentized residuals where sigma/scale is also a LOOO approximation.

I need to decide whether GLMInfluence should be more like MLEInfluence or like OLSInfluence.
(When I make changes right now, some unit tests fail, at different places for different changes, either in the comparison MLE-GLM or in the comparison OLS-GLM.)

update
GLMResults.get_influence explicitly specifies resid argument.
taking resid_pearson from results class in MLEInfluence.__init__ does not apply.

new issue #7955 for misspecification question

@josef-pkt

Copy link
Copy Markdown
Member Author

Should be green now

This changes that scaled resid_pearson is attached as resid in both MLE and GLMInfluence.
It does not change resid_studentized, it just moves where scaling is done.

The assumption now is that if resid is specified as argument in the Influence class, then it needs to be scaled and not unscaled resid_pearson.
That still leaves the problem that we only have internally studentized resid with fixed scale. External studentizing of resid would have to compensate for the scaling already included in resid.

@josef-pkt

Copy link
Copy Markdown
Member Author

BinaryModel are a bit of a hybrid now, after I had added a link to them.
standard implementation was pdf/cdf methods.
_deriv_mean_dparams uses link.inverse_deriv instead of pdf
Bernoulli with nonlinear mean/link function versus censored latent variable

to compare:
OrderModel also uses cdf, pdf and a distribution as argument, instead of a CDFLink.
It's only a censored latent model. (with estimated censoring thresholds)

In discrete count models, we don't have an alternative interpretation and attributes for log-link, exp-mean function.

@josef-pkt

josef-pkt commented Dec 17, 2021 •

Copy link
Copy Markdown
Member Author

????

What's the interpretation of Generalized Leverage in zero-inflated models?
AFAIR, I never looked at that for ZI models. A brief google search doesn't find much.
Main problem:
Definition of GL is based on the derivative of predicted y w.r.t sample observation y, generalized hat matrix.
If y=0, then there is a discontinuity. It goes from zero to something positive and changes in which likelihood "regime" it is.

The relevant function is _deriv_score_obs_dendog

Analytical derivative (with or without jump) are difficult, but not impossible. I could also use just the intensive margin without jump.
If I use finite difference numdiff, then it will jump.
If I use complex step derivatives, then it might not jump. (I don't know how CS handles discontinuities, the complex part might also make it jump regimes. It looks like that in inequalities.

np.array(0 + 1e-8j), np.array(0 + 1e-8j) > 0
(array(0.+1.e-08j), True)

np.array([0, 0 + 1e-8j]) > 0
array([False,  True])

One likely problem with numdiff is the division by the step size, the jump part shouldn't be normalized by step-size.

update
doesn't seem to work
complex step has _deriv_score_obs_dendog all zeros
finite difference has huge values with small stepsize (epsilon), and changes a lot when I increase epsilon
something is weird

my current version of GenericZeroInflated._deriv_score_obs_dendog:

        from statsmodels.tools.numdiff import _approx_fprime_scalar
        endog_original = self.endog
        def f(y):
            if y.ndim == 2 and y.shape[1] == 1:
                y = y[:, 0]
            self.endog = y
            sf = self.score_obs(params)  #, endog=y)
            self.endog = endog_original
            return sf

        ds = _approx_fprime_scalar(self.endog[:, None], f, epsilon=1e-2)
        return ds

update 2
I didn't monkey patch the right endog, need endog of model_main

            self.endog = y
            self.model_main.endog = y
            sf = self.score_obs(params)  #, endog=y)
            self.endog = endog_original
            self.model_main.endog = endog_original

Then

  • CS fails in gammaln which does not allow complex numbers
  • finite difference numdiff: values looks ok for y>0, but large for y == 0. the latter seems to come from jump divided by stepsize. Derivative goes to +/- inf as stepsize -> 0 (it's a jump at 0)

@josef-pkt

josef-pkt commented Dec 17, 2021 •

Copy link
Copy Markdown
Member Author

doesn't look good for generalized leverage in zero-inflated models

I found articles for influence measures in zero-inflated models, like cooks distance and similar with the generic definition.
But searching the article, doesn't show any occurrence of "leverage".

There is one article that has generalized leverage and zero-inflated in the title, but it seems to be only available in gated Chinese website. And the article doesn't show up in the authors pages at public research websites.

maybe an alternative: looking at intensive and extensive margins separately (I didn't look at the following article)

Yang, Yan, and Douglas G Simpson. 2012. “Conditional Decomposition Diagnostics for Regression Analysis of Zero-Inflated and Left-Censored Data.” Statistical Methods in Medical Research 21 (4): 393–408. https://doi.org/10.1177/0962280210387525.

update I skimmed the article and it doesn't seem to have any influence outlier diagnostics.
The decomposition seems to be in marginal versus conditional mean which we already have in predict-which.
The only or main interesting thing is that it looks at tobit. left censoring in the same context as zero-inflated models.

For now:

  • skip zi for get_influnece
  • make leverage optional in MLEInfluence
  • use approximation, e.g. only intensive margin in _deriv_score_obs_dendog (needs to be analytical
    I guess that wouldn't show an influential point with zero endog, e.g. possible zero outlier.
  • ...

@josef-pkt

josef-pkt commented Dec 17, 2021 •

Copy link
Copy Markdown
Member Author

more about likelihood computation and dependence on endog, specifically ZI models:

_deriv_score_obs_dendog needs to change endog when using numdiff

in NBP, GPP, I added endog as extra argument to score_factor. score_factor there is self contained and only calls predict which does not depend on endog. So the endog, argument in score_factor reflects all effects of endog on score.

in ZI models it is much trickier.
score_obs calls methods in the model (self) or in model_main that use the attached self.endog.
As in the previous comment, I need to temporarily replace both model.endog and model_main endog.

However, endog might also affect other attributes in the model. The main design in statsmodels assumes that endog is fixed.
Specifically, the zero masks.
Currently, GenericZeroInflated recomputes the mask in loglike and score functions:

        zero_idx = np.nonzero(y == 0)[0]
        nonzero_idx = np.nonzero(y)[0]

This is a lot of duplicated work, However, it means that the mask is recomputed when I use numdiff and change endog internally.
When we move the mask creation to the __init__ for computational efficiency, then the mask will be fixed, unless we reset also the mask. In that case, a numdiff derivative wrt. endog, would only have the intensive margin, with fixed "regime" mask.

Similar pattern will occur in other switching, censoring, selection models, when we take a derivative wrt. a variable or parameter that affects regime membership of an observation.
Censoring in survival model is different because there it is assumed that censoring is exogenous, and does not depend on a variable of parameter of interest. So, we will not need a derivative that changes censoring status.

Bottomline, I guess, Even if likelihood is smooth and satisfies all regularity conditions wrt parameter, we might not have smoothness or regularity conditions for all post-estimation methods.
MLEInfluence only applies to smooth parts, and we need to skip or find alternatives when smoothness and regularity assumptions for post-estimation are not satisfied.

The same will be true for local influence analysis, which we don't have yet.
e.g. the article for influence in ZINB does not include a section on the usually included outcome perturbation.

(I will be less surprised next time I run into weird numdiff results.)

Garay, Aldo M., Elizabeth M. Hashimoto, Edwin M. M. Ortega, and Víctor H. Lachos. 2011. “On Estimation and Influence Diagnostics for Zero-Inflated Negative Binomial Regression Models.” Computational Statistics & Data Analysis 55 (3): 1304–18. https://doi.org/10.1016/j.csda.2010.09.019.

Xie, Feng-Chang, Bo-Cheng Wei, and Jin-Guan Lin. 2008. “Assessing Influence for Pharmaceutical Data in Zero-Inflated Generalized Poisson Mixed Models.” Statistics in Medicine 27 (18): 3656–73. https://doi.org/10.1002/sim.3233.

@josef-pkt

josef-pkt commented Dec 17, 2021 •

Copy link
Copy Markdown
Member Author

MLEInfluence methods that depend on hat_matrix

  • d_params : why? is dividing by 1 - hii like a small sample correction, newton-raphson updating wouldn't have it
  • resid_studentized : without hii it would be just original resid_pearson
  • resid_score_factor : new method, studentize could be optional
  • resid_score : studentize=False as option

the other methods only depend on hat_matrix through d_params

Do we use a default hat_matrix_diag = zeros or = k_params / nobs?
In d_params, we can skip it if not available.

an alternative would be to use a different definition of leverage.
e.g. define it directly in terms of x outliers. (Mahalanobis distance)
This would work in the plot, and would be closer to exog outlier handling in robust estimation.

In zi models we could base it on joint exog, but where we would have to remove duplicate (explanatory variables that are in both exog)

edit I'm working with a constant only model. That implies that all observations have the same exog values. There are no influential points in terms of x-outliers.
Trace of hat_matrix is k_vars, so values on diagonal are just k / nobs (k is rank of x, not number of columns in singular case)
then 1 - hii = (1 - k / n) = (n - k) / n which is just a small sample correction

edit 2
Mahalanobis distance would be a useful alternative for the influence plot, x outliers versus y (resid) outliers.
It might not be useful for statistics that rely on the generalized leverage derivative interpretation.

For now, this PR:

  • allow hat_matrix to be None.
  • skip it in d_params if None
  • resid_score_factor add studentize option
  • adjust summary frame (skip hat matrix, use resid_pearson or skip also?
  • let plot_influence fail

@josef-pkt

Copy link
Copy Markdown
Member Author

I have it working in the last commit, but not verified numbers yet.
changes in MLEInfluence to allow hat_matrix_diag to be None, intended for ZI models, or cases when we don't have _deriv_score_obs_dendog

in summary_frame we only have dfbetas, cooks_d and dffits/d_fittedvalues

(Pdb) summ = influ.summary_frame()
(Pdb) summ.head()
   dfb_inflate_const  dfb_const   cooks_d  dffits_internal
0          -0.034345  -0.019906  0.001576         0.005020
1          -0.034345   0.024599  0.001785         0.040394

likelihood distance LD might also work
I haven added other, non-studentized resid yet to summary_frame.

@lgtm-com

lgtm-com Bot commented Dec 17, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts when merging 242b1f6 into d9f21bb - view on LGTM.com

new alerts:

  • 1 for Module is imported more than once
  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

new plan

  • add hat_diag_exog than just uses the plain hatmatrix of combined exog as in OLS
  • use it only in plot_influence, if hat_matrix_diag is None: then plot hat_diag_xog with resid_pearson
  • use (optional ?) small sample correction in d_params if no GL (corresponding to uniform hat_diag)
  • studetized resid remains as not available

aside:

Barros, Michelli, Manuel Galea, Víctor Leiva, and Manoel Santos-Neto. 2018. “Generalized Tobit Models: Diagnostics and Application in Econometrics.” Journal of Applied Statistics 45 (1): 145–67. https://doi.org/10.1080/02664763.2016.1268572.

Tobit for elliptical/symmetric distribution
influence measures do not include GL and output perturbation

Barros, Michelli, Manuel Galea, Manuel González, and Víctor Leiva. 2010. “Influence Diagnostics in the Tobit Censored Response Model.” Statistical Methods & Applications 19 (3): 379–97. https://doi.org/10.1007/s10260-010-0135-y.

This one includes GL and standardized/studentized deviance and martingale residuals !
p. 386 They set the derivative w.r.t endog to zero for the censored observation, i.e. no extensive margin

@josef-pkt

josef-pkt commented Dec 20, 2021 •

Copy link
Copy Markdown
Member Author
  • index_plot bad choice of shortcut for y_var option, it's not possible to display other resid

this should be at least criterion.startswith('resid_stu')

        elif criterion.startswith('resid'):
            y = self.resid_studentized
            ylabel = "Internally Studentized Residuals"

my workaround in notebook with ZIP which does not have studentized residuals

influ._resid_pearson = influ.resid
influ.plot_index(y_var="_resid_pearson");
  • another problem with index plot: resid_score is a method and y_var in index plot need to be attributes/property

  • resid_score is just cooks_distance without k_vars normalization in this example, ZIP

influ.resid_score() / influ.cooks_distance[0]
array([1.99999911, 2.00000126, 2.00000202, 1.99999915, 2.00000059,
       2.00000192, 2.00000015, 2.00000091, 1.99999908, 2.00000139,
...

However, k_vars in cooks_d is exog.shape[1] and not k_params, in zi example

Aside: in overidentified GMM we don't have k_params == len(score) (number of moment conditions.
Cook's distance is a measure on params, resid_score is a measure for score_obs.
I'm not sure when they are identical and not just based on asymptotically equivalent tests.
Cooks_d, are based on one-step approximation of d_params which just uses score_obs and hessian, but with 1 / (1-hii) correction.

I think articles on influence in ZIP and similar don't use the k_params normalization of cooks distance, ARAIR, and briefly checking on of the articles.

One difference in implementation:
Our cooks_distance uses cov_params, resid_score uses negative hessian (OIM).
This will cause differences with non-robust cov_params.

len(res.params), influ.k_vars
(3, 2)
  • another problem: my new hat_matrix_exog_diag currently uses the main exog, and not column_stack of all exog

BetaModel has _get_exog method used in score_test.
We don't have yet anything generic in ZeroInflated model that indicates that it has two exog.

@josef-pkt

Copy link
Copy Markdown
Member Author

for docs:

I will expand on the definitions for the various measures and differences in the MLEInfluence class docstring. We will need to add it to the rst docs.
The get_influence methods can get a docstring with model specific details as in ZI models, even if it just calls super.

@josef-pkt

Copy link
Copy Markdown
Member Author

see issue #7964 for differences between Probit MLEInfluence and GLMInfluence.

It looks like we get quite a bit different and ahead of other packages here.
This also means smaller mistakes like using k_vars instead of k_params will be more difficult to find.
One possibility to check is to compare with explicit LOOO loop.

And we don't have local influence measures yet.

@josef-pkt

Copy link
Copy Markdown
Member Author

exog in MLEInfluence:

  • it's only used in the new hat_matrix_exog_diag
  • I guess it was added as __init__ kwd because of the pattern in GLM and OLS Influence

options for multi-exog case

  • use the keyword and column_stack in the results.get_influence method, so exog is combined exog
  • access all exog through model._get_exogs as in BetaModel for score_tests, and column_stack in MLEInfluence
  • use result._get_hat_matrix_exog_diag method in analogy to GLM.get_hat_matrix_diag

We need more cases of multi-exog models. What's the better design is unclear.

BetaModel has generalized leverage hat_matrix_diag.
I'm not sure we need to create a combined exog matrix by default. We should make it lazy in hat_matrix_exog_diag so we only increase memory consumption if users request it, or it's needed as in ZI models.

I guess lazy access to _get_exogs is better for now.

Another alternative:
We could define hat_matrix_score_diag and use score_obs. That would be like an OPG version of GLM hatmatrix (I think).
We already have score_obs in MLEInfluence, and we don't have problems with smoothness in cases like ZI.
The difference is that the score_obs includes the residuals (if there is a residual representation, or something similar if not)
It wouldn't be just a measure of x-outlyingness or x influence.
(i.e. it might end up being an OPG version of resid_score and cooks_distance)

@lgtm-com

lgtm-com Bot commented Dec 20, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts when merging 0273e14 into d9f21bb - view on LGTM.com

new alerts:

  • 1 for Module is imported more than once
  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

I think I've got now all I want here.
However, unit test coverage is pretty bad, mostly smoke or assert shape outside of models that have a GLM equivalent model.

@josef-pkt

Copy link
Copy Markdown
Member Author

oops, I forgot to add _get_exogs to ZI. (It irrelevant if inflation prob is constant)

@lgtm-com

lgtm-com Bot commented Dec 20, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts when merging cdeb4c5 into d9f21bb - view on LGTM.com

new alerts:

  • 1 for Module is imported more than once
  • 1 for Unreachable code

@lgtm-com

lgtm-com Bot commented Dec 21, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts when merging 7551cd3 into d9f21bb - view on LGTM.com

new alerts:

  • 1 for Module is imported more than once
  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

aside (as reminder): https://www.statsmodels.org/dev/pitfalls.html#other-problems
I want to add a section about "True parameters outside domain of model"
e.g ZI models with no zero-inflation or zero-deflation. NB with no overdispersion or with underdispersion.
e.g. #3863 #3337

Would be good to also mention this in the corresponding class docstrings

but I need to amend the commit here first

@josef-pkt

josef-pkt commented Dec 21, 2021 •

Copy link
Copy Markdown
Member Author

another idea: looking at outlier measure based on loglikeobs
(just trying something out, no literature search yet)
In discrete models this corresponds to transformation of the pmf evaluated at the observed endog

artificial example with add x and y outliers (model is ZeroInflatedPoisson)

influ.resid_nlike = np.exp(-influ.results.model.loglikeobs(influ.results.params))
influ.plot_index(y_var="resid_nlike");

image

This plot (above) looks similar to resid_score and cooks_d index plots
However resid_pearson plot (below) is not very informative, does not indicate any "strange" observations:

image

@lgtm-com

lgtm-com Bot commented Dec 21, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts when merging 15e97c0 into 9dd53ac - view on LGTM.com

new alerts:

  • 1 for Module is imported more than once
  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

I amended and removed duplicate import
LGTM complaint about unreachable code stays, It's quite likely that I will change this again.

merging when green

(I'm not sure what comes next, maybe diagnostic again if I can make up my mind about module locations)

@lgtm-com

lgtm-com Bot commented Dec 21, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 61909db into 9dd53ac - view on LGTM.com

new alerts:

  • 1 for Unreachable code

@josef-pkt
josef-pkt merged commit 590384e into statsmodels:main Dec 21, 2021
@josef-pkt
josef-pkt deleted the post_estimation branch October 19, 2022 19:25
@josef-pkt josef-pkt added this to the 0.14 milestone Feb 3, 2023
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.

1 participant