This is an archival dump of old wiki content --- see scipy.org for current material.
Please see http://scipy-cookbook.readthedocs.org/

Attachment 'test_kmeans.py'

Download

   1 #!/usr/bin/env python
   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 	# knum = 7
  10 	obs = scvq.whiten(obs)
  11 
  12 	# run kmeans with diffirent number of clusters
  13 	for knum in range(2, 8):
  14 		codebook, dist = scvq.kmeans(obs, knum)
  15 		ind, dist = scvq.vq(obs, codebook)
  16 
  17 		# visualize
  18 		# plt.ion()
  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 		# the cluster centroid
  32 		plt.plot(codebook[:, 0], codebook[:, 1], "ko")
  33 
  34 		# the plot size
  35 		plt.xlim((-0.3, 3.8))
  36 		plt.ylim((-0.3, 3.8))
  37 	plt.show()
  38 # end.def
  39 
  40 #--------------------------------------------------------------
  41 if __name__ == "__main__":
  42 	test_kmeans()

New Attachment

File to upload
Rename to
Overwrite existing attachment of same name

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.