Skip to content

ENH: add dispersion models, heteroscedasticity with full MLE - #7778

Open
josef-pkt wants to merge 8 commits into
statsmodels:mainfrom
josef-pkt:dispersion_models
Open

josef-pkt wants to merge 8 commits into
statsmodels:mainfrom
josef-pkt:dispersion_models

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Oct 2, 2021 •

Copy link
Copy Markdown
Member

update this has been generalized to MultiLinkModel, not restricted to mean-variance models anymore.

see #7639

getting started

code based on miscmodels TLinearModel and __init__ from BetaModel.

class structure not clear yet

  • 2-parameter version is largely generic, currently Gaussian and Gamma as subclasses, currently only link_scale, no link for mean
    gamma will need link for mean for endog and mean > 0
  • T model 3 parameter model with possibility to constrain 3 parameter to fixed value, only link_scale, mean mean link, and df inoriginal parameterization,, no link to force > 0 (or > eps)

Most likely distribution specific code, loglike, ..., will be delegated to new family classes (or genmod families if available) #7769

@pep8speaks

pep8speaks commented Oct 2, 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-10-11 20:06:35 UTC

@lgtm-com

lgtm-com Bot commented Oct 2, 2021

Copy link
Copy Markdown

This pull request introduces 3 alerts when merging 3d8b5b0 into f67fc16 - view on LGTM.com

new alerts:

  • 2 for Unused import
  • 1 for Unused local variable

@josef-pkt

josef-pkt commented Oct 2, 2021 •

Copy link
Copy Markdown
Member Author

I'm also getting a discrepancy in scale estimate between GammaHet and GLM-Gamma.
That seems to be #7526 (comment)

If I fix the scale and use observed hessian in GLM, then cov_params are close to inverting the mean parameter part of MLE negative hessian.

The GammaHet MLE model here estimates constant scale, exog_scale is ones.

mod_gamm is GammaHet
res_g is GLM-Gamma

h = mod_gamm.hessian(res_gamm.params)
cov_mp = np.linalg.inv(-h[:2, :2])  

cov_mp / res_g.cov_params()
array([[0.99462738, 1.00100461],
       [1.00100461, 1.00711887]])

with good agreement on params (using default convergence tolerance and bfgs in both models)

res_gamm.params, res_g.params, res_gamm.params[:2] / res_g.params - 1
(array([0.00658727, 0.07562221, 0.93225802]),
 array([0.00658726, 0.07562214]),
 array([9.15233469e-07, 9.38663903e-07]))

@josef-pkt

Copy link
Copy Markdown
Member Author

Gamma model with estimated heteroscedasticity compared to GLM-gamma with var_weight = 1 / scale_predicted_mle
GLM gamma with fixed scale=1

params agree,
bse differ by around 5% (bse from full MLE model, inverting hessian, not inverting submatrix of hessian)

res_gamm2.params, res_g2.params, res_gamm2.params[:2] / res_g2.params - 1
(array([0.00601749, 0.06861526, 0.88220389, 3.38323729]),
 array([0.00601748, 0.06861521]),
 array([7.76995125e-07, 8.07322542e-07]))

res_gamm2.bse, res_g2.bse, res_gamm2.bse[:2] / res_g2.bse #- 1
(array([1.30617706e-03, 1.58849550e-02, 1.51875160e-01, 2.80790159e+00]),
 array([0.00124546, 0.01503052]),
 array([1.04875205, 1.05684657]))

bse are closer if we use mean-parameter submatrix of hessian

hess2 = mod_gamm2.hessian(res_gamm2.params)
bse_mp2 = np.sqrt(np.diag(np.linalg.inv(-hess2[:2, :2])))
bse_mp2
array([0.00124338, 0.01508773])

bse_mp2, res_g2.bse, bse_mp2 / res_g2.bse
(array([0.00124338, 0.01508773]),
 array([0.00124546, 0.01503052]),
 array([0.99832867, 1.00380628]))

(one parameter) GLM/LEF: also have mean orthogonal to scale/dispersion (EIM)

@josef-pkt

josef-pkt commented Oct 3, 2021 •

Copy link
Copy Markdown
Member Author

maybe I should try johnsonsu as a 4 parameter distribution, 2 mean like and 2 var/scale like parameters. two identity links and two log links.

maybe similar to copula distribution and CopulaModel, with a list of marginals, Here it would be a list of links and a tuple of args.

The list of links could be in generic code, base classes. When we have a specific subclass we can use named keywords for the links.
One decision problem is on the names of the parameters.
johnsonsu in scipy has (a, b, loc, scale)
in wikipedia it's all greek (xi, lambda, gamma, delta) (which I would remember for about 15 seconds)

In terms of transformation (a, b) are loc and scale in the base (normal) distribution that is sinh transformed.
Because, johnsonsu is in general not symmetric, loc is not the mean.

mean in wikipedia is
{ \xi -\lambda \exp {\frac {\delta ^{-2}}{2}}\sinh \left({\frac {\gamma }{\delta }}\right)}

another question: Do we want to have offset for each parameters?

(Could we use offset and empty exog for one of a parameter? Would that be easier than using the constraint mask?)

@josef-pkt

Copy link
Copy Markdown
Member Author

likely design
Keep loc/mean, scale as main parameters as in Het2pModel, but add additional args for shape parameters.
This would also cover the t model.
Models for endog > 0, would need fixed loc=0. e.g. model(endog, 0, exog_scale=...) use exog=0 as flag that the first arg, i.e. loc, is zero. This would cover weibull, and scale-AFT models with shape parameters.

The default for args, if no exog for them is specified, is constant, and identity link.

Limited constraints: fix arg, but don't fix coefficients for exog within arg.
E.g. this could be model(endog, exog, exog_extra=(df, ), ...) for t-distribution with fixed df, or
model(endog, exog, exog_extra=(None, 1), ...) for johnsonsu with estimated constant loc of base distribution and scale of base distribution fixed to 1. model(endog, exog, exog_extra=(x_baseloc, 1), ...)

I'm not sure yet how to specify exog_extra, If we use tuple exog_extra=(x_baseloc, x_basescale), then we don't need shape names.


fun, when it works, first try

nobs = 1000, constant parameters, exogs are ones

class Johnsonsu(HetkpModel):
    
    def _loglikeobs(self, mu, scale, *args, endog=None):
        if self.k_args == 2:
            ll_obs = stats.johnsonsu.logpdf(endog, 0, 1, mu, scale)
        else:
            ll_obs = stats.johnsonsu.logpdf(endog, *args, mu, scale)
        return ll_obs

image

@josef-pkt

Copy link
Copy Markdown
Member Author

gamlss has JSU with 4 link functions
https://search.r-project.org/CRAN/refmans/gamlss.dist/html/JSU.html

parameters:
mu | vector of location parameter values
sigma | vector of scale parameter values
nu | vector of skewness nu parameter values
tau | vector of kurtosis tau parameter values

and "obvious" link defaults
mu.link = "identity", sigma.link = "log", nu.link = "identity", tau.link = "log"

aside:
gamlss also adds links to family, like GLM
https://search.r-project.org/CRAN/refmans/gamlss.dist/html/gamlss.family.html

@josef-pkt

Copy link
Copy Markdown
Member Author

I need unit test, just regression tests, so I don't mess up (much) during refactoring.

MultiLinkModel is still missing pieces to support links and exog for all distribution parameters.

@josef-pkt

Copy link
Copy Markdown
Member Author

links are not yet implemented for all params, currently only link_scale.
If we make family required, then links would not be in the __init__ signature of the model if they are attached to the family as in GLM.

We also have the new BetaModel as comparison test case available. It follows the same Het pattern, but uses precision instead of scale.

Currently MultiLinkModel is agnostic to the meaning of the parameters. We have 2 explicit and an arbitrary number of extra parameters. Interpretation of parmeters depends on the loglikelihood function which generically delegates to _loglikeobs implemented by subclass, or in future by families
ll_obs = self._loglikeobs(*args, endog=self.endog)

This means that families like Beta could just interpret the second arg as precision.
Similarly, the first parameter is either mean or loc, e.g. in positive LEF models, loc is fixed and the first parameter is mean.
I guess, this also means that in AFT, we could just use the first parameter as scale or precision.
However, currently MultiLinkModel is implemented for distributions with at least 2 parameters. AFT models have one main parameter plus optional extra parameters.

If we add subclasses of MultiLinkModel that are for categories of models, and delegate e.g. a scipy distribution, then we would have to choose a parameterization, e.g. either scale or precision in AFT-type models.

On naming problem is that MultiLinkModel use names, mean, scale, based on the initial Het dispersion/ heteroscedasticity models. This will be confusing if scale in the specific case is actually precision.
I don't really want to switch to more generic parameter names par0, par1.

@josef-pkt

Copy link
Copy Markdown
Member Author

BetaMultiLinkModel as testcase also works, compared with betareg.BetaModel.
However, the scale parameter now is actually precision, i.e. inverse scale.

I'm not happy with the nongeneric name scale for the second parameter.

not yet: #7666 generalized extreme value and weibull
first parameter is scale/precision, second parameter is a shape parameter

exponential distribution is not supported by MultiLink because it has only 1 parameter.

@josef-pkt

Copy link
Copy Markdown
Member Author

code style check sucks: import warnings, os E401 multiple imports on one line

test failures on some machines with BetaMultilink bse when using rtol = 1e-5, atol = 1e-5
I guess convergence tolerance and numdiff hessian. BetaModel has analytical hessian and clips at eps > 0
I try with rtol = 1e-4.

@josef-pkt

Copy link
Copy Markdown
Member Author

eponential is also a special case of gamma GLM with dispersion parameter scale=1, according to answers here
https://stats.stackexchange.com/questions/240455/fitting-exponential-regression-model-by-mle
We also have it as special case in DiscreteNegativeBinomial. (? I never tried. NegBin is discrete)

The main other one parameter families are discrete, like Binomial, Bernoulli, Logit, Probit, and Poisson.

Related 2 parameter family (that I wanted for a long time) Beta-Binomial.
Problem is that it needs the number of trials like Binomial, which doesn't directly fit in the current setting.
If we model proportion (like internally in GLM binomial), then we would need var_weights in generic implementation. Otherwise, we need exposure/n_trials. None of them are available in the current MultiLinkModel.
Without explicit support, a subclass could still use it in _loglikeobs (using init` kwarg n_trials attribute)

In my current examples, _loglikeobs is "static", i.e. does not use any state in self (endog is currently required even though endog=None is keyword arg)

@josef-pkt

josef-pkt commented Oct 8, 2021 •

Copy link
Copy Markdown
Member Author

Beta-Binomial works essentially out of the box, based on #2632 (comment)

Example with nobs i= 1000, constant mean and dispersion, n_trials=7
Estimated results in terms of predicted standard BB distribution parameters a, b and implied mean, variance agree well with data generating process.

stats.betabinom.rvs(n, a, b
nobs = 5000
y_bb = stats.betabinom.rvs(n, a, b, size=nobs)
ex_const = np.ones(nobs)[:, None]
ex_trend = np.column_stack((np.ones(nobs), np.linspace(-1, 1, nobs)))

mod = BetaBinomialMultiLink(y_bb, ex_const, exog_scale=ex_const, 
                            link=links.Logit(),
                            link_scale=links.Log(),
                            n_trials=n * np.ones(nobs),
                            k_extra=0,
                           )
res = mod.fit(start_params=[0.5, 0.1], method="bfgs")
print(res.summary())
m_est, s_est = mod._predict_dargs(res.params)

convert_ms(m_est[0], 1 / s_est[0], n)
(7, 4.963919299079351, 5.8947670006941415)
n, a, b
(7, 5, 6)

stats.betabinom.stats(n, a, b)
(array(3.18181818), array(2.60330579))
 
n * m_est[0], var_scale(m_est[0], s_est[0], constant n_trials=n)
(3.19996674867385, 2.61606030021153)

df_model is still wrong in BB, with 2 exog each, I have df_model=3, it should be 2 (2 slope exog in total)

@josef-pkt

josef-pkt commented Oct 8, 2021 •

Copy link
Copy Markdown
Member Author

The basics for MultiLinkModel works.

Where do we put it?
MultiLink should be a base model similar to GenericLikelihoodModel, but base.model is getting large.
Another option is to add a base_multilink module in othermod.

How much more do we generalize the MultiLink class?

Currently, the user needs to provide start_params. In the general case, the first two distribution parameters, mean and variance/scale based on the Het interpretation, could be anything. We don't have enough information to compute reasonable start_params by default. (e.g. scale versus precision versus some kind of dispersion parameter)

Predict is not yet generalized to multilink. The assumption is that the first distribution parameter and first exog provides the mean. That's only true for models with mean parameterization, GLM-families, Beta, BetaBinomial and symmetric families like gaussian and T. It will not be the mean in survival/lifetime models like AFT, or in extreme value analysis, genextreme, genpareto.

I still don't like the misuse of the name scale which could mean anything.

Het could be a subclass, that adds additional parts that rely on mean-scale parameterization
(aside: Heteroscedasticity is also not precise, because all GLM families except Gaussian are inherently heteroscedastic. The additional Het is dispersion (a variance parameter) that depends on some exog.
)

Specific Extensions:
Offsets and freq_weights can be generically implemented (in analogy to GLM).
I'm not sure if var_weights would add any additional benefits, given that we are already modelling the variance/dispersion.

What are useful subclasses of MultiLinkModel?

e.g.

  • The original HET case: first parameter mean, second parameter scale, EIM is block diagonal in mean parameter versus other parameters. eg. z = (y - m) / sqrt(s) E(y) = m parameterization (m, s) or (m, 1/s) (Gamma doesn't have this)
  • non-orthogonal HET, some loc parameter and some dispersion/variance parameter plus extra params, e.g. skewed distributions lik johnsonsu.
  • distributions on R+ with loc fixed and no mean parameterization, e.g. AFT,

@josef-pkt

josef-pkt commented Oct 8, 2021 •

Copy link
Copy Markdown
Member Author

and minimal Weibull that works
df_model = 1 is still wrong. this should be df_null = 0, i.e. constant only model with 2 constants
default param names don't make sense for this parameterization

class WeibullMultiLink(odm.MultiLinkModel):
​
    def _loglikeobs(self, sc, sh, endog=None):
        params_ex = sc
        params_shape = sh
        llf = stats.weibull_min.logpdf(
            endog, params_shape, scale=np.sqrt(sc))
        return llf

sc, sh = 10, 1
np.random.seed(489981634)
y_wei = stats.weibull_min.rvs(sh, scale=np.sqrt(sc), size=nobs)
​
mod = WeibullMultiLink(y_wei, ex_const, exog_scale=ex_const, 
                            link=links.identity(), #Log(),
                            link_scale=links.identity(),
                            k_extra=0,
                           )
sdp = [10, 1]
sp = [mod.link(sdp[0]), mod.link_scale(sdp[1])]
res = mod.fit(start_params=sp, method="bfgs")
print(res.summary(xname=["scale", "shape"]))

GeneralizedPoisson also works

@josef-pkt

josef-pkt commented Oct 9, 2021 •

Copy link
Copy Markdown
Member Author

preliminary plan for modules:

  • othermod.base_model contains MultiLinkModel and MeanHetModel (or a name like that, HetModel, DispersionModel, ?)
  • othermod.dispersion_model: models for specific families/distributions, Gaussian, T, maybe johnsonsu (*)
  • discrete.dispersion_model: BetaBinomial, GPPHet, NegBinPHet, maybe some base on DiscretizeCountDistribution
  • discrete.count_model: add zeroinflated version of dispersionmodel, 3 part models, subclass of ZeroInflated
  • ???: families on R+, AFT, where do does go?
  • ???: other families for [0, 1]: more than BetaModel, where do those go?

another generic class: CensoredModel and TruncatedModels
we need those for AFT, censored survival data, hurdle models for counts
#7638 censoring and truncation,
#7165 truncated count
Classes using cdf will need to distinguish between discrete and continuous models.
sf for discrete requires adjustment if we want Prob(y >= k) = sf(k - 1)

(*) johnsonsu and other skewed distributions on real line will have a loc instead of mean parameter.
predict will need to be different.

statsmodels.distributions.dfamilies as api module, collecting classes from
_dfamilies_cont
_dfamilies_discrete
and possibly _dfamilies_mixed

If we get a larger number of distribution families, then we should split in submodules like scipy.

@josef-pkt

josef-pkt commented Oct 10, 2021 •

Copy link
Copy Markdown
Member Author

I'm thinking now more of not really naming the second parameter, and use numbering instead, e.g. exog_1
To get inherited data handling, we could unwrap the exog_extras, e.g. exog_2, exog_3 in call to super.

Maybe zero based names is not so intuitive: exog, exog_2, exog_3, ...
Internally we need a list, but that just holds references to the individual attribute, so no extra memory.

Not nice, but we could put exog extras in kwargs, and corresponding links.
If we have two named parameters, then putting extras in kwargs might not be so bad because it is only for extra parameters that are unlikely to have exog, like df in t-distribution.

Problem: If we don't store, __init__ arguments as attributes with the same name, similar to exposure, ...then we need to make sure to get correct _init_kwds, get_init_kwds.
Might not be so bad in this case because we don't transform any data arrays.

Names of distribution parameters, like "scale" are only used in summay() and maybe returned dataframes.

@josef-pkt

Copy link
Copy Markdown
Member Author

naming

Should I rename dargs to dparams for distribution parameters?
No, dargs sounds more like a tuple (similar to use in copulas).
dparams sounds more like an array that includes all distribution parameters

@josef-pkt

Copy link
Copy Markdown
Member Author

one more design decision:

In base class MultiLinkModel, I could include the second parameter among the extras.
Then we only have one named and required parameter, all others are in lists and optional.
Internally for the computations we could even have all dargs in lists, so we have just one loop over dargs.

The dispersion/het subclass could still have two explicit parameters and the others as optional extras.

@josef-pkt

Copy link
Copy Markdown
Member Author

superseded by #7793 which contains most code of this PR (but not the history)

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

Labels

comp-othermod superseded Used for PRs with content that is superseded by a newer PR type-enh

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants