您可以通过检查相关矩阵的特征值来检测高度多重共线性。极低的特征值表明数据是共线的,对应的特征向量显示哪些变量是共线的。
如果数据中不存在共线性,您会认为没有一个特征值接近于零:
>>> xs = np.random.randn(100, 5) # independent variables
>>> corr = np.corrcoef(xs, rowvar=0) # correlation matrix
>>> w, v = np.linalg.eig(corr) # eigen values & eigen vectors
>>> w
array([ 1.256 , 1.1937, 0.7273, 0.9516, 0.8714])
但是,如果说x[4] - 2 * x[0] - 3 * x[2] = 0,那么
>>> noise = np.random.randn(100) # white noise
>>> xs[:,4] = 2 * xs[:,0] + 3 * xs[:,2] + .5 * noise # collinearity
>>> corr = np.corrcoef(xs, rowvar=0)
>>> w, v = np.linalg.eig(corr)
>>> w
array([ 0.0083, 1.9569, 1.1687, 0.8681, 0.9981])
其中一个特征值(这里是第一个)接近于零。对应的特征向量为:
>>> v[:,0]
array([-0.4077, 0.0059, -0.5886, 0.0018, 0.6981])
忽略几乎为零的系数,上面基本上说x[0]、x[2] 和x[4] 是共线的(如预期的那样)。如果标准化xs 值并乘以该特征向量,结果将徘徊在零附近,方差很小:
>>> std_xs = (xs - xs.mean(axis=0)) / xs.std(axis=0) # standardized values
>>> ys = std_xs.dot(v[:,0])
>>> ys.mean(), ys.var()
(0, 0.0083)
请注意,ys.var() 基本上是接近于零的特征值。
因此,为了捕获高多重线性,请查看相关矩阵的特征值。