You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
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)
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.
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
@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.)
@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].
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.
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!
Activity
vincentarelbundock commentedon May 23, 2014
Copying your SO response here.
ENH: add vif_ridge closes statsmodels#1669
josef-pkt commentedon Nov 13, 2016
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.
ENH: add vif_ridge closes statsmodels#1669
ENH: add vif_ridge closes statsmodels#1669
ENH: add vif_ridge closes statsmodels#1669
ENH: add vif_ridge closes statsmodels#1669
gjpelletier commentedon May 21, 2025
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
josef-pkt commentedon May 21, 2025
@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, wherez = (x - mean(x))/ std(x)(Aside: Windows update broke my main working computer/notebook. I'm not able to check details right now.)
gjpelletier commentedon May 22, 2025
Hi Josef,
For example, if I use the following input data for X and y:
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:
This results in the following output of ridge regression coefficients from sklearn and statsmodels
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
josef-pkt commentedon May 22, 2025
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 observationpenalty, 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
averagedleast squares.So yes,
pen_factors = alpha / n_sampleslooks correct to me for sklearn ridge regression.gjpelletier commentedon May 22, 2025
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
ENH: add vif_ridge closes statsmodels#1669