python - 我不了解在 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
解决方案
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
它是正确的,你可以用树状图来验证
- 元素
1
,2
并4
在集群中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
推荐阅读
- python - 如何在 Python 中的 Selenium 上设置 cookie?
- python - 如何使用 pandas 数据框向绘图甘特图添加垂直线?
- python - os.path.join 用于获取级别路径
- apache-kafka - 了解kafka中间件通信
- python - 如何在同一个列表中有两个不同的排序顺序?
- mysql - 如何在 MySQL Workbench 8.0.14 中修改 mysqldump 命令参数?
- chromecast - 带有 Widevine DRM 的 Chromecast CAF
- conditional - Maximo 处理规则
- ubuntu - 如何更改仪表板管理员
- sql-server - 尝试安装 sql server express 2014 或 2008 时如何修复“库未注册”