Skip to content

ENH: measures for multicollinearity - #2380

Closed
josef-pkt wants to merge 24 commits into
statsmodels:mainfrom
josef-pkt:multicollinearity
Closed

josef-pkt wants to merge 24 commits into
statsmodels:mainfrom
josef-pkt:multicollinearity

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Apr 30, 2015 •

Copy link
Copy Markdown
Member

additional measures for multicollinearity and enhanced variance inflation factor

relevant issues
#2376 treatment of constant for variance inflation factor
#1669 vif for ridge regression, base for non-loop calculation
#2157 general request for multicollinearity measures
#6249 problems with implicit or no constant
#2378 condition number, scaling

related issues
#1744 diagnostic messages including multicollinearity
#2062 use reduced column space for singular design matrices, I started to work on this with fit_transformed fit_constrained pattern
#1534 partially related for dropping singular, perfectly collinear columns
#4582 sequential dropping of large vif columns

Note:
Definition of "perfect collinearity" and "singular", "reduced rank" design matrices are subject to floating point noise and have different thresholds. see #1662

@josef-pkt josef-pkt added this to the 0.8 milestone Apr 30, 2015
@josef-pkt

Copy link
Copy Markdown
Member Author

floating point noise is machine dependent.

@josef-pkt
josef-pkt force-pushed the multicollinearity branch from e9103d7 to ba98b72 Compare May 1, 2015 00:45
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.03%) to 83.88% when pulling ba98b72 on josef-pkt:multicollinearity into a1f53b0 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

new unit test fail again in all python versions. Again, floating point noise is not "reliable"
(tests pass on my Windows 64bit python 3.4 with different noise)

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.02%) to 83.89% when pulling 247b8eb on josef-pkt:multicollinearity into a1f53b0 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.01%) to 83.9% when pulling ff73f37 on josef-pkt:multicollinearity into a1f53b0 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.01%) to 83.9% when pulling 0fa5fa9 on josef-pkt:multicollinearity into a1f53b0 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

test error in some version was invalid scalar indexing, most likely with older numpy.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 83.95% when pulling ca577a0 on josef-pkt:multicollinearity into a1f53b0 on statsmodels:master.

@josef-pkt
josef-pkt force-pushed the multicollinearity branch 3 times, most recently from 8a599e0 to 266de3c Compare May 2, 2015 00:50
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.06%) to 83.97% when pulling 4403101 on josef-pkt:multicollinearity into a1f53b0 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

Finally all green

test coverage above 90% but still a few missing options, besides untested ValueErrors.

I'm about finished here, it has all the functions I want right now. But, it would benefit from another API review.

constant handling:
default is that users don't add a constant to the data matrix and we standardize.
Other cases are a bit more questionable. We could scale vif using x.var(0), without scaling everything to scale 1.

What should the results for vif_selection be? Currently, None returned as second element as place holder.

open enhancements:

  • incomplete support for pandas, and missing one unit test (for pandas return in vif_selection)
  • more attributes for classes. what?
    (eigenvalues and condition number are not implemented/available in "sequential" class
  • currently we return floating point noise for singular design, no threshold for defining as singular or infinite vif, tiny eigenvalues or huge vif (above 1e12)
  • missing handling
  • other measures that I don't remember. ?
  • refactoring to streamline and DRYing

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.

threshold is not documented

sequence of moment_matrix and standardize is reversed, also in other docstrings

@josef-pkt

Copy link
Copy Markdown
Member Author

TODO: minor cleanup, rebase, merge

@josef-pkt

Copy link
Copy Markdown
Member Author

missing: check official import path (diagnostic ?), add to api and rst docs

@josef-pkt

Copy link
Copy Markdown
Member Author

bump, the comments sound there is only some cosmetics left to do.

What's the status?

(Why are you asking me, you wrote it?
No, it was a younger me that wrote it, I don't know.)

@josef-pkt josef-pkt modified the milestones: 0.9, 0.8 Feb 9, 2017
@josef-pkt

Copy link
Copy Markdown
Member Author

bump again
there is a new PR #3366 that does parts of this in a similar way

@josef-pkt
josef-pkt force-pushed the multicollinearity branch from 4403101 to d79b5a5 Compare May 20, 2017 04:37
@coveralls

coveralls commented May 20, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 90.456% when pulling d79b5a5 on josef-pkt:multicollinearity into 90e2af8 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased (no merge conflict), appveyor errors in unrelated statespace

about standardized (zscored) variables: need to check what it is doing here.
There is a newer issue (somewhere ?) that the collinearity threshold is on standardized variables, and we need both, what we actually use for numerical stability, and standardized for what is the underlying "multicollinearity" problem for the parameter estimate.

"""base class for multicollinearity measures
"""

def __init__(self, data, moment_matrix=None, standardize=True,

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.

need separate center deman option, i.e. scale to unit norm-2 length

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.

and option to demean only non-constant variables


"""

def __init__(self, data, moment_matrix=None, standardize=True,

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.

option for scaling without demeaning

self._init_moment(xm)
else:
if standardize:
x = (x - x.mean(0)) / 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.

alternative: allow constant but don't demean it


This corresponds to R^2 in a linear regression of one variable on all
others, including a constant if standarize is true, i.e. data was
demeaned.

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.

explain whether or when centered or uncentered rsquared

variables.

Warning: This uses the matrix inverse of the moment matrix, which can
produce nans or raise exceptions in singular or near-singular cases.

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.

check is this exog-scale invariant, it should be

@josef-pkt josef-pkt Jan 25, 2020 •

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.

possible problem here: I think this method assumes that mom_inv is demeaned to have an interpretation as correlation

(not checked, I'm working on semi-partial correlation and in an example I get a diff of around 1e-4 for semi-partial corr between corr and mom (xtx) versions.


@cache_readonly
def eigenvalues(self):
"""eigenvalue of the correlation matrix

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.

correlation matrix only if standardize, otherwise it's of the moment matrix

return evals

@cache_readonly
def condition_number(self):

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 condition_index or replace by that
np.sqrt(eigvals.max() / eigvals)


"""

def __init__(self, data, moment_matrix=None, standardize=True):

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.

same her, allow demean and scaling separately

return 1 - self.rss / self.tss


def vif(data, standardize=True, moment_matrix=None, ridge_factor=1e-14):

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.

replace standardize as above

@josef-pkt

Copy link
Copy Markdown
Member Author

not sure:

corr_partial and corr_semipartial (not yet included) only make sense if the data is standardized, i.e moment matrix mom is in correlation form. We don't get statistics that make sense on raw scaling and on standardizing in this case.

Those two could be in a stats.correlation module, especially if they get p-values for equal zero hypothesis test.

@josef-pkt

Copy link
Copy Markdown
Member Author

To the last point, methods that require correlation (i.e. standardized moment matrix)

We can just add a warning, if we don't have enough information to determine whether we have a correlation matrix or not, and maybe raise if we know we don't and cannot reconstruct it internally.
(One thing to check is whether we can handle the case with an explicit constant, i.e. scaled but not demeaned data as we have for Belsley's cond_index and variance decomposition.)

@josef-pkt

josef-pkt commented Jul 23, 2021 •

Copy link
Copy Markdown
Member Author

move to milestone 0.14.

The main open issue is design, how to handle both cases with and without constant, and possibly with scaling.
i.e. measures based on x'x versus cov(x) versus corr(x).

AFAIR, there is no clean separation for methods that apply to only one or the other cases.

edit it might be easier to split into two classes normalized (cov, corr) and raw (with constant in x)

@josef-pkt

josef-pkt commented Jun 24, 2022 •

Copy link
Copy Markdown
Member Author

2 options here for refactoring to disentangle with and without constant

  • keep both matrices, with and without constant around, and compute with whichever is appropriate or chosen in option
  • split class into two, or three with a base class, one userfacing class for with constant, and one for without constant.

scaling:

  • for methods that can be computed with or without scaling, e.g. corr versus cov in no constant case, we can add option.
  • scale invariant methods are computed without option with whatever is more convenient e.g. vif using cov/corr

for first option, an all-in-one class

  • user needs to provide full data, or full moment matrix including constant
  • we drop standardize=True, option
  • internally we keep all versions of with/without constant and with/without scaling (maybe cached attributes, so it could be lazy)

Problem with this is that some cached properties need to be methods instead, we will need to add options for scaling/constant treatment.
Or, alternatively, we would need several cached attributes with appropriate post_fix qualifier in name.

I guess it will be easier to first try out 2 subclasses.
e.g. use current class with and without explicit constant, and compare results. And then try to split in terms of results.

Also
table of condition indices is missing, AFAICS. Belsley used explicit constant and normed/scaled, AFAIR
Do I have a notebook with those?

update
notebook is try_cond_index.ipynb Last Checkpoint: 02/16/2020
The notebook seems to have too many versions of cond_index, no decision which version should be included or how different versions can be included.

update2
the notebook has

import statsmodels.stats.multicollinearity as mcoll
st = mcoll.cond_index(mpg).frame_styled()
st

but there is no cond_index in the PR on github.
tracking this: in an old folder with the original checkout of the branch, there is an additional commit with cond_index functions that hasn't been pushed

@josef-pkt

josef-pkt commented Jun 25, 2022 •

Copy link
Copy Markdown
Member Author

I pushed the old cond_index commit

new cond_index code has no unit test coverage,
otherwise PR is all green

@josef-pkt

josef-pkt commented Jun 25, 2022 •

Copy link
Copy Markdown
Member Author

based on R log, to compare results with R packages, I had used initially olsrr function

> library(olsrr)
> model <- lm(mpg ~ disp + hp + wt + qsec, data = mtcars)
> ols_eigen_cindex(model)

but then only

> library(mctest)
> eigprop(xx)

@josef-pkt josef-pkt modified the milestones: 0.14, 0.15 Nov 30, 2022
@josef-pkt

Copy link
Copy Markdown
Member Author

From an answer by myself on the mailing list to different condition numbers in the OLS notebook

Something like this should make it as introduction into the docs

"
Note, there are different condition numbers depending on scaling.

  1. The summary() reports the raw condition number, ie. condition number of exog without rescaling.
    This is relevant for numerical accuracy of the linear algebra computation for the given exog.
    It is not only affected by collinearity but also by bad scaling of the variables.

  2. The multicollinearity literature like Belsley Kuh Welsh use the condition number of the norm scaled exog which is the one described in the notebook.
    This does not alert the user if their actual exog is badly scaled. It's more a measure of inherent multicollinearity.

  3. Another branch of the multicollinearity literature defines multicollinearity for standardized exog (drop constant, demean and scale).
    This additionally does not detect problems with the constant, for example singular exog because of the dummy variable trap.

Each measure alerts to different effects.
The choice for summary was to alert to problems with the actual exog provided by the user.
"

bashtage added a commit that referenced this pull request Oct 28, 2026
…ar_index

Continue the work of #2380 and #7711 with a smaller
API that is exported from statsmodels.stats.api.

- vif computes the variance inflation factors of all columns from the
  eigendecomposition of the correlation matrix. It accepts a data matrix or
  a covariance or correlation matrix (is_moment), returns a Series for a
  DataFrame, raises for constant columns or skips them (has_constant), and
  returns inf for columns that are collinear with other columns.
- vif_ridge computes the ridge VIF of all penalization factors with one
  decomposition and has the same arguments.
- collinear_index flags columns that are collinear with preceding columns
  using Gram-Schmidt with reorthogonalization and a relative tolerance.
- The MultiCollinearity classes and vif_selection are removed. The classes
  duplicated the functions, did not return pandas objects and had unfinished
  handling of constants and singular data. vif_selection returned a
  placeholder.
- cache_readonly, which no longer exists, and np.corrcoef(bias=...), which
  was removed in NumPy 2, are not used anymore.

The tests are rewritten. They compare with R (car::vif and the aliased
columns of lm, in tests/results/results_multicollinearity.py), with OLS, with
variance_inflation_factor and with the SAS output for ridge VIF of the
original pull request.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
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