Created
September 19, 2011 13:59
-
-
Save jrosebr1/1226553 to your computer and use it in GitHub Desktop.
Methods to perform hierarchical agglomerative clustering using SciPy and parse the clusters.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cluster(self): | |
# ... # | |
# cluster the codes together using hierarchical agglomerative | |
# clustering and then parse the returned clusters | |
self.clusters = hierarchy.linkage(clusterCodes, "single", "euclidean") | |
self.clusters = self.parseClusters(self.clusters, numClusters) | |
# ... # | |
def parseClusters(self, clusters, numClusters): | |
# initialize the parsed clusters dictionary and the current | |
# cluster index | |
parsed = {} | |
j = len(self.index) | |
# loop over the clusters | |
for i in range(0, len(self.index) - numClusters): | |
# grab the index of the two clusters that were merged | |
# together | |
idA = int(clusters[i][0]) | |
idB = int(clusters[i][1]) | |
# try to grab the set of nodes already in the cluster | |
# for each ID | |
nodesA = parsed.get(idA, set()) | |
nodesB = parsed.get(idB, set()) | |
# if the first node set is larger than zero, delete the | |
# cluster ID | |
if len(nodesA) > 0: | |
del parsed[idA] | |
# if the second node set is larger than zero, delete the | |
# cluster ID | |
if len(nodesB) > 0: | |
del parsed[idB] | |
# if the first ID is less than the length of the index, then | |
# add the ID to the nodes | |
if idA < len(self.index): | |
nodesA.add(idA) | |
# if the second ID is less than the length of the index, then | |
# add the ID to the nodes | |
if idB < len(self.index): | |
nodesB.add(idB) | |
# take the union of the set of nodes, update the parsed clusters | |
# dictionary, and then increment the next available cluster ID | |
nodesA = nodesA.union(nodesB) | |
parsed[j] = nodesA | |
j += 1 | |
# return the parsed clusters dictionary | |
return parsed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could anyone tell me please how can I perform Agglomerative clustering on an image??? I have got the slightest idea of this algo.