Skip to content

ENH: add functionality Improve the stability for regression models with multicollinearity to statsmodels.regression (… - #6935

Open
sergiolevin wants to merge 3 commits into
statsmodels:mainfrom
sergiolevin:improve_stability
Open

sergiolevin wants to merge 3 commits into
statsmodels:mainfrom
sergiolevin:improve_stability

Conversation

@sergiolevin

@sergiolevin sergiolevin commented Jul 31, 2020 •

Copy link
Copy Markdown

…WLS, OLS, GLM or any other model that uses WLS) Pseudo Inverse (method=‘pinv’) may product unstable results coefficients (params) values that are extremely larg. The current QR decomposition (mothod=‘qr’) decomposition does not handle the multicollinearity in practice, because of numerical errors in the process of calculating the eigenvalues and the rank of the R matrix.

  • closes #xxxx
  • tests added / passed.
  • code/documentation is well formatted.
  • properly formatted commit message. See
    NumPy's guide.
Details

Notes:

  • It is essential that you add a test when making code changes. Tests are not
    needed for doc changes.
  • When adding a new function, test values should usually be verified in another package (e.g., R/SAS/Stata).
  • When fixing a bug, you must add a test that would produce the bug in master and
    then show that it is fixed with the new code.
  • New code additions must be well formatted. Changes should pass flake8. If on Linux or OSX, you can
    verify you changes are well formatted by running
    git diff upstream/master -u -- "*.py" | flake8 --diff --isolated
    
    assuming flake8 is installed. This command is also available on Windows
    using the Windows System for Linux once flake8 is installed in the
    local Linux environment. While passing this test is not required, it is good practice and it help
    improve code quality in statsmodels.
  • Docstring additions must render correctly, including escapes and LaTeX.

…WLS, OLS, GLM or any other model that uses WLS) Pseudo Inverse (method=‘pinv’) may product unstable results coefficients (params) values that are extremely larg. The current QR decomposition (mothod=‘qr’) decomposition does not handle the multicollinearity in practice, because of numerical errors in the process of calculating the eigenvalues and the rank of the R matrix.
@pep8speaks

pep8speaks commented Jul 31, 2020 •

Copy link
Copy Markdown

Hello @sergiolevin! 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-08-02 14:39:37 UTC

@sergiolevin sergiolevin changed the title Improve the stability form regression models with multicollinearity (… ENH: add functionality Improve the stability form regression models with multicollinearity to statsmodels.regression (… Jul 31, 2020
@sergiolevin sergiolevin changed the title ENH: add functionality Improve the stability form regression models with multicollinearity to statsmodels.regression (… ENH: add functionality Improve the stability for regression models with multicollinearity to statsmodels.regression (… Jul 31, 2020
@bashtage

Copy link
Copy Markdown
Member

Dropping variables is a large change that will need a large refactoring, and a discussion. We have preferred to be explicit in the sense that users need to pass a well specified model and ideally should get an error raised when their exog matrix is numerically singular.

@josef-pkt

Copy link
Copy Markdown
Member

Thanks, pivoting QR was still missing

AFAIU it will set the coefficients of singular or near singular pivoted exog to zero, so effectively dropping them.

@coveralls

coveralls commented Jul 31, 2020 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 88.185% when pulling 023ce02 on sergiolevin:improve_stability into cb99c88 on statsmodels:master.

@josef-pkt

josef-pkt commented Jul 31, 2020 •

Copy link
Copy Markdown
Member

@bashtage I think it's good as an option, similar to R and Stata, but won't become a default for us.

Currently we also warn but do not raise on singular and return a regularized solution (pinv).

Problem with pivoting is that the exog that are dropped depend on the details of the data and will not produce consistent results (param indices) across similar samples. (That's why I don't like it even though it has often been requested.)

Related: It would also be possible to make an (additional) standalone function for users to check their design matrix for multicollinearity using pivoting QR.
I have a simples, non-pivoting funtions in my multicollinearity PR
https://github.com/statsmodels/statsmodels/pull/2380/files#diff-d8db19fefba02c5e988cc9db0168ef13R494

My function preserves the order and drops later columns instead of ordered by pivoting.

@bashtage bashtage left a comment

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.

Quite a few things to fix. Ultimately I think this need to happen before fit at model creation using a new kwarg about handelling collinearity.

I also know from personal experience that a more sophisticated algorithm is needed to ensure that the pivoting is reproducible when there are columns that are exactly Collinear. There is some in the deterministic modules.

Comment thread statsmodels/regression/linear_model.py Outdated
if 'tol' in kwargs:
tol = kwargs['tol']
else:
tol = 1e-7

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.

Tol needs to depend on machine precision and the number of variables. See numpy or the other uses of pivoting in statsmodels.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

My 2cent regarding numerical errors in computers. You may estimate the error (or in this case the tolerance) in the case that the numerical error is caused by rounding error of a sum of large number of elements.
It may not be trivial to estimate the errors in the case the errors are related to a singular value (like calculating the inverse of a rank deficient matrix)

It is common in many different tools (R, SAS …) to set the “tol” value as a parameter the user can set, and I’ve used the R defaults “tol = 1e-7”.

There is also some terminology issue and in this case the term “singular” refer to a mathematical point that is not defined (in the inverse matrix of X’X) where in Singular Value Decomposition the “Singular” is some scale parameter.

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.

It is common in many different tools (R, SAS …) to set the “tol” value as a parameter the user can set, and I’ve used the R defaults “tol = 1e-7”.

It is OK for the user to set it, but the default should be set in a mathematically sound way. 1e-7 is arbitrary.

Comment thread statsmodels/regression/linear_model.py Outdated
sortP = np.argsort(P)

if n_singular > 0:
rng = range(self.rank)

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.

Use a slice, not a range object.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in commit 023ce02

Comment thread statsmodels/regression/linear_model.py Outdated
tol = 1e-7

singular_preds = abs(np.diagonal(R)) < tol
n_singular = sum(singular_preds)

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.

Use np sum not python sum.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in commit 023ce02

Comment thread statsmodels/regression/linear_model.py Outdated
else:
tol = 1e-7

singular_preds = abs(np.diagonal(R)) < tol

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.

Same for abs

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in commit 023ce02

self.effects = effects = np.dot(Q.T, self.wendog)
beta = np.linalg.solve(R, effects)
elif method == "qr-pivot":
Q, R, P = linalg.qr(self.wexog, mode='economic', pivoting=True)

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.

Only lower case variables in general.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The variable names are set to be consistent with the code of method = “qr” in RegressionModel.fit

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.

Sins of the father should not be committed again.

elif method == "qr-pivot":
Q, R, P = linalg.qr(self.wexog, mode='economic', pivoting=True)
self.exog_Q, self.exog_R, self.exog_P = Q, R, P

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.

Do these need to be stored?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

These elements of the qr decomposition are stored to be consistent with RegressionModel.fit (… method= “qr” ) to allow users who are already using these elements in the ‘qr’ method to be able to migrate to “qr-pivot”

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.

those are pivoted Q, R matrices, so they might not have a use that is consistent with unpivoted QR

Comment thread statsmodels/regression/linear_model.py Outdated

# Cache singular values from R.
self.wexog_singular_values = np.linalg.svd(R, 0, 0)
if 'tol' in kwargs:

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.

Use kwargs.get with a default value.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in commit 023ce02

Rr = R[rng, :][:, rng]
effects = np.dot(Qq.T, self.wendog)
beta = linalg.solve_triangular(Rr, effects)
beta = np.concatenate((beta, np.repeat(0.0, n_singular)))[sortP]

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.

It isn't right to set these to 0 since they will still appear in later calculations as variables

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I believe there is no solution that will be able to be a “perfect” choice of dealing with redundant variables. The options are:
- setting the value of the redundant variables to NA
- removing these variables
- setting the variable to 0
I’ve picked the last choice ‘0’ is the most consistent choice for the following reasons:

  • It is consistent with regularization method that “trim” or “remove” variables from the model (LASSO for example), although it is not a regularization algorithm
  • It is much more practical compared of setting NA. A user already using statsmodels regression will not expect to get coefficient with NA values. The efforts that current users will need to convert any existing code to the ‘qr-pivot’ with NA coefficient values is almost impossible.
  • The same practical issues will raise for the solution of removing the variables.
  • And conceptually these variable contribute nothing “0” by adding them to the model because thay have full multi-collinearity

Considering all options (and there is not optimal solution for this issue), it would make more sense for me to keep the variables and set the coefficient values to 0.

self.normalized_cov_params = normalized_cov_params[sortP, :][:, sortP]
else:
self.effects = np.dot(Q.T, self.wendog)
beta = linalg.solve_triangular(R, self.effects)[sortP]

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.

Can't you just sort columns first and avoid multiple sorts.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Actually there is only one sort and the algorithm only apply the permutation multiple times.

The reason it’s using the “triagonal solve” for the linear equations instead of rearranging the R matrix and solve the linear equations using the invers matrix of R. Triagonal solve is more efficient (O(n^2)) and more accurate compared to taking the inverse of a matrix O(n^3) (or close to it).

Applying the sort permutation on the way it is may looks more complex but overall it solves the linear equations with complexity of O(n^2) and offers better accuracy.

@josef-pkt

Copy link
Copy Markdown
Member

Ultimately I think this need to happen before fit at model creation using a new kwarg about handelling collinearity.

It's possible to keep it in fit, similar to options for regularization in fit_regularized. The advantage is that we still have the full model available. (or fit_constrained, essentially we are computing a zero constrained solution)
If we put it in model creation, then the user can as well just use a function to drop variables. Maybe not in WLS if we drop columns in wexog and not exog.

(One question is how post-estimation results are handled. We already have cases where the cov_params is singular and has zeros. fit_regularized in discrete adds nans instead of zeros for dropped columns, AFAIR)

@bashtage

Copy link
Copy Markdown
Member

(One question is how post-estimation results are handled. We already have cases where the cov_params is singular and has zeros. fit_regularized in discrete adds nans instead of zeros for dropped columns, AFAIR)

It is very hard to know that subsequent statistics are correct. It is also hard to tell the difference between a coefficient that is dropped and one that is numerically 0. This falls into the category of magic when variables are dropped without notifying that some values in results may be incorrect or misleading.

@bashtage

Copy link
Copy Markdown
Member

Another issue with having it in fit is that it could change the model instance if tol is different which may then affect previously created results. There has been a concerted effort to avoid models that can have a non-trivial state change after initialization.

@bashtage

Copy link
Copy Markdown
Member

If the reduced rank path went into fit regularized then it would make more sense since that is ultimately what this method is doing.

@lgtm-com

lgtm-com Bot commented Jul 31, 2020

Copy link
Copy Markdown

This pull request introduces 1 alert when merging ecf8a2d into cb99c88 - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

Copy link
Copy Markdown
Member

There has been a concerted effort to avoid models that can have a non-trivial state change after initialization.

If we consider it as constrained estimation for the full model, then there is no change in the underlying model.

For example, in fit_zeros and fit_constrained, I construct an auxiliary model that imposes the constraints on the exog. That model has a different set of exog. But the original model keeps the exog and parameter space but where parameters are estimated under a constrained.
cov_params relies on the distribution of the params under constrained estimation and is rank reduced, but the dimension and ordering of params and exog is independent of the constraints. I think the same will happen here.

i.e. we don't do feature selection and create a reduced model, we are estimating the original model imposing some constraints or regularization conditions.

Independent of how we eventually offer this option, I think it will be good to have it to match R and Stata (with maybe different dropped variables). It has been requested for a long time.

see also #2062 and related

@josef-pkt

Copy link
Copy Markdown
Member

There are still details to look out for, for example making sure that df_resid and df_model and their use takes the regularization constraint into account. (I never checked the theory or monte carlos for endogenously dropping collinear variables with QR.)

However, we have this problem also in other cases like penalized estimation, so that Results.df_resid correctly reflects fit options, but Model.df_resid if it exists refers to the original model. Methods in the results instance are only allowed to use the results.df_resid and not a results.model.df_resid directly.

@bashtage

bashtage commented Aug 2, 2020

Copy link
Copy Markdown
Member

I really think this should be either a standalone function or a model creation option (and would also be good). It seems to be difficult to ensure that post estimation features are correct when variables have been dropped given the parameters are not being reshaped. The only other option would be to have a special case in fit that creates a new model using the surviving columns of the original exog and then returns the fit of this new model which won't be dropping anything. This seems to be a very convoluted path to get the right result, when the same check can do into the __init__.

There is also an issue where there is no need to use QR factorization after dropping columns since the X'X matrix will always be well-conditioned, and lstsq is faster in this base. This suggests to me that dropping collinear variances is really orthogonal to fitting this model.

@josef-pkt

Copy link
Copy Markdown
Member

It seems to be difficult to ensure that post estimation features are correct when variables have been dropped given the parameters are not being reshaped.

difficult but important.
and we already have it for other fit methods. Reduced rank cov_params is not really different from the current pinv case. What's missing for that case are checks for "estimability", or estimable contrasts.

I'm against variable selection in __init__ of core models, This changes the unrestricted parameter space, which makes comparison across models much worse.

@bashtage

bashtage commented Aug 2, 2020 via email

Copy link
Copy Markdown
Member

@bashtage

bashtage commented Aug 2, 2020 via email

Copy link
Copy Markdown
Member

@sergiolevin

Copy link
Copy Markdown
Author

(One question is how post-estimation results are handled. We already have cases where the cov_params is singular and has zeros. fit_regularized in discrete adds nans instead of zeros for dropped columns, AFAIR)

It is very hard to know that subsequent statistics are correct. It is also hard to tell the difference between a coefficient that is dropped and one that is numerically 0. This falls into the category of magic when variables are dropped without notifying that some values in results may be incorrect or misleading.

Least Square solution (including GLM or any other algorithm that uses the WLS) will never (in practice) produce a coefficient that is identical to 0. Having a perfect 0 (not close to 0) is a good enough indicative for coefficients that are dropped.

@sergiolevin

sergiolevin commented Aug 2, 2020 •

Copy link
Copy Markdown
Author

If the reduced rank path went into fit regularized then it would make more sense since that is ultimately what this method is doing.

Not sure this fit regularized model. At a conceptual level, regularization pose some restrictions on the coefficients to deal with issues related to dimensionality of the model. In this case the process set a 0 coefficient to coefficients that have multicollinearity. Mathematically this is the right solution of the regression equations

@sergiolevin

Copy link
Copy Markdown
Author

I really think this should be either a standalone function or a model creation option (and would also be good). It seems to be difficult to ensure that post estimation features are correct when variables have been dropped given the parameters are not being reshaped. The only other option would be to have a special case in fit that creates a new model using the surviving columns of the original exog and then returns the fit of this new model which won't be dropping anything. This seems to be a very convoluted path to get the right result, when the same check can do into the __init__.

There is also an issue where there is no need to use QR factorization after dropping columns since the X'X matrix will always be well-conditioned, and lstsq is faster in this base. This suggests to me that dropping collinear variances is really orthogonal to fitting this model.

Not sure I understand the first part. Calculating a model on a subset of the original exog and return the fit is equivalent to what the supposed ‘qr-pivot’ method is doing. Dropping columns may result with inconsistency when running the model on N columns and getting back only fewer coefficients. Mathematically if there is a full multicollinearity the right answer will be to set one or more coefficients as 0 since all the information is encapsulated with a linear combination of other variables.

The use of the QR decomposition is mainly because it’s much more accurate than having the inverse. I’ve run into cases where the linear equations had non redundant solution using QR with pivoting and the inverse of X’X matrix was singular when calculated directly. Using the inverse of X’X may end up with unstable solution again.

@lgtm-com

lgtm-com Bot commented Aug 2, 2020

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 023ce02 into 0c2cda3 - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

@bashtage

bashtage commented Aug 7, 2020

Copy link
Copy Markdown
Member

Not sure I understand the first part. Calculating a model on a subset of the original exog and return the fit is equivalent to what the supposed ‘qr-pivot’ method is doing. Dropping columns may result with inconsistency when running the model on N columns and getting back only fewer coefficients. Mathematically if there is a full multicollinearity the right answer will be to set one or more coefficients as 0 since all the information is encapsulated with a linear combination of other variables.

I don't agree with that. The most correct answer is to return NaN values, or absent that, to raise an error that the model is not estimable. There is no unique solution when columns are perfectly collinear, and dropping columns is changing the model (but not the best achievable fit). When you drop columns you are choosing one of infinitely many solutions to the least squares problem.

The use of the QR decomposition is mainly because it’s much more accurate than having the inverse. I’ve run into cases where the linear equations had nonredundant solution using QR with pivoting and the inverse of X’X matrix was singular when calculated directly. Using the inverse of X’X may end up with unstable solution again.

But once you have dropped columns you know that matrix is not particularly close to being singular, any of the methods including lstsq, which is the fastest, should be able to provide numerically stable results. I don't think in general we want to directly invert X'X ever. Personally I never liked the pinv solution to the redundant variable issue in statsmodels.

@bashtage

bashtage commented Aug 7, 2020

Copy link
Copy Markdown
Member

Not sure this fit regularized model. At a conceptual level, regularization pose some restrictions on the coefficients to deal with issues related to dimensionality of the model. In this case the process set a 0 coefficient to coefficients that have multicollinearity.

Regularization imposes restrictions on the quantity that needs to be inverted so that its inverse is well defined. This is precisely what is happening here. That regularization can sometimes be implemented in terms of parameter restrictions is just a useful consequence. Other methods, for example, eigenvalue cleaning, directly alter the matrix that needs to be inverted.

Mathematically this is the right solution of the regression equations

How can it be "right" when there are multiple solutions that have 0 coefficients? That doesn't sound very precise to me.

@bashtage

bashtage commented Aug 7, 2020

Copy link
Copy Markdown
Member

Least Square solution (including GLM or any other algorithm that uses the WLS) will never (in practice) produce a coefficient that is identical to 0. Having a perfect 0 (not close to 0) is a good enough indicative for coefficients that are dropped.

This is not true. There are cases where regression is used in hypothesis testing where some control variables have been explicitly orthogonalized so that they will produce a 0 coefficient.

@josef-pkt

Copy link
Copy Markdown
Member

#2407 is one of the issues based on my previous work for constrained fit methods that keeps the original model, with rank reduced cov_params in original parameter space.
We need to be able to handle this to impose constraints whether they are explicit or as here implicit as identification restrictions.

@josef-pkt

Copy link
Copy Markdown
Member

see also #4705

With categorical interactions that have empty cells, patsy leaves a column of zeros in the exog.

effects = np.dot(Qq.T, self.wendog)
beta = linalg.solve_triangular(Rr, effects)
beta = np.concatenate((beta, np.repeat(0.0, n_singular)))[sortP]
self.effects = np.concatenate((effects, np.repeat(np.NaN, n_singular)))

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.

this will need unit tests for anova_lm
I don't know if this should be nan or zero or something else

@josef-pkt

josef-pkt commented Mar 6, 2023 •

Copy link
Copy Markdown
Member

I started a new overview issue for problems related to singular exog. #8721

Main task left here is to check that more of the results methods and attributes and postestimation features like anova_lm are correct, i.e. correspond to the model that drops the variables in exog directly.

possible problem check df_xxx and their usage. (effective degrees of freedom)

aside: I started the look at this again because scipy got a similar PR

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