clc
clear
close all
P=[0 1;2.5 7;2 2;5 9;6 2; 3 7;1 9;1 3;7 1;8 4;6.5,3.5];%生成0-10之间二维11个点
k=3;%分三类
max_g=1000;%最大迭代次数
min_x=0;max_x=10;min_y=0;max_y=10;
ch=randperm(size(P,1));
ch=ch(1:k);
temp1a=P(ch,:);
for i=1:max_g
sprintf('迭代次数%d',i)
%分类
L1=zeros(1,size(P,1));
for j=1:size(P,1)
d=zeros(1,k);
for m=1:k
d(m)=norm([P(j,:)-temp1a(m,:)]);
end
[~,index]=min(d);
L1(j)=index;
end
LL1(i,:)=L1;
temp2a=temp1a;
for j=1:k
T=find(L1==j);%j=3
if size(T,2)~=0
temp2a(j,:)=sum(P(T,:))/size(T,2);
else
temp2a(j,:)=[min_x+(max_x-min_x)*rand,min_y+(max_y-min_y)*rand];
end
end
if i==1
temp1a=temp2a;
else
if sum(sum(temp2a-temp1a))==0
break
else
temp1a=temp2a;
end
end
end
Pa1=i;
%%
temp1b=P(ch,:);
for i=1:max_g
sprintf('迭代次数%d',i)
%分类
L2=zeros(1,size(P,1));
for j=1:size(P,1)
d=zeros(1,k);
for m=1:k
d(m)=norm([P(j,:)-temp1b(m,:)]);
end
[~,index]=min(d);
L2(j)=index;
end
LL2(i,:)=L2;
temp2b=temp1b;
for j=1:k
T=find(L2==j);%j=3
D=zeros(size(T,2),size(T,2));
for m=1:size(T,2)
for n=1:size(T,2)
D(m,n)=norm(P(T(m),:)-P(T(n),:));
end
end
DD=sum(D);
[~,index]=min(DD);
temp2b(j,:)=P(T(index),:);
end
if i==1
temp1b=temp2b;
else
if sum(sum(temp2b-temp1b))==0
break
else
temp1b=temp2b;
end
end
end
Pa2=i;
%%
figure(1)
we1=['.r','.g','.b','.k','.m','.y'];
we2=['xr','xg','xb','xk','xm','xy'];
for i=1:size(temp2a,1)
plot(temp2a(i,1),temp2a(i,2),we2(2*i-1:2*i),'MarkerSize',12)
hold on
end
for i=1:k
T=find(L1==i);
for j=1:size(T,2)
plot(P(T(j),1),P(T(j),2),we1(2*i-1:2*i),'MarkerSize',12)
hold on
end
end
disp(['K-means算法结果',num2str(L1)])
disp('K-means算法聚类中心')
temp2a
title('K-means算法结果')
axis([min_x max_x min_y max_y])
figure(2)
we1=['.r','.g','.b','.k','.m','.y'];
we2=['xr','xg','xb','xk','xm','xy'];
for i=1:size(temp2b,1)
plot(temp2b(i,1),temp2b(i,2),we2(2*i-1:2*i),'MarkerSize',12)
hold on
end
for i=1:k
T=find(L2==i);
for j=1:size(T,2)
plot(P(T(j),1),P(T(j),2),we1(2*i-1:2*i),'MarkerSize',12)
hold on
end
end
disp(['K-medoids算法结果',num2str(L2)])
disp('K-medoids算法聚类中心')
temp2b
title('K-medoids算法结果')
axis([min_x max_x min_y max_y])
- 1
- 2
- 3
- 4
- 5
- 6
前往页