Skip to content

ENH/SUMM: add rvs or distributions to families #106

Open

Description

@josef-pkt

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")

Activity

  1. josef-pkt commented on May 3, 2012

    @josef-pkt
    MemberAuthor

    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

  2. josef-pkt commented on May 23, 2014

    @josef-pkt
    MemberAuthor

    To answer a question http://stackoverflow.com/questions/23812355/statsmodels-plotting-the-fitted-distribution
    I went through matching up the parameterization:

    # -*- coding: utf-8 -*-
    """
    Created on Thu May 22 19:30:54 2014
    
    Author: Josef Perktold
    License: BSD-3
    
    """
    
    
    import numpy as np
    from scipy import stats
    import statsmodels.api as sm
    
    nobs = 1000
    n, p = 50, 0.25
    dist0 = stats.nbinom(n, p)
    y = dist0.rvs(size=nobs)
    x = np.ones(nobs)
    
    loglike_method = 'nb1'
    res = sm.NegativeBinomial(y, x, loglike_method=loglike_method).fit(start_params=[0.1, 0.1])
    
    print dist0.mean()
    print res.params
    
    mu = res.predict()   # use if not constant
    mu = np.exp(res.params[0])
    alpha = res.params[1]
    
    if loglike_method == 'nb1':
        Q = 1
    elif loglike_method == 'nb2':    
        Q = 0
    
    size = 1. / alpha * mu**Q
    prob = size / (size + mu)
    
    print 'data generating parameters', n, p
    print 'estimated params          ', size, prob
    
    #estimated distribution
    dist_est = stats.nbinom(size, prob)
    
    #compare
    
    #dist_est.pmf()
    
  3. josef-pkt commented on May 23, 2014

    @josef-pkt
    MemberAuthor

    Frank is adding a get_distribution method to the Results classes in https://github.com/chengfulun/statsmodels/compare/mice

    NegativeBinomial can follow the same pattern.

  4. modified the milestones: 0.6, 0.7 on Aug 17, 2014
  5. agartland commented on May 27, 2016

    @agartland

    @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

  6. josef-pkt commented on May 27, 2016

    @josef-pkt
    MemberAuthor

    @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.

  7. njwhite commented on Mar 20, 2017

    @njwhite
  8. josef-pkt commented on Feb 14, 2020

    @josef-pkt
    MemberAuthor

    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

    np.random.seed(1)
    
    # Generate data
    x=np.random.uniform(0, 10,50000)
    x2 = sm.add_constant(x)
    a = 0.5
    b = 0.2
    y_true = 1/(a+(b*x))
    # Add error 
    scale = 2 # the scale parameter I'm trying to obtain
    shape = y_true/scale # given that, for Gamma, mu = scale*shape
    #y = np.random.gamma(shape=shape, scale=scale)
    
    #JP try other parameterization
    y = np.random.gamma(shape=1 / scale, scale=y_true * scale)
    #y = np.random.gamma(shape=0.5, scale=y_true/0.5)
    
    # Run model
    model = sm.GLM(y, x2, family=sm.families.Gamma()).fit() #method='newton') 
    
    model.summary()
    
                     Generalized Linear Model Regression Results                  
    ==============================================================================
    Dep. Variable:                      y   No. Observations:                50000
    Model:                            GLM   Df Residuals:                    49998
    Model Family:                   Gamma   Df Model:                            1
    Link Function:          inverse_power   Scale:                          1.9929
    Method:                          IRLS   Log-Likelihood:                -23286.
    Date:                Thu, 13 Feb 2020   Deviance:                   1.2752e+05
    Time:                        21:51:33   Pearson chi2:                 9.96e+04
    No. Iterations:                     9                                         
    Covariance Type:            nonrobust                                         
    ==============================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    const          0.5079      0.010     49.866      0.000       0.488       0.528
    x1             0.1973      0.003     68.433      0.000       0.192       0.203
    ==============================================================================
    
  9. removed this from the 0.7 milestone on Apr 6, 2021
  10. josef-pkt commented on Jun 27, 2021

    @josef-pkt
    MemberAuthor

    GLM.get_distribution binomial should not hard code n=1
    currently dist.binom(n=1, p=fit)
    where fit = self.predict(...)

    also NegativeBinomial, InverseGaussian and Tweedie are missing in GLM.get_distribution

    for Tweedie we should be able to get rvs from Gamma-Poisson mixture but likely not much else for now.

  11. josef-pkt commented on Jun 27, 2021

    @josef-pkt
    MemberAuthor

    I just got confused again

    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.

  12. josef-pkt commented on Jun 27, 2021

    @josef-pkt
    MemberAuthor

    Design, interface

    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

  13. josef-pkt commented on Jun 27, 2021

    @josef-pkt
    MemberAuthor

    Usage, internal usecases

    • 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)
    • ...?
  14. josef-pkt commented on Jul 2, 2021

    @josef-pkt
    MemberAuthor

    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.

  15. josef-pkt commented on Jul 2, 2021

    @josef-pkt
    MemberAuthor

    I'm going to move the family specific part of GLM.get_distribution to the family classes, instead of using the current isinstance checks.

            if isinstance(self.family, families.Gaussian):
                return dist.norm(loc=fit, scale=np.sqrt(scale))
    
            elif isinstance(self.family, families.Binomial):
                return dist.binom(n=1, p=fit)
    ...
    
  16. josef-pkt commented on Jul 2, 2021

    @josef-pkt
    MemberAuthor

    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.

  17. josef-pkt commented on Jul 2, 2021

    @josef-pkt
    MemberAuthor

    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

    size = 1. / alpha
    prob = size / (size + mu)
    dist_est = stats.nbinom(size, prob)
    

    where alpha is the fixed family parameter

  18. josef-pkt commented on Jul 5, 2021

    @josef-pkt
    MemberAuthor

    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.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.

  19. josef-pkt commented on Jul 5, 2021

    @josef-pkt
    MemberAuthor

    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_distribution we need the model and distribution for counts, and not for rates and proportions.

  20. josef-pkt commented on Jul 6, 2021

    @josef-pkt
    MemberAuthor

    Binomial: get_distribution in #7535

    • 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.

  21. josef-pkt commented on Apr 14, 2023

    @josef-pkt
    MemberAuthor

    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

  22. changed the title [-]add rvs or distributions to families[/-] [+]ENH/SUMM: add rvs or distributions to families[/+] on Apr 14, 2023
  23. josef-pkt commented on Apr 14, 2023

    @josef-pkt
    MemberAuthor

    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)

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

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions