Repository navigation
ENH: Add vif, vif_ridge and collinear_index (multicollinearity, takeover of #7711) - #10623
Merged
Merged
Conversation
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]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
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
marked this pull request as ready for review
October 27, 2026 21:38
This was referenced Oct 28, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
closes #7711
closes #2380
closes #1669
closes #2376
closes #6249
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/headare cherry-picked unchanged onto currentmain(the only difference is thatstatsmodels/stats/moment_helpers.pykeeps the version ofmain, 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 fromstatsmodels.stats.api, documented indocs/source/stats.rstanddiagnostic.rst, with a bullet indocs/source/release/version0.15.1.rst.vif(data, *, is_moment=False, has_constant="raise")datais a data matrix, or a covariance/correlation matrix withis_moment=True.Seriesfor aDataFrame.vif_ridge(data, pen_factors, *, is_moment=False, has_constant="raise")DataFrame(factors x variables) for aDataFrame.collinear_index(data, tol=None)(idx_collinear, idx_keep),Indexof labels for aDataFrame.variance_inflation_factorinoutliers_influenceis not changed (see decisions); only itsSee Alsoplaceholder (xxx : class ... does not exist yet) now points tovif.Decisions to review
MultiCollinearity*classes are removed, not kept.MultiCollinearityBase,MultiCollinearityandMultiCollinearitySequentialduplicated 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 isnp.linalg.cond. A class withfrom_model(requested by bashtage on ENH: Add multicollinearity tools (rebase/improve #2380) #7711) is not included. With formulas the recipe isvif(res.model.data.orig_exog, has_constant="skip"), which is in the docstring example and is tested under both formula engines. Afrom_modelcan be added later on top ofvif.vif_selectionis dropped. It returned(idx, None)with a placeholder, has an arbitrary defaultthreshold=10, and inverts a matrix at each step. Backward selection on top ofvifis a possible follow-up.variance_inflation_factoris not delegated to the new code.mainalready centers the data (standardize=True), so its results equalviffor 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, whilevifreturnsinffor collinear columns. Per column, delegation would also not be faster.vifalways centers the data (equivalent to including a constant). A constant column raises aValueErrorby default, with the positions in the message.has_constant="skip"returnsNaNat the constant columns and leaves the other columns unchanged, which keeps the positions aligned and makesres.model.exogusable. Implicit constants (a full set of dummies with no constant column) are not detected: the dummies are perfectly collinear after centering and getinf, 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.ridge_factor=1e-14is replaced by an eigendecomposition. A column isinfif 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 falseinf; 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.collinear_indextakes one relativetol(defaultmax(nobs, k) * eps, asmatrix_rank) instead ofatol, rtolon 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
statsmodels.tools.decorators.cache_readonlyno longer exists (import error);np.corrcoef(..., bias=True)removed in NumPy 2; ambiguous truth value attest_multicollinearity.py:161;TestMultiCollinearSingular1/2calledOLSon rank-deficient designs (SingularMatrixWarningis an error in the test suite); 12 ruff errors; not exported instats.api; not in the docs; no release note. All of these disappear with the rewrite.vif(vectorised),vif_ridge,collinear_index, the idea of a moment matrix as input, the SAS ridge VIF table of the tests (verbatim).standardizeandridge_factorarguments removed (vifalways centers; the ridge factor is replaced by the null space detection).vif_ridge(corr_x, pen_factors, is_corr=True)becamevif_ridge(data, pen_factors, is_moment=False)so that it takes data by default likevif.rsquared_partial,corr_partial,tss,rss,eigenvalues,condition_number;vif_selection; the old tests (replaced).Verification
R reference: R 4.6.1 with
car3.1.5. The code and the values are instatsmodels/stats/tests/results/results_multicollinearity.py. Note that R was run from the Windows installation, not from WSL.car::vifforlm(Employed ~ ., longley)(six regressors, VIF from 3.6 to 1788.5), a four regressor subset, andlm(mpg ~ disp + hp + wt + drat + qsec, mtcars).vifagrees to about 3e-12 relative on Longley (test tolerance 1e-9).variance_inflation_factorofmainis checked against the same mtcars values with and without a constant.collinear_indexagainst the aliased (NA) coefficients oflmfor a design with an exactly collinear column and for a constant with a full set of dummies.vif_ridgeagainst the SAS table from ENH: Add multicollinearity tools (rebase/improve #2380) #7711 (tolerance of the printed 3 decimals), and the exact formulainv(R + kI) R inv(R + kI).vifalso againstOLSauxiliary regressions (centered sums of squares so that large VIF are accurate) and againstvariance_inflation_factor.Speed, single thread (
OPENBLAS_NUM_THREADS=1), 1000 observations,variance_inflation_factorcalled for each column of a design with a constant, as users do it today:vifThese 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
infand the other columns exact.collinear_indextakes 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
mainwith the*.pyfiles of this branch copied over it:Not done: the Sphinx docs were not built (the rst additions are small);
tools/validate_docstrings.pyreports only the three summary-style messages that it also reports for existing functions such asacorr_ljungbox; no Windows or macOS run, and no CI yet.Related issues
variance_inflation_factorand the treatment of the constant and of implicit constants. The behavior inmainis already the centered definition, which agrees withvifand with R, andvifdocuments the definition and the implicit constant case. This PR does not change that function, but the maintainer decided that the documented behavior settles both issues, so they are listed undercloses.fit_collinear), SUMM: singular exog (again) #8721 (singular exog summary) and REF/ENH vif variance inflation factor and feature selection #4582 (feature_selection_vif) are not covered.collinear_indexandvifare building blocks for them.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.
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.