comparison toolboxes/FullBNT-1.0.7/netlabKPM/kmeans_demo.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:e9a9cd732c1e
1 function kmeans_demo()
2
3 % Generate T points from K=5 1D clusters, and try to recover the cluster
4 % centers using k-means.
5 % Requires BNT, netlab and the matlab stats toolbox v4.
6
7 K = 5;
8 ndim = 1;
9 true_centers = 1:K;
10 sigma = 1e-6;
11 T = 100;
12 % data(t,:) is the t'th data point
13 data = zeros(T, ndim);
14 % ndx(t) = i means the t'th data point is sample from cluster i
15 %ndx = sample_discrete(normalise(ones(1,K)));
16 ndx = [1*ones(1,20) 2*ones(1,20) 3*ones(1,20) 4*ones(1,20) 5*ones(1,20)];
17 for t=1:T
18 data(t) = sample_gaussian(true_centers(ndx(t)), sigma, 1);
19 end
20 plot(1:T, data, 'x')
21
22
23
24 % set the centers randomly from Gauss(0)
25 mix = gmm(ndim, K, 'spherical');
26 h = plot_centers_as_lines(mix, [], T);
27
28 if 0
29 % Place initial centers at K data points chosen at random, but add some noise
30 choose_ndx = randperm(T);
31 choose_ndx = choose_ndx(1:K);
32 init_centers = data(choose_ndx) + sample_gaussian(0, 0.1, K);
33 mix.centres = init_centers;
34 h = plot_centers_as_lines(mix, h, T);
35 end
36
37 if 0
38 % update centers using netlab k-means
39 options = foptions;
40 niter = 10;
41 options(14) = niter;
42 mix = gmminit(mix, data, options);
43 h = plot_centers_as_lines(mix, h, T);
44 end
45
46 % use matlab stats toolbox k-means with multiple restarts
47 nrestarts = 5;
48 [idx, centers] = kmeans(data, K, 'replicates', nrestarts, ...
49 'emptyAction', 'singleton', 'display', 'iter');
50 mix.centres = centers;
51 h = plot_centers_as_lines(mix, h, T);
52
53 % fine tune with EM; compute covariances of each cluster
54 options = foptions;
55 niter = 20;
56 options(1) = 1; % display cost fn at each iter
57 options(14) = niter;
58 mix = gmmem(mix, data, options);
59 h = plot_centers_as_lines(mix, h, T);
60
61 %%%%%%%%%
62 function h = plot_centers_as_lines(mix, h, T)
63
64 K = mix.ncentres;
65 hold on
66 if isempty(h)
67 for k=1:K
68 h(k)=line([0 T], [mix.centres(k) mix.centres(k)]);
69 end
70 else
71 for k=1:K
72 set(h(k), 'xdata', [0 T], 'ydata', [mix.centres(k) mix.centres(k)]);
73 end
74 end
75 hold off
76