Skip to content

Design: OLS issue, perfect collinearity #3824

Closed

Description

@SergicHill

The standard OLS model estimation cannot be computed when there is a linear dependence among regressors (see https://en.wikipedia.org/wiki/Ordinary_least_squares ). This is the case for example, when a regression has a constant and dummy variables which in sum give a vector of 1s. However, the current version of the function statsmodels.api.OLS(y,x) computes something, that something is nonsense. To see the problem by yourselves, try to run the following code:


import numpy as np
import statsmodels.api as sm

y=np.array([1,2,1,4,6,1,7,8,1,10])

x = np.array([[ 1, 1,0], [2, 1,0], [ 3, 1,0],
[4, 1,0], [5, 1,0], [6, 0,1],[7, 0,1],
[8, 0,1], [ 9, 0,1], [10, 0,1]])
cx = sm.add_constant(x)

print "cx="
print cx
print "y="
print y

model = sm.OLS(y,cx)
results = model.fit()
print "estimates of the regression="
print results.params

Instead of producing something like "The regression cannot be run because the regressors are linearly depedent" it gives INCORRECT output:
cx=
[[ 1. 1. 1. 0.]
[ 1. 2. 1. 0.]
[ 1. 3. 1. 0.]
[ 1. 4. 1. 0.]
[ 1. 5. 1. 0.]
[ 1. 6. 0. 1.]
[ 1. 7. 0. 1.]
[ 1. 8. 0. 1.]
[ 1. 9. 0. 1.]
[ 1. 10. 0. 1.]]
y=
[ 1 2 1 4 6 1 7 8 1 10]
estimates of the regression=
[-1.66666667 1.2 0.86666667 -2.53333333]

Activity

  1. kshedden commented on Jul 18, 2017

    @kshedden
    Contributor

    I have not looked closely at this code. But using the pseudo-inverse to calculate the least squares fit gives the minimum norm element among all possible solutions. Thus it is not arbitrary. See below for details. While the estimates themselves are not nonsense, the standard errors, etc. may be, hence the warning at the bottom of the summary table.

    https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse#Minimum_norm_solution_to_a_linear_system

  2. josef-pkt commented on Jul 19, 2017

    @josef-pkt
    Member

    There are several discussions on stackoverflow for handling singular design matrices across packages
    both Stata and R drop columns by default, statsmodels uses pinv

    e.g. https://stackoverflow.com/questions/37472963/statmodels-in-python-package-how-exactly-duplicated-features-are-handled/37499160#37499160

    we show the warning, the user needs to decide about proper handling of singular or near singular matrices, and/or check whether the usage of the pinv regularized version makes sense, e.g. predict works if relationship are stable, inference works for "estimable" functions of the params.

  3. josef-pkt commented on Jul 19, 2017

    @josef-pkt
    Member

    While I think we will not change the default, there are open issues to have more options and supporting function for singular/collinear design matrices and design matrices with high multicollinearity.
    e.g. #2380, #2062

  4. SergicHill commented on Jul 19, 2017

    @SergicHill
    Author

    You should not call this function OLS because the standard OLS requires the input matrix to have full column rank. The current OLS function might produce multiple bugs in the users' code, which are very hard to find!
    The issues are:
    a) The estimates that the current OLS function produces have no econometric sense (which presumes to be a "partial derivative" of y w.r.t. x). The the statistics derived from them might be misleading.
    b) Take a look at https://en.wikipedia.org/wiki/Ordinary_least_squares, which says "This formulation highlights the point that estimation can be carried out if, and only if, there is no perfect multicollinearity between the explanatory variables". This is a standard econometric requirement.
    c) Your approach of solving the estimation problem gives not unique solution (i.e. estimates), see at https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse#Minimum_norm_solution_to_a_linear_system
    "all of whose infinitude of solutions are given by this last equation", which one your code suggest is unknown to the users.

    Suggested solution: Give a different name to the current OLS function ( e.g. pseudoOLS) and introduce an OLS function that requires full rank independent variables matrix (like in all respected econometric packages: R, Stata, SAS, Eview etc).

  5. josef-pkt commented on Jul 19, 2017

    @josef-pkt
    Member

    It is still OLS for the usual case when the design matrix is well conditioned.
    The rest is up to the user, in interactive work the user can see the warning message, in programmatic use the user can check the rank attribute of the model.

    For general problems with multicollinearity, having a singular design is not really different from having a highly multicollinear design. Besides smallest eigenvalue and condition number we also have variance inflation factor to check how serious the multicollinearity problem is.

    One reason that it is very very unlikely that this will change is that it is convenient for cases where we are not interested in the parameters itself, but in some statistics that are independent of the choice of an arbitrary solution among the infinite number of "equivalent" least squares solution, e.g. fittedvalues/prediction and r_squared.

    Stata and R do not required a non-singular design, they just drop an "arbitrary" column.

  6. SergicHill commented on Jul 19, 2017

    @SergicHill
    Author

    Conceptual bugs are very difficult to find, but this version of OLS leads to it. First, I see no warning messages re full rank. Second, you suggest that "in programmatic use the user can check the rank attribute of the model" but that will happen only if the user is aware that the function a) needs the full rank assumption b) the function drops the full rank assumption, otherwise the bug will pops up only in action, that might lead to a disaster. Who will be responsible?

    The good analogy of this case is a situation when someone buys a walmart bicycle, names it as a Toyota car, and invites his friends for a ride on his Toyota car. You can easily predict their surprise when they see this car...:) There is a huge body of literature that studies OLS properties which assumes full rank and users presume these properties hold, but in fact they do not!

    The current OLS produces statistics, named as e.g. t-statistics, which in fact has no standard meaning of a t-statistics, I am not sure that r_square retains its meaning as well.

    What to do: If you are reluctant to replace the function name, another option is to provide the current OLS function with an argument a la "method of inverse", which can be standard inverse (X'*X)^-1 by default and/or pseudoinverse by choice. In the latter case, the computed statistics should be either omitted or marked with a note that they might have no standard meaning or something of that sort. In addition, the OLS function documentation must be supplemented with a reference to the academic literature that outlines OLS properties when the full rank assumption is dropped.
    Does it make sense?

  7. ChadFulton commented on Jul 19, 2017

    @ChadFulton
    Member

    I agree that conceptually there is no problem here - OLS is a linear projection onto the column space of X, and this is still true even if X has less than full rank. This is also true if the regressors are random.

    with a reference to the academic literature that outlines OLS properties when the full rank assumption is dropped.

    Among many others, Rao and Mitra have a number of works on this. Their book, "Generalized Inverse of Matrices and Its Applications", is excellent, but a short survey article is http://digitalassets.lib.berkeley.edu/math/ucb/text/math_s6_v1_article-32.pdf


    I have never looked at this part of Statsmodels before, and I'm sure there are a variety of trade-offs, but implementation-wise it looks like there is a continuity issue in computing the normalized covariance parameters:

    y = np.array([[1.2, 0.4, 2.5, -0.5, 1.3]]).T
    x = np.ones((5, 2))
    
    res1 = sm.OLS(y, x).fit()
    print res1.normalized_cov_params
    [[ 0.05  0.05]
     [ 0.05  0.05]]
    

    whereas if we perturb the exogenous vector slightly

    eps = 1e-10
    x[-1, -1] += eps
    res2 = sm.OLS(y, x).fit()
    print res2.normalized_cov_params
    [[  1.25000e+20  -1.25000e+20]
     [ -1.25000e+20   1.25000e+20]]
    

    If we are concerned about continuity, it seems like we would either want the covariance parameters for the non-identified coefficients to go to infinity as epsilon goes to zero, or else we may want to consider computing normalized_cov_params as pinv(x'x) rather than, as it currently is, pinv(x).dot(x').

    xtx = x.T.dot(x)
    pxtx = np.linalg.pinv(xtx)
    print pxtx
    [[ 0.05  0.05]
     [ 0.05  0.05]]
    
  8. josef-pkt commented on Jul 19, 2017

    @josef-pkt
    Member

    @ChadFulton related #2628
    There are equvalent thresholds for pinv x and xTx

    (I hate typing on an iPad)

  9. ChadFulton commented on Jul 19, 2017

    @ChadFulton
    Member

    There are equvalent thresholds for pinv x and xTx

    Good point, I guess we can't avoid a threshold somewhere.

  10. SergicHill commented on Jul 19, 2017

    @SergicHill
    Author

    Folks:
    There is no problem with using pseudo-inverse matrix in the function, which you call OLS. The problem is with the name of that function and potential errors that the name induces. For example, t-statistics computed on the basis of your function either not applicable or have different meaning, however, users might have no idea about it, because the standard OLS method, see e.g. Econometric Analysis by Greene, or Stata or R etc. always assumes full rank. This is what I point to as a conceptual error.
    Chad, the .pdf file you refers explores pseudo-inverse operator (I have no objection against this operator), but that paper does not tells us about the particular statistics that are associated and reported with this OLS function... So it is not directly relevant to the raised issue.

  11. josef-pkt commented on Jul 19, 2017

    @josef-pkt
    Member

    two more #146 #2011

    and start of a FAQ #1672

    rcond pinv(x) versus pinv(x.T x) #1662

    related bad scaling for nonlinear models #1131, but scaling can have a large effect in the near singular case (bouncing around the numerical singularity threshold)


    I think the better car analogy:
    OLS is like a car where the passenger side airbag is turned off by default. It doesn't matter if there is no passenger or if there is no accident. It is good if there is a baby seat. It is bad if you are an adult passenger in a car accident. (Better check the setting of the airbag.)

  12. SergicHill commented on Jul 19, 2017

    @SergicHill
    Author

    Do you indeed check the airbag setting (or that it is indeed an airbag) when you rent a car or take a passenger place? Or, instead, assume that the airbag functions properly, i.e. as you expect it to function in the case of a disaster. Imagine that airbag engineers set a constraint to it: remain intact if the car speed is less then 120 m/h and you are not actively warned about it. Would you be happy?

  13. josef-pkt commented on Jul 19, 2017

    @josef-pkt
    Member

    some history on this recurrent theme
    https://groups.google.com/d/msg/pystatsmodels/AZXNfPcq_HI/vyD_1MEvfEwJ
    https://groups.google.com/d/msg/pystatsmodels/IqXK0SkDcnw/Zn25sy9dcsIJ

    so far status-quo ante always won (pinv was inherited from the precursor of statsmodels)

    AFAIK, SAS and SPSS use a generalized inverse in some cases. But they have additional support for hypothesis for "estimable function", which I still don't understand. There is some related code from pre-statsmodels times still in statsmodels although completely unused.

    OLS also has a QR method for the estimation, but I never checked very carefully how it behaves with singular or almost singular at threshold exog matrices. It doesn't regularize, so it should fail at some point, and produce noise before that.

    Note, I think raising an explicit warnings.warn would be helpful. IIRC, Kevin recently added the warning text to the html summary, which was only in the as_text before (i.e. print shows it but the default without print in a notebook didn't show the warning message at the end of summary.)

    (another similar perennial issue: check for nans/missing values and the default nan handling. My opinion is moving towards an explicit warning.warn in that case also.)

  14. SergicHill commented on Jul 19, 2017

    @SergicHill
    Author

    From one of the above links I read that one persons warns that computed statistics have no sense if the exogenous have no full rank (i.e. what I said above). However, the eventual response to it is "In my experience, I find that completely unnecessary task mainly because virtually all my models are not full column rank. " This kind of a discussion reminds me talking of a deaf with a blind....Do not take it personally, though.

  15. SergicHill commented on Jul 19, 2017

    @SergicHill
    Author

    Why being explicit about the inversion method is so difficult issue?

  16. ChadFulton commented on Jul 19, 2017

    @ChadFulton
    Member

    Chad, the .pdf file you refers explores pseudo-inverse operator (I have no objection against this operator), but that paper does not tells us about the particular statistics that are associated and reported with this OLS function... So it is not directly relevant to the raised issue.

    The paper tells you why and how OLS with a generalized inverse is valid, see section 5. It is a bit abbreviated, but the book I referenced has several chapters on the subject.

    here is no problem with using pseudo-inverse matrix in the function, which you call OLS. The problem is with the name of that function and potential errors that the name induces. For example, t-statistics computed on the basis of your function either not applicable or have different meaning, however, users might have no idea about it, because the standard OLS method, see e.g. Econometric Analysis by Greene, or Stata or R etc. always assumes full rank. This is what I point to as a conceptual error.

    There are two issues: (1) is OLS via generalized inverse in the presence of multicollinearity valid, and (2) practically, what should a statistical software do about multicollinearity.

    My point is that for (1) the answer is yes! OLS via generalized inverse in the presence of multicollinearity is indeed valid, including point estimates, fitted values, t-statistics, etc. This is what I was pointing out in the Rao and Mitra references. You seem to be arguing that something about it is invalid, and that, I think, is why you are receiving push-back (at least from me).

    When you have (perfect) multicollinearity, one or more columns are linearly dependent and there are an infinite set of combinations of coefficients on those columns that would satisfy the least squares solution. When you drop one or more columns to make the X matrix full rank, what you are doing is imposing a particular solution in which some of the coefficients have been chosen to be zero.

    The method in Statsmodels, using a pseudo-inverse, also imposes a particular solution, and this is possible because the Moore-Penrose pseudo-inverse is unique. You could even use other pseudo-inverses, and they too would yield different, but valid, solutions.

    Now, as to (2), I have no opinion about what should practically be done. Dropping columns in the case of perfect multicollinearity would be fine with me, as would leaving it as-is and warning the user in the notes section. Or having an option.

  17. josef-pkt commented on Jul 19, 2017

    @josef-pkt
    Member

    However, the eventual response to it is "In my experience, I find that completely unnecessary task mainly because virtually all my models are not full column rank. "

    That comes from one tradition in statistics, we estimate an overparameterized model, but then we only look at constraints, contrasts or linear combinations that are identified. This is in contrast to parameterizing the model so that the coefficients are identified and can be directly interpreted in the desired way.

    Aside: I'm not taking any subject criticism personally. (I grew up at UCLA and University of Chicago.)

    Why being explicit about the inversion method is so difficult issue?

    The use of pinv is supposed to be pretty explicit in the documentation, docstrings and multicollinearity warning at the end of summary. If it's not clear enough, then it should be improved.
    (e.g. http://www.statsmodels.org/dev/pitfalls.html#unidentified-parameters )
    Renaming OLS is out of question because of backwards compatibility, but also because I don't see a strong enough reason that behavior in edge cases should determine the name.

    What other options we get for singular or multicollinear cases is still an open question.
    fit_regularized and TheilRidge or similar are explicit in the name but they also have proper multicollinearity options where it is not just an edge case.


    real life analogies are always inappropriate because real life almost never has a replay button.
    i.e. run the model, look at the results, check that the model and results make sense (diagnostic checks), rinse, rerun

    another idea: #1908 not implemented because of lack of wo/man-power and other work has higher priority.

  18. SergicHill commented on Jul 19, 2017

    @SergicHill
    Author

    Chad:
    1a. Which particular page , line (of section 5?) of Rao et al. paper discusses t-statistics of OLS via generalized inverse?
    1b. "and they too would yield different, but valid, solutions." what does it mean? If endogenous y is generated by a perfectly collinear model. I doubt there is a way to get back (or estimate) its original coefficients (consistently).
    2. If the matter is so simple and obvious then why numerous econometrics books and software applications consider only full rank exogenous variables?
    3. "When you have (perfect) multicollinearity...", it might be that you are confusing the actual world and the model that is supposed to describe it. It might be that the actual world is not affected by perfect multicollinearity, but rather by independent components of the relevant forces. As you remember, the idea of a coefficients in a regression is a partial derivative, e.g. y=a+b1x+b2z+error, the coefficient of b1 is the direct effect of x on y stripped from the effect of x on y via z. If x and z are the same (i.e. perfect collinearity), then the explanation above makes no sense. You can as a researcher come up with a new theory and underlying meaning of the regression coefficients in that case, but that will not be a standard OLS anymore, and as such should bear a different name.
    4. My motto is that standard functions should have standard properties. There are excellent academic outlets for revolutionary ideas.
    5. What to do? I suggest either dropping extra collinear variable ( like it is done in Stata) with a warning or make an optional argument re the inverse method (to keep the current developments intact the latter method might be preferable, if possible).

  19. ChadFulton commented on Jul 20, 2017

    @ChadFulton
    Member

    1a. Which particular page , line (of section 5?) of Rao et al. paper discusses t-statistics of OLS via generalized inverse?

    It constructs a best linear unbiased estimator, where "best" refers to the variance of the estimator. The t-stats are constructed from the variance of the estimator. It looks like it doesn't give the formula for the standard errors in the paper, but those are available in Theorem 7.2.3 ("Expressions for variance and covariances of BLUE estimators") of their book, where they give V(p' \hat \beta) = \sigma^2 p' (X' X)^- p, for any unbiased estimable linear function p, where (X' X)^- is any pseudo-inverse, and with \hat \beta = (X' X)^- X' Y.

    Edit: I meant to say that V(p' \hat \beta) is the variance / covariance matrix. Obviously the standard errors can be computed from that.

    The usual standard errors with perfect multicollinearity are infinite for the linearly dependent variables, and that's a perfectly reasonable statement. The idea behind constructing the sampling distribution of the unbiased estimable linear functions p is to form a particular combination of the linearly dependent variables that you can distinguish the contribution of, and for those linear combinations of estimators, you can construct a finite variance, e.g. \sigma^2 p' (X' X)^- p.

    1b. "and they too would yield different, but valid, solutions." what does it mean? If endogenous y is generated by a perfectly collinear model. I doubt there is a way to get back (or estimate) its original coefficients (consistently).

    Right, I'm not saying you can achieve the marginal effects of the explanatory variables separately, that's impossible. A "solution" is a coefficient vector that minimizes the sum of squared errors, and with perfect multicollinearity there are many solutions.

    1. If the matter is so simple and obvious then why numerous econometrics books and software applications consider only full rank exogenous variables?

    I suppose to require as little linear algebra as possible?

    it might be that you are confusing the actual world and the model that is supposed to describe it

    It could be that we have different aims. I'm making a purely technical point, that OLS computed via pseudo-inverse in the presence of perfect multicollinearity has a rigorous and valid definition, as in Rao and Mitra.

  20. ChadFulton commented on Jul 20, 2017

    @ChadFulton
    Member

    It could be that we have different aims. I'm making a purely technical point, that OLS computed via pseudo-inverse in the presence of perfect multicollinearity has a rigorous and valid definition, as in Rao and Mitra.

    You may be more interested in Chapter 5 of Searle's book "Linear Models", which has a less cryptic presentation than Rao and Mitra.

  21. SergicHill commented on Jul 20, 2017

    @SergicHill
    Author

    Chad:
    Are the estimates consistent? I think not.
    What is their asymptotic distribution? Perhaps, not well defined.
    Is there any scientific reason to push forward models that cannot be identified? What is a chance for making into a serious journal a paper with an obviously non-identifiable model? I would not be surprised if it becomes desk rejected....
    Is it true that 5 = (0/0)*5 ? This trick reminds me the proof of the unbiasedness of your OLS estimates.
    Are we trying to find the truth or instead trying to fight for a life in a court room?
    It is time to move on. My suggestions was outlined above, let me repeat it here: I suggest either dropping extra collinear variable ( like it is done in Stata) with a warning or make an optional argument re the inverse method (to keep the current developments intact the latter method might be preferable, if possible).

  22. ChadFulton commented on Jul 20, 2017

    @ChadFulton
    Member

    I agree, it does seem like we're not making any forward progress :) Nonetheless, if you are actually interested in this subject, I do recommend the references above.

    If you'd like to submit a PR to allow an option for dropping columns in case of perfect multicollinearity, in my opinion that would be a good addition.

  23. changed the title [-]OLS issue[/-] [+]Design: OLS issue, perfect collinearity[/+] on Feb 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions