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