| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 67 |
|
| 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 |
|
| 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 |
|
| 87 |
if (self.__data == [] or len(self.__data) == 1 or |
| 88 |
count == self.__initial_length): |
| 89 |
return self.__data |
| 90 |
|
| 91 |
|
| 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 |
| 101 |
|
| 102 |
|
| 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 |
|
| 160 |
self.__clusters = [] |
| 161 |
for _ in range(clustercount): |
| 162 |
self.__clusters.append([]) |
| 163 |
|
| 164 |
|
| 165 |
count = 0 |
| 166 |
for item in input_: |
| 167 |
self.__clusters[count % clustercount].append(item) |
| 168 |
count += 1 |