Debian Codegraph @

cluster/method/hierarchical.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 from functools import partial
19 import logging
20
21 from cluster.cluster import Cluster
22 from cluster.matrix import Matrix
23 from cluster.method.base import BaseClusterMethod
24 from cluster.linkage import single, complete, average, uclus
25
26
27 logger = logging.getLogger(__name__)
28
29
30 class HierarchicalClustering(BaseClusterMethod):
31 """
32 Implementation of the hierarchical clustering method as explained in a
33 tutorial_ by *matteucc*.
34
35 Object prerequisites:
36
37 * Items must be sortable (See `issue #11`_)
38 * Items must be hashable.
39
40 .. _issue #11: https://github.com/exhuma/python-cluster/issues/11
41 .. _tutorial: http://www.elet.polimi.it/upload/matteucc/Clustering/tutorial_html/hierarchical.html
42
43 Example:
44
45 >>> from cluster import HierarchicalClustering
46 >>> # or: from cluster import *
47 >>> cl = HierarchicalClustering([123,334,345,242,234,1,3],
48 lambda x,y: float(abs(x-y)))
49 >>> cl.getlevel(90)
50 [[345, 334], [234, 242], [123], [3, 1]]
51
52 Note that all of the returned clusters are more than 90 (``getlevel(90)``)
53 apart.
54
55 See :py:class:`~cluster.method.base.BaseClusterMethod` for more details.
56
57 :param data: The collection of items to be clustered.
58 :param distance_function: A function which takes two elements of ``data``
59 and returns a distance between both elements (note that the distance
60 should not be returned as negative value!)
61 :param linkage: The method used to determine the distance between two
62 clusters. See :py:meth:`~.HierarchicalClustering.set_linkage_method` for
63 possible values.
64 :param num_processes: If you want to use multiprocessing to split up the
65 work and run ``genmatrix()`` in parallel, specify num_processes > 1 and
66 this number of workers will be spun up, the work split up amongst them
67 evenly.
68 :param progress_callback: A function to be called on each iteration to
69 publish the progress. The function is called with two integer arguments
70 which represent the total number of elements in the cluster, and the
71 remaining elements to be clustered.
72 """
73
74 def __init__(self, data, distance_function, linkage=None, num_processes=1,
75 progress_callback=None):
76 if not linkage:
77 linkage = single
78 logger.info("Initializing HierarchicalClustering object with linkage "
79 "method %s", linkage)
80 BaseClusterMethod.__init__(self, sorted(data), distance_function)
81 self.set_linkage_method(linkage)
82 self.num_processes = num_processes
83 self.progress_callback = progress_callback
84 self.__cluster_created = False
85
86 def publish_progress(self, total, current):
87 """
88 If a progress function was supplied, this will call that function with
89 the total number of elements, and the remaining number of elements.
90
91 :param total: The total number of elements.
92 :param remaining: The remaining number of elements.
93 """
94 if self.progress_callback:
95 self.progress_callback(total, current)
96
97 def set_linkage_method(self, method):
98 """
99 Sets the method to determine the distance between two clusters.
100
101 :param method: The method to use. It can be one of ``'single'``,
102 ``'complete'``, ``'average'`` or ``'uclus'``, or a callable. The
103 callable should take two collections as parameters and return a
104 distance value between both collections.
105 """
106 if method == 'single':
107 self.linkage = single
108 elif method == 'complete':
109 self.linkage = complete
110 elif method == 'average':
111 self.linkage = average
112 elif method == 'uclus':
113 self.linkage = uclus
114 elif hasattr(method, '__call__'):
115 self.linkage = method
116 else:
117 raise ValueError('distance method must be one of single, '
118 'complete, average of uclus')
119
120 def cluster(self, matrix=None, level=None, sequence=None):
121 """
122 Perform hierarchical clustering.
123
124 :param matrix: The 2D list that is currently under processing. The
125 matrix contains the distances of each item with each other
126 :param level: The current level of clustering
127 :param sequence: The sequence number of the clustering
128 """
129 logger.info("Performing cluster()")
130
131 if matrix is None:
132 # create level 0, first iteration (sequence)
133 level = 0
134 sequence = 0
135 matrix = []
136
137 # if the matrix only has two rows left, we are done
138 linkage = partial(self.linkage, distance_function=self.distance)
139 initial_element_count = len(self._data)
140 while len(matrix) > 2 or matrix == []:
141
142 item_item_matrix = Matrix(self._data,
143 linkage,
144 True,
145 0)
146 item_item_matrix.genmatrix(self.num_processes)
147 matrix = item_item_matrix.matrix
148
149 smallestpair = None
150 mindistance = None
151 rowindex = 0 # keep track of where we are in the matrix
152 # find the minimum distance
153 for row in matrix:
154 cellindex = 0 # keep track of where we are in the matrix
155 for cell in row:
156 # if we are not on the diagonal (which is always 0)
157 # and if this cell represents a new minimum...
158 cell_lt_mdist = cell < mindistance if mindistance else False
159 if ((rowindex != cellindex) and
160 (cell_lt_mdist or smallestpair is None)):
161 smallestpair = (rowindex, cellindex)
162 mindistance = cell
163 cellindex += 1
164 rowindex += 1
165
166 sequence += 1
167 level = matrix[smallestpair[1]][smallestpair[0]]
168 cluster = Cluster(level, self._data[smallestpair[0]],
169 self._data[smallestpair[1]])
170
171 # maintain the data, by combining the the two most similar items
172 # in the list we use the min and max functions to ensure the
173 # integrity of the data. imagine: if we first remove the item
174 # with the smaller index, all the rest of the items shift down by
175 # one. So the next index will be wrong. We could simply adjust the
176 # value of the second "remove" call, but we don't know the order
177 # in which they come. The max and min approach clarifies that
178 self._data.remove(self._data[max(smallestpair[0],
179 smallestpair[1])]) # remove item 1
180 self._data.remove(self._data[min(smallestpair[0],
181 smallestpair[1])]) # remove item 2
182 self._data.append(cluster) # append item 1 and 2 combined
183
184 self.publish_progress(initial_element_count, len(self._data))
185
186 # all the data is in one single cluster. We return that and stop
187 self.__cluster_created = True
188 logger.info("Call to cluster() is complete")
189 return
190
191 def getlevel(self, threshold):
192 """
193 Returns all clusters with a maximum distance of *threshold* in between
194 each other
195
196 :param threshold: the maximum distance between clusters.
197
198 See :py:meth:`~cluster.cluster.Cluster.getlevel`
199 """
200
201 # if it's not worth clustering, just return the data
202 if len(self._input) <= 1:
203 return self._input
204
205 # initialize the cluster if not yet done
206 if not self.__cluster_created:
207 self.cluster()
208
209 return self._data[0].getlevel(threshold)
210
211 def display(self):
212 """
213 Prints a simple dendogram-like representation of the full cluster
214 to the console.
215 """
216 # initialize the cluster if not yet done
217 if not self.__cluster_created:
218 self.cluster()
219
220 self._data[0].display()