Skip to content

ENH: Add vif, vif_ridge and collinear_index (multicollinearity, takeover of #7711) - #10623

Merged
bashtage merged 29 commits into
statsmodels:mainfrom
bashtage:wip-multicollinearity-vif
Oct 28, 2026
Merged

bashtage merged 29 commits into
statsmodels:mainfrom
bashtage:wip-multicollinearity-vif

Conversation

@bashtage

@bashtage bashtage commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

closes #7711
closes #2380
closes #1669
closes #2376
closes #6249

  • tests added / passed.
  • code/documentation is well formatted.
  • properly formatted commit message.

Draft takeover of the multicollinearity work of josef-pkt in #2380 and #7711, with a smaller public API. The 23 commits of josef-pkt and the one commit of bashtage in the range merge-base..pull/7711/head are cherry-picked unchanged onto current main (the only difference is that statsmodels/stats/moment_helpers.py keeps the version of main, which already has the docstring changes of that commit). The changes are in 3 commits on top, so the history of #7711 is preserved.

What the PR adds

New module statsmodels.stats.multicollinearity, exported from statsmodels.stats.api, documented in docs/source/stats.rst and diagnostic.rst, with a bullet in docs/source/release/version0.15.1.rst.

Function Purpose
vif(data, *, is_moment=False, has_constant="raise") VIF of all columns at once from the correlation matrix. data is a data matrix, or a covariance/correlation matrix with is_moment=True. Series for a DataFrame.
vif_ridge(data, pen_factors, *, is_moment=False, has_constant="raise") VIF of ridge regression for all penalization factors from one eigendecomposition. DataFrame (factors x variables) for a DataFrame.
collinear_index(data, tol=None) Columns that are perfectly collinear with preceding columns (design matrix semantics, no demeaning). Returns (idx_collinear, idx_keep), Index of labels for a DataFrame.

variance_inflation_factor in outliers_influence is not changed (see decisions); only its See Also placeholder (xxx : class ... does not exist yet) now points to vif.

Decisions to review

  1. The MultiCollinearity* classes are removed, not kept. MultiCollinearityBase, MultiCollinearity and MultiCollinearitySequential duplicated the standalone functions, returned no pandas objects, had documented incomplete handling of constants and singular data, and josef-pkt said on ENH: Add multicollinearity tools (rebase/improve #2380) #7711 that the interface is too confusing. Functions only is the smaller surface that I could test against R. The one-line replacements: rsquared_partial = 1 - 1 / vif(...), condition number is np.linalg.cond. A class with from_model (requested by bashtage on ENH: Add multicollinearity tools (rebase/improve #2380) #7711) is not included. With formulas the recipe is vif(res.model.data.orig_exog, has_constant="skip"), which is in the docstring example and is tested under both formula engines. A from_model can be added later on top of vif.
  2. vif_selection is dropped. It returned (idx, None) with a placeholder, has an arbitrary default threshold=10, and inverts a matrix at each step. Backward selection on top of vif is a possible follow-up.
  3. variance_inflation_factor is not delegated to the new code. main already centers the data (standardize=True), so its results equal vif for the non-constant columns (tested with and without a constant column and against R). Delegating would change its edge cases: it clips VIF at 1e15 and warns for condition number above 1e4, while vif returns inf for collinear columns. Per column, delegation would also not be faster.
  4. Constants. VIF is defined for regressions with a constant, so vif always centers the data (equivalent to including a constant). A constant column raises a ValueError by default, with the positions in the message. has_constant="skip" returns NaN at the constant columns and leaves the other columns unchanged, which keeps the positions aligned and makes res.model.exog usable. Implicit constants (a full set of dummies with no constant column) are not detected: the dummies are perfectly collinear after centering and get inf, which is documented and tested. A moment matrix that is not centered (x.T @ x) gives the VIF of regressions without a constant, also documented and tested.
  5. Singular data. The old inverse plus ridge_factor=1e-14 is replaced by an eigendecomposition. A column is inf if it has weight in the numerical null space of the correlation matrix, and the other columns get the exact value from the pseudo inverse. An ad hoc scan of 651 random designs (6-39 columns, one exact relation among three columns, with and without a near-collinear pair of columns with VIF up to 1e10) found no missed and no false inf; the scan is not part of the test suite, the tests contain representative cases. Limits (documented): VIF above about 1e12 is floating point noise, and a column whose weight in an exact relation is below about 1e-7 is not flagged.
  6. Tolerances and float32. collinear_index takes one relative tol (default max(nobs, k) * eps, as matrix_rank) instead of atol, rtol on the variance. It uses Gram-Schmidt with reorthogonalization against the non-collinear preceding columns, so a collinear column does not change the result for later columns (QR without pivoting can). float32 data are converted to float64; a linear combination computed in float32 is only collinear to float32 precision and is not flagged (tested).

Against #7711

Fixed statsmodels.tools.decorators.cache_readonly no longer exists (import error); np.corrcoef(..., bias=True) removed in NumPy 2; ambiguous truth value at test_multicollinearity.py:161; TestMultiCollinearSingular1/2 called OLS on rank-deficient designs (SingularMatrixWarning is an error in the test suite); 12 ruff errors; not exported in stats.api; not in the docs; no release note. All of these disappear with the rewrite.
Kept vif (vectorised), vif_ridge, collinear_index, the idea of a moment matrix as input, the SAS ridge VIF table of the tests (verbatim).
Changed Pandas in gives pandas out. Constants are explicit. standardize and ridge_factor arguments removed (vif always centers; the ridge factor is replaced by the null space detection). vif_ridge(corr_x, pen_factors, is_corr=True) became vif_ridge(data, pen_factors, is_moment=False) so that it takes data by default like vif.
Dropped The three classes with rsquared_partial, corr_partial, tss, rss, eigenvalues, condition_number; vif_selection; the old tests (replaced).

Verification

R reference: R 4.6.1 with car 3.1.5. The code and the values are in statsmodels/stats/tests/results/results_multicollinearity.py. Note that R was run from the Windows installation, not from WSL.

  • car::vif for lm(Employed ~ ., longley) (six regressors, VIF from 3.6 to 1788.5), a four regressor subset, and lm(mpg ~ disp + hp + wt + drat + qsec, mtcars). vif agrees to about 3e-12 relative on Longley (test tolerance 1e-9). variance_inflation_factor of main is checked against the same mtcars values with and without a constant.
  • collinear_index against the aliased (NA) coefficients of lm for a design with an exactly collinear column and for a constant with a full set of dummies.
  • vif_ridge against the SAS table from ENH: Add multicollinearity tools (rebase/improve #2380) #7711 (tolerance of the printed 3 decimals), and the exact formula inv(R + kI) R inv(R + kI).
  • vif also against OLS auxiliary regressions (centered sums of squares so that large VIF are accurate) and against variance_inflation_factor.

Speed, single thread (OPENBLAS_NUM_THREADS=1), 1000 observations, variance_inflation_factor called for each column of a design with a constant, as users do it today:

variables per column loop vif speed-up max relative difference
5 2.2 ms 0.14 ms 16x 3e-15
20 21.9 ms 0.24 ms 93x 2e-14
60 234.7 ms 0.68 ms 344x 4e-13
120 1714.7 ms 1.89 ms 907x 4e-12

These are smaller than the speed-ups of the plain matrix inverse in #7711 (about 39x, 273x and 2000x at 20, 60 and 120 variables, measured earlier on the PR as it stood), because the eigendecomposition is what makes exactly collinear columns inf and the other columns exact. collinear_index takes 0.5 ms for 20 and 6 ms for 120 columns.

Commands that were run and passed. Python files only changed, so the checks ran in WSL (Ubuntu-24.04, Python 3.13, NumPy 2.5.4, pandas 3.1.0, SciPy 1.18.1) on a copy of main with the *.py files of this branch copied over it:

export OPENBLAS_NUM_THREADS=1
python -m pytest -p no:xdist statsmodels/stats/tests/test_multicollinearity.py          # 53 passed (patsy, default)
SM_FORMULA_ENGINE=formulaic python -m pytest -p no:xdist statsmodels/stats/tests/test_multicollinearity.py   # 53 passed
python -m pytest -p no:xdist --doctest-modules statsmodels/stats/multicollinearity.py    # 3 passed (docstring examples)
python -m pytest -n 3 -m "(not slow and not example)" statsmodels/stats statsmodels/tools/tests/test_scalar_arguments.py statsmodels/regression/tests/test_glsar_gretl.py   # 3949 passed, 12 skipped, 1 xfailed
ruff check statsmodels/stats/multicollinearity.py statsmodels/stats/tests/test_multicollinearity.py statsmodels/stats/tests/results/results_multicollinearity.py statsmodels/stats/api.py statsmodels/stats/outliers_influence.py   # All checks passed
ruff format --diff statsmodels/stats/multicollinearity.py statsmodels/stats/tests/test_multicollinearity.py statsmodels/stats/tests/results/results_multicollinearity.py   # nothing to format

Not done: the Sphinx docs were not built (the rst additions are small); tools/validate_docstrings.py reports only the three summary-style messages that it also reports for existing functions such as acorr_ljungbox; no Windows or macOS run, and no CI yet.

Related issues

Status

Draft for review by the maintainer. Not marked ready for review. The last sentence of the AI Disclosure below (personally read and verified every line) is an attestation of the submitter, bashtage, to confirm after reviewing the diff; the diff has not been reviewed by a human yet.

AI Disclosure

Contributions must comply with the statsmodels AI Policy.

Tick exactly one of the following. If AI tools were used, replace the <...>
placeholders in the second option with the tool name(s) and how the tool's output was
used.

  • No AI tools were used to develop this pull request.
  • AI tools were used.
    Tool(s): Claude Code (Claude Sonnet 5.5).
    Used for: drafting the implementation, the tests and the documentation, running the R reference computations, the benchmarks and the test runs.
    I have personally read, understood, and can explain every line of this diff, and
    have verified the statistical/numerical correctness of the change.

josef-pkt and others added 29 commits October 27, 2026 20:35
Improve testing and ensure working with pandas
…ar_index

Continue the work of statsmodels#2380 and statsmodels#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]>
The penalization factors are added to the diagonal of the correlation
matrix, so they are on the scale of standardized variables. Standardize
the Longley columns first to make this explicit. The result is the same,
since vif_ridge standardizes through the correlation matrix.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@bashtage
bashtage marked this pull request as ready for review October 27, 2026 21:38
@bashtage
bashtage merged commit 8ffe8ab into statsmodels:main Oct 28, 2026
13 checks passed
@bashtage
bashtage deleted the wip-multicollinearity-vif branch October 28, 2026 07:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants