clear;clc;
data=[0 1 0 1 2 1 2 3 6 7 8 6 7 8 9 7 8 9 8 9;0 0 1 1 1 2 2 2 6 6 6 7 7 7 7 8 8 8 9 9];
figure(1)
plot(data(1,:),data(2,:),'r*')
zeros(1,length(data));
K=3;
Y=Kmeans(data,K) ; %%数据分类的结果
function Y = Kmeans(data,K)
c = K;
% load('DataTwo_163507080.mat');
D = [data',zeros(length(data),1)];
%InitClaasify 初始化所属类别
D1 = D;
D1(:,1)=(D(:,1)-min(D(:,1)))/(max(D(:,1))-min(D(:,1)));
D1(:,2)=(D(:,2)-min(D(:,2)))/(max(D(:,2))-min(D(:,2)));
SUM = D1(:,1)+D1(:,2);
CLA = (c-1)*[SUM-min(SUM)]/(max(SUM)-min(SUM))+1; % CLA所属类
D(:,3)= round(CLA(:)); %%%(x,y,CLA所属类)
G=zeros(c,3);
for i = 1 : c
GI = D(D(:,3)==i,1:2);
G(i,1:2)=mean(GI); %%%对不同类内的x,y求均值,即聚类中心
G(i,3)=length(GI); %%% G的第三列:不同类的个数
end
Je = 0;
for i = 1:length(D)
ca = D(i,3); % ca:初始的所属类别 %%%Je 所有类内距离之和
Je = Je+norm(D(i,1:2)-G(ca,1:2))^2; %norm(A),A 为矩阵,即求2范数
end
N = 200;
while( N > 0)
% N = 0;
%%%%%%计算每个数据点对数据中心的改变%%%%%%
for r = 1:length(D) %%%D的长度
i = D(r,3); %%% i表示元素的类别
for j = 1:c
if( i == j)
% ro(i)=G(i,3)*norm(D(r,1:2)-G(i,1:2))^2/(G(i,3)-1);
% else
% ro(j)=G(j,3)*norm(D(r,1:2)-G(j,1:2))^2/(G(j,3)+1);
ro(i)=norm(D(r,1:2)-G(i,1:2))^2;
else
ro(j)=norm(D(r,1:2)-G(j,1:2))^2;
end
end
%%%%%% ro:当前数据点与不同的聚类中心之间的距离,维数 center_n*1 %%%%%%
[MIN, k] = min(ro); % r = 1:length(D) %%%D的长度
if( ro(i)> ro(k))
D(r,3) = k; %%%更新所在聚类
G(k,1:2) = (G(k,1:2)*G(k,3)+D(r,1:2))/(G(k,3)+1);
G(i,1:2) = (G(i,1:2)*G(i,3)-D(r,1:2))/(G(i,3)-1);
G(k,3) = G(k,3)+1;
G(i,3) = G(i,3)-1;
Je = Je - ro(i) + ro(k);
end
end
N = N-1;
end
G; %%%最终的聚类中心
Je;
figure(2);
title('分类结果图:');xlabel('x1');ylabel('x2');
hold all;
xlabel('x');ylabel('y');
for s=1:c
if s==1
scatter(G(s,1),G(s,2),'r*');text(G(s,1)+0.1,G(s,2)+0.1,'1');
elseif s==2
scatter(G(s,1),G(s,2),'ro');text(G(s,1)+0.1,G(s,2)+0.1,'2');
% ,legend('ro')
elseif s==3
scatter(G(s,1),G(s,2),'rx'); text(G(s,1)+0.1,G(s,2)+0.1,'3');
else plot(G(s,1),G(s,2),'m.');
end
end
hold all;
for i = 1:length(D)
if(D(i,3) == 1)
plot(D(i,1),D(i,2),'b*');
elseif(D(i,3) == 2)
plot(D(i,1),D(i,2),'bo');
elseif(D(i,3) == 3)
plot(D(i,1),D(i,2),'bx');
elseif(D(i,3) == 4)
plot(D(i,1),D(i,2),'g+');
else
plot(D(i,1),D(i,2),'m.');
end
end
hold on;
% Y = D(:,3);
Y=D;
end