Skip to content

ENH: add ultra-high screening with SCAD - #4683

Merged
josef-pkt merged 16 commits into
statsmodels:masterfrom
josef-pkt:screening
May 29, 2018
Merged

josef-pkt merged 16 commits into
statsmodels:masterfrom
josef-pkt:screening

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

selecting variables for k_vars >> nobs

This is a generic function that takes a model or model class as argument to find and estimate the final model with selected exog.
requires a model with PenalizedMixing merged in #4576
Currently checked for Poisson and GLM-Poisson.

example (used for test case)
https://gist.github.com/josef-pkt/a90eb8be076276874a0d026ad6c7efa0
and GLM version
https://gist.github.com/josef-pkt/df6ef0dcf42d99dee4afeb968f4f4c94

unit tests will most likely be: "it works" and not verified against other packages

TODOs and limitations in class docstring.
API not clear yet

I'm not sure whether I want to merge a basic version or add more options.

@josef-pkt

Copy link
Copy Markdown
Member Author

parking an idea for patch processing, no time right now

user provides an iterator exog_iterator over patches of exog

for exog_candidates in exog_iterator:
    <screen exog_candidates>
    <store winners and index>

finalize
    <combine winners>
    <screen exog_winners>
create final model and full indices (subset + within subset index)

@josef-pkt

josef-pkt commented May 23, 2018 •

Copy link
Copy Markdown
Member Author

put ranking in a separate method so we can swap it, e.g. in subclass.
That might also work with terms, where we could assign the same rank to each column that belongs to the same term. Evaluating terms will be more expensive than ranking single columns, because we need something corresponding to a joint hypothesis, which might still be simple because dummies for a categorical are orthogonal to each other, e.g. we could take the sup or mean ranking criterion.

However, that only covers variable addition, Dropping variables uses SCAD and we would need to penalize terms instead of columns (fused).

@coveralls

coveralls commented May 23, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.07%) to 83.144% when pulling 1710e78 on josef-pkt:screening into 6611e87 on statsmodels:master.

@codecov-io

codecov-io commented May 23, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #4683 into master will increase coverage by 0.06%.
The diff coverage is 94.68%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4683      +/-   ##
==========================================
+ Coverage   80.48%   80.55%   +0.06%     
==========================================
  Files         567      569       +2     
  Lines       86707    87094     +387     
  Branches     9772     9805      +33     
==========================================
+ Hits        69787    70156     +369     
- Misses      14675    14685      +10     
- Partials     2245     2253       +8
Impacted Files Coverage Δ
statsmodels/discrete/discrete_model.py 87.79% <100%> (+0.02%) ⬆️
statsmodels/base/tests/test_screening.py 100% <100%> (ø)
statsmodels/base/_penalized.py 80% <100%> (+0.45%) ⬆️
statsmodels/base/_penalties.py 78.86% <80.95%> (+0.65%) ⬆️
statsmodels/base/_screening.py 88.51% <88.51%> (ø)
statsmodels/imputation/bayes_mi.py 93.28% <0%> (+0.04%) ⬆️

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 6611e87...1710e78. Read the comment docs.

@josef-pkt

josef-pkt commented May 23, 2018 •

Copy link
Copy Markdown
Member Author

instead of screen_vars we should screen_exog

This would work as a results method a bit similarly to variable addition score/LM test.
If we want to do score_tests using the screening selected variables, then we would have to or should also add multiple testing correction to score_test results, and allow specifying the number of tests.

GLM(endog, exog_always, ...).fit().screen_exog(exog_candidates)

This could even be nested, and we keep previously selected exog, which might be useful if we have hierachical terms or variables grouped by importance, e.g.
main effect, interaction effect except we don't support categorical/multi-column yet
higher order polynomials or interaction polynomials

results_ = GLM(endog, exog_always, ...).fit()
for ex in exog_patches:
    results_ = results_.screen_exog(ex).results_final

or maybe it should be a model method

x = (np.random.rand(nobs, k_vars) + 1.* (np.random.rand(nobs, 1)-0.5)) * 2 - 1
x *= 1.2

x = (x - x.mean()) / x.std(0)

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.

bug this doesn't properly standardize
needs x.mean(0)

Comment thread statsmodels/base/_screening.py Outdated
else:
predicted = res_pen.model.predict(p)
# this is currently hardcoded for Poisson
resid_pearson = (endog - predicted) / np.sqrt(predicted)

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.

should I use resid_pearson or divided by variance (resid / variance) ?
both are orthogonality conditions but the second might correspond to WLS because exog is not weighted (i.e. is not wexog)

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.

Add freq_weights if in model

resid_pearson = (endog - predicted) / np.sqrt(predicted)

mom_cond = np.abs(resid_pearson.dot(x1))**2
mcs = np.sort(mom_cond)[::-1]

@josef-pkt josef-pkt May 24, 2018 •

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.

We can use now numpy partial sort using partition
But we might need to handle ties at the boundary
E.g I want to use ties for groups of exog like categorical

See threshold below

Comment thread statsmodels/base/_screening.py Outdated
idx_full = [(bidx, idx)
for bidx, batch in enumerate(exog_idx)
for idx in batch]
ex_final_idx = res_screen_final.idx_nonzero[1:] - 1

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 -1 here hard codes that exog_keep is constant only in my example, same above line 193, 194

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.

there is still a TODO for only indexing exog_candidates and not exog_keep

Comment thread statsmodels/base/_screening.py Outdated
exog_idx = []
for ex in exog_iterator:
res_screen = self.screen_exog(ex, maxiter=20)
res_batches.append(res_screen)

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.

We should not keep res_screen around, too much memory, unless it's a user option.
some history was added for debugging.

@josef-pkt

Copy link
Copy Markdown
Member Author

I added a commit "add PoissonResults resid_pearson" which can be removed if master gains it before merging this PR, see #2107 and related.
resid_pearson is a property and not cached. see #4681 (pearson_resid might not be a heavily used attribute for now)

Logit or GLM-Logit seems a difficult case for screening, I'm xfailing them because we don't select the right exog, at least one "true" is missing and some others are there instead.
Trying to manually fine tune the screener options didn't help so far.
I guess there is either a bug, or not enough information in the dataset even though I increased nobs to 300. At nobs=100, even the oracle params are not very close to the DGP params.

The screener options are now __init__ keywords and I added ranking_attr to switch which results attribute or model method is used to compute the ranking, e.g. in GLM it is now possible to use results.model.score_factor(results.params) by specifying ranking_attr="score_factor"

@josef-pkt

Copy link
Copy Markdown
Member Author

I guess we should also have an option to get something closer to score_test for variable addition by projecting exog candidates on included exog.

@josef-pkt

josef-pkt commented May 25, 2018 •

Copy link
Copy Markdown
Member Author

tests now pass after increasing the smallest nonzero params, but there are extra variables with small params, If I increase penalization further then one or two of the true parameters gets heavily penalized and shrunk towards zero, e.g. from around 0.6 to less than 0.1.

I adjusted the unit test to compare the params for the true nonzero variables ignoring the extra params.

I also added projection on existing exog (currently hard coded and not an option). I think this corresponds now to the score_test statistic for adding one variable, but I didn't check the math.
(We might have to take score_factor into account when projecting, i.e. WLS projection with score_factor as weights, or something like that to get full score_test statistic.)

Choosing penalization parameters for this case will still be a problem.

If the main interest is in variable selection, then we should also check wald or score tests on the final selection from the screening process.
E.g. in one of the more strongly penalized cases in one variation of my example a true parameters was shrunk from around 0.5 to 0.05, the unpenalized score of that variable was pretty large, which most likely indicates that penalization is too strong. (based just on some quick calculation in pdb on a failing test case)

@josef-pkt

Copy link
Copy Markdown
Member Author

getting close to merging

a bit more cleanup and early stopping in screen_exog iteration

@josef-pkt

Copy link
Copy Markdown
Member Author

effect of stopping iteration if idx_nonzero didn't change:
before unit test take around 6.1 seconds,
after adding convergence check 3.3 seconds.

@josef-pkt josef-pkt changed the title WIP/ENH: add ultra-high screening with SCAD ENH: add ultra-high screening with SCAD May 26, 2018
@josef-pkt

Copy link
Copy Markdown
Member Author

(last push went initially by accident into the main repo. I deleted that branch again.)

last commit uses self._null_drop_keys, but I left the workaround code still in SCADSmoothed because we still need to check and fix Null for other models than subclasses of DiscreteModel.
e.g. GLM has hard coded null model computation and will not use a subclass of GLM.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging a8f6bf8 into 6611e87 - view on lgtm.com

new alerts:

  • 1 for Unreachable code

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

one updated notebook
https://gist.github.com/josef-pkt/b94cbeb1a0663930bf0aa5381b3a1064

I'm finished with the code, I think I got everything that I wanted in this round.
ScreeningResults doesn't have a summary, the unit tests are still largely copy-paste-adjust

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging 3f22939 into 6611e87 - view on lgtm.com

new alerts:

  • 1 for Unreachable code

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

I had forgotten to respond to my own review comments
amended and force pushed

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging 9aa0d60 into 6611e87 - view on lgtm.com

new alerts:

  • 1 for Unreachable code

Comment posted by lgtm.com

@josef-pkt

josef-pkt commented May 28, 2018 •

Copy link
Copy Markdown
Member Author

almost all red, but locally tests are passing, and one appveyor passes.
something got messed up in the last commit, or increasing maxiter default hit a bug that already existed.

one failure is with a new assert that might be just on the boundary.
one error if k_keep != 1 in initialization of iterations is still hardcoded for the constant-only case
(numpy changed behavior if mask length didn't match array length in boolean indexing)

        idx_nonzero = [0]
        keep = np.array([True])

@josef-pkt

Copy link
Copy Markdown
Member Author

I fixed the starting keep indices

I also needed to add fit_kwds after all because maxiter in Logit is too small. maxiter in Logit.fit is only 35 which is much too small for bfgs. I use a default of 200, that can be overwritten by user in fit_kwds.

The test failure in test_logit_screening does not seem close to a threshold problem, but it didn't converge on my computer because of low maxiter.
However, I don't know if that is enough to make 'bfgs' in other scipy versions happy.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging 2198e10 into 6611e87 - view on lgtm.com

new alerts:

  • 1 for Unreachable code

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging 5f90c4d into 6611e87 - view on lgtm.com

new alerts:

  • 1 for Unreachable code

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

There is one more indexing problem left from my initial version:
In the trimming stage we treat the exog_keep in the same way as all others, i.e. if one of the parameters is below threshold_trim, than an exog_keep will be trimmed away.

@josef-pkt

Copy link
Copy Markdown
Member Author

If we don't trim exog_keep, then there is no way to start with an empty model, i.e. we cannot screen all variables including constant. But it's unlikely that this will show up in usage, so it will not be supported.
I don't think we need to make trimming exog_keep optional.

Using exog_keep=None or using exog_keep=np.ones((nobs,0)) as exog in initial model raises exceptions.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging 1710e78 into 6611e87 - view on lgtm.com

new alerts:

  • 1 for Unreachable code

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

all green, merging,
(I need a break from penalizing.)

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.

3 participants