Repository navigation
ENH: add functionality Improve the stability for regression models with multicollinearity to statsmodels.regression (… - #6935
sergiolevin wants to merge 3 commits into
Conversation
…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.
|
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 |
|
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. |
|
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. |
|
@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. My function preserves the order and drops later columns instead of ordered by pivoting. |
bashtage
left a comment
There was a problem hiding this comment.
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.
| if 'tol' in kwargs: | ||
| tol = kwargs['tol'] | ||
| else: | ||
| tol = 1e-7 |
There was a problem hiding this comment.
Tol needs to depend on machine precision and the number of variables. See numpy or the other uses of pivoting in statsmodels.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| sortP = np.argsort(P) | ||
|
|
||
| if n_singular > 0: | ||
| rng = range(self.rank) |
There was a problem hiding this comment.
Use a slice, not a range object.
| tol = 1e-7 | ||
|
|
||
| singular_preds = abs(np.diagonal(R)) < tol | ||
| n_singular = sum(singular_preds) |
| else: | ||
| tol = 1e-7 | ||
|
|
||
| singular_preds = abs(np.diagonal(R)) < tol |
| 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) |
There was a problem hiding this comment.
Only lower case variables in general.
There was a problem hiding this comment.
The variable names are set to be consistent with the code of method = “qr” in RegressionModel.fit
There was a problem hiding this comment.
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 | ||
|
|
There was a problem hiding this comment.
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”
There was a problem hiding this comment.
those are pivoted Q, R matrices, so they might not have a use that is consistent with unpivoted QR
|
|
||
| # Cache singular values from R. | ||
| self.wexog_singular_values = np.linalg.svd(R, 0, 0) | ||
| if 'tol' in kwargs: |
There was a problem hiding this comment.
Use kwargs.get with a default value.
| 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] |
There was a problem hiding this comment.
It isn't right to set these to 0 since they will still appear in later calculations as variables
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
Can't you just sort columns first and avoid multiple sorts.
There was a problem hiding this comment.
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.
It's possible to keep it in (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. |
|
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. |
|
If the reduced rank path went into fit regularized then it would make more sense since that is ultimately what this method is doing. |
|
This pull request introduces 1 alert when merging ecf8a2d into cb99c88 - view on LGTM.com new alerts:
|
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. 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 |
|
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. |
|
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 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. |
difficult but important. I'm against variable selection in |
|
The pinv case is already wrong which is why I have always pushed for raise
on singular exog. For example, the pinv case gives finite length conf ints.
…On Sun, Aug 2, 2020, 13:50 Josef Perktold ***@***.***> wrote:
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.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#6935 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ABKTSRK32UU2JB4OUPG7XFLR6VOKTANCNFSM4PQUY25Q>
.
|
|
I mean in the case of singular exog plus pinv.
On Sun, Aug 2, 2020, 13:58 Kevin Sheppard <[email protected]>
wrote:
… The pinv case is already wrong which is why I have always pushed for raise
on singular exog. For example, the pinv case gives finite length conf ints.
On Sun, Aug 2, 2020, 13:50 Josef Perktold ***@***.***>
wrote:
> 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.
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <#6935 (comment)>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/ABKTSRK32UU2JB4OUPG7XFLR6VOKTANCNFSM4PQUY25Q>
> .
>
|
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. |
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 |
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. |
|
This pull request introduces 1 alert when merging 023ce02 into 0c2cda3 - view on LGTM.com new alerts:
|
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.
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. |
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.
How can it be "right" when there are multiple solutions that have 0 coefficients? That doesn't sound very precise to me. |
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. |
|
#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. |
|
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))) |
There was a problem hiding this comment.
this will need unit tests for anova_lm
I don't know if this should be nan or zero or something else
|
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 |
…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.
NumPy's guide.
Details
Notes:
needed for doc changes.
then show that it is fixed with the new code.
verify you changes are well formatted by running
flake8is installed. This command is also available on Windowsusing the Windows System for Linux once
flake8is installed in thelocal Linux environment. While passing this test is not required, it is good practice and it help
improve code quality in
statsmodels.