IMP  2.3.1
The Integrative Modeling Platform
kmeans/kmeans_example.py

Create a set and points and cluster it, printing the resulting cluster centers

1 ## \example kmeans/kmeans_example.py
2 # Create a set and points and cluster it, printing the resulting cluster
3 # centers
4 
5 import IMP
6 import IMP.kmeans
7 
8 
9 def add_points(km):
10  # add data
11  km.add_data_pt([1, 2])
12  km.add_data_pt([10, 12])
13  km.add_data_pt([0, -1])
14  km.add_data_pt([11, 13])
15  km.add_data_pt([0, 0])
16  km.add_data_pt([1, 0])
17  km.add_data_pt([9.4, 10])
18  km.add_data_pt([9.2, 11])
19  km.add_data_pt([0, 0])
20 
21 IMP.base.set_log_level(IMP.base.PROGRESS)
22 km = IMP.kmeans.KMeans()
23 add_points(km)
24 # cluster data
25 k = 2
26 km.execute(k)
27 # print centers one by one
28 print "\nCenters:"
29 nCenters = km.get_number_of_centers() # this should actually be equal to k
30 print "Number of centers (k): ", nCenters
31 for i in range(0, nCenters):
32  print "Center ", i, " ", km.get_center(i)
33 
34 # print data point assignments
35 n = km.get_number_of_data_points()
36 assignments = km.get_assignments()
37 sqrdist = km.get_squared_distance_to_centers()
38 print "Number of points: ", n
39 for i in range(0, n):
40  print "Point ", i, ": "
41  print km.get_data_point(i)
42  print "Cluster center: ", assignments[i], \
43  " sqrt-dist: ", sqrdist[i]