我试图计算python中简单数据集中每列的方差膨胀因子(VIF):
a b c d
1 2 4 4
1 2 6 3
2 3 7 4
3 2 8 5
4 1 9 4
我已经使用usdm library中的vif函数在R中完成了此操作,该函数提供了以下结果:
a <- c(1, 1, 2, 3, 4)
b <- c(2, 2, 3, 2, 1)
c <- c(4, 6, 7, 8, 9)
d <- c(4, 3, 4, 5, 4)
df <- data.frame(a, b, c, d)
vif_df <- vif(df)
print(vif_df)
Variables VIF
a 22.95
b 3.00
c 12.95
d 3.00
然而,当我使用statsmodel vif function在python中执行相同操作时,我的结果是:
a = [1, 1, 2, 3, 4]
b = [2, 2, 3, 2, 1]
c = [4, 6, 7, 8, 9]
d = [4, 3, 4, 5, 4]
ck = np.column_stack([a, b, c, d])
vif = [variance_inflation_factor(ck, i) for i in range(ck.shape[1])]
print(vif)
Variables VIF
a 47.136986301369774
b 28.931506849315081
c 80.31506849315096
d 40.438356164383549
即使输入相同,结果也大不相同。一般来说,statsmodel VIF函数的结果似乎是错误的,但是我不确定这是因为我调用它的方式还是函数本身的问题。
我希望有人可以帮我弄清楚我是否错误地调用了statsmodel函数或解释了结果中的差异。如果它是函数的问题,那么python中是否有任何VIF替代品?
答案 0 :(得分:12)
我认为这是因为Python的OLS存在差异。在python方差膨胀系数计算中使用的OLS默认情况下不会添加截距。你肯定想在那里进行拦截。
您要做的是在矩阵中再添加一列,ck,填充一列以表示常量。这将是等式的截距项。完成此操作后,您的值应正确匹配。
编辑:用一些
替换零答案 1 :(得分:12)
正如其他人和Josef Perktold在this post中提到的那样,函数的作者variance_inflation_factor
期望解释变量矩阵中存在常量。在将值传递给函数之前,可以使用statsmodel中的add_constant
将所需的常量添加到数据框中。
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tools.tools import add_constant
df = pd.DataFrame(
{'a': [1, 1, 2, 3, 4],
'b': [2, 2, 3, 2, 1],
'c': [4, 6, 7, 8, 9],
'd': [4, 3, 4, 5, 4]}
)
X = add_constant(df)
>>> pd.Series([variance_inflation_factor(X.values, i)
for i in range(X.shape[1])],
index=X.columns)
const 136.875
a 22.950
b 3.000
c 12.950
d 3.000
dtype: float64
我相信您也可以使用assign
将常量添加到数据框的最右侧列:
X = df.assign(const=1)
>>> pd.Series([variance_inflation_factor(X.values, i)
for i in range(X.shape[1])],
index=X.columns)
a 22.950
b 3.000
c 12.950
d 3.000
const 136.875
dtype: float64
源代码本身相当简洁:
def variance_inflation_factor(exog, exog_idx):
"""
exog : ndarray, (nobs, k_vars)
design matrix with all explanatory variables, as for example used in
regression
exog_idx : int
index of the exogenous variable in the columns of exog
"""
k_vars = exog.shape[1]
x_i = exog[:, exog_idx]
mask = np.arange(k_vars) != exog_idx
x_noti = exog[:, mask]
r_squared_i = OLS(x_i, x_noti).fit().rsquared
vif = 1. / (1. - r_squared_i)
return vif
修改代码以将所有VIF作为一系列返回也很简单:
from statsmodels.regression.linear_model import OLS
from statsmodels.tools.tools import add_constant
def variance_inflation_factors(exog_df):
'''
Parameters
----------
exog_df : dataframe, (nobs, k_vars)
design matrix with all explanatory variables, as for example used in
regression.
Returns
-------
vif : Series
variance inflation factors
'''
exog_df = add_constant(exog_df)
vifs = pd.Series(
[1 / (1. - OLS(exog_df[col].values,
exog_df.loc[:, exog_df.columns != col].values).fit().rsquared)
for col in exog_df],
index=exog_df.columns,
name='VIF'
)
return vifs
>>> variance_inflation_factors(df)
const 136.875
a 22.950
b 3.000
c 12.950
Name: VIF, dtype: float64
答案 2 :(得分:5)
对于以后来此线程的人(例如我):
import numpy as np
import scipy as sp
a = [1, 1, 2, 3, 4]
b = [2, 2, 3, 2, 1]
c = [4, 6, 7, 8, 9]
d = [4, 3, 4, 5, 4]
ck = np.column_stack([a, b, c, d])
cc = sp.corrcoef(ck, rowvar=False)
VIF = np.linalg.inv(cc)
VIF.diagonal()
此代码给出
array([22.95, 3. , 12.95, 3. ])
[编辑]
为回应评论,我尝试了尽可能多地使用DataFrame
(颠倒矩阵需要使用numpy
)。
import pandas as pd
import numpy as np
a = [1, 1, 2, 3, 4]
b = [2, 2, 3, 2, 1]
c = [4, 6, 7, 8, 9]
d = [4, 3, 4, 5, 4]
df = pd.DataFrame({'a':a,'b':b,'c':c,'d':d})
df_cor = df.corr()
pd.DataFrame(np.linalg.inv(df.corr().values), index = df_cor.index, columns=df_cor.columns)
代码给出
a b c d
a 22.950000 6.453681 -16.301917 -6.453681
b 6.453681 3.000000 -4.080441 -2.000000
c -16.301917 -4.080441 12.950000 4.080441
d -6.453681 -2.000000 4.080441 3.000000
对角线元素给出VIF。
答案 3 :(得分:1)
波士顿数据的示例:
VIF 是通过辅助回归计算的,因此不依赖于实际拟合。
见下文:
from patsy import dmatrices
from statsmodels.stats.outliers_influence import variance_inflation_factor
import statsmodels.api as sm
# Break into left and right hand side; y and X
y, X = dmatrices(formula="medv ~ crim + zn + nox + ptratio + black + rm ", data=boston, return_type="dataframe")
# For each Xi, calculate VIF
vif = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
# Fit X to y
result = sm.OLS(y, X).fit()
答案 4 :(得分:1)
尽管已经很晚了,但是我正在对给出的答案进行一些修改。如果使用@ Chef1075解决方案,则在删除多重共线性之后要获得最佳设置,则将丢失相关的变量。我们只需要删除其中之一。为此,我使用@steve答案提供了以下解决方案:
import pandas as pd
from sklearn.linear_model import LinearRegression
def sklearn_vif(exogs, data):
'''
This function calculates variance inflation function in sklearn way.
It is a comparatively faster process.
'''
# initialize dictionaries
vif_dict, tolerance_dict = {}, {}
# form input data for each exogenous variable
for exog in exogs:
not_exog = [i for i in exogs if i != exog]
X, y = data[not_exog], data[exog]
# extract r-squared from the fit
r_squared = LinearRegression().fit(X, y).score(X, y)
# calculate VIF
vif = 1/(1 - r_squared)
vif_dict[exog] = vif
# calculate tolerance
tolerance = 1 - r_squared
tolerance_dict[exog] = tolerance
# return VIF DataFrame
df_vif = pd.DataFrame({'VIF': vif_dict, 'Tolerance': tolerance_dict})
return df_vif
df = pd.DataFrame(
{'a': [1, 1, 2, 3, 4,1],
'b': [2, 2, 3, 2, 1,3],
'c': [4, 6, 7, 8, 9,5],
'd': [4, 3, 4, 5, 4,6],
'e': [8,8,14,15,17,20]}
)
df_vif= sklearn_vif(exogs=df.columns, data=df).sort_values(by='VIF',ascending=False)
while (df_vif.VIF>5).any() ==True:
red_df_vif= df_vif.drop(df_vif.index[0])
df= df[red_df_vif.index]
df_vif=sklearn_vif(exogs=df.columns,data=df).sort_values(by='VIF',ascending=False)
print(df)
d c b
0 4 4 2
1 3 6 2
2 4 7 3
3 5 8 2
4 4 9 1
5 6 5 3
答案 5 :(得分:0)
如果您不想处理variance_inflation_factor
和add_constant
,而只想使用公式。请考虑以下功能。
import pandas as pd
import seaborn as sns
import numpy as np
import statsmodels.formula.api as smf
# define function
def get_vif(exogs, data):
'''Return VIF (variance inflation factor) DataFrame
Args:
exogs (list): list of exogenous/independent variables
data (DataFrame): the df storing all variables
Returns:
VIF and Tolerance DataFrame for each exogenous variable
Notes:
Assume we have a list of exogenous variable [X1, X2, X3, X4].
To calculate the VIF and Tolerance for each variable, we regress
each of them against other exogenous variables. For instance, the
regression model for X3 is defined as:
X3 ~ X1 + X2 + X4
And then we extract the R-squared from the model to calculate:
VIF = 1 / (1 - R-squared)
Tolerance = 1 - R-squared
The cutoff to detect multicollinearity:
VIF > 10 or Tolerance < 0.2
'''
# initialize arrays
vif_array = np.array([])
tolerance_array = np.array([])
# create formula for each exogenous variable
for exog in exogs:
not_exog = [i for i in exogs if i != exog]
formula = f"{exog} ~ {' + '.join(not_exog)}"
# extract r-squared from the fit
r_squared = smf.ols(formula, data=data).fit().rsquared
# calculate VIF
vif = 1/(1-r_squared)
vif_array = np.append(vif_array, vif).round(2)
# calculate tolerance
tolerance = 1-r_squared
tolerance_array = np.append(tolerance_array, tolerance)
# return VIF DataFrame
df_vif = pd.DataFrame({'VIF': vif_array, 'Tolerance': tolerance_array},
index=exogs)
return df_vif
[In]
df = sns.load_dataset('car_crashes')
exogs = ['alcohol', 'speeding', 'no_previous', 'not_distracted']
get_vif(exogs=exogs, data=df)
[Out]
VIF Tolerance
alcohol 3.44 0.291030
speeding 1.88 0.530690
no_previous 3.11 0.321132
not_distracted 2.67 0.374749
答案 6 :(得分:-1)
我根据在Stack和CrossValidated上看到的其他一些帖子编写了此函数。它会显示超出阈值的要素,并返回删除了要素的新数据框。
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tools.tools import add_constant
def calculate_vif_(df, thresh=5):
'''
Calculates VIF each feature in a pandas dataframe
A constant must be added to variance_inflation_factor or the results will be incorrect
:param X: the pandas dataframe
:param thresh: the max VIF value before the feature is removed from the dataframe
:return: dataframe with features removed
'''
const = add_constant(df)
cols = const.columns
variables = np.arange(const.shape[1])
vif_df = pd.Series([variance_inflation_factor(const.values, i)
for i in range(const.shape[1])],
index=const.columns).to_frame()
vif_df = vif_df.sort_values(by=0, ascending=False).rename(columns={0: 'VIF'})
vif_df = vif_df.drop('const')
vif_df = vif_df[vif_df['VIF'] > thresh]
print 'Features above VIF threshold:\n'
print vif_df[vif_df['VIF'] > thresh]
col_to_drop = list(vif_df.index)
for i in col_to_drop:
print 'Dropping: {}'.format(i)
df = df.drop(columns=i)
return df
答案 7 :(得分:-1)
此处使用dataframe python代码:
import numpy as np
import scipy as sp
a = [1, 1, 2, 3, 4]
b = [2, 2, 3, 2, 1]
c = [4, 6, 7, 8, 9]
d = [4, 3, 4, 5, 4]
import pandas as pd
data = pd.DataFrame()
data["a"] = a
data["b"] = b
data["c"] = c
data["d"] = d
cc = np.corrcoef(data, rowvar=False)
VIF = np.linalg.inv(cc)
VIF.diagonal()
array([22.95, 3. , 12.95, 3. ])