K均值算法matlab代码实现
生活随笔
收集整理的這篇文章主要介紹了
K均值算法matlab代码实现
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
%%%K-meansclear all
clc%% 構(gòu)造隨機(jī)數(shù)據(jù)
mu1=[0 0 0];
S1=[0.23 0 0;0 0.87 0;0 0 0.56];
data1=mvnrnd(mu1,S1,100); %產(chǎn)生高斯分布數(shù)據(jù)%%第二類數(shù)據(jù)
mu2=[1.25 1.25 1.25];
S2=[0.23 0 0;0 0.87 0;0 0 0.56];
data2=mvnrnd(mu2,S2,100);%第三個(gè)類數(shù)據(jù)
mu3=[-1.25 1.25 -1.25];
S3=[0.23 0 0;0 0.87 0;0 0 0.56];
data3=mvnrnd(mu3,S3,100);mu4=[1.5 1.5 1.5];
S4=[0.23 0 0;0 0.87 0;0 0 0.56];
data4 =mvnrnd(mu4,S4,100);%顯示數(shù)據(jù)
figure;
plot3(data1(:,1),data1(:,2),data1(:,3),'+');
title('原始數(shù)據(jù)');
hold on
plot3(data2(:,1),data2(:,2),data2(:,3),'r+');
plot3(data3(:,1),data3(:,2),data3(:,3),'g+');
plot3(data4(:,1),data4(:,2),data3(:,3),'y+');
grid on;data=[data1;data2;data3;data4];
[row,col] = size(data);
K = 4;
max_iter = 300;%%迭代次數(shù)
min_impro = 0.1;%%%%最小步長(zhǎng)
display = 1;%%%判定條件
center = zeros(K,col);
U = zeros(K,col);
%% 初始化聚類中心
mi = zeros(col,1);
ma = zeros(col,1);
for i = 1:colmi(i,1) = min(data(:,i));ma(i,1) = max(data(:,i));center(:,i) = ma(i,1) - (ma(i,1) - mi(i,1)) * rand(K,1);
end%% 開(kāi)始迭代
for o = 1:max_iter%% 計(jì)算歐氏距離,用norm函數(shù)for i = 1:Kdist{i} = [];for j = 1:rowdist{i} = [dist{i};data(j,:) - center(i,:)];endendminDis = zeros(row,K);for i = 1:rowtem = [];for j = 1:Ktem = [tem norm(dist{j}(i,:))];end[nmin,index] = min(tem);minDis(i,index) = norm(dist{index}(i,:));end%% 更新聚類中心for i = 1:Kfor j = 1:colU(i,j) = sum(minDis(:,i).*data(:,j)) / sum(minDis(:,i));endend%% 判定if displayendif o >1,if max(abs(U - center)) < min_impro;break;elsecenter = U;endend
end%% 返回所屬的類別class = [];for i = 1:rowdist = [];for j = 1:Kdist = [dist norm(data(i,:) - U(j,:))];end[nmin,index] = min(dist);class = [class;data(i,:) index];end%% 顯示最后結(jié)果
[m,n] = size(class);
figure;
title('聚類結(jié)果');
hold on;
for i=1:row if class(i,4)==1 plot3(class(i,1),class(i,2),class(i,3),'ro'); elseif class(i,4)==2plot3(class(i,1),class(i,2),class(i,3),'go'); elseif class(i,4) == 3plot3(class(i,1),class(i,2),class(i,3),'bo'); elseplot3(class(i,1),class(i,2),class(i,3),'yo'); end
end
grid on;
?
總結(jié)
以上是生活随笔為你收集整理的K均值算法matlab代码实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ActivityManager kill
- 下一篇: 多分类器算法的思想