您的观测值少于特征,因此V
scipy 代码计算的协方差矩阵是奇异的。代码不检查这一点,并盲目地计算协方差矩阵的“逆”。因为这个数值计算的逆基本上是垃圾,所以乘积(x-y)*inv(V)*(x-y)
(其中x
和y
是观察值)可能会变成负数。然后该值的平方根导致nan
。
例如,这个数组也会产生一个nan
:
In [265]: x
Out[265]:
array([[-1. , 0.5, 1. , 2. , 2. ],
[ 2. , 1. , 2.5, -1.5, 1. ],
[ 1.5, -0.5, 1. , 2. , 2.5]])
In [266]: squareform(pdist(x, 'mahalanobis'))
Out[266]:
array([[ 0. , nan, 1.90394328],
[ nan, 0. , nan],
[ 1.90394328, nan, 0. ]])
这是“手动”完成的马氏计算:
In [279]: V = np.cov(x.T)
理论上V
是单数;以下值实际上为 0:
In [280]: np.linalg.det(V)
Out[280]: -2.968550671342364e-47
但inv
没有看到问题,并返回一个逆:
In [281]: VI = np.linalg.inv(V)
让我们计算 和 之间的距离x[0]
,并验证当我们使用 时x[2]
我们得到了相同的非 nan 值(1.9039):pdist
VI
In [295]: delta = x[0] - x[2]
In [296]: np.dot(np.dot(delta, VI), delta)
Out[296]: 3.625
In [297]: np.sqrt(np.dot(np.dot(delta, VI), delta))
Out[297]: 1.9039432764659772
当我们尝试计算 和 之间的距离时,会发生以下x[0]
情况x[1]
:
In [300]: delta = x[0] - x[1]
In [301]: np.dot(np.dot(delta, VI), delta)
Out[301]: -1.75
然后该值的平方根给出nan
。
在 scipy 0.16(将于 2015 年 6 月发布)中,您将收到错误而不是 nan 或垃圾。错误消息描述了问题:
In [4]: x = array([[-1. , 0.5, 1. , 2. , 2. ],
...: [ 2. , 1. , 2.5, -1.5, 1. ],
...: [ 1.5, -0.5, 1. , 2. , 2.5]])
In [5]: pdist(x, 'mahalanobis')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-a3453ff6fe48> in <module>()
----> 1 pdist(x, 'mahalanobis')
/Users/warren/local_scipy/lib/python2.7/site-packages/scipy/spatial/distance.pyc in pdist(X, metric, p, w, V, VI)
1298 "singular. For observations with %d "
1299 "dimensions, at least %d observations "
-> 1300 "are required." % (m, n, n + 1))
1301 V = np.atleast_2d(np.cov(X.T))
1302 VI = _convert_to_double(np.linalg.inv(V).T.copy())
ValueError: The number of observations (3) is too small; the covariance matrix is singular. For observations with 5 dimensions, at least 6 observations are required.