Single Linkage Clustering Of Edit Distance Matrix With Distance Threshold Stopping Criterion
I'm trying to assign flat, single-linkage clusters to sequence IDs separated by an edit distance < n, given a square distance matrix. I believe scipy.cluster.hierarchy.fclusterd
Solution 1:
You did not set the metric parameter.
The default then is metric='euclidean'
, not precomputed.
Solution 2:
Figured it out by passing linkage()
to fcluster()
, which supports metric='precomputed'
unlike fclusterdata()
.
fcluster(linkage(condensed_dm, metric='precomputed'), criterion='distance', t=20)
Answer :
import pandas as pd
from scipy.spatial.distance import squareform
from scipy.cluster.hierarchy import linkage, fcluster
cols = ['a', 'b', 'c', 'd']
df = pd.DataFrame([{'a': 0, 'b': 29467, 'c': 35, 'd': 13},
{'a': 29467, 'b': 0, 'c': 29468, 'd': 29470},
{'a': 35, 'b': 29468, 'c': 0, 'd': 38},
{'a': 13, 'b': 29470, 'c': 38, 'd': 0}],
index=cols)
dm_cnd = squareform(df.values)
clusters_20 = fcluster(linkage(dm_cnd, metric='precomputed'), criterion='distance', t=20)
clusters_50 = fcluster(linkage(dm_cnd, metric='precomputed'), criterion='distance', t=50)
clusters_100 = fcluster(linkage(dm_cnd, metric='precomputed'), criterion='distance', t=100)
names_clusters_20 = {n: c for n, c inzip(cols, clusters_20)}
names_clusters_50 = {n: c for n, c inzip(cols, clusters_50)}
names_clusters_100 = {n: c for n, c inzip(cols, clusters_100)}
names_clusters_20
>>>{'a': 1, 'b': 3, 'c': 2, 'd': 1}
names_clusters_50
>>>{'a': 1, 'b': 2, 'c': 1, 'd': 1}
names_clusters_100
>>>{'a': 1, 'b': 2, 'c': 1, 'd': 1}
As a function:
import pandas as pd
from scipy.spatial.distance import squareform
from scipy.cluster.hierarchy import fcluster, linkage
defcluster_df(df, method='single', threshold=100):
'''
Accepts a square distance matrix as an indexed DataFrame and returns a dict of index keyed flat clusters
Performs single linkage clustering by default, see scipy.cluster.hierarchy.linkage docs for others
'''
dm_cnd = squareform(df.values)
clusters = fcluster(linkage(dm_cnd,
method=method,
metric='precomputed'),
criterion='distance',
t=threshold)
names_clusters = {s:c for s, c inzip(df.columns, clusters)}
return names_clusters
Post a Comment for "Single Linkage Clustering Of Edit Distance Matrix With Distance Threshold Stopping Criterion"