1.Matlab中相关函数介绍
1.1
pdist函数
metric’取值如下:
‘euclidean’:欧氏距离(默认);‘seuclidean’:标准化欧氏距离;
‘mahalanobis’:马氏距离;‘cityblock’:布洛克距离;
‘minkowski’:明可夫斯基距离;‘cosine’:
‘correlation’:
‘jaccard’: ‘chebychev’:Chebychev距离。
1.2 squareform 函数
对于M个点的数据集X,pdist之后的Y将是具有M*(M-1)/2个元素的行向量。
Y这样的显示虽然节省了内存空间,但对用户来说不是很易懂,如果需要对这些距离进行特定操作的话,也不太好索引。MATLAB中可以用 squareform把Y转换成方阵形式,方阵中<i,j>位置的数值就是X中第i和第j点之间的距离,显然这个方阵应该是个对角元素为0的对称阵。
1.3 linkage函数
method:可取值如下:
‘single’:最短距离法(默认);
‘complete’:最长距离法;
‘average’:未加权平均距离法;
‘weighted’: 加权平均法;
‘centroid’:质心距离法;
‘median’:加权质心距离法;
‘ward’:内平方距离法(最小方差算法)
1.4 dendrogram函数
1.5
cophenet函数
cophene检验一定算法下产生的二叉聚类树和实际情况的相符程度,就是检测二叉聚类树中各元素间的距离和pdist计算产生的实际的距离之间有多大的相关性,另外也可以用inconsistent表示量化某个层次的聚类上的节点间的差异性。
1.6 cluster 函数
1.7
clusterdata 函数
1.8 Inconsistent
S_i是除了叶节点外,所有深度低于(M+i)不超过DEPTH的节点(包括M+i节点自身)
而Inconsistent计算的是S_i的距离的平均值。
计算深度会影响不一致系数的计算结果,计算深度比较大时,不一致系数的增量能反映出当前步引入的新样品与该类中心(涉及该类中所有样品)的距离远近,计算深度比较小时,不一致系数的增量仅能反映出当前步引入的新样品与上几步聚类中涉及的样品的中心的距离远近。
2.Matlab聚类程序的设计
2.1方法一:一次聚类法(直接使用clusterdata函数)
X=[11978 12.5 93.5 31908;…;57500 67.6 238.0 15900];
T=clusterdata(X,0.9)
结果:
结果:
ans =
1
1
表明两个观测属于同一类。
再如下面的例子:
x1=randn(10,1);
x2=randn(10,1)+10;
x3=randn(10,1)+20;
x=[x1;x2;x3];
y=randn(30,1);
T=clusterdata([x,y],3)
temp1=find(T==1)
plot(x(temp1),y(temp1),'rd','markersize',10,'markerfacecolor','r')
hold on
temp1=find(T==2)
plot(x(temp1),y(temp1),'yd','markersize',10,'markerfacecolor','y')
temp1=find(T==3)
plot(x(temp1),y(temp1),'kd','markersize',10,'markerfacecolor','k')
legend('cluster 1','cluster 2','cluster 3')
结果如下图:
表明两个观测属于同一类。
再如下面的例子:
x1=randn(10,1);
x2=randn(10,1)+10;
x3=randn(10,1)+20;
x=[x1;x2;x3];
y=randn(30,1);
T=clusterdata([x,y],3)
temp1=find(T==1)
plot(x(temp1),y(temp1),'rd','markersize',10,'markerfacecolor','r')
hold on
temp1=find(T==2)
plot(x(temp1),y(temp1),'yd','markersize',10,'markerfacecolor','y')
temp1=find(T==3)
plot(x(temp1),y(temp1),'kd','markersize',10,'markerfacecolor','k')
legend('cluster 1','cluster 2','cluster 3')
结果如下图:
2.2 方法二和方法三设计流程:分步聚类
Step1
用pdist函数计算相似矩阵,有多种方法可以计算距离,
进行计算之前有时会先将数据用zscore函数进行标准化。
---------------------------------------------------------------------
ZSCOREStandardized z score.
Z =ZSCORE(X) returns a centered, scaled version of X, the same size asX.
For vectorinput X, Z is the vector of z-scores (X-MEAN(X)) ./ STD(X).For
matrix X,z-scores are computed using the mean and standard deviation
along eachcolumn of X.
For higher-dimensional arrays,z-scores are
computedusing the mean and standard deviation along the first
non-singleton dimension.
The columnsof Z have sample mean zero and sample standard deviation one
(unless acolumn of X is constant, in which case that column of Z is
constant at0).
---------------------------------------------------------------------
X2=zscore(X);
---------------------------------------------------------------------
X2=zscore(X);
Y2=pdist(X2); %计算距离
Step2
Z2=linkage(Y2);
Step3
C2=cophenet(Z2,Y2); //0.94698
Step4 创建聚类,并作出谱系图
T=cluster(Z2,6);