如何从sklearn AgglomerativeClustering遍历树?

时间:2014-12-09 18:54:35

标签: python machine-learning scipy scikit-learn hierarchical-clustering

我在https://github.com/alvations/anythingyouwant/blob/master/WN_food.matrix

有一个numpy文本文件数组

这是术语和彼此之间的距离矩阵,我的术语列表如下:http://pastebin.com/2xGt7Xjh

我使用以下代码生成层次结构集群:

import numpy as np
from sklearn.cluster import AgglomerativeClustering

matrix = np.loadtxt('WN_food.matrix')
n_clusters = 518
model = AgglomerativeClustering(n_clusters=n_clusters,
                                linkage="average", affinity="cosine")
model.fit(matrix)

为了获得每个学期的聚类,我本可以做到:

for term, clusterid in enumerate(model.labels_):
    print term, clusterid

如何遍历AgglomerativeClustering输出的树?

是否可以将其转换为scipy树状图(http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.cluster.hierarchy.dendrogram.html)?之后我如何遍历树状图?

2 个答案:

答案 0 :(得分:14)

我已经为sklearn.cluster.ward_tree回答了类似的问题: How do you visualize a ward tree from sklearn.cluster.ward_tree?

AgglomerativeClustering以相同的方式在children_属性中输出树。这是对AgglomerativeClustering的病房树问题中代码的改编。它以树的每个节点的形式(node_id,left_child,right_child)输出树的结构。

import numpy as np
from sklearn.cluster import AgglomerativeClustering
import itertools

X = np.concatenate([np.random.randn(3, 10), np.random.randn(2, 10) + 100])
model = AgglomerativeClustering(linkage="average", affinity="cosine")
model.fit(X)

ii = itertools.count(X.shape[0])
[{'node_id': next(ii), 'left': x[0], 'right':x[1]} for x in model.children_]

https://stackoverflow.com/a/26152118

答案 1 :(得分:1)

这是A.P.的答案,下面的代码将为您提供会员字典。 member [node_id]给出所有数据点索引(零到n)。

on_split是A.P集群的简单重新格式化,它给出了在node_id被分割时形成的两个集群。

up_merge告知将哪个node_id合并到其中,以及必须将哪些node_id合并到其中。

ii = itertools.count(data_x.shape[0])
clusters = [{'node_id': next(ii), 'left': x[0], 'right':x[1]} for x in fit_cluster.children_]

import copy
n_points = data_x.shape[0]
members = {i:[i] for i in range(n_points)}
for cluster in clusters:
    node_id = cluster["node_id"]
    members[node_id] = copy.deepcopy(members[cluster["left"]])
    members[node_id].extend(copy.deepcopy(members[cluster["right"]]))

on_split = {c["node_id"]: [c["left"], c["right"]] for c in clusters}
up_merge = {c["left"]: {"into": c["node_id"], "with": c["right"]} for c in clusters}
up_merge.update({c["right"]: {"into": c["node_id"], "with": c["left"]} for c in clusters})