Skip to content

Instantly share code, notes, and snippets.

@jrosebr1
Created September 19, 2011 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrosebr1/1226553 to your computer and use it in GitHub Desktop.
Save jrosebr1/1226553 to your computer and use it in GitHub Desktop.
Methods to perform hierarchical agglomerative clustering using SciPy and parse the clusters.
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
@Mahamk
Copy link

Mahamk commented Apr 14, 2013

Could anyone tell me please how can I perform Agglomerative clustering on an image??? I have got the slightest idea of this algo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment