资源简介
k-means自适应聚类算法的matlab程序,根据文献中描述的算法编的,欢迎高手指教
代码片段和文件信息
% ---------------------first step---------------------
% --initialize 找到距离最大的两个样本x1x2作为初始中心
%function K_means(example centerNum)
clear
clc
example = [0 0 1;
0 1 2;
9 10 8;
10 9 11;
10 10 10;
20 20 19;
19 17 18;
20 18 19;
40 41 40;
39 40 38];
centerNum = 2;
[exampleNum exampleDimension] = size(example);
centerNumMax =exampleNum*(exampleNum-1)/2;
distance=zeros(1centerNumMax);
maxdice=0;
x1=0;
x2=0;
m=0;
for i=1:exampleNum
for j=i+1:exampleNum
m=m+1;
distance(m) = sqrt(sum((example(i :)-example(j :)).^2));
if distance(m)>maxdice;
maxdice=distance(m);
x1=i;
x2=j;
end
end
end
% -------------------second step-----------------------
% --assign by the Euclidean distance
%将数据集剩下的数据对象分别计算到xl,x2 的距离,将其划分
%到距离小的那个中心的类中,标记,同时记下最小的距离。
center = [];
center = [center;example(x1:);example(x2:)];
elementNum = zeros(1 centerNum);% --record the number of elements in each cluster
clusterElement = [];
distance = zeros(exampleNum centerNum);
for i = 1:(exampleNum)
for j = 1:centerNum
%%% --distance is a matrix that indicate the Euclidean distance between the example i and the center j
distance(i j) = sqrt(sum((example(i :)-center(j :)).^2));
end
end
for i = 1:exampleNum
[value posi] = min(distance(i :));
% --record the elements of each clusterElement
elementNum(posi) = elementNum(posi) + 1;
clusterElement(elementNum(posi):posi) = example(i :);
end
% ---------------------third step------------------------
% --calculate the new center of each cluster/平均值法求新的聚类中心
newcenter = zeros(centerNum exampleDimension);
for i = 1:centerNum
for j = 1:elementNum(i)
newcenter(i :) = newcenter(i :) + clusterElement( j :i);
end
newcenter(i :) = newcenter(i :)./elementNum(i);
end
center=newcenter;
%------------------------计算DB-------------------------------
S=zeros(1centerNum);
M=[];
R=[];
for i =1:centerNum
s=0;
for j =1:elementNum(i)
s=s+sum((clusterElement(j:i)-center(i:)).^2);
end
S(i)=sqrt(s/elementNum(i));
end
D=zeros(1centerNum);
for i =1:centerNum
for j=i+1:centerNum
M(ij)=sqrt(sum((center(i :)-center(j :)).^2));
R(ij)=(S(i)+S(j))/M(ij);
if (D(i) D(i)=R(ij);
end
end
end
DB=(sum(D))/centerNum;
%newCenter = [newCenter;example(x1:);example(x2:)];
%------------------forth step-------------------------------
%-------借鉴最大、最小距离max{min(d(c1,j),d(c2,j))},查找到的xj-----------
while 1
distance = zeros(exampleNum centerNum);
for i = 1:(exampleNum)
for j = 1:centerNum
%%%
评论
共有 条评论