多重共线性检验之⽅差膨胀因⼦VIF
过程
1、构造每⼀个⾃变量与其余⾃变量的线性回归模型,例如,数 据集中含有p个⾃变量,则第⼀个⾃变量与其余⾃变量的线性组合可以 表⽰为
R2
,进⽽计算第 ⼀个⾃变量的⽅差膨胀因⼦VIF:
2、根据如上线性回归模型得到相应的判决系数
import pandas as pd
import numpy as np
from sklearn import model_lection
import statsmodels.api as sn
from statsmodels.stats.outliers_influence import variance_inflation_factor
sdata = pd.read_csv("../input/traindatas/char7/Predict to Profit.csv")
lumns)
X = sn.add_constant(sdata.loc[:,['RD_Spend', 'Marketing_Spend']])
vif = pd.DataFrame()
vif["Ficture"]= X.columns
vif["Fctor"]=[variance_inflation_factor(X.values,i)for i in range(X.shape[1])]
print(vif)
执⾏结果如下,如上结果所⽰,两个⾃变量对应的⽅差膨胀因⼦均低于10,说明构 建模型的数据并不存在多重共线性。如果发现变量之间存在多重共线性 的话,可以考虑删除变量或者重新选择模型
Index(['RD_Spend', 'Administration', 'Marketing_Spend', 'State', 'Profit'], dtype='object')
Ficture Fctor
0 const 4.540984
1 RD_Spend 2.026141
2 Marketing_Spend 2.026141
过程计算
import pandas as pd
import numpy as np
from sklearn import model_lection
import statsmodels.api as sn
from statsmodels.stats.outliers_influence import variance_inflation_factor
sdata = pd.read_csv("../input/traindatas/char7/Predict to Profit.csv")
model = sn.formula.ols("RD_Spend~Marketing_Spend",data=sdata).fit()
print(1/(1-model.rsquared))
执⾏结果
2.026140603233619
上⾯我仅仅计算了以RD_Spend为因变量计算的VIF值,和上⾯的⼀样,为2.026140603233619