Skip to content

Instantly share code, notes, and snippets.

@gerritgr
Created March 20, 2019 09:27
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 gerritgr/4d905d2b9bb38552e99ee42739a0e924 to your computer and use it in GitHub Desktop.
Save gerritgr/4d905d2b9bb38552e99ee42739a0e924 to your computer and use it in GitHub Desktop.
Hierarchical Clustering from distance function
def cluster_from_distances(data_points, dist_func, cluster_num):
from scipy.cluster.hierarchy import linkage, cut_tree
points = list()
for d1 in data_points:
d_list = [dist_func(d1,d2) for d2 in data_points]
points.append(d_list)
import scipy.spatial.distance as ssd
points = ssd.squareform(points)
Z = linkage(points, 'ward')
cluster_indicators = cut_tree(Z, n_clusters=cluster_num)
cluster_indicators = [c[0] for c in cluster_indicators]
return cluster_indicators
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment