Skip to content

Penalized mle scad rebased2 - #4576

Merged
josef-pkt merged 41 commits into
statsmodels:masterfrom
josef-pkt:penalized_mle_scad_rebased2
May 21, 2018
Merged

josef-pkt merged 41 commits into
statsmodels:masterfrom
josef-pkt:penalized_mle_scad_rebased2

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Apr 30, 2018 •

Copy link
Copy Markdown
Member

another rebase, rebased #3677, which is a rebase of #2374
new PR because an error when running the test might be a incorrect merge conflict resolution.

I haven't looked at any details yet, I just want to see how "bad" it is.

some of the generic results creation code in this branch might be outdated by now, or not my preferred design anymore
i.e. #2393 still has no clean solution, AFAIK

Design issues

transformed params might need a more closer look (e.g. NegativeBinomial)
I fixed it in the unit test, which is mostly checking internal structure, i.e. which start_params was used.
But I don't know if any code outside on unit tests will need to handle parameters that are transformed during the optimization.

possible source of bug:
if score is computed as sum(score_obs) in the super model class, then we might be adding the penality twice, once in score_obs (called on the final class) and once score (when final class calls super().score)
GLM uses sum(score_obs) after refactoring in 0.9

This looks like a serious problem now, and I don't see a clean way of working around it.
We would need a flag or keyword to tell whether we should add the penalty in score_obs or not.
However, a keyword in score_obs with a default like penal=None does not work, because we want no penal if score_obs is called from score, and we need penalization if score_obs is called to create cov_params with robust cov_type.

The same might happen if loglike/loglike_obs is used.

Short term workaround: score is NOT allowed to use score_obs, e.g. use extra helper method _score_obs in GLM that is called by both score and score_obs
DONE this in GLM

inheritance and tsa
The new methods, _fit_zeros and _fit_collinear are in base.LikelihoodModel and so they will also be inherited by tsa models which might not make much sense, and most likely will not work anyway.
-> maybe use a pure Mixin class without method overlap for those extra methods and add to top level subclasses like DiscreteModel and GLM, and RLM, and GenericLikelihoodModel... Or, create a new intermediate class for non-tsa likelihood models.

df_effective, aic, bic
In order to be able to use information criteria like aic, we need effective degrees of freedom, or effective variable count. I don't know how we should define this for general MLE.
I don't remember the details: For Gauss-Newton Regression we can get the linear model analog which might have just the hessian, e.g. something like (score_obs * (hessian dot score_obs.T).T).sum(1) in analogy to the hat matrix and its trace.

standardization versus weights
Often exog are standardized or rescaled to make the relative weights less scale dependent. This is up to the user, but rescaled exog will not have nice interpretable params. For that case we could also to the rescaling internally and backtransform the result, as in fit_transformed idea. Alternatively, we can choose weights proportional to exog.std(0) in the univariate case, but full prior covariance matrix (arbitrary linear restrictions) needs to be defined by the user or by statsmodels for built-in shrinkage targets, e.g. spline penalization or penalization of categorical exog.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging 6c9f896 into 40e4f56 - view on lgtm.com

new alerts:

  • 2 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

looks better than I thought

  • 2 precision problems test tol stricter than convergence tol in regression test
  • mle_settings is now defined in more classes, it looks like existence of mle_settings does not guarantee that we have a start_params key
             # check fit optimizer arguments, if mle_settings is available
             if hasattr(res2, 'mle_settings'):
    
  • Negative Binomial has a failure because dispersion params is the log transformed versions and is missing the exp

Comment thread statsmodels/base/_penalized.py Outdated
if pen_weight is None:
pen_weight = self.pen_weight

sc = super(PenalizedMixin, self).scoreobs(params)

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.

Why does this not fail?
scoreobs should be score_obs

I think this is only used in the sandwich cov, so the robust sandwich cov_ types will use the unpenalized score_obs?

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging c2c4c60 into 40e4f56 - view on lgtm.com

new alerts:

  • 2 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

@coveralls

