解释SciPy层次聚类树形图的输出? (也许发现了一个错误...)

时间:2016-07-03 02:54:02

标签: python machine-learning scipy hierarchical-clustering dendrogram

我试图找出scipy.cluster.hierarchy.dendrogram的输出是如何工作的......我以为我知道它是如何工作的,我能够使用输出来重建树形图,但似乎我不理解它已经存在了Python 3这个模块的版本中的错误。

此答案how do I get the subtrees of dendrogram made by scipy.cluster.hierarchy表示dendrogram输出词典提供的dict_keys(['icoord', 'ivl', 'color_list', 'leaves', 'dcoord']) w /具有相同的大小,因此您可以zip他们和plt.plot他们重建树状图。

看起来很简单,当我使用Python 2.7.11时我确实恢复了工作但是一旦我升级到Python 3.5.1我的旧脚本没有给我相同的结果。

我开始重新编写我的集群以获得一个非常简单的可重复示例,并认为我可能在Python 3.5.1版本的SciPy version 0.17.1-np110py35_1中发现了一个错误。要使用Scikit-learn数据集b / c,大多数人都会从conda发行版中获得该模块。

为什么这些不排成一列,为什么我不能以这种方式重建树形图?

# Init
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()

# Load data
from sklearn.datasets import load_diabetes

# Clustering
from scipy.cluster.hierarchy import dendrogram, fcluster, leaves_list
from scipy.spatial import distance
from fastcluster import linkage # You can use SciPy one too

%matplotlib inline

# Dataset
A_data = load_diabetes().data
DF_diabetes = pd.DataFrame(A_data, columns = ["attr_%d" % j for j in range(A_data.shape[1])])

# Absolute value of correlation matrix, then subtract from 1 for disimilarity
DF_dism = 1 - np.abs(DF_diabetes.corr())

# Compute average linkage
A_dist = distance.squareform(DF_dism.as_matrix())
Z = linkage(A_dist,method="average")

# I modded the SO code from the above answer for the plot function
def plot_tree( D_dendro, ax ):
    # Set up plotting data
    leaves = D_dendro["ivl"]
    icoord = np.array( D_dendro['icoord'] )
    dcoord = np.array( D_dendro['dcoord'] )
    color_list = D_dendro["color_list"]

    # Plot colors
    for leaf, xs, ys, color in zip(leaves, icoord, dcoord, color_list):
        print(leaf, xs, ys, color, sep="\t")
        plt.plot(xs, ys,  color)

    # Set min/max of plots
    xmin, xmax = icoord.min(), icoord.max()
    ymin, ymax = dcoord.min(), dcoord.max()

    plt.xlim( xmin-10, xmax + 0.1*abs(xmax) )
    plt.ylim( ymin, ymax + 0.1*abs(ymax) )

    # Set up ticks
    ax.set_xticks( np.arange(5, len(leaves) * 10 + 5, 10))
    ax.set_xticklabels(leaves, fontsize=10, rotation=45)

    plt.show()

fig, ax = plt.subplots()
D1 = dendrogram(Z=Z, labels=DF_dism.index, color_threshold=None, no_plot=True)
plot_tree(D_dendro=D1, ax=ax)

enter image description here

attr_1  [ 15.  15.  25.  25.]   [ 0.          0.10333704  0.10333704  0.        ]   g
attr_4  [ 55.  55.  65.  65.]   [ 0.          0.26150727  0.26150727  0.        ]   r
attr_5  [ 45.  45.  60.  60.]   [ 0.          0.4917828   0.4917828   0.26150727]   r
attr_2  [ 35.   35.   52.5  52.5]   [ 0.          0.59107459  0.59107459  0.4917828 ]   b
attr_8  [ 20.    20.    43.75  43.75]   [ 0.10333704  0.65064998  0.65064998  0.59107459]   b
attr_6  [ 85.  85.  95.  95.]   [ 0.          0.60957062  0.60957062  0.        ]   b
attr_7  [ 75.  75.  90.  90.]   [ 0.          0.68142114  0.68142114  0.60957062]   b
attr_0  [ 31.875  31.875  82.5    82.5  ]   [ 0.65064998  0.72066112  0.72066112  0.68142114]   b
attr_3  [  5.       5.      57.1875  57.1875]   [ 0.          0.80554653  0.80554653  0.72066112]   b

这是一个没有标签,只有x轴的icoordenter image description here

因此检查颜色未正确映射。它表示[ 15. 15. 25. 25.]的{​​{1}}与icoord一致,但根据值看起来与attr_1一致。此外,它不会一直到最后一个叶子(attr_4),并且b / c attr_9icoord的长度比{{1}的长度少1 1}}标签。

dcoord

1 个答案:

答案 0 :(得分:3)

icoorddcoordcolor_list描述了链接,而不是叶子。 icoorddcoord给出了"拱门的坐标" (对于图中的每个链接,(即颠倒的U或J形状),color_list是这些拱的颜色。在完整的情节中,正如您所观察到的那样,icoord等的长度将比ivl的长度小一个。

请勿尝试将ivl列表与icoorddcoordcolor_list列表对齐。它们与不同的东西有关。