You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ENH/SUMM: add rvs or distributions to families #106
I have problems generating random variables for nbinom NegativeBinomial GLM example, because it takes two parameters. I'm not sure I got the correct parameterization for gamma.
It would be useful to directly have an rvs method in the families, or alternatively the scipy.stats distribution attached.
The distribution would also be useful for a new method predict_distribution.
Should scipy.stats be imported lazily, or is it already imported anyway?
update #7535 add proper get_distribution to GLM and families update2 #7929 add get_distribution to discrete count models to model and results classes #7707 overview what's available for post-estimation
open design question
method in results instance ?
separate out convert_params (currently defined in discrete.NegativeBinomialP)
direct access to implied statistics, e.g. Poisson results has predict_prob, new count models have predict(... which="prob")
@josef-pkt after trying to wrap my head around the parameterization myself, finding the above was very useful! Thanks. Did something like get_distribution ever make it into GLM result objects? Its very helpful to have an rvs for diagnosing a fit
@agartland As far as I know it hasn't been merged systematically, and not for negative binomial.
The MICE version that was merged, uses PMM predictive mean matching which doesn't use get_distribution, AFAIR.
(I think I saw a get_distribution somewhere else in the code some time ago but don't remember.)
I wrote a simulate_tweedie function recently so that I was able to experiment with data that I know comes form the correctly specified distribution, but it's currently stuck in a notebook.
There was a question on stats.stackexchange a while ago about simulating Probit, which was incorrect. So, that is also not obvious to all users.
Poisson and Gaussian are easy because they have the standard mean (variance) parameterization. I don't remember Gamma, but IIRC I didn't have any surprised the last time I tried.
I should have the negative binomial parameter transformation above converted to helper functions, but don't remember where I put them, and whether I committed them somewhere.
scale in statsmodels is variance parameter not standard deviation parameter scale in scipy distribution is standard deviation parameter, i.e. it is rescaling the random variable.
regression RegressionModels has get_distribution with dist_class(loc=fit, scale=np.sqrt(scale))
aside: maybe add *args in RegressionModel.get_distribution for additional shape parameters, e.g. df for t-distribution.
AFAICS, the current get_distribution are methods of the models and most of them call model.predict.
This does not support formulas.
We need a Results.get_distribution method that should have similar interface as Results.predict, e.g. handle formula transformations.
Computational:
possible code duplication with predict, i.e. checking exog, offset, exposure and any other possible extra variables.
Maybe it doesn't happen in results method if we just call predict.
Possible duplication between results.get_distribution and model.get_distribution.
reusing already existing values, e.g. we could use fittedvalues/mu directly if exog is None.
discrete models do not have get_prediction, but NBP model class has convert_params(self, params, mu)
with different signature than get_prediction, i.e. uses precomputed mu for predicted mean.
My trial example is a 2-sample case, where I want get_prediction also just for the unique exog instead of for each observation.
another: in new distributions.discrete.DiscretizedModel, I had used get_distr method instead of full name get_distribution
mediation: seems to be currently the only internal user
distributed AFAIR, GLM.get_distribution was added during distributed GSOC, file search doesn't find any usage
parametric bootstrap, that's what I'm looking at right now, but just to check code
diagnostic, e.g. PIT for gof tests, gof plots, maybe with simulated envelopes, p-values
simulated power analysis for models (but I managed to get some asymptotic power results also for regression models, e.g. noncentrality parameters for wald tests in models)
change in API in GLM get_distribution(self, params, scale=1., ...
scale needs to be used for norm, gamma, ...
With a default it is easy to make a mistake and forget about scale. (I just did.)
For this we need to treat scale in the same way as params:
make it a required arg in the model class, GLM
use estimated scale together with estimated scale if or when we add it to the results class.
We don't get inference on statistics based on the fully specified distribution in GLM because we don't have scale, auxiliary parameters included in cov_params.
not clear: I guess I should include var_weights in get_distribution #7528
for gaussian it should be obvious, similar to WLS
I guess the same for gamma and inverse gaussian
not clear for Binomial and Poisson, var_weights are for the case when endog are rates and proportions. I don't remember the details how this would work out.
Ambiguous case for NegativeBinomial and Tweedie. var_weights could be dispersion in likelihood.
We don't have a distribution class for Tweedie yet, so that raises NotImplementedError.
NegativeBinomial var_weights ?
Currently loglike_obs in all families include var_weights.
One of my unit tests that I'm currently writing fails, NegativeBinomial test case has results.scale != 1.
Currently scale in discrete GLM models can have dispersion to improve wald tests, cov_params. QMLE
But for get_distribution scale different from 1. does not define a proper distribution.
The actual problem I have is in unit tests. In family.get_distribution I ignore scale for Poisson and Negbin, so it's one.
The unit test uses #7528 var_endog = res1.model.family.variance(res1.fittedvalues) * res1.scale
which uses the "wrong" scale for the assumed NegativeBinomial.
AFAIK, we currently have no attribute as a flag for scale_mle = 1, instead we use explicit instance checks to special case those distributions
e.g. GLM.estimate_scale uses
if not self.scaletype:
if isinstance(self.family, (families.Binomial, families.Poisson,
families.NegativeBinomial)):
return 1.
else:
return self._estimate_x2_scale(mu)
we need either a binary or a 3-value flag:
for scale: Only discrete distribution have mle scale=1
for diagnostics: We might need discrete, continuous and mixed, where mixed handles tweedie (and might also apply to zero-inflated continuous mixture models when we add those).
I think I go for 3-values: dist_type="discrete" "continuous" and "mixed"
then we can use: if self.family.dist_type == "discrete": scale = 1
my plan for GLMDiagnostic class #130, #7166 is to have a continuous and a discrete version and ignore tweedie.
#2698 Binomial endog is converted to proportion
Poisson can handle rates when used together with var_weights.
for get_distribution we need the model and distribution for counts, and not for rates and proportions.
default is n_trials=1, ie. for a single Bernoulli trial, n_trials of sample is ignored
that corresponds to fittedvalues and similar which are for n=1, i.e. for proportions
optional n_trials keyword in family.Binomial.get_distribution to return distribution instance for binomial with n > 1
AFAICS, we don't have currently a predict for the counts in GLM binomial, i.e. expected counts for sample n_trials or user specified n_trials in predict.
GLM families Poisson, ... that don't have scale, ignore scale and var_weights arguments in the family get_distribution method.
It would be better to raise an exception or at least a warning if those are not 1 or None.
We need the arguments for generic calling consistency, but they should not be different from no-op default.
"""
new pattern for return shape, was inconsistent before:
get_distribution returns frozen distribution with 1-dim args, kwargs #8780
Activity
josef-pkt commentedon May 3, 2012
example that I just found again
http://statsmodels.sourceforge.net/devel/_modules/statsmodels/miscmodels/count.html#PoissonGMLE.predict_distribution
for some distributions we would have to create our own distribution class, e.g. zero inflated poisson
STATA has cdf and pmf probabilites directly as a post-estimation option
josef-pkt commentedon May 23, 2014
To answer a question http://stackoverflow.com/questions/23812355/statsmodels-plotting-the-fitted-distribution
I went through matching up the parameterization:
josef-pkt commentedon May 23, 2014
Frank is adding a
get_distributionmethod to the Results classes in https://github.com/chengfulun/statsmodels/compare/miceNegativeBinomial can follow the same pattern.
agartland commentedon May 27, 2016
@josef-pkt after trying to wrap my head around the parameterization myself, finding the above was very useful! Thanks. Did something like
get_distributionever make it into GLM result objects? Its very helpful to have anrvsfor diagnosing a fitjosef-pkt commentedon May 27, 2016
@agartland As far as I know it hasn't been merged systematically, and not for negative binomial.
The MICE version that was merged, uses PMM predictive mean matching which doesn't use get_distribution, AFAIR.
(I think I saw a get_distribution somewhere else in the code some time ago but don't remember.)
I wrote a simulate_tweedie function recently so that I was able to experiment with data that I know comes form the correctly specified distribution, but it's currently stuck in a notebook.
There was a question on stats.stackexchange a while ago about simulating Probit, which was incorrect. So, that is also not obvious to all users.
Poisson and Gaussian are easy because they have the standard mean (variance) parameterization. I don't remember Gamma, but IIRC I didn't have any surprised the last time I tried.
I should have the negative binomial parameter transformation above converted to helper functions, but don't remember where I put them, and whether I committed them somewhere.
njwhite commentedon Mar 20, 2017
@josef-pkt http://stackoverflow.com/a/23819461/42543 has logic for converting the
NegativeBinomialparameters intonandp, if that's useful.josef-pkt commentedon Feb 14, 2020
another one: GLM gamma does not look obvious
https://stackoverflow.com/questions/60215085/calculating-scale-dispersion-of-gamma-glm-using-statsmodels#60215085
AFAICS, the code in GLM.get_distribution is wrong for
scale != 1, i.e. doesn't match the full distribution even if though it gets the mean correctly.After trial and error and some math, I think it should be
y = np.random.gamma(shape=1 / scale, scale=y_expected * scale)aside: estimates don't look very close to data generating process if most x are large with inverse link
adjusted example from stackoverflow shows good agreement of parameters between estimates an DGP
josef-pkt commentedon Jun 27, 2021
GLM.get_distributionbinomial should not hard code n=1currently
dist.binom(n=1, p=fit)where
fit = self.predict(...)also NegativeBinomial, InverseGaussian and Tweedie are missing in
GLM.get_distributionfor Tweedie we should be able to get
rvsfrom Gamma-Poisson mixture but likely not much else for now.josef-pkt commentedon Jun 27, 2021
I just got confused again
scalein statsmodels is variance parameter not standard deviation parameterscalein scipy distribution is standard deviation parameter, i.e. it is rescaling the random variable.regression RegressionModels has get_distribution with
dist_class(loc=fit, scale=np.sqrt(scale))aside: maybe add
*argsinRegressionModel.get_distributionfor additional shape parameters, e.g. df for t-distribution.josef-pkt commentedon Jun 27, 2021
Design, interface
AFAICS, the current
get_distributionare methods of the models and most of them call model.predict.This does not support formulas.
We need a
Results.get_distributionmethod that should have similar interface asResults.predict, e.g. handle formula transformations.Computational:
Maybe it doesn't happen in results method if we just call predict.
Possible duplication between results.get_distribution and model.get_distribution.
discrete models do not have get_prediction, but NBP model class has
convert_params(self, params, mu)with different signature than get_prediction, i.e. uses precomputed mu for predicted mean.
My trial example is a 2-sample case, where I want get_prediction also just for the unique exog instead of for each observation.
another: in new
distributions.discrete.DiscretizedModel, I had usedget_distrmethod instead of full nameget_distributionjosef-pkt commentedon Jun 27, 2021
Usage, internal usecases
distributedAFAIR, GLM.get_distribution was added duringdistributedGSOC, file search doesn't find any usagejosef-pkt commentedon Jul 2, 2021
change in API in GLM
get_distribution(self, params, scale=1., ...scale needs to be used for norm, gamma, ...
With a default it is easy to make a mistake and forget about scale. (I just did.)
For this we need to treat scale in the same way as params:
We don't get inference on statistics based on the fully specified distribution in GLM because we don't have scale, auxiliary parameters included in cov_params.
josef-pkt commentedon Jul 2, 2021
I'm going to move the family specific part of GLM.get_distribution to the family classes, instead of using the current isinstance checks.
josef-pkt commentedon Jul 2, 2021
not clear: I guess I should include
var_weightsin get_distribution #7528for gaussian it should be obvious, similar to WLS
I guess the same for gamma and inverse gaussian
not clear for Binomial and Poisson, var_weights are for the case when endog are rates and proportions. I don't remember the details how this would work out.
Ambiguous case for NegativeBinomial and Tweedie. var_weights could be dispersion in likelihood.
We don't have a distribution class for Tweedie yet, so that raises NotImplementedError.
NegativeBinomial var_weights ?
Currently loglike_obs in all families include var_weights.
josef-pkt commentedon Jul 2, 2021
reminder: GLM NegativeBinomial is NB2, I will add it to the family docstring
according to the conversion in a comment above this, NB2, Q=0, corresponds to
where
alphais the fixed family parameterjosef-pkt commentedon Jul 5, 2021
problem with scale:
One of my unit tests that I'm currently writing fails, NegativeBinomial test case has results.scale != 1.
Currently scale in discrete GLM models can have dispersion to improve wald tests, cov_params. QMLE
But for get_distribution scale different from 1. does not define a proper distribution.
The actual problem I have is in unit tests. In family.get_distribution I ignore scale for Poisson and Negbin, so it's one.
The unit test uses #7528
var_endog = res1.model.family.variance(res1.fittedvalues) * res1.scalewhich uses the "wrong" scale for the assumed NegativeBinomial.
AFAIK, we currently have no attribute as a flag for scale_mle = 1, instead we use explicit instance checks to special case those distributions
e.g.
GLM.estimate_scaleuseswe need either a binary or a 3-value flag:
for scale: Only discrete distribution have mle scale=1
for diagnostics: We might need discrete, continuous and mixed, where mixed handles tweedie (and might also apply to zero-inflated continuous mixture models when we add those).
I think I go for 3-values:
dist_type="discrete""continuous" and "mixed"then we can use:
if self.family.dist_type == "discrete": scale = 1my plan for GLMDiagnostic class #130, #7166 is to have a continuous and a discrete version and ignore tweedie.
josef-pkt commentedon Jul 5, 2021
not clear yet: Rates and Proportions in GLM
#2698 Binomial endog is converted to proportion
Poisson can handle rates when used together with var_weights.
for
get_distributionwe need the model and distribution for counts, and not for rates and proportions.josef-pkt commentedon Jul 6, 2021
Binomial: get_distribution in #7535
that corresponds to fittedvalues and similar which are for n=1, i.e. for proportions
AFAICS, we don't have currently a predict for the counts in GLM binomial, i.e. expected counts for sample n_trials or user specified n_trials in predict.
josef-pkt commentedon Apr 14, 2023
copied from #8723 (comment)
"""
Another "cleanup"
GLM families Poisson, ... that don't have scale, ignore scale and var_weights arguments in the family get_distribution method.
It would be better to raise an exception or at least a warning if those are not 1 or None.
We need the arguments for generic calling consistency, but they should not be different from no-op default.
"""
new pattern for return shape, was inconsistent before:
get_distribution returns frozen distribution with 1-dim args, kwargs #8780
[-]add rvs or distributions to families[/-][+]ENH/SUMM: add rvs or distributions to families[/+]josef-pkt commentedon Apr 14, 2023
keeping this open for now as SUMM issue.
We will need a new SUMM or roadmap issue with remaining issues and todos for
get_distribution(but I don't have a full overview right now)