Spectral Clustering 并用silhouette指标值确定最优聚类数目

clusterDatathon.py 说明:

输入:(dataExample)

 

处理:选择一系列的cluster数目,进行spectral clustering(经过比较,感觉spectral clustering可能效果好一点),通过silhouette指标值确定最优聚类数目

输出:

 代码如下:

 1 import pandas as pd
 2 import numpy as np
 3 from sklearn import metrics
 4 from sklearn.cluster import SpectralClustering
 5 
 6 ##读入data
 7 dfs = pd.read_excel(r"C:UsersYiDesktopdatathondataExample.xls")
 8 dfs = dfs.values
 9 [n_examples,n_features]=dfs.shape
10 
11 ##用spectral clustering
12 ##用一系列的cluster数目,根据silhouette指标值确定最优分类数目
13 small=5
14 large=40
15 silScore=np.zeros([1,large-small+1])
16 
17 for i in range(small,large):
18     clustering_i = SpectralClustering(n_clusters=i,assign_labels="discretize",random_state=5).fit(dfs)
19     labels = clustering_i.labels_
20     silScore[0,i-small]=metrics.silhouette_score(dfs, labels, metric='euclidean')
21 
22 ##找到silhouette指标值最大时 cluster数目                                               
23 index=np.argmax(silScore)
24 
25 ##此时的聚类结果
26 n_clusters=index+small
27 cluster_result=SpectralClustering(n_clusters,assign_labels="discretize",random_state=5).fit(dfs)
28 labels_result=cluster_result.labels_
29 
30 ##输出各example的所属类
31 print("the number of clusters: 
", n_clusters)
32 print("to which cluster, the example belongs: 
",labels_result)
原文地址:https://www.cnblogs.com/yizhaoAI/p/10399800.html