Skip to content

ENH: sweep algorithm and sequential OLS with QR - #6268

Open
josef-pkt wants to merge 6 commits into
statsmodels:mainfrom
josef-pkt:stepwise
Open

josef-pkt wants to merge 6 commits into
statsmodels:mainfrom
josef-pkt:stepwise

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

this should add stepwise regression, sweep algorithm and sequential OLS
see #1809

currently it is mainly a script I wrote in 2012 converted to a module and two unit tests

also related to
PR #2380 multicollinearity properties of inverse covariance, and
PR #6265 for updating and downdating inverse covariance matrices

one submatrix of the sweep matrix contains the inverse product matrix and is updated similarly to #6265

@pep8speaks

pep8speaks commented Nov 22, 2019 •

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 2020-01-06 18:20:39 UTC

@coveralls

coveralls commented Nov 22, 2019 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.4%) to 87.368% when pulling 02df2ea on josef-pkt:stepwise into 79c61b3 on statsmodels:master.

@lgtm-com

lgtm-com Bot commented Nov 22, 2019

Copy link
Copy Markdown

This pull request introduces 25 alerts and fixes 1 when merging 6bf62bc into 79c61b3 - view on LGTM.com

new alerts:

  • 20 for Module is imported with 'import' and 'import from'
  • 4 for Module is imported more than once
  • 1 for Wrong number of arguments in a call

fixed alerts:

  • 1 for Unused import

@josef-pkt

Copy link
Copy Markdown
Member Author

amended first commit with pep-8 cleaning and force pushed

@lgtm-com

lgtm-com Bot commented Nov 23, 2019

Copy link
Copy Markdown

This pull request introduces 24 alerts and fixes 1 when merging 0f9ca0e into 79c61b3 - view on LGTM.com

new alerts:

  • 20 for Module is imported with 'import' and 'import from'
  • 4 for Module is imported more than once

fixed alerts:

  • 1 for Unused import

@codecov

codecov Bot commented Nov 23, 2019 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.35294% with 126 lines in your changes missing coverage. Please review.
✅ Project coverage is 84.97%. Comparing base (79c61b3) to head (02df2ea).
⚠️ Report is 4424 commits behind head on main.

Files with missing lines Patch % Lines
statsmodels/regression/_stepwise.py 59.34% 113 Missing and 11 partials ⚠️
statsmodels/regression/tests/test_stepwise.py 98.33% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6268      +/-   ##
==========================================
+ Coverage   84.56%   84.97%   +0.41%     
==========================================
  Files         643      642       -1     
  Lines      101188   103635    +2447     
  Branches    11104    11326     +222     
==========================================
+ Hits        85568    88069    +2501     
+ Misses      13173    13074      -99     
- Partials     2447     2492      +45     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

