K均值聚类matlab

%%%%%%% 对给定的二维点集,利用Kmeans方法进行聚类

clc, clear all, close all

%% 1.数据导入
%%%构造一组数据,其分类数目从直观上比较明显
mu1 = [1 1];
Sigma1 = [0.5 0; 0 0.5];
mu2 = [3 3];
Sigma2 = [0.2 0; 0 0.2];
% rng(1); %%% 加了rng(1),使得每次运行程序时,种子固定,产生的随机数是一样的,绘出的图形是一样的
X = [mvnrnd(mu1,Sigma1,1000);mvnrnd(mu2,Sigma2,1000)]; %%%%%产生高斯分布数据。X是一个2000*2的矩阵,表示2000个二维点
%%%绘图示意
plot(X(:,1),X(:,2),'ko')
title('Scatter Plot')
xlim([min(X(😃) max(X(😃)]) % Make axes have the same scale
ylim([min(X(😃) max(X(😃)])

%% 2.聚类

e=0.01; %%%若聚类中心在迭代前后变化小于e,则跳出循环
iter = 1000; %%%最大迭代次数

[n,~]=size(X);%%%得到x的行数,即样本或向量的个数n
idx = zeros(n,1); %%%Idx(i)表示第i个点的类别,值为1或者2
temp=randperm(n,2);%%%产生2个n以内的随机整数
clusters=[X(temp(1)😅;X(temp(2)😅] %%%在样本中随机取两点作为初始的两个聚类中心
new_clusters=zeros(2,2); %%%%迭代中的聚类中心,先设为0矩阵

%% 请在下述两行注释之间填写代码,针对给出的平面点集,把它们分为两类
m=2;
s=1;
D = zeros(2,n);
v1=clusters(1,:);
v2=clusters(2,:);
V1 = zeros(2,1000);
V2 = zeros(2,1000);
V1(:,2) = v1;
V2(:,2) = v2;
while(abs(V1(1,s) - V1(1,s+1)) > e || abs(V1(2,s) - V1(2,s+1) > e || abs(V2(1,s) - V2(1,s+1)) > e || abs(V2(2,s) - V2(2,s+1)) > e)||s<iter)
s = s +1;
for i = 1 : n
D(1,i) = sqrt((X(i,1) - V1(1,s))^2 + (X(i,2) - V1(2,s))^2);
end
for i = 1 : n
D(2,i) = sqrt((X(i,1) - V2(1,s))^2 + (X(i,2) - V2(2,s))^2);
end
A = zeros(2,n); % A用于存放第一类的数据点
B = zeros(2,n); % B用于存放第二类的数据点
for i = 1: n
[min_distance,index] = min(D(:,i));
if index == 1 % 点属于第一个聚类中心
idx(i)=1;
A(1,i) = X(i,1);
A(2,i) = X(i,2);
else % 点属于第二个聚类中心
idx(i)=2;
B(1,i) = X(i,1);
B(2,i) = X(i,2);
end
end
indexA = find(A(1,:) ~= 0); % 找出第一类中的点
indexB = find(B(1,:) ~= 0); % 找出第二类中的点
V1(1,s+1) = mean(A(1,indexA));
V1(2,s+1) = mean(A(2,indexA));
V2(1,s+1) = mean(B(1,indexB));
V2(2,s+1) = mean(B(2,indexB)); % 更新两个聚类中心
clusters(:,1) = [V1(1,s) V2(1,s)];
clusters(:,2) = [V1(2,s) V2(2,s)];
end

%% 3.绘图。
figure;
plot(X(idx1,1),X(idx1,2),'r.','MarkerSize',12)%%%%%%% X(idx1,1)是这样解读的:括号中idx=1表示“属于第1类为镇”的点,后一个1表示第一个分量
hold on
plot(X(idx
2,1),X(idx==2,2),'b.','MarkerSize',12)%%%%%%% 画第2类点

plot(clusters(:,1),clusters(:,2),'ko',...
'LineWidth',2,...
'MarkerSize',10,...
'MarkerEdgeColor','k',...
'MarkerFaceColor',[0.5,0.5,0.5])%%%%画聚类中心
xlim([min(X(😃) max(X(😃)]) % Make axes have the same scale
ylim([min(X(😃) max(X(😃)])
legend('Cluster 1','Cluster 2')
title 'Cluster'
hold off

posted @ 2021-09-12 21:17  藤井栀  阅读(200)  评论(0)    收藏  举报