当我们运行分层聚类算法时,有没有一种方法可以将标签分配给数据帧?

2024-03-29 09:33:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在测试几种聚类算法,并得到了一些很好的结果。我做的最后一件事是运行一个层次聚类算法。这是我的密码

# Libraries
import pandas as pd
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
 
df = df_final[['Volume_Used', 'Biz_Expense', 'Biz_Revenue']]

 
# Calculate the distance between each sample
Z = linkage(df, 'ward')
 
# Control number of clusters in the plot + add horizontal line.
dendrogram(Z, color_threshold=240)
plt.axhline(y=240, c='grey', lw=1, linestyle='dashed')

# Show the graph
plt.show()

这就产生了这个

enter image description here

最终的结果是乱七八糟的,所以我什么都看不到,这很好。有没有办法将这些结果集群映射到数据帧?现在,我正在运行KMeans、aggregative、optics、dbscan、affinity propagation等。在每个实例中,我都会获得标签并将标签集群附加到数据帧中,只需这样做

df_final['cluster_number_optics']=labels

有没有一种方法可以为分层集群做同样的事情?我觉得应该有这样的东西,但我不知道怎么做,因为这种集群与其他类型的集群非常不同