1
2 import matplotlib.pyplot as plt
3 import scipy.cluster.vq as scvq
4 import scipy as sp
5
6
7 def test_kmeans():
8 obs = sp.random.uniform(0, 10, (1000, 2))
9
10 obs = scvq.whiten(obs)
11
12
13 for knum in range(2, 8):
14 codebook, dist = scvq.kmeans(obs, knum)
15 ind, dist = scvq.vq(obs, codebook)
16
17
18
19 plt.ioff()
20 plt.figure(knum)
21 colors = ["b*", "g+", "ro", "yp", "ms", "ch", "wx"]
22
23 for icluster in range(knum):
24 x = (ind == icluster).nonzero()[0]
25 plt.plot(obs[x, 0], obs[x, 1], colors[icluster])
26
27 for iline in range(sp.size(x)):
28 plt.plot([obs[x[iline], 0], codebook[icluster, 0]],
29 [obs[x[iline], 1], codebook[icluster, 1]], "k--")
30
31
32 plt.plot(codebook[:, 0], codebook[:, 1], "ko")
33
34
35 plt.xlim((-0.3, 3.8))
36 plt.ylim((-0.3, 3.8))
37 plt.show()
38
39
40
41 if __name__ == "__main__":
42 test_kmeans()
, as shown below in the list of files. Do
link, since this is subject to change and can break easily.