Python中的一维马氏距离 [英] One dimensional Mahalanobis Distance in Python
问题描述
我一直在尝试验证我的代码以计算用 Python 编写的马哈拉诺比斯距离(并仔细检查以比较OpenCV中的结果) )
我的数据点均为1维(5行x 1列)。
I've been trying to validate my code to calculate Mahalanobis distance written in Python (and double check to compare the result in OpenCV) My data points are of 1 dimension each (5 rows x 1 column).
在 OpenCV(C ++)中,我成功地计算了数据点的维度时的马氏距离。
In OpenCV (C++), I was successful in calculating the Mahalanobis distance when the dimension of a data point was with above dimensions.
下面的代码在矩阵尺寸为5行x 1列的情况下计算马氏距离时未成功。 但是当矩阵中的列数大于1时有效:
The following code was unsuccessful in calculating Mahalanobis distance when dimension of the matrix was 5 rows x 1 column. But it works when the number of columns in the matrix are more than 1:
import numpy;
import scipy.spatial.distance;
s = numpy.array([[20],[123],[113],[103],[123]]);
covar = numpy.cov(s, rowvar=0);
invcovar = numpy.linalg.inv(covar)
print scipy.spatial.distance.mahalanobis(s[0],s[1],invcovar);
我收到以下错误:
Traceback (most recent call last):
File "/home/abc/Desktop/Return.py", line 6, in <module>
invcovar = numpy.linalg.inv(covar)
File "/usr/lib/python2.6/dist-packages/numpy/linalg/linalg.py", line 355, in inv
return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
IndexError: tuple index out of range
推荐答案
一维马氏距离真的很容易手动计算:
One-dimensional Mahalanobis distance is really easy to calculate manually:
import numpy as np
s = np.array([[20], [123], [113], [103], [123]])
std = s.std()
print np.abs(s[0] - s[1]) / std
(将公式简化为一维情况)。
(reducing the formula to the one-dimensional case).
但是 scipy.spatial.distance
的问题是出于某些原因 np。给定一组1d变量时,cov
返回标量,即零维数组。您要传递2d数组:
But the problem with scipy.spatial.distance
is that for some reason np.cov
returns a scalar, i.e. a zero-dimensional array, when given a set of 1d variables. You want to pass in a 2d array:
>>> covar = np.cov(s, rowvar=0)
>>> covar.shape
()
>>> invcovar = np.linalg.inv(covar.reshape((1,1)))
>>> invcovar.shape
(1, 1)
>>> mahalanobis(s[0], s[1], invcovar)
2.3674720531046645
这篇关于Python中的一维马氏距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!