Skip to content

ENH/REF generic get_prediction - #7870

Merged
josef-pkt merged 7 commits into
statsmodels:mainfrom
josef-pkt:get_prediction_generic
Nov 18, 2021
Merged

josef-pkt merged 7 commits into
statsmodels:mainfrom
josef-pkt:get_prediction_generic

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

see #7833 for design and comments

@josef-pkt

Copy link
Copy Markdown
Member Author

test failure: I missed one call to moved module

>       from statsmodels.genmod._prediction import params_transform_univariate
E       ModuleNotFoundError: No module named 'statsmodels.genmod._prediction'

statsmodels/regression/tests/test_predict.py:218: ModuleNotFoundError

@josef-pkt

josef-pkt commented Nov 9, 2021 •

Copy link
Copy Markdown
Member Author

supporting endpoint transformation for k_extra (e.g. NBP) looks messy in the current setting.
exog * cov_params has inconsistent shapes, but it's hard coded in many places.

I need something like a linear/link version of NonlinearDeltaCov that takes summary statistics linear jacobian, cov and link.
Then we can call it with slices of cov_params and the correct exog for jacobian.
This would also work for multi-link models for individual distribution/family dargs, e.g. precision in BetaModel.

Refactoring the current code would either require to extend exog with "jacobian" columns of zeros for the unused extra parameters, e.g. add 1 column in NB, NBP and GPP.
Or, alternatively, we would need to carry slices/indices around and slice cov_params each time to get the appropriate submatrix.
Reusing results.t_test has the same problem, it always requires full "jacobian", i.e. restriction matrix needs to have as many columns as parameters.
Actually, t_test can take a cov_p directly. and LikelihoodModelResults.cov_params has a "column" keyword to select submatrices. This means I could reuse t_test for subset linear prediction.

@josef-pkt
josef-pkt force-pushed the get_prediction_generic branch from 64450c3 to 1b9707c Compare November 10, 2021 15:06
@josef-pkt

Copy link
Copy Markdown
Member Author

latest commit "ENH/REF: add get_prediction_monotonic, add get_prediction to CountRes… "
is still dirty.
I got get_prediction to work for my notebook examples with NB, NBP and GP. But didn't clean anything yet. No unit tests yet. Creates new function and class based on a copy of the get_prediction glm version.
`get_prediction(which="linear") is unfinished. I most likely want a specific Results class for linear predictor(s). (unless we use identity link and the "monotonic" class)

@josef-pkt

josef-pkt commented Nov 10, 2021 •

Copy link
Copy Markdown
Member Author

BUG with pandas exog_predict
So far I have used only plain numpy arrays

with pandas in an NB example (data is transformed docvis, #1742 (comment) )

pred = res.get_prediction(exog.mean(0))
print(pred.summary_frame())
          predicted        se  ci_lower  ci_upper
private    6.160406  0.091027  5.984556  6.341424
medicaid   6.160406  0.091027  5.984556  6.341424
aget       6.160406  0.091027  5.984556  6.341424
aget2      6.160406  0.091027  5.984556  6.341424
educyr     6.160406  0.091027  5.984556  6.341424
actlim     6.160406  0.091027  5.984556  6.341424
totchr     6.160406  0.091027  5.984556  6.341424
const      6.160406  0.091027  5.984556  6.341424

pred = res.get_prediction(exog=np.asarray(exog).mean(0))
print(pred.summary_frame())
   predicted        se  ci_lower  ci_upper
0   6.160406  0.091027  5.984556  6.341424

exog.mean(0)
private      0.490769
medicaid     0.155966
aget         1.846404
aget2        5.036815
educyr      11.181868
actlim       0.332323
totchr       1.841554
const        1.000000
dtype: float64

In Stata (params agree at 4 to 6 decimals)

. margins , atmeans

Adjusted predictions                            Number of obs     =      3,629
Model VCE    : OIM

Expression   : Predicted number of events, predict()
at           : private         =    .4907688 (mean)
               medicaid        =    .1559658 (mean)
               aget            =    1.846404 (mean)
               aget2           =    5.036815 (mean)
               educyr          =    11.18187 (mean)
               actlim          =     .332323 (mean)
               totchr          =    1.841554 (mean)

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   6.160416   .0910274    67.68   0.000     5.982006    6.338827
------------------------------------------------------------------------------

note, Stats uses delta method confint, I use endpoint in this case:

pred.conf_int(method='delta')
array([[5.98199705, 6.33881512]])

@lgtm-com

lgtm-com Bot commented Nov 10, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts and fixes 1 when merging 1b9707c into 718b4c5 - view on LGTM.com

new alerts:

  • 2 for Unused local variable

fixed alerts:

  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

Stata margin by default computes average prediction with delta method inference

. margins

Predictive margins                              Number of obs     =      3,629
Model VCE    : OIM

Expression   : Predicted number of events, predict()

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   6.807195   .1083883    62.80   0.000     6.594758    7.019632
------------------------------------------------------------------------------

My get_prediction can now do this also (but currently returns a NonlinearDeltaCov instance

pred = res.get_prediction(use_mean=True)
print(pred, "\n", pred.summary())
<statsmodels.stats._delta_method.NonlinearDeltaCov object at 0x000000B6334A0AC0> 
                              Test for Constraints                             
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
c0             6.8072      0.108     62.804      0.000       6.595       7.020
==============================================================================

pred.conf_int()
array([[6.59475693, 7.01962926]])

@josef-pkt

Copy link
Copy Markdown
Member Author

CI failures are pep-8 and LGTM unused name

more results:

Stata using predict_nl

It looks like we need to specify explicit linear predictor expression.

Stata also has an option for p-value for H0: predicted=0, but those are very small because predicted values are large.

. predictnl fitted2 = exp(_b[private]*private + _b[medicaid]*medicaid + _b[aget]*aget + _b[aget2]*aget2 + _b[educyr]*educyr +
>  _b[actlim]*actlim + _b[totchr]*totchr + _b[_cons]), wald(fitted_t) se(fitted_se) ci(fitted_low fitted_upp)
note: confidence intervals calculated using Z critical values

This creates the corresponding columns in the data matrix

Results agree with mine, except small differences in confint, delta versus endpoint method

@josef-pkt

Copy link
Copy Markdown
Member Author

and confint for average prob(y = 0) and y=1

Stata:

. margins, predict(pr(0))

Predictive margins                              Number of obs     =      3,629
Model VCE    : OIM

Expression   : Pr(docvis=0), predict(pr(0))

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   .0882665   .0035069    25.17   0.000     .0813931    .0951398
------------------------------------------------------------------------------


. margins, predict(pr(1))

Predictive margins                              Number of obs     =      3,629
Model VCE    : OIM

Expression   : Pr(docvis=1), predict(pr(1))

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   .1071998   .0020503    52.29   0.000     .1031813    .1112182
------------------------------------------------------------------------------

mine (still no option to choose for which y=k to compute prob):

pred = res.get_prediction(which="prob", use_mean=True)
print(pred.summary())
                             Test for Constraints                             
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
c0             0.0883      0.004     25.170      0.000       0.081       0.095
c1             0.1072      0.002     52.286      0.000       0.103       0.111
c2             0.1061      0.001     89.092      0.000       0.104       0.108
c3             0.0974      0.001    101.081      0.000       0.095       0.099
...


ci0 = pred.conf_int()[0]
ci0, ci0 - [0.0813931, 0.0951398]
(array([0.08139216, 0.09513864]), 
array([-9.37623130e-07, -1.16085304e-06]))

@josef-pkt

josef-pkt commented Nov 10, 2021 •

Copy link
Copy Markdown
Member Author

Stata also allows margins for sum of probabilities for intervals of k and for survival function sf value.
We don't have yet a predict which option for that

. margins, predict(pr(2,.))

Predictive margins                              Number of obs     =      3,629
Model VCE    : OIM

Expression   : Pr(docvis>=2), predict(pr(2,.))

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   .8045338   .0054522   147.56   0.000     .7938476    .8152199
------------------------------------------------------------------------------


. margins, predict(pr(0,1))

Predictive margins                              Number of obs     =      3,629
Model VCE    : OIM

Expression   : Pr(0<=docvis<=1), predict(pr(0,1))

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   .1954662   .0054522    35.85   0.000     .1847801    .2061524
------------------------------------------------------------------------------

@josef-pkt

Copy link
Copy Markdown
Member Author

Related, I would also like to get the quantile function, ppf and isf, but for discrete rv, those are step functions and delta method does not work (we need at least continuous first derivatives),

@josef-pkt

Copy link
Copy Markdown
Member Author

ZeroInflatedNegativeBinomialP predict or get_prediction changes offset, exposure if None

If offset and exposure are not given by the user, then the attribute is not available in the model_main.
After calling get_prediction offset and exposure become arrays of zeros.
mod_zinb.model_main.offset, mod_zinb.model_main.exposure

Most likely, there is a problem in the code of this PR.

@josef-pkt

Copy link
Copy Markdown
Member Author

BUG: zeroinflated model.predict returns nobs array of exog_infl is not proved but scalar exog is.
e.g. my unit tests failed for at_means with wrong exog_infl.

predict needs to raise an exception if exog is specified in predict, but exog_infl is not and model.exog_infl is not just a constant.
The current predict gives exog_infl=None to the inflation submodel, which interprets None as that we want the in-sample exog.
(I guess if exog is not a single row, then we should get a broadcasting exception.)

@josef-pkt

josef-pkt commented Nov 13, 2021 •

Copy link
Copy Markdown
Member Author

api of NonlinearDeltaCov and PredictionResults are not consistent
e.g. predicted is method in the former and attribute in the latter.

I currently cannot write common unit test functions or methods for negbinp and zinegbinp

Design: I will add a prediction results wrapper around NonlinearDeltaCov.
The main reason is that I don't want to directly expose joint inference, cov, wald_test, to users in predict.
get_prediction is supposed to handle large (predict) nobs, and a mistake to call cov or wald_test could easily blow up the memory with (nobs, nobs) arrays.

@josef-pkt
josef-pkt force-pushed the get_prediction_generic branch from 1b9707c to e76cac7 Compare November 14, 2021 18:40
@pep8speaks

pep8speaks commented Nov 14, 2021 •

Copy link
Copy Markdown

Hello @josef-pkt! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

There are currently no PEP 8 issues detected in this Pull Request. Cheers! 🍻

Comment last updated at 2021-11-18 21:48:38 UTC

@josef-pkt

Copy link
Copy Markdown
Member Author

right now I have several different version of get_prediction_xxx and PredictionResult
_delta, _monotonic and _glm/Mean in prediction_inference and I didn't change the linear version in regression_getPrediction
Those still need to be streamlined and maybe we delete one.
_glm/Mean is mainly for backwards compatibility because _monotonic changed the attribute and method names

unit tests for NBP with link/monotonic version for mean, and ZINBP with all delta method
I have not yet cleaned up get_prediction(which="linear")

Another case will be BetaModel with two link functions. I haven't tried it yet.
No predict which yet in GLM and discrete Binary model

undecided: default for use_mean (will be renamed to average). Currently it is False, but it would be safer if it is True for which="prob".
If default average=None, then we can select a which dependent default.

I also still would like to add freq_weights, so we can compute "population averages".
I guess it should be a model.predict option. But it would be just adding one line in the generic get_prediction_delta.
model.predict does not do any averaging so freq_weights is not really necessary there.

Need meta-information in Prediction results instance, e.g. which, if delta method, ...

another undecided: replicating margins
Margins can be computed with get_predictions but we would need any to allow extra functions like dydx, "eydx", ...
Discrete change could be computed if we allow two exog, x1, x2, for predict and we compute average(f(x2) - f(x1)).
But get_prediction, in contrast to get_margeff, does not construct any exog_predict itself.

@lgtm-com

lgtm-com Bot commented Nov 14, 2021

Copy link
Copy Markdown

This pull request introduces 3 alerts and fixes 1 when merging e76cac7 into ac106a5 - view on LGTM.com

new alerts:

  • 1 for Unused local variable
  • 1 for Unused import
  • 1 for Explicit export is not defined

fixed alerts:

  • 1 for Unreachable code

@josef-pkt
josef-pkt force-pushed the get_prediction_generic branch from e76cac7 to 63b4e8c Compare November 16, 2021 15:51
@lgtm-com

lgtm-com Bot commented Nov 16, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 63b4e8c into 6d7d42e - view on LGTM.com

new alerts:

  • 1 for Unused local variable

fixed alerts:

  • 1 for Unreachable code

@josef-pkt

josef-pkt commented Nov 16, 2021 •

Copy link
Copy Markdown
Member Author

naming question
User provided response y or k vector for `which="prob". I want to add option for it but not sure about keyword name.

Internally we use counts in count models predict.
But it doesn't generalize to non-count models, and is not explicit enough.
It should also work for cdf/sf probabilities and for bin probabilities, which we still need to add for other use cases like chisquare tests.
Maybe y_prob the values of the response, depvar for which we compute probabilities.
y here is not an observed endog, it's just arbitrary values at which we evaluate pdf/pmf and cdf.

values or endog_values?

update renamed to y_values

@josef-pkt

Copy link
Copy Markdown
Member Author

get_prediction for Logit and Poisson was added in #7597 for 0.14. I can still change the return class
GLM will need deprecation when I use new name predicted and similar without _mean postfix.

unit tests to change are statsmodels.genmod.tests.test_glm.TestGlmPoisson and TestGlmBernoulli

@josef-pkt

Copy link
Copy Markdown
Member Author

I need to add link to Logit and Probit for generic get_prediction.

Adding link and family (already in countmodels) as public methods/property takes us further down the "inverse" path.
It will also become difficult in discrete and othermod to switch to inverse link classes, ilink, mean function and variance functions.

@josef-pkt
josef-pkt force-pushed the get_prediction_generic branch from 63b4e8c to eed7e1f Compare November 17, 2021 18:01
@josef-pkt

Copy link
Copy Markdown
Member Author

I'm moving get_prediction to DiscreteResults.
multinomial raises NotImplementedError (that doesn't work yet)
Logit and Poisson use now generic get prediction.
Probit inherits but no unit tests for it. I don't see unit tests for GLM-probit in genmod test_glm.py
I also have not checked get_prediction for the old NegativeBinomial yet, and not for GeneralizedPoisson

@lgtm-com

lgtm-com Bot commented Nov 17, 2021

Copy link
Copy Markdown

This pull request fixes 1 alert when merging eed7e1f into 6d7d42e - view on LGTM.com

fixed alerts:

  • 1 for Unreachable code

@josef-pkt

josef-pkt commented Nov 17, 2021 •

Copy link
Copy Markdown
Member Author

The latest commit broke MLEInfluence, failures/errors in statsmodels/stats/tests/test_influence.py for Logit and Poisson
MLEInfluence is also used for unit testing GLMInfluence.

I still need more consistency in post-estimation API.
Need alias methods and deprecation of methods for get_prediction_glm

And large parts of the newer post-estimation features still don't handle multilink models like BetaModel. That will need another round of refactoring across the board.

update amended and force pushed, alias methods in glm and regression PredictionResults classes
generic code does not use _mean postfix anymore

The influence classes themselves use _mean and fittedvalues, which assumes mean parameterization

@josef-pkt

Copy link
Copy Markdown
Member Author

Another naming problem in multilink models like Het and multilink models.

Our second link is for a variance/scale/dispersion parameter, which is in most cases not the same as the variance itself.
eg predict(which="scale") or which="var" or which="precision" needs to distinguish between the distribution parameter (dargs) and the actual property of the distribution.
example BetaBinomial with different parameterization
In BetaModel the precision parameter is often called psi, but I don't like uninformative greek names.

one more:
multiple returns in predict and get_prediction,
e.g. if we want to return dargs mu and sigma, mean and scale parameter (similar to the use in get_prediction)

  • current multi-return case, which="prob" in get_prediction will mainly be used with averaging.
  • dargs need to be observation specific, so we cannot rely on averaging
  • multivariate endog predictions, e..g multinomial and ordinal are not yet supported by generic get_prediction

@josef-pkt
josef-pkt force-pushed the get_prediction_generic branch from eed7e1f to e5166ef Compare November 17, 2021 22:48
@lgtm-com

lgtm-com Bot commented Nov 17, 2021

Copy link
Copy Markdown

This pull request fixes 1 alert when merging e5166ef into 6d7d42e - view on LGTM.com

fixed alerts:

  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

all green, time to clean up

I need followup PRs for multinomial #7888 and for multilink BetaModel.
Then we need more use cases, e.g. what other which can we add (eg. `"dydx", cdf ?) and diagnostics.

I haven't looked yet at use cases for joint cov and wald_test that we get with NonlinearDeltaCov.
e.g. in the multinomial response case we would have the joint cov for the predicted probabilities. (I already added a multinomial cov as helper function for diagnostics that is not used yet, AFAIR)

I haven't added any deprecation warnings in this PR. Those need to be added later. Final API is still somewhat open.

@josef-pkt
josef-pkt force-pushed the get_prediction_generic branch from e5166ef to c764bbc Compare November 18, 2021 17:01
@lgtm-com

lgtm-com Bot commented Nov 18, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts and fixes 1 when merging c764bbc into 6d7d42e - view on LGTM.com

new alerts:

  • 2 for Missing call to `__init__` during object initialization

fixed alerts:

  • 1 for Unreachable code

@josef-pkt
josef-pkt force-pushed the get_prediction_generic branch from 963d91b to 9b83bbf Compare November 18, 2021 20:10
@josef-pkt

Copy link
Copy Markdown
Member Author

That's about finished for this round.
either merge or another quick review.

next ?

@josef-pkt josef-pkt mentioned this pull request Nov 18, 2021
16 of 20 tasks
@lgtm-com

lgtm-com Bot commented Nov 18, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts and fixes 1 when merging 9b83bbf into 1fd553d - view on LGTM.com

new alerts:

  • 2 for Missing call to `__init__` during object initialization

fixed alerts:

  • 1 for Unreachable code

@josef-pkt
josef-pkt force-pushed the get_prediction_generic branch from 9b83bbf to 6e484f4 Compare November 18, 2021 21:48
@lgtm-com

lgtm-com Bot commented Nov 18, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts and fixes 1 when merging 6e484f4 into 1fd553d - view on LGTM.com

new alerts:

  • 2 for Missing call to `__init__` during object initialization

fixed alerts:

  • 1 for Unreachable code

@josef-pkt
josef-pkt merged commit 8c1bfe7 into statsmodels:main Nov 18, 2021
@josef-pkt josef-pkt mentioned this pull request Nov 27, 2021
3 of 17 tasks
@josef-pkt
josef-pkt deleted the get_prediction_generic branch October 19, 2022 19:40
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.

2 participants