距离是不相似性的一种度量。要把一个量称为距离应满足三条性质:
- ,若,则 反身性
- 对称性
- 三角不等式
一、pdist
D = pdist(X,distance)
- 欧几里德距离 Euclidean distance('euclidean')
欧氏距离虽然很有用,但也有明显的缺点。
一:它将样品的不同属性(即各指标或各变量)之间的差别等同看待,这一点有时不能满足实际要求。
二:它没有考虑各变量的数量级(量纲),容易犯大数吃小数的毛病。所以,可以先对原始数据进行规范化处理再进行距离计算。
- 标准欧几里德距离 Standardized Euclidean distance('seuclidean')
where is the diagonal matrix whose jth diagonal element is , where is the vector of standard deviations.
相比单纯的欧氏距离,标准欧氏距离能够有效的解决上述缺点。注意,这里的在许多Matlab函数中是可以自己设定的,不一定非得取标准差,可以依据各变量的重要程度设置不同的值,如knnsearch函数中的Scale属性。
- 马哈拉诺比斯距离 Mahalanobis distance('mahalanobis')
马氏距离是由P. C. Mahalanobis提出的,表示数据的协方差距离。它是一种有效的计算两个未知样本集的相似度的方法。与欧式距离不同的是它考虑到各种特性之间的联系(例如:一条关于身高的信息会带来一条关于体重的信息,因为两者是有关联的)并且是尺度无关的(scale-invariant),即独立于测量尺度。
如果协方差矩阵为单位矩阵,那么马氏距离就简化为欧式距离,如果协方差矩阵为对角阵,则其也可称为正规化的欧氏距离.
马氏优缺点:
- 曼哈顿距离(城市区块距离) City block metric('cityblock')
- 切比雪夫距离 Chebychev distance('chebychev')
- 闵可夫斯基距离 Minkowski metric('minkowski')
Notice that for the special case of p = 1, the Minkowski metric gives the city block metric, for the special case of p = 2, the Minkowski metric gives the Euclidean distance, and for the special case of p = ∞, the Minkowski metric gives the Chebychev distance.
闵可夫斯基距离由于是欧氏距离的推广,所以其缺点与欧氏距离大致相同。
- 夹角余弦距离 Cosine distance('cosine')
与Jaccard距离相比,Cosine距离不仅忽略0-0匹配,而且能够处理非二元向量,即考虑到变量值的大小
- 相关距离 Correlation distance('correlation') 特别有用
Correlation距离主要用来度量两个向量的线性相关程度。
- 汉明距离 Hamming distance('hamming')
两个向量之间的汉明距离的定义为两个向量不同的变量个数所占变量总数的百分比。
- 杰卡德距离 Jaccard distance('jaccard')
Jaccard距离常用来处理仅包含非对称的二元(0-1)属性的对象。很显然,Jaccard距离不关心0-0匹配,而Hamming距离关心0-0匹配。
- Spearman distance ('spearman')
-
where
-
rsj is the rank of xsj taken over x1j, x2j, ...xmj, as computed by tiedrank
-
rs and rt are the coordinate-wise rank vectors of xs and xt, i.e., rs = (rs1, rs2, ... rsn)
-
二、pdist2
D = pdist2(X,Y,distance)
D = pdist2(X,Y,'minkowski',P)
D = pdist2(X,Y,'mahalanobis',C)
D = pdist2(X,Y,distance,'Smallest',K)
D = pdist2(X,Y,distance,'Largest',K)
[D,I] = pdist2(X,Y,distance,'Smallest',K)
[D,I] = pdist2(X,Y,distance,'Largest',K)