only case endog_idx=-1
'''
rr = self.rs_current
return (rr[-1, :-1] / np.diag(rr)[:-1, None])

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 computes for all variables except endog at index -1
It is not restricted to variables that are not yet in exog. (If we sweep an already swept variable, then we reverse the sweep, according to some references.)

I think this is 2-dim, how all parameters change for sweeping each variable.
columns are parmeters for a single regression
rows are the variables that are swept

@josef-pkt

Copy link
Copy Markdown
Member Author

AFAICS, there is currently no easy way to clone a StepwiseOLSSweep instance

it is designed for stepwise regression where we go forwards (or backwards when that works), but we only keep hold of one instance. We evaluate candidate sweeps with params_new and rss_diff which don't need a new instance.

However, if we want all-subsets regression, or best-subsets regression, then the structure of models to evaluate is tree like and we need to go down different or all branches from a subroot. In this case, we need to hold on to the subroot case while evaluated a branch.
The minimal state information is the sweep matrix, rs_current and the index of swept variables, is_exog. Everything else should be fixed state during sweeps.

One likely possibility: Create a Sweep class that uses only minimum information, e.g. product or moment matrix, xy.T @ xy, or sweep matrix and is_exog mask. The former is just a special case of the latter if is_exog is empty set.
similar to #2380 and #6265

either add from_data class method to initialize from data, or create a data sweep class and delegate to instances of the barebones sweep class.

@josef-pkt

Copy link
Copy Markdown
Member Author

current limitation in StepwiseOLSSweep

sweep algorithm is generic for multivariate exog, but results statistics are only for a single endog assumed to be in the last column and row of the product and sweep matrix.
i.e. designed for stepwise regression in OLS, where next step can be chosen according to the effect of adding one regressor on some fit statistic for one endogenous variable.

In general we would have 3 sets, included exog, not yet included exog and endog
The sweep algorithm doesn't distinguish between not yet included exog and endog, but we need that distinction for fit and results statistics.

@josef-pkt

josef-pkt commented Nov 23, 2019 •

Copy link
Copy Markdown
Member Author

downdating, i.e. dropping variables, works by just sweeping and already swept variable

is_exog flips boolean in each sweep, so this looks correct,

stols = StepwiseOLSSweep(y, x)
for k in range(stols.k_vars_x):
    stols.sweep(k)
    print(stols.rss, stols.is_exog)
87.69307373380349 [ True False False False False]
65.77474327543813 [ True  True False False False]
31.63719661423127 [ True  True  True False False]
31.28363145361321 [ True  True  True  True False]

for k in range(stols.k_vars_x)[::-1]:
    stols.sweep(k)
    print(stols.rss, stols.is_exog)
31.63719661423127  [ True  True  True False False]
65.77474327543814  [ True  True False False False]
87.6930737338035   [ True False False False False]
151.02333361371993 [False False False False False]

@josef-pkt

Copy link
Copy Markdown
Member Author

still bug in untested methods, e.g. ftest_sweep

however, it looks like we can look at adding and dropping variables at the same time in ftest_sweep.
I fixed the bugs for the case when we add a variable, but the f_test will flip if we delete a variable.
sign could be inferred from is_exog, if False, then we add; if True, then we drop variable.

equivalent to ols results compare_f_test which compares ssr.

bse is already correct, so we can also add tvalues and pvalues for wald test for dropping variables

@josef-pkt

josef-pkt commented Nov 23, 2019 •

Copy link
Copy Markdown
Member Author

pattern for add and drop,
Compute xxx_new or xxx_diff vectorized if we sweep any of the non-endog variables.
If we have rss_new, then we can also compute aic_new and llf_new, using also df_resid_new, df_modelwc_new. The latter would need distinction between adding and deleting variables.
e.g. df_add_del = 1 - 2 * is_exog is either -1 or +1

Some of those are the same computations as a sweep but only for smaller parts of the sweep matrix, mainly related to endog column. That's still computationally more efficient than several full sweeps from the same starting matrix.

This would make it easy to evaluate 1-step changes to the set of included exog.

@josef-pkt

Copy link
Copy Markdown
Member Author

Darlington has a description for how to compute all subset regression in 2**k sweeps
http://node101.psych.cornell.edu/Darlington/allsets.htm
This uses only one sequence of sweeps and we do not need to keep several sweep matrices in memory

Floating point noise will accumulate with a large number of sweeps.
Maybe restart when we only have one variable in the model. (Instead of doing the last sweep that brings us back to a one variable model, we start from the original zero variable model and do the one variable sweep.)
Using those as break points in the sequence would make it trivially parallel.

@josef-pkt

Copy link
Copy Markdown
Member Author

parameters of interest and exog that are always included

StepwiseOLSSweep has a delta df_model option self.ddof_model
This was intended for the case when we don't want to unselect some variables of interest, I did something similar for absorbed OLS.

needs example and unit tests

We want a similar option for all subset regression, i.e. absorb variables of interest and then do the all subset regression using aic or similar with corrected df. Then users can go back to original model with the selected model(s).

Ultrahigh screening includes the never to penalize or unselect variables of interest directly instead of absorbing them.
An analogy and alternative implementation would be here to start with a partial sweep matrix (exog_keep are already swept) and evaluate sweep for not-of-interest exog (confounders) in the all subset sweep sequence.

extension: do all subset sweep only on part of exog, e.g. a block of columns somewhere in the middle between exog_keep and endog in the xy sweep matrix.
The only part we need is to restrict the sweep index sequence to that set of indices.

invalid models
All subset regression is based on one sweep sequence. We cannot skip steps for undesired models in general because we need to get across those gaps.
If the fraction of undesired or invalid models is not too large, then we can just drop them after a full sweep sequence, e.g. if the column selection drops individual levels of categorical variables, or elements of multi-column terms like splines and polynomials.

@josef-pkt

Copy link
Copy Markdown
Member Author

more ideas to support use cases for sweeping

#6237 model averaging, model selection uncertainty and sensitivity to specification

suppose we have some parameters of interest and many confounders

If we use the full sweep matrix for an all subset or another large sweep of the confounders, then we should also store the parameters of interest for every sweep or model.
We can do either full sensitivity for the parameters of interest (as in the plot for #6223) or a set of best models, e.g. those within a distance of the best aic model if we also have aic, aicc or similar available.

We need options about what to store and whether to make storing extra attributes conditional on some "goodness" criterion.

alternative way of blocking
exog_keep, endog, exog_extra instead of exog_keep, exog_extra, endog.
This would make it easier to replace or add to exog_extra
IIRC, I did this in ultrahigh screening when we want to construct terms on the fly or when we don't want to load all possible exog into memory at once.

(maybe not, currently endog in last column is hard coded)

@josef-pkt

josef-pkt commented Nov 24, 2019 •

Copy link
Copy Markdown
Member Author

now with an all subset regression function, adding keep_idx for variables that are never dropped was easy.
I stick for now with blocking [exog_keep, exog_evaluate, endog].

aside for keeping results:
StepwiseOLSSweep records the history of sweeps and models.
The all_subsets function keeps a second list of results of all models.
Option for users to choose which attributes to store is not yet implemented.
all_subsets returns a results class, we can compute some results in that class if we just store the sufficient statistics, e.g. we can compute aic in each model and store, or compute it at the end for all results using ssr and df_modelwc
This still needs work.

Sensitivity plots in example I have seen for #6223 include confidence interval of the parameter of interest for each model. Currently I'm not keeping enough information from the sweeped models to be able to compute conf_int. conf_int are also not yet available in StepwiseOLSSweep class

@lgtm-com

lgtm-com Bot commented Nov 24, 2019

Copy link
Copy Markdown

This pull request introduces 24 alerts and fixes 1 when merging f961dd6 into 79c61b3 - view on LGTM.com

new alerts:

  • 20 for Module is imported with 'import' and 'import from'
  • 4 for Module is imported more than once

fixed alerts:

  • 1 for Unused import

@josef-pkt

Copy link
Copy Markdown
Member Author

@bashtage

Copy link
Copy Markdown
Member

Seems to be a lot of code that isn't used. Can some/all of the unused code be removed?

@josef-pkt

Copy link
Copy Markdown
Member Author

Seems to be a lot of code that isn't used. Can some/all of the unused code be removed?

Most of the code should be used or have unit tests by the time I'm finished. Some might find use later.
The big part that is unclear is code for computing a good sweep sequence. This might not work well because it is similar to a travelling salesman problem and finding a good sequence might take more time than just running undesired sweeps/regressions.
I found a reference for the all subset sweep sequence. Trying to improve on a simple binary list of all subset, leaves a smaller percentage of redundant cases. But, I didn't manage to get very far with finding an improvement in the sweep sequence for other sets of models than all subsets,
I wrote some of the functions for investigating this, but they might not be of general interest.

(I haven't looked enough at sequential QR again to see if this is the version I want. I think I wanted something different now, but related code will be useful for graph-lasso type models, i.e. sparse or penalized inverse covariance matrices.)

@josef-pkt

Copy link
Copy Markdown
Member Author

moved to 0.14

main problem is that I didn't work on SequentialOLSQR in the second round and don't just want to delete it.

@josef-pkt

josef-pkt commented May 23, 2024 •

Copy link
Copy Markdown
Member Author

I ran into this by chance

quick try: main part of SequentialQR seems to work as intended

nobs, k_vars = 100, 5
x = np.column_stack((np.ones(nobs), np.random.randn(nobs, k_vars - 1)))
beta = np.ones(k_vars) / k_vars
u = 0.5 * np.random.randn(nobs)
y = x @ beta + u
                     
res = SequentialOLSQR(y, x)
np.column_stack((res.llf_all(), res.ic_all(ic="aic"), res.ic_all()))
array([[-102.03258318,  206.06516637,  208.67033655],
       [ -95.37368615,  194.74737231,  199.95771268],
       [ -92.91962283,  191.83924566,  199.65475622],
       [ -83.3737339 ,  174.74746779,  185.16814853],
       [ -73.54571837,  157.09143674,  170.11728767]])

for i in range(1, k_vars+1):
    ri = OLS(y, x[:, :i]).fit()
    print(ri.llf, ri.aic, ri.bic)
-102.03258318276943 206.06516636553886 208.67033655152696
-95.37368615462589 194.74737230925177 199.95771268122795
-92.9196228322524 191.8392456645048 199.65475622246908
-83.3737338952269 174.7474677904538 185.16814853440619
-73.5457183720623 157.0914367441246 170.11728767406504

update
getting params
p.sum(1) is beta of full model
.cumsum(1) are all params from sequential partial regression

p = np.linalg.inv(res.r[:-1, :-1]) * res.r[:-1, -1]
p, p.sum(1), p.cumsum(1).T
for i in range(1, k_vars+1):
    ri = OLS(y, x[:, :i]).fit()
    print(ri.params)
print()
print(p.cumsum(1).T)

[0.20471574]
[0.22426868 0.25039368]
[0.1993411  0.21923522 0.13921109]
[0.19454249 0.20112247 0.1436216  0.25842756]
[0.20079682 0.2036138  0.14544594 0.22650996 0.23317207]

[[ 0.20471574  0.          0.          0.         -0.        ]
 [ 0.22426868  0.25039368  0.          0.         -0.        ]
 [ 0.1993411   0.21923522  0.13921109  0.         -0.        ]
 [ 0.19454249  0.20112247  0.1436216   0.25842756 -0.        ]
 [ 0.20079682  0.2036138   0.14544594  0.22650996  0.23317207]]

@josef-pkt

Copy link
Copy Markdown
Member Author

I finally remembered more about SequentialOLSQR

It cannot be used to estimate sequential parameters, that's why I ignored it in my last round here.

The intention and usecase for it was variable selection where we have a predefined sequence of variables.
Examples were adding lags in an autoregression, or adding polynomial terms for nonlinearity.
(B-splines and similar do not work for this unless they are sequentially orthogonalized, because adding knots changes previous basis functions.)

The QR works for computing partial sum of squares which is all we need to compute llf and information criteria.

@josef-pkt

josef-pkt commented May 25, 2024 •

Copy link
Copy Markdown
Member Author

There are still several mistakes, unfinished parts in Sequential

e.g. normalized covparams
should only have r without last column and row (R in OLS.fit does not include endog)
and matrix algebra (A B)^-1 = B^-1 A^-1 (e.g. answer in https://math.stackexchange.com/questions/688339/product-of-inverse-matrices-ab-1)
and r_inv is not yet a cached property and need call ().

corrected versions for the full model

np.linalg.inv(res.r[:-1, :-1].T @ res.r[:-1, :-1]) / ri.normalized_cov_params
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

rxi = np.linalg.inv(res.r[:-1, :-1])
rxi @ rxi.T / ri.normalized_cov_params
array([[1., 1., 1., 1., 1.],
...

I don't know if we can easily get bse, or at least bse and tvalue for the last parameter of each submodel in the sequence.
That might need explicit partitioned matrix inverse. Or some anova type ess based test.

Another aside, but for the future: This also looks like we can get some sequential effectsize measure, eta, ...
i.e. in the style of a type 1 anova.
We have all the sum of squares for it.

Related: we compute pacf in a similar way.

statsmodels.tsa.stattools._autolag does the full loop for sequential OLS
model choice criteria aic, bic and t-test (tvalue < critical value for last param in sequence submodel)
So we will still need that tvalues to replace ols loop in autolag.

extension:
it should be possible to use cholesky on X' X instead of QR, we only use the R part. (I have not looked at that in a long time)
That might save memory an speedup in cases like autolag, e.g. most pacf methods are based on acf and not full data.

@josef-pkt

Copy link
Copy Markdown
Member Author

update
sequence of normalized cov params is also easy

because of the triangular structure of R, invers of R is sequential i.e previous blocks remain unchanged when adding a variable
so we only need one inv(R)
and then dot on subblock

the following produces a sequence of normalized cov_params

for i in range(1, k_vars+1):
    ncp = rxi[:i, :i] @ rxi[:i, :i].T

and getting the normalized variance for the last parameter is also easy, e.g. one np.einsum of rxi = np.linalg.inv(res.r[:-1, :-1])

ncp = [rxi[:i, :i] @ rxi[:i, :i].T for i in range(1, k_vars+1)]
[ncpi[-1, -1] for ncpi in ncp]
[0.010000000000000002,
 0.011159464144287512,
 0.010259240837956311,
 0.010233258179253012,
 0.009820647838100873]

np.einsum("ij,ji -> i", rxi, rxi)
array([0.01      , 0.01115946, 0.01025924, 0.01023326, 0.00982065])

for i in range(1, k_vars+1):
    ri = OLS(y, x[:, :i]).fit()
    print(ri.normalized_cov_params[-1, -1])
0.010000000000000005
0.011159464144287508
0.01025924083795631
0.010233258179253007
0.009820647838100873

From there we should have then everything I wanted.
Just needs unit tests to verify everything.

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.

4 participants