Skip to content

ENH: variance inflation factor #1669

Closed

Description

@josef-pkt

variance inflation factor in outlier_influence uses the definition to calculate vif for one parameter instead of using linalg to calculate all of them at once

see my answer and example script which includes vif for Ridge Regression
http://stackoverflow.com/questions/23660120/variance-inflation-factor-in-ridge-regression-in-python/23665644#23665644

Activity

  1. vincentarelbundock commented on May 23, 2014

    @vincentarelbundock

    Copying your SO response here.

    Variance inflation factor for Ridge regression is just three lines. I checked it with the example on the UCLA statistics page.
    A variation of this will make it into the next statsmodels release. Here is my current function:

    def vif_ridge(corr_x, pen_factors, is_corr=True):
        """variance inflation factor for Ridge regression
    
        assumes penalization is on standardized variables
        data should not include a constant
    
        Parameters
        ----------
        corr_x : array_like
            correlation matrix if is_corr=True or original data if is_corr is False.
        pen_factors : iterable
            iterable of Ridge penalization factors
        is_corr : bool
            Boolean to indicate how corr_x is interpreted, see corr_x
    
        Returns
        -------
        vif : ndarray
            variance inflation factors for parameters in columns and ridge
            penalization factors in rows
    
        could be optimized for repeated calculations
        """
        corr_x = np.asarray(corr_x)
        if not is_corr:
            corr = np.corrcoef(corr_x, rowvar=0, bias=True)
        else:
            corr = corr_x
    
        eye = np.eye(corr.shape[1])
        res = []
        for k in pen_factors:
            minv = np.linalg.inv(corr + k * eye)
            vif = minv.dot(corr).dot(minv)
            res.append(np.diag(vif))
        return np.asarray(res)
    
  2. added this to the 0.8 milestone on Apr 10, 2015
  3. added a commit that references this issue on May 1, 2015
    34e717e
  4. josef-pkt commented on Nov 13, 2016

    @josef-pkt
    MemberAuthor

    maybe of interest, I never saw much on vif and ridge except in 1970 or 1971 articles.
    (I didn't read it, too many sums with too many indices, no BIG linear algebra, looking very briefly.

    García, José, Román Salmerón, Catalina García, and María del Mar López Martín. 2016. “Standardization of Variables and Collinearity Diagnostic in Ridge Regression.” International Statistical Review 84 (2): 245–66. doi:10.1111/insr.12099.

  5. added a commit that references this issue on May 20, 2017
    dee0cc6
  6. added a commit that references this issue on Nov 1, 2017
    8b0e962
  7. added a commit that references this issue on Nov 1, 2019
    a08130e
  8. added a commit that references this issue on Sep 9, 2021
    f07d273
  9. gjpelletier commented on May 21, 2025

    @gjpelletier

    variance inflation factor in outlier_influence uses the definition to calculate vif for one parameter instead of using linalg to calculate all of them at once

    see my answer and example script which includes vif for Ridge Regression http://stackoverflow.com/questions/23660120/variance-inflation-factor-in-ridge-regression-in-python/23665644#23665644

    Hi Josef,

    Which of the following should be used as the input of the pen_factors in your function vif_ridge that was posted here and on stackoverflow:

    option 1: pen_factor = alpha
    option 2: pen_factor = alpha * np.sum(coefficients ** 2)

    Also, should alpha be scaled by n_samples for input to vif_fidge? (e.g. alpha = alpha_input / n_samples)?

    Best regards,

    Greg Pelletier

  10. josef-pkt commented on May 21, 2025

    @josef-pkt
    MemberAuthor

    @gjpelletier
    That depends on what the penalization factor in your ridge regression is.
    I've never seen your option 2, but various ridge functions can use penalization factors that either raw or scaled by variance or scaled by n_samples.

    Note my function uses correlation, so the ridge factor is assumed to be the same for standardized/scaled/zscored variables . Penalization weights are not equal across unscaled variables in the function.
    Also, correlation divides by nobs, so ridge factor also should be per nobs,
    corr(x) + k/ n *eye = (z'z + k * eye) / n, where z = (x - mean(x))/ std(x)

    (Aside: Windows update broke my main working computer/notebook. I'm not able to check details right now.)

  11. gjpelletier commented on May 22, 2025

    @gjpelletier

    @gjpelletier That depends on what the penalization factor in your ridge regression is. I've never seen your option 2, but various ridge functions can use penalization factors that either raw or scaled by variance or scaled by n_samples.

    Note my function uses correlation, so the ridge factor is assumed to be the same for standardized/scaled/zscored variables . Penalization weights are not equal across unscaled variables in the function. Also, correlation divides by nobs, so ridge factor also should be per nobs, corr(x) + k/ n *eye = (z'z + k * eye) / n, where z = (x - mean(x))/ std(x)

    (Aside: Windows update broke my main working computer/notebook. I'm not able to check details right now.)

    Hi Josef,

    For example, if I use the following input data for X and y:

    import numpy as np
    import pandas as pd 
    import statsmodels.api as sm
    from sklearn.linear_model import Lasso, Ridge
    np.random.seed(142131)
    n = 500
    d = pd.DataFrame()
    d['A'] = np.random.normal(size=n)
    d['B'] = d['A'] + np.random.normal(scale=0.25, size=n)
    d['C'] = np.random.normal(size=n)
    d['D'] = np.random.normal(size=n)
    d['intercept'] = 1
    d['Y'] = 5 - 2*d['A'] + 1*d['D'] + np.random.normal(size=n)
    y = np.asarray(d['Y'])
    X = np.asarray(d[['intercept', 'A', 'B', 'C', 'D']])
    

    If I want to get the same ridge regression results using sklearn and statsmodels, then I have to use different input values of alpha for each to get the same output of rigde regression coefficients as shown in the following code:

    # use sklearn Ridge
    alpha_sklearn = 1
    ridge = Ridge(alpha=alpha_sklearn, fit_intercept=True)
    ridge.fit(X=np.asarray(d[['A', 'B', 'C', 'D']]), y=y)
    print('output params from sklearn with alpha = 1: \n',ridge.intercept_, ridge.coef_)
    
    # use statsmodels OLS fit_regularized L1_wt=0
    # NOTE: we need to re-scale the alpha parameter used in sklearn to get samee results in statsmodels
    n_samples = X.shape[0]
    alpha_statsmodels = np.array([0, 1., 1., 1., 1.]) / n_samples  # scaling of alpha by n
    ols = sm.OLS(y, X).fit_regularized(L1_wt=0., alpha=alpha_statsmodels)
    print('output params from statsmodels with alpha = 1 / n_samples: \n',ols.params)
    

    This results in the following output of ridge regression coefficients from sklearn and statsmodels

    ridge params from sklearn intercept and coefs: 
     4.997208595888691 [-2.00968258  0.03363013 -0.02144874  1.02895154]
    ridge params from statsmodels with alpha=alpha/n: 
     [ 4.9972086  -2.00968258  0.03363013 -0.02144874  1.02895154]
    

    In other words, if I use an input value of alpha=1 with sklearn, then I need to use an input value of alpha=1/n_samples with statsmodels if I want to get the same results for ridge regression.

    Based on this behavior, it appears that the sklearn implementation of ridge regression is internally scaling the alpha parameter by n_samples. Therefore, I am thinking that if I am using your vif_ridge function with sklearn for my analysis, then the input values of pen_factors for vif_ridge should be as follows:

    pen_factors = alpha / n_samples

    where alpha is the input value that I use for the sklearn Ridge function, and n_samples is X.shape[0].

    Does that approach look correct to you?

    Best,

    Greg

  12. josef-pkt commented on May 22, 2025

    @josef-pkt
    MemberAuthor

    I found
    https://stats.stackexchange.com/questions/575752/number-of-samples-in-scikit-learn-cost-function-for-ridge-lasso-regression

    From this it looks like alpha in ridge is penalization for sum of squares (no division by n_samples) while Lasso has per observation penalization (total penalization is n_samples * alpha)

    The vif penalization assumes per observation penalty, so alpha / n_samples for Ridge and just alpha for Lasso or elastic net.
    (The vif function however only applies to L2 penalization)

    Based on this and your example, fit_regularized in statsmodels should correspond to elastic net in sklearn which also uses averaged least squares.

    So yes, pen_factors = alpha / n_samples looks correct to me for sklearn ridge regression.

  13. gjpelletier commented on May 22, 2025

    @gjpelletier

    I found https://stats.stackexchange.com/questions/575752/number-of-samples-in-scikit-learn-cost-function-for-ridge-lasso-regression

    From this it looks like alpha in ridge is penalization for sum of squares (no division by n_samples) while Lasso has per observation penalization (total penalization is n_samples * alpha)

    The vif penalization assumes per observation penalty, so alpha / n_samples for Ridge and just alpha for Lasso or elastic net. (The vif function however only applies to L2 penalization)

    Based on this and your example, fit_regularized in statsmodels should correspond to elastic net in sklearn which also uses averaged least squares.

    So yes, pen_factors = alpha / n_samples looks correct to me for sklearn ridge regression.

    Hi Josef,

    Thank you very much for your advice. This is very helpful, and I really appreciate it. I am very sorry that your main working computer has broken down. Wishing your computer a speedy recovery!

    Best,

    Greg

  14. added a commit that references this issue on Oct 28, 2026
    c396478
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions