Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
b7f7697
ENH: add SCAD to base._penalties
josef-pkt Apr 27, 2015
c8bb33f
BUG penalties missing weights
josef-pkt May 12, 2015
9bcaa6c
ENH: PenalizedMixin with Poisson test case
josef-pkt May 12, 2015
51ae68e
REF: PenalizedMixin python 2 compatibility
josef-pkt May 13, 2015
53113ac
ENH: linear model fit raise if method is unknown
josef-pkt May 13, 2015
4275012
ENH: add LikelihoodModel._fit_zeros, several hacks see #2393
josef-pkt May 13, 2015
2b40d01
ENH/REF: add LikelihoodModel._fit_collinear, adjust _fit_zeros and tests
josef-pkt May 14, 2015
ffec867
TST: use same optimizer method to replicate fit
josef-pkt May 14, 2015
b3d7f36
REF _fit_zeros copy mle_settings to results instance
josef-pkt May 14, 2015
1fd64b8
TST lower precision in test_zero_collinear
josef-pkt May 15, 2015
8a48481
TST: test_zero_collinear: check first we got correct optimizer kwds
josef-pkt May 15, 2015
cc80a7a
TST test_zero_collinear lower precision for resid and predict
josef-pkt May 15, 2015
8eae204
TST: TestGenericNegativeBinomial add const, test_zero_collinear lower…
josef-pkt May 15, 2015
b1ce0b7
REF: use auxiliary fit params as starting values for result creation
josef-pkt May 15, 2015
7bead12
TST: test_zero_collinear reduce precision for resid some more
josef-pkt May 15, 2015
513b64b
REF PenalizedMixin switch to `_fit_zeros` for final results instance
josef-pkt May 15, 2015
b5de3f9
TST test_zero_collinear add tests (loop) for cov_type HC0
josef-pkt May 15, 2015
cbde690
TST add PenalizedLogit tests (copy - replace - adjust)
josef-pkt May 15, 2015
74a8649
TST/BUG PenalizedMixin extend _init_keys, fix unit tests, add HC tests
josef-pkt May 16, 2015
dc5c9a0
ENH/BUG: `_fit_zeros` copy cov_type information to returned results
josef-pkt May 16, 2015
367a4b6
ENH: add restriction matrix to SCADSmoothed (experimental)
josef-pkt May 25, 2015
7938389
ENH: SCADSmoothed add linear restriction
josef-pkt May 28, 2015
8eef828
TST: adjust test for refactoring changes and precision issues
josef-pkt May 1, 2018
7f33d63
TST: work around transformed start_params for NegativeBinomial
josef-pkt May 1, 2018
cbb3f85
BUG rename scoreobs -> score_obs
josef-pkt May 1, 2018
86a9018
ENH/TST: add GLMPenalized test cases, basic
josef-pkt May 2, 2018
9089b7a
TST: GLM Poisson compated to discrete Poisson
josef-pkt May 2, 2018
d8e40d2
BUG/ENH/TST: fix count model predict default closes #4595
josef-pkt May 5, 2018
d45786d
REF: add `**kwds` to PenalizedMixin
josef-pkt May 7, 2018
e733e04
TST: test_penalized: add GLMLogit and GLMGaussian for Oracle case
josef-pkt May 9, 2018
c26dbfc
TST: test binomial count, numdiff for score and hessian
josef-pkt May 9, 2018
d24a9ef
BUG fix bug in penalized hessian and score_numdiff with tests
josef-pkt May 9, 2018
97cd6d6
ENH/TST: trim option, also for GLM, add and adjust unit tests
josef-pkt May 15, 2018
412bf82
REF/CLN: keyword name change and partial cleanup
josef-pkt May 17, 2018
2509eea
ENH: add L2 Penalty class, tests compare with TheilGLS
josef-pkt May 17, 2018
69d5f2f
REF: switch to NonePenalty by default
josef-pkt May 17, 2018
e5b883c
REF/TST shift SmoothedSCAD to zero, add left out test_penalties
josef-pkt May 17, 2018
6002174
DOC/CLN docstring [skip ci]
josef-pkt May 18, 2018
e2df1f3
REF: _penalties: rename and deprecate grad and wts/wt see #4642
josef-pkt May 18, 2018
2aa55e8
ENH: _penalties add deriv2 to PseudoHuber and L2
josef-pkt May 19, 2018
4ece026
REF/CLN: rename one wts in penalties, cleanup comments and line breaks
josef-pkt May 21, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
195 changes: 195 additions & 0 deletions statsmodels/base/_penalized.py
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

timestamp accurate?

Copy link
Copy Markdown
Member Author

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


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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this do anything here? base class is object. Pretty harmless, except that having args prevents making kwds explicit, and the kwds.pop pattern is a recipe for silently ignoring misspelled kwargs.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is important. With multiple inheritance the super is the model class in this case, i.e. GLM or Poisson in the examples, and then all the way up to base.model.


# 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):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be consistent with statsmodels.genmod.familes, perhaps loglike_obs?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I prefer loglike_obs, but in the past, e.g. discrete Poisson, we (or I) started with loglikeobs.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a big deal, but any reason why nobs_sc instead of nobs as used elsewhere?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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
(At some point, likely in the same year when I wrote this, I was also working on models like panel data models where score_obs could be the number of cross-sectional units instead of nobs.)

if pen_weight != 0:
sc -= pen_weight / nobs_sc * self.penal.grad(params)

return sc

def hessian_numdiff(self, params, pen_weight=None, **kwds):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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. NegativeBinomial._score_nb1?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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.
(NegativeBinomial is different because it dispatches score to one of the _score_xxx)

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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
Loading