python凝聚聚类算法中如何打印每个聚类的数据

2024-05-16 03:41:54 发布

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

我是python机器学习工具的新手,我编写了凝聚层次聚类的代码,但我不知道是否有任何方法可以打印每个图簇的数据。 算法的输入是5个数字(0,1,2,3,4),除了绘制簇外,我还需要单独打印每个簇的值,如下所示 cluster1=[1,2,4] cluster2=[0,3]

更新:我想获得根据这条线和其他线绘制和着色的数据plt.scatter(points[y_hc==0,0], points[y_hc==0,1],s=100,c='cyan'),根据此代码,这些数字(1,2,4)在一个簇中,具有相同的颜色,(0,3)在簇2中,因此,我需要在终端中打印这些数据(每个簇的数据)。此代码只是绘图数据

import numpy as np 
import matplotlib.pyplot as plt 
from sklearn.datasets import make_blobs
dataset= make_blobs(n_samples=5, n_features=2,centers=4, cluster_std=1.6, random_state=50)
points= dataset[0]

import scipy.cluster.hierarchy as sch 
from sklearn.cluster import AgglomerativeClustering

dendrogram = sch.dendrogram(sch.linkage(points,method='ward'))
plt.scatter(dataset[0][:,0],dataset[0][:,1])
hc = AgglomerativeClustering(n_clusters=4, affinity='euclidean',linkage='ward')
y_hc= hc.fit_predict(points)
plt.scatter(points[y_hc==0,0], points[y_hc==0,1],s=100,c='cyan')
plt.scatter(points[y_hc==1,0], points[y_hc==1,1],s=100,c='yellow')
plt.scatter(points[y_hc==2,0], points[y_hc==2,1],s=100,c='red')
plt.scatter(points[y_hc==3,0], points[y_hc==3,1],s=100,c='green')
plt.show()

Tags: 数据代码fromhcimportas绘制plt
1条回答
网友
1楼 · 发布于 2024-05-16 03:41:54

做了一些研究之后,似乎没有一种简单的方法可以从scipydendrogram函数中获取集群标签

下面是几个选项/解决方法

选择一

使用scipylinkagefcluster函数执行聚类并获取标签:

Z = sch.linkage(points, 'ward') # Note 'ward' is specified here to match the linkage used in sch.dendrogram.
labels = sch.fcluster(Z, t=10, criterion='distance') # t chosen to return two clusters.

# Cluster 1
np.where(labels == 1)

输出:(array([0, 3]),)

# Cluster 2
np.where(labels == 2)

输出:(array([1, 2, 4]),)

选择二

修改当前对sklearn的使用以返回两个集群:

hc = AgglomerativeClustering(n_clusters=2, affinity='euclidean',linkage='ward') # Again, 'ward' is specified here to match the linkage in sch.dendrogram.
y_hc = hc.fit_predict(points)

# Cluster 1
np.where(y_hc == 0)

输出:(array([0, 3]),)

# Cluster 2
np.where(y_hc == 1)

输出:(array([1, 2, 4]),)

相关问题 更多 >