显示scipy树形图的簇标签

时间:2016-03-08 16:53:36

标签: python matplotlib scipy dendrogram

我使用分层聚类来聚类单词向量,我希望用户能够显示显示聚类的树形图。但是,由于可能有数千个单词,我希望这个树形图被截断到一些合理的价值,每个叶子的标签是该群集中最重要单词的字符串。

我的问题是,according to the docs"标签[i]值是仅当它对应于原始观察而不是非观察时放在第i个叶子节点下的文本单身集群。" 我认为这意味着我不能标记集群,只能标记奇点?

为了说明,这是一个简短的python脚本,它生成一个简单的标记树形图:

import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
from matplotlib import pyplot as plt

randomMatrix = np.random.uniform(-10,10,size=(20,3))
linked = linkage(randomMatrix, 'ward')

labelList = ["foo" for i in range(0, 20)]

plt.figure(figsize=(15, 12))
dendrogram(
            linked,
            orientation='right',
            labels=labelList,
            distance_sort='descending',
            show_leaf_counts=False
          )
plt.show()

a dendrogram of randomly generated points

现在让我们说我要截断到只有5片叶子,并且对于每片叶子,将它标记为" foo,foo,foo ...",即组成的单词那个集群。 (注意:生成这些标签不是问题。)我将其截断,并提供一个匹配的标签列表:

labelList = ["foo, foo, foo..." for i in range(0, 5)]
dendrogram(
            linked,
            orientation='right',
            p=5,
            truncate_mode='lastp',
            labels=labelList,
            distance_sort='descending',
            show_leaf_counts=False
          )

以及这里的问题,没有标签:

enter image description here

我认为这里可能有一个用于参数' leaf_label_func'但我不确定如何使用它。

2 个答案:

答案 0 :(得分:2)

使用leaf_label_func参数是正确的。

除了创建绘图之外,树形图函数还返回包含多个列表的字典(它们在文档中称为R)。您创建的leaf_label_func必须从R ["离开"]中获取值并返回所需的标签。设置标签的最简单方法是运行树形图两次。使用no_plot=True获取用于创建标签贴图的字典。然后再次创建情节。

randomMatrix = np.random.uniform(-10,10,size=(20,3))
linked = linkage(randomMatrix, 'ward')

labels = ["A", "B", "C", "D"]
p = len(labels)

plt.figure(figsize=(8,4))
plt.title('Hierarchical Clustering Dendrogram (truncated)', fontsize=20)
plt.xlabel('Look at my fancy labels!', fontsize=16)
plt.ylabel('distance', fontsize=16)

# call dendrogram to get the returned dictionary 
# (plotting parameters can be ignored at this point)
R = dendrogram(
                linked,
                truncate_mode='lastp',  # show only the last p merged clusters
                p=p,  # show only the last p merged clusters
                no_plot=True,
                )

print("values passed to leaf_label_func\nleaves : ", R["leaves"])

# create a label dictionary
temp = {R["leaves"][ii]: labels[ii] for ii in range(len(R["leaves"]))}
def llf(xx):
    return "{} - custom label!".format(temp[xx])

## This version gives you your label AND the count
# temp = {R["leaves"][ii]:(labels[ii], R["ivl"][ii]) for ii in range(len(R["leaves"]))}
# def llf(xx):
#     return "{} - {}".format(*temp[xx])


dendrogram(
            linked,
            truncate_mode='lastp',  # show only the last p merged clusters
            p=p,  # show only the last p merged clusters
            leaf_label_func=llf,
            leaf_rotation=60.,
            leaf_font_size=12.,
            show_contracted=True,  # to get a distribution impression in truncated branches
            )
plt.show()

答案 1 :(得分:1)

你可以简单地写:

hierarchy.dendrogram(Z, labels=label_list)

这是一个很好的例子,使用熊猫数据框:

import numpy as np
import pandas as pd
from scipy.cluster import hierarchy
import matplotlib.pyplot as plt

data = [[24, 16], [13, 4], [24, 11], [34, 18], [41, 
6], [35, 13]]
frame = pd.DataFrame(np.array(data), columns=["Rape", 
"Murder"], index=["Atlanta", "Boston", "Chicago", 
"Dallas", "Denver", "Detroit"])

Z = hierarchy.linkage(frame, 'single')
plt.figure()
dn = hierarchy.dendrogram(Z, labels=frame.index)