coveralls commented May 1, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.2%) to 83.074% when pulling 4ece026 on josef-pkt:penalized_mle_scad_rebased2 into ec3b6d0 on statsmodels:master.

@josef-pkt

josef-pkt commented May 1, 2018 •

Copy link
Copy Markdown
Member Author

tests fail with scipy <= 0.17 with I guess convergence problems with bfgs.
We will have scipy at least 0.18 for statsmodels 0.10, so not relevant anymore.

next I'm renaming scoreobs. I verfied that renaming it, runs it (and would raise exception in super().scoreobs)
However, I don't see any changes when running the unit tests locally,, precision in Poisson HC0 test looks about the same, maybe penalization is too small in those tests to have a large, visible effect on bse.
(maybe older scipy are affected, correction score_obs is irrelevant for optimization in discrete because score is independently defined)

possible source of bug:
if score is computed as sum(score_obs) in the super model class, then we might be adding the penality twice, once in score_obs (called on the final class) and once score (when final class calls super().score)
GLM uses sum(score_obs) after refactoring in 0.9

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging 656a301 into 40e4f56 - view on lgtm.com

new alerts:

  • 2 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

currently there are only test classes for Logit and Poisson, not for GLM

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging bce88bd into 40e4f56 - view on lgtm.com

new alerts:

  • 2 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

@josef-pkt
josef-pkt force-pushed the penalized_mle_scad_rebased2 branch from bce88bd to 7d778f9 Compare May 1, 2018 23:06
@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging 7d778f9 into 465d1b3 - view on lgtm.com

new alerts:

  • 2 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

@josef-pkt
josef-pkt force-pushed the penalized_mle_scad_rebased2 branch from 7d778f9 to 297805b Compare May 2, 2018 02:00
@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging 297805b into 465d1b3 - view on lgtm.com

new alerts:

  • 2 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

last change added GLMPenalize test
They don't fail, but require a small adjustment to pen_weights.
Looking more closely, bfgs has convergence problems in GLM because of the incorrect score (double penalization)

If I add GLM._score_obs, so that GLM score does not call GLM.score_obs, then discrete Poisson and GLM Poisson agree for params at around atol=1e-7 or rtol=5e-7 for the "non-zero" params
(the zero params are not actually zero, but most of them are around 1e-5, one zero param is -0.0164)
using example from TestPenalizedPoissonOracleHC and TestPenalizedGLMPoissonOracleHC

interesting observation (I don't have any intuition)
HC0 compare to nonrobust reduces the bse for the non-zero params by 2.5 to 5%, but strongly reduces bse of the "zero" params

@josef-pkt

Copy link
Copy Markdown
Member Author

maybe a new compat issue with numpy in VAR irf errband mc (likely float index) on a travis 2.7
E IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

investigate tomorrow it it persists

@josef-pkt
josef-pkt force-pushed the penalized_mle_scad_rebased2 branch from 297805b to a0b4283 Compare May 2, 2018 03:34
@codecov-io

codecov-io commented May 2, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #4576 into master will increase coverage by 0.16%.
The diff coverage is 92.67%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4576      +/-   ##
==========================================
+ Coverage   80.32%   80.48%   +0.16%     
==========================================
  Files         564      567       +3     
  Lines       85747    86707     +960     
  Branches     9685     9772      +87     
==========================================
+ Hits        68872    69787     +915     
- Misses      14653    14674      +21     
- Partials     2222     2246      +24
Impacted Files Coverage Δ
statsmodels/regression/mixed_linear_model.py 81.81% <0%> (ø) ⬆️
statsmodels/base/tests/test_penalties.py 100% <100%> (ø)
statsmodels/discrete/discrete_model.py 87.77% <100%> (+0.03%) ⬆️
statsmodels/regression/linear_model.py 91.18% <100%> (+0.14%) ⬆️
statsmodels/base/_penalties.py 78.2% <79.22%> (+37.38%) ⬆️
statsmodels/base/_penalized.py 79.54% <79.54%> (ø)
statsmodels/base/model.py 85.3% <96.82%> (+1.71%) ⬆️
statsmodels/base/tests/test_generic_methods.py 96.43% <97.14%> (+0.2%) ⬆️
statsmodels/base/tests/test_penalized.py 99.04% <99.04%> (ø)
statsmodels/stats/descriptivestats.py 24.13% <0%> (ø) ⬆️
... and 6 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update ec3b6d0...4ece026. Read the comment docs.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging a0b4283 into 3d87728 - view on lgtm.com

new alerts:

  • 2 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

@josef-pkt
josef-pkt force-pushed the penalized_mle_scad_rebased2 branch from a0b4283 to c3675fc Compare May 2, 2018 04:30
@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging c3675fc into 3d87728 - view on lgtm.com

new alerts:

  • 2 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

cls.res2 = modp.fit(method='bfgs', maxiter=100, disp=0)

mod = PoissonPenalized(y, x, penal=cls.penalty)
#mod.pen_weight *= 1.5

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.

pls delete commented-out

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 as reminder that we use a different pen_weight now

def _initialize(cls):
y, x = cls.y, cls.x
modp = PoissonPenalized(y, x[:, :cls.k_nonzero], penal=cls.penalty)
modp.pen_weight *= 10 # meed to penalize more to get oracle selection

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.

typo "need"?


mod = LogitPenalized(y, x, penal=cls.penalty)
#mod.pen_weight *= 1.5
#mod.penal.tau = 0.05

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.

pls delete commented-out

assert_equal(self.res1.bse[self.k_nonzero:], 0)


# the following classes are copies of Poisson with model adjustments

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.

this same comment occurs on L384. is it accurate/needed in both places?

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.

reminder that we might be able to parameterize this better with less code duplication
(but I don't change the structure in this PR.)

def _initialize(cls):
y, x = cls.y, cls.x
x = x[:, :4]
offset = -0.25 * np.ones(len(y)) # also check offset

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 clear what this comment means. Is it saying that this test class exists to make sure tests are run with non-None offset?

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.

The test is for binomial count, but as extra we also check the offset

pen = smpen.L2ContraintsPenalty(restriction=restriction)
mod = GLMPenalized(y, x, family=family.Gaussian(),
penal=pen)
# make pen_weight large to force redundant to close to zero

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 multiplying by 1 (next line) accomplish the goal described in this comment?

mod = GLMPenalized(y, x, family=family.Gaussian(),
penal=pen)
# make pen_weight large to force redundant to close to zero
mod.pen_weight *= 1

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.

Is changing model.pen_weight in-place going to be an encouraged user behavior? If so, the pen_weight in place as of model.fit should be attached to the Result object.

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 opened several issues for this, e.g. #4585 #4664 Design is not clear yet.
Currently the ability to change pen-weight conveniently as attribute wins, i.e. being able to tune penalization is more important than having a robust results instance.

def setup_class(cls):
x0 = np.linspace(-0.2, 0.2, 11)
cls.params = np.column_stack((x0, x0))
cls.pen = smpen.L2() No newline at end of file

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.

missing newline at end of file

# If self.exposure exists, it will already be in logs.
exposure = getattr(self, 'exposure', 0)
# the following is copied from GLM predict (without family/link check)
# Use fit offset if appropriate

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 necessarily for this PR) if this is used multiple times, it may merit a helper method. Especially since IIRC there are some TODO notes regarding how to keep track of what has and has not been logged.

@jbrockmendel

Copy link
Copy Markdown
Contributor

Generally looks good. The only non-formatting issue I have is a mutability/re-fit concern described here.

@josef-pkt

Copy link
Copy Markdown
Member Author

@jbrockmendel Thanks for reviewing.
I replied to some comments with explanations and will go over the rest tomorrow.

@josef-pkt
josef-pkt force-pushed the penalized_mle_scad_rebased2 branch from eed924b to 4ece026 Compare May 21, 2018 17:08
@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging 4ece026 into ec3b6d0 - view on lgtm.com

new alerts:

  • 2 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

I missed two or three CLN, but maybe I don't bother anymore.

@josef-pkt

Copy link
Copy Markdown
Member Author

all green, merging

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants