www.gusucode.com > K聚类分析源码程序 > K聚类分析源码程序/code/demo.m

    
clc;
clear;
close all;

x = [];
idxTruth = [];

for i = 1:5
    theta = pi*rand(1)/2;
    rmean(i,:) = [(20*rand(1) - 10) (20*rand(1) - 10)];
    covariance = covm2d(theta, (.75*rand(1)+.25), (.75*rand(1)+.25));
    xClust = normdist(400, 2, rmean(i,:), covariance);
    idxTruth = [idxTruth; i*ones(400,1)];
    x = [x; xClust];
end

h = figure
scatter(x(:,1),x(:,2),3,idxTruth)
axis equal
title('truth clustering')
saveas(h,'fig1.fig')

%% Bayes error cluster %%
idxBayes = nearestcenter(x,rmean);
voi_bayes = varinfo(idxBayes,idxTruth);

h = figure
scatter(x(:,1),x(:,2),3,idxBayes)
axis equal
title(strcat('Bayes error clustering: voi = ',num2str(voi_bayes)))
saveas(h,'fig2.fig')

%% Kmeans %%
idxKmeans = kmeans(x,5);
voi_kmeans = varinfo(idxKmeans,idxTruth);

h = figure
scatter(x(:,1),x(:,2),3,idxKmeans)
axis equal
title(strcat('kmeans clustering: voi = ',num2str(voi_kmeans)))
saveas(h,'fig3.fig')