• 大小: 1KB
    文件类型: .zip
    金币: 1
    下载: 0 次
    发布日期: 2021-04-17
  • 语言: Matlab
  • 标签: kmedoids  MATLAB  

资源简介

简单且容易理解的k-medoids聚类算法matlab源代码

资源截图

代码片段和文件信息

function [indscidx] = kmedoids(Dk)
% [indscidx] = kmedioids(Dk)
%
% Performs k-mediods clustering; only requires a distance matrix D and
% number of clusters k.  Finds cluster assignments “inds“ to minimize the
% following cost function: 

% sum(D(inds==iinds==i)2) summed over i=1:k 
    
% Determining cluster assignments and cluster centers are both done in an
% efficient vectorized way.  Cluster assignment is O(nk) and cluster
% centering is O(k*(max cluster size)^2)
%
% INPUTS
% D: nxn all-pairs distance matrix
% k: number of clusters
%
% OUTPUTS
% inds: nx1 vector of assignments of each sample to a cluster id
% cidx: kx1 vector of sample indices which make up the cluster centers
%
% DEMO
% Run with no arguments for demo with 2d points sampled from 3 gaussians
% using the gmdistribution function from the stats toolbox

% Written by Ben Sapp September 2010
% benjamin.sapp@gmail.com

if nargin == 0
    demo();
    return;
end

n = size(D1);

% randomly assign centers:
cidx = randperm(n);
cidx = sort(cidx(1:k));

iter = 0;
while 1
    inds = assign_pts_to_clusters(Dcidx);
    [cidxenergy_next] = update_centers(Dindscidxk);
    
    if iter>0 && energy_next == energy 
        break;
    end
    energy = energy_next;
    
    fprintf(‘iter: %04d energy: %.02f\n‘iterenergy)
    iter = iter+1;
end

function inds = assign_pts_to_clusters(Dcidx)
S  = D(cidx:);
[valsinds] = min(S[]1);

function [cidxenergy] = update_centers(Dindscidxk)
energy_next = nan(k1);
for i=1:k
   indsi = find(inds==i);
   [energy_next(i)minind] = min(sum(D(indsiindsi)2));
   cidx(i) = indsi(minind);
end

energy = sum(energy_next);


function demo()
% problem params
k = 3;
n = 2000;
MU = [1 2;-1 -2; 3 0];
SIGMA = cat(3[2 0;0 .5][1 0;0 1] eye(2));
p = ones(13)/3;
obj = gmdistribution(MUSIGMAp);
pts = random(objn)‘;

%form all-pairs distance matrix in an efficient way
X = pts‘;
temp = sum(X.^22);
X=sqrt(2)*X;
D=-X*X‘;
D=bsxfun(@plusDtemp);
D=bsxfun(@plusDtemp‘);

%run kmedioids
[indscidx] = kmedioids(Dk);

%display
clf hold on axis square
c = lines(k);
for i=1:k
    ptsi = pts(:inds==i);
    ctrpt = pts(:cidx(i));
    plot(ptsi(1:)ptsi(2:)‘.‘‘color‘c(i:))
    plot(ctrpt(1)ctrpt(2)‘kx‘‘markersize‘22‘linewidth‘6)    
end




 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----
     文件        2289  2014-04-23 02:13  kmedoids\kmedoids.m
     目录           0  2014-04-27 04:14  kmedoids\

评论

共有 条评论