Repository navigation
Penalized mle scad rebased2 #4576
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
b7f7697
c8bb33f
9bcaa6c
51ae68e
53113ac
4275012
2b40d01
ffec867
b3d7f36
1fd64b8
8a48481
cc80a7a
8eae204
b1ce0b7
7bead12
513b64b
b5de3f9
cbde690
74a8649
dc5c9a0
367a4b6
7938389
8eef828
7f33d63
cbb3f85
86a9018
9089b7a
d8e40d2
d45786d
e733e04
c26dbfc
d24a9ef
97cd6d6
412bf82
2509eea
69d5f2f
e5b883c
6002174
e2df1f3
2aa55e8
4ece026
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,195 @@ | ||
| # -*- coding: utf-8 -*- | ||
| """ | ||
| Created on Sun May 10 08:23:48 2015 | ||
|
|
||
| Author: Josef Perktold | ||
| License: BSD-3 | ||
| """ | ||
|
|
||
| import numpy as np | ||
| from ._penalties import NonePenalty | ||
| from statsmodels.tools.numdiff import approx_fprime_cs, approx_fprime | ||
|
|
||
|
|
||
| class PenalizedMixin(object): | ||
| """Mixin class for Maximum Penalized Likelihood | ||
|
|
||
| Parameters | ||
| ---------- | ||
| args and kwds for the model super class | ||
| penal : None or instance of Penalized function class | ||
| If penal is None, then NonePenalty is used. | ||
| pen_weight : float or None | ||
| factor for weighting the penalization term. | ||
| If None, then pen_weight is set to nobs. | ||
|
|
||
|
|
||
| TODO: missing **kwds or explicit keywords | ||
|
|
||
| TODO: do we adjust the inherited docstrings? | ||
| We would need templating to add the penalization parameters | ||
|
|
||
| """ | ||
|
|
||
| def __init__(self, *args, **kwds): | ||
|
|
||
| # pop extra kwds before calling super | ||
| self.penal = kwds.pop('penal', None) | ||
| self.pen_weight = kwds.pop('pen_weight', None) | ||
|
|
||
| super(PenalizedMixin, self).__init__(*args, **kwds) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. does this do anything here? base class is
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is important. With multiple inheritance the |
||
|
|
||
| # TODO: define pen_weight as average pen_weight? i.e. per observation | ||
| # I would have prefered len(self.endog) * kwds.get('pen_weight', 1) | ||
| # or use pen_weight_factor in signature | ||
| if self.pen_weight is None: | ||
| self.pen_weight = len(self.endog) | ||
|
|
||
| if self.penal is None: | ||
| # unpenalized by default | ||
| self.penal = NonePenalty() | ||
| self.pen_weight = 0 | ||
|
|
||
| self._init_keys.extend(['penal', 'pen_weight']) | ||
|
|
||
| def loglike(self, params, pen_weight=None, **kwds): | ||
| if pen_weight is None: | ||
| pen_weight = self.pen_weight | ||
|
|
||
| llf = super(PenalizedMixin, self).loglike(params, **kwds) | ||
| if pen_weight != 0: | ||
| llf -= pen_weight * self.penal.func(params) | ||
|
|
||
| return llf | ||
|
|
||
|
|
||
| def loglikeobs(self, params, pen_weight=None, **kwds): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To be consistent with statsmodels.genmod.familes, perhaps
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, I prefer
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I leave it to another PR to change loglikeobs in discrete and here. |
||
| if pen_weight is None: | ||
| pen_weight = self.pen_weight | ||
|
|
||
| llf = super(PenalizedMixin, self).loglikeobs(params, **kwds) | ||
| nobs_llf = float(llf.shape[0]) | ||
|
|
||
| if pen_weight != 0: | ||
| llf -= pen_weight / nobs_llf * self.penal.func(params) | ||
|
|
||
| return llf | ||
|
|
||
| def score_numdiff(self, params, pen_weight=None, method='fd', **kwds): | ||
| """score based on finite difference derivative | ||
|
|
||
| """ | ||
| if pen_weight is None: | ||
| pen_weight = self.pen_weight | ||
|
|
||
| loglike = lambda p: self.loglike(p, pen_weight=pen_weight, **kwds) | ||
|
|
||
| if method == 'cs': | ||
| return approx_fprime_cs(params, loglike) | ||
| elif method == 'fd': | ||
| return approx_fprime(params, loglike, centered=True) | ||
| else: | ||
| raise ValueError('method not recognized, should be "fd" or "cs"') | ||
|
|
||
| def score(self, params, pen_weight=None, **kwds): | ||
| if pen_weight is None: | ||
| pen_weight = self.pen_weight | ||
|
|
||
| sc = super(PenalizedMixin, self).score(params, **kwds) | ||
| if pen_weight != 0: | ||
| sc -= pen_weight * self.penal.grad(params) | ||
|
|
||
| return sc | ||
|
|
||
| def score_obs(self, params, pen_weight=None, **kwargs): | ||
| if pen_weight is None: | ||
| pen_weight = self.pen_weight | ||
|
|
||
| sc = super(PenalizedMixin, self).score_obs(params, **kwargs) | ||
| nobs_sc = float(sc.shape[0]) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not a big deal, but any reason why
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't remember, but it's just a temp variable over a few lines |
||
| if pen_weight != 0: | ||
| sc -= pen_weight / nobs_sc * self.penal.grad(params) | ||
|
|
||
| return sc | ||
|
|
||
| def hessian_numdiff(self, params, pen_weight=None, **kwds): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does this need to be part of the public API, or is it analogous to e.g.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I keep it public. It is convenient to check new penalty functions that we or users can add. |
||
| """hessian based on finite difference derivative | ||
|
|
||
| """ | ||
| if pen_weight is None: | ||
| pen_weight = self.pen_weight | ||
| loglike = lambda p: self.loglike(p, pen_weight=pen_weight, **kwds) | ||
|
|
||
| from statsmodels.tools.numdiff import approx_hess | ||
| return approx_hess(params, loglike) | ||
|
|
||
| def hessian(self, params, pen_weight=None, **kwds): | ||
| if pen_weight is None: | ||
| pen_weight = self.pen_weight | ||
|
|
||
| hess = super(PenalizedMixin, self).hessian(params, **kwds) | ||
| if pen_weight != 0: | ||
| h = self.penal.deriv2(params) | ||
| if h.ndim == 1: | ||
| hess -= np.diag(pen_weight * h) | ||
| else: | ||
| hess -= pen_weight * h | ||
|
|
||
| return hess | ||
|
|
||
| def fit(self, method=None, trim=None, **kwds): | ||
| """minimize negative penalized log-likelihood | ||
|
|
||
| Parameters | ||
| ---------- | ||
| method : None or str | ||
| Method specifies the scipy optimizer as in nonlinear MLE models. | ||
| trim : Boolean or float | ||
| Default is False or None, which uses no trimming. | ||
| If trim is True or a float, then small parameters are set to zero. | ||
| If True, then a default threshold is used. If trim is a float, then | ||
| it will be used as threshold. | ||
| The default threshold is currently 1e-4, but it will change in | ||
| future and become penalty function dependent. | ||
| kwds : extra keyword arguments | ||
| This keyword arguments are treated in the same way as in the | ||
| fit method of the underlying model class. | ||
| Specifically, additional optimizer keywords and cov_type related | ||
| keywords can be added. | ||
|
|
||
| """ | ||
| # If method is None, then we choose a default method ourselves | ||
|
|
||
| # TODO: temporary hack, need extra fit kwds | ||
| # we need to rule out fit methods in a model that will not work with | ||
| # penalization | ||
| if hasattr(self, 'family'): # assume this identifies GLM | ||
| kwds.update({'max_start_irls' : 0}) | ||
|
|
||
| # currently we use `bfgs` by default | ||
| if method is None: | ||
| method = 'bfgs' | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. maybe better lbfgs |
||
|
|
||
| if trim is None: | ||
| trim = False | ||
|
|
||
| res = super(PenalizedMixin, self).fit(method=method, **kwds) | ||
|
|
||
| if trim is False: | ||
| # note boolean check for "is False", not "False_like" | ||
| return res | ||
| else: | ||
| if trim is True: | ||
| trim = 1e-4 # trim threshold | ||
| # TODO: make it penal function dependent | ||
| # temporary standin, only checked for Poisson and GLM, | ||
| # and is computationally inefficient | ||
| drop_index = np.nonzero(np.abs(res.params) < trim) [0] | ||
| keep_index = np.nonzero(np.abs(res.params) > trim) [0] | ||
|
|
||
| if drop_index.any(): | ||
| # TODO: do we need to add results attributes? | ||
| res_aux = self._fit_zeros(keep_index, **kwds) | ||
| return res_aux | ||
| else: | ||
| return res | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
timestamp accurate?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, that was timestamp in my original PR