SciPy 树状图绘制

SciPy Dendrogram Plotting

我正在玩分层文档聚类,实际上我的工作流程差不多是这样的:

df = pandas.read_csv(file, delimiter='\t', index_col=0) # documents-terms matrix (very sparse)
dist_matrix = cosine_similarity(df)

linkage_matrix = ward(dist_matrix)
labels = fcluster(linkage_matrix, 5, criterion='maxclust')

然后我希望得到 5 个聚类,但是当我绘制树状图时

fig, ax = plt.subplots(figsize=(15, 20))  # set size
    ax = dendrogram(linkage_matrix, orientation="right")
    plt.tick_params( \
        axis='x',  # changes apply to the x-axis
        which='both',  # both major and minor ticks are affected
        bottom='off',  # ticks along the bottom edge are off
        top='off',  # ticks along the top edge are off
        labelbottom='off')

    plt.tight_layout()  # show plot with tight layout

    plt.savefig('ward_clusters.png', dpi=200)  # save figure as ward_clusters

我得到以下图表

根据颜色我可以看到 3 个簇,而不是 5 个!我是不是误解了树状图的意思?

  • 首先,如果你只想做5个簇,就用labels(你没有用的带fcluster的那一行)。

在标签中:数据集中的每个点都由一个数字表示。这些数字是您的集群的 ID。

  • 如果您想使用树状图并绘制 5 个不同的聚类,那么您必须 "cut" 您的树状图。

在x=5(5左右)处画一条竖线,认为左边的每个树状图都是独立的。

人工地将树状图切割成 5 个部分(或 5 个簇)。

要添加一些颜色来区分它们,只需修改以下代码(由于您没有提供数据集,我使用 iris 数据集向您展示了一种可能的解决方案)

from scipy.cluster.hierarchy import *
from sklearn.datasets import load_iris
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

iris= load_iris()

data = iris['data']
df = pd.DataFrame(data, columns = iris['feature_names'])

# Somehow, we have something equivalent to work with now
dist_matrix = cosine_similarity(df)
linkage_matrix = ward(dist_matrix)

fig, ax = plt.subplots(figsize=(20, 10))

#here just put 5 for the color_threshold, which correspond to the position of the vertical line
ax = dendrogram(linkage_matrix, color_threshold =0.7)

plt.tick_params( \
    axis='x',
    which='both',
    bottom='off',
    top='off',
    labelbottom='off')

plt.show()