您好,欢迎来到锐游网。
搜索
您的当前位置:首页实验三-K-均值聚类算法实验报告

实验三-K-均值聚类算法实验报告

来源:锐游网
-----WORD格式--可编辑--专业资料-----

实验三 K-Means聚类算法

一、 实验目的

1) 加深对非监督学习的理解和认识

2) 掌握动态聚类方法K-Means 算法的设计方法

二、 实验环境

1) 具有相关编程软件的PC机

三、 实验原理

1) 非监督学习的理论基础

2) 动态聚类分析的思想和理论依据 3) 聚类算法的评价指标

四、算法思想

K-均值算法的主要思想是先在需要分类的数据中寻找K组数据作为初始聚类中心,然后计算其他数据距离这三个聚类中心的距离,将数据归入与其距离最近的聚类中心,之后再对这K个聚类的数据计算均值,作为新的聚类中心,继续以上步骤,直到新的聚类中心与上一次的聚类中心值相等时结束算法。

实验代码

function km(k,A)%函数名里不要出现“-” warning off

[n,p]=size(A);%输入数据有n个样本,p个属性

cid=ones(k,p+1);%聚类中心组成k行p列的矩阵,k表示第几类,p是属性 %A(:,p+1)=100; A(:,p+1)=0; for i=1:k

%cid(i,:)=A(i,:); %直接取前三个元祖作为聚类中心 m=i*floor(n/k)-floor(rand(1,1)*(n/k)) cid(i,:)=A(m,:); cid; end Asum=0; Csum2=NaN; flags=1; times=1; while flags flags=0;

times=times+1;

%计算每个向量到聚类中心的欧氏距离 for i=1:n for j=1:k

dist(i,j)=sqrt(sum((A(i,:)-cid(j,:)).^2));%欧氏距离

--完整版学习资料分享----

-----WORD格式--可编辑--专业资料-----

end

%A(i,p+1)=min(dist(i,:));%与中心的最小距离 [x,y]=find(dist(i,:)==min(dist(i,:))); [c,d]=size(find(y==A(i,p+1))); if c==0 %说明聚类中心变了 flags=flags+1; A(i,p+1)=y(1,1); else

continue; end end i flags for j=1:k Asum=0;

[r,c]=find(A(:,p+1)==j); cid(j,:)=mean(A(r,:),1); for m=1:length(r)

Asum=Asum+sqrt(sum((A(r(m),:)-cid(j,:)).^2)); end

Csum(1,j)=Asum; end

sum(Csum(1,:))

%if sum(Csum(1,:))>Csum2 % break; %end

Csum2=sum(Csum(1,:)); Csum;

cid; %得到新的聚类中心 end times

display('A矩阵,最后一列是所属类别'); A

for j=1:k

[a,b]=size(find(A(:,p+1)==j)); numK(j)=a; end numK times

xlswrite('data.xls',A);

五、算法流程图

--完整版学习资料分享----

-----WORD格式--可编辑--专业资料-----

开 始 读入要分类的数据 设置初始聚类中心 计算数据到K个聚类中心的距离 将数据分入与其距离最小的聚类 计算新的聚类中心 聚类中心是否收敛? 否 是 输出K个分类好的聚类 结 束

六、实验结果

>>Kmeans

6 iterations, total sum of distances = 204.821

--完整版学习资料分享----

-----WORD格式--可编辑--专业资料-----

10 iterations, total sum of distances = 205.886 16 iterations, total sum of distances = 204.821 9 iterations, total sum of distances = 205.886 ........

9 iterations, total sum of distances = 205.886 8 iterations, total sum of distances = 204.821 8 iterations, total sum of distances = 204.821 14 iterations, total sum of distances = 205.886 14 iterations, total sum of distances = 205.886 6 iterations, total sum of distances = 204.821 Ctrs =1.07 -1.06321.0482 1.3902-1.1442 -1.1121 SumD =.294463.593976.9329

七、实验心得

初始的聚类中心的不同,对聚类结果没有很大的影响,而对迭代次数有显著的影响。数据的输入顺序不同,同样影响迭代次数,而对聚类结果没有太大的影响。

--完整版学习资料分享----

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- ryyc.cn 版权所有 湘ICP备2023022495号-3

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务