⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mykmeans.m

📁 实现聚类K均值算法: K均值算法:给定类的个数K
💻 M
字号:
% function [centres, options, post, errlog] = kmeans(...)%% This function has been adopted from a k means implementation% copyright (c) Christopher M Bishop, Ian T Nabney (1996, 1997)clear;x=load('yeast.txt');[m,n]=size(x);data=x;[ndata, data_dim] = size(data);ncentres=10;  %聚类个数限制niters = 50; %循环次数限制err=0.00001;olde=10000;%产生若干个聚类中心for i=1:ncentres   ind=round(rand*ndata);   centres(i,:)=data(ind,:);end% Matrix to make unit vectors easy to constructid = eye(ncentres);% Main loop of algorithmfor n = 1:niters  % Save old centres to check for termination  old_centres = centres;    % Calculate posteriors based on existing centres    for i=1:ndata        for j=1:ncentres       ss=0;       for k=1:data_dim         ss=ss+(data(i,k)-centres(j,k))*(data(i,k)-centres(j,k));       end       d2(i,j)=sqrt(ss/data_dim);    end  end    % Assign each point to nearest centre  [minvals, index] = min(d2', [], 1);  post = id(index,:);  num_points = sum(post, 1);  % Adjust the centres based on new posteriors  for j = 1:ncentres    if (num_points(j) > 0)      centres(j,:) = sum(data(find(post(:,j)),:), 1)/num_points(j);    end  end  % Error value is total squared distance from cluster centres  e = sum(minvals);  fprintf(1, 'Cycle %4d  Error %11.6f\n', n, e);    if n > 1    % Test for termination    if  abs(old_e - e) < err     %      return;    end  end  old_e = e;endc=index;[m,n]=size(x);for i=1:ncentres                              %生成与类别数相对应的文件,用于保存各类样本  fn=strcat('class',int2str(i));  fn=strcat(fn,'.txt');  fid(i)=fopen(fn,'w');endfor i=1:m                              %将各样本存入相应的类别文件  for j=1:n    fprintf(fid(c(i)),'%d ',x(i,j));  end  fprintf(fid(c(i)),'\n');endfor i=1:ncentres                               %关闭所有文件  fclose(fid(i));end

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -