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:\Users\Yi\Desktop\datathon\dataExample.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", n_clusters)
32 print("to which cluster, the example belongs: \n",labels_result)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM