首页 > 解决方案 > 我不了解在 fcluster 中工作的阈值的详细行为(方法 ='完成')

问题描述

Xi=[[0,5,10,8,3],[5,0,1,3,2],[10,1,0,5,1],[8,3,5,0,6] ,[3,2,1,6,0]]

Xi = 距离矩阵

shc.fcluster(shc.linkage(Xi,'complete'),9,criterion='distance')

在此代码中,阈值 = 9

聚类后​​的结果是array([3, 1, 1, 2, 1], dtype=int32)

我不明白为什么不数组 [2 ,1 ,1, 1, 1]

此图像表示聚类后 https://drive.google.com/file/d/17806FuPuNpJiqhT12jiuFOMGNUvB1vjT/view?usp=sharing

标签: pythonscipycluster-computinghierarchical-clusteringdendrogram

解决方案


import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
from scipy.spatial.distance import pdist
import matplotlib.pyplot as plt
import seaborn as sns

你有这个距离矩阵

Xi = np.array([[0,5,10,8,3],[5,0,1,3,2],[10,1,0,5,1],[8,3,5,0,6],[3,2,1,6,0]])

我们可以想象为

df = pd.DataFrame(Xi)
# fill NaNs and mask 0s
df.fillna(0, inplace=True)
mask = np.zeros_like(df)
mask[np.triu_indices_from(mask)] = True
sns.heatmap(df, annot=True, fmt='.0f', cmap="YlGnBu", mask=mask);

在此处输入图像描述

现在,我们得到 pdist

p = pdist(Xi)

和联动

Z = linkage(p, method='complete')

你设置9为阈值所以

dendrogram(Z)
plt.axhline(9, color='k', ls='--');

在此处输入图像描述

你有 3 个集群

fcluster(Z, 9, criterion='distance')

array([3, 1, 1, 2, 1], dtype=int32)
#      0  1  2  3  4   <- elements

它是正确的,你可以用树状图来验证

  • 元素124在集群中1
  • 3簇中的元素2
  • 0簇中的元素3

如果你只想要两个集群,你必须选择12,例如,作为thershold

dendrogram(Z)
plt.axhline(12, color='k', ls='--');

在此处输入图像描述

所以你有你预期的结果

fcluster(Z, 12, criterion='distance')

array([2, 1, 1, 1, 1], dtype=int32)
#      0  1  2  3  4   <- elements

推荐阅读