Debian Codegraph @

cluster/method/kmeans.py

raw symbols SCIP
1 #
2 # This is part of "python-cluster". A library to group similar items together.
3 # Copyright (C) 2006 Michel Albert
4 #
5 # This library is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by the
7 # Free Software Foundation; either version 2.1 of the License, or (at your
8 # option) any later version.
9 # This library is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 # for more details.
13 # You should have received a copy of the GNU Lesser General Public License
14 # along with this library; if not, write to the Free Software Foundation,
15 # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 #
17
18
19 from cluster.util import ClusteringError, centroid, minkowski_distance
20
21
22 class KMeansClustering(object):
23 """
24 Implementation of the kmeans clustering method as explained in a tutorial_
25 by *matteucc*.
26
27 .. _tutorial: http://www.elet.polimi.it/upload/matteucc/Clustering/tutorial_html/kmeans.html
28
29 Example:
30
31 >>> from cluster import KMeansClustering
32 >>> cl = KMeansClustering([(1,1), (2,1), (5,3), ...])
33 >>> clusters = cl.getclusters(2)
34
35 :param data: A list of tuples or integers.
36 :param distance: A function determining the distance between two items.
37 Default (if ``None`` is passed): It assumes the tuples contain numeric
38 values and appiles a generalised form of the euclidian-distance
39 algorithm on them.
40 :param equality: A function to test equality of items. By default the
41 standard python equality operator (``==``) is applied.
42 :raises ValueError: if the list contains heterogeneous items or if the
43 distance between items cannot be determined.
44 """
45
46 def __init__(self, data, distance=None, equality=None):
47 self.__clusters = []
48 self.__data = data
49 self.distance = distance
50 self.__initial_length = len(data)
51 self.equality = equality
52
53 # test if each item is of same dimensions
54 if len(data) > 1 and isinstance(data[0], tuple):
55 control_length = len(data[0])
56 for item in data[1:]:
57 if len(item) != control_length:
58 raise ValueError("Each item in the data list must have "
59 "the same amount of dimensions. Item "
60 "%r was out of line!" % (item,))
61 # now check if we need and have a distance function
62 if (len(data) > 1 and not isinstance(data[0], tuple) and
63 distance is None):
64 raise ValueError("You supplied non-standard items but no "
65 "distance function! We cannot continue!")
66 # we now know that we have tuples, and assume therefore that it's
67 # items are numeric
68 elif distance is None:
69 self.distance = minkowski_distance
70
71 def getclusters(self, count):
72 """
73 Generates *count* clusters.
74
75 :param count: The amount of clusters that should be generated. count
76 must be greater than ``1``.
77 :raises ClusteringError: if *count* is out of bounds.
78 """
79
80 # only proceed if we got sensible input
81 if count <= 1:
82 raise ClusteringError("When clustering, you need to ask for at "
83 "least two clusters! "
84 "You asked for %d" % count)
85
86 # return the data straight away if there is nothing to cluster
87 if (self.__data == [] or len(self.__data) == 1 or
88 count == self.__initial_length):
89 return self.__data
90
91 # It makes no sense to ask for more clusters than data-items available
92 if count > self.__initial_length:
93 raise ClusteringError(
94 "Unable to generate more clusters than "
95 "items available. You supplied %d items, and asked for "
96 "%d clusters." % (self.__initial_length, count))
97
98 self.initialise_clusters(self.__data, count)
99
100 items_moved = True # tells us if any item moved between the clusters,
101 # as we initialised the clusters, we assume that
102 # is the case
103
104 while items_moved is True:
105 items_moved = False
106 for cluster in self.__clusters:
107 for item in cluster:
108 res = self.assign_item(item, cluster)
109 if items_moved is False:
110 items_moved = res
111 return self.__clusters
112
113 def assign_item(self, item, origin):
114 """
115 Assigns an item from a given cluster to the closest located cluster.
116
117 :param item: the item to be moved.
118 :param origin: the originating cluster.
119 """
120 closest_cluster = origin
121 for cluster in self.__clusters:
122 if self.distance(item, centroid(cluster)) < self.distance(
123 item, centroid(closest_cluster)):
124 closest_cluster = cluster
125
126 if id(closest_cluster) != id(origin):
127 self.move_item(item, origin, closest_cluster)
128 return True
129 else:
130 return False
131
132 def move_item(self, item, origin, destination):
133 """
134 Moves an item from one cluster to anoter cluster.
135
136 :param item: the item to be moved.
137 :param origin: the originating cluster.
138 :param destination: the target cluster.
139 """
140 if self.equality:
141 item_index = 0
142 for i, element in enumerate(origin):
143 if self.equality(element, item):
144 item_index = i
145 break
146 else:
147 item_index = origin.index(item)
148
149 destination.append(origin.pop(item_index))
150
151 def initialise_clusters(self, input_, clustercount):
152 """
153 Initialises the clusters by distributing the items from the data.
154 evenly across n clusters
155
156 :param input_: the data set (a list of tuples).
157 :param clustercount: the amount of clusters (n).
158 """
159 # initialise the clusters with empty lists
160 self.__clusters = []
161 for _ in range(clustercount):
162 self.__clusters.append([])
163
164 # distribute the items into the clusters
165 count = 0
166 for item in input_:
167 self.__clusters[count % clustercount].append(item)
168 count += 1