TShopping

 找回密碼
 註冊
搜索
查看: 1445|回復: 0
打印 上一主題 下一主題

[教學] Scikit-Learn 演算法 分群

[複製鏈接]
跳轉到指定樓層
1#
發表於 2021-5-27 16:59:47 | 只看該作者 |只看大圖 回帖獎勵 |倒序瀏覽 |閱讀模式
 
Push to Facebook
程式碼
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import pandas as pd
  4. from sklearn import datasets

  5. iris=datasets.load_iris() #下載資料
  6. X=iris.data
  7. X=X[:,2:4]

  8. from sklearn.cluster import AgglomerativeClustering
  9. #Sklearn
  10. # n_clusters: 要分成幾群 ,給定數值
  11. # affinity: 距離的計算方式,"euclidean","l1","l2","manhattan","cosine"...¶
  12. # linkage: 群與群之間的距離,"ward","complete","average","single"
  13. ml=AgglomerativeClustering(n_clusters=3,affinity='euclidean',linkage='ward')
  14. ml.fit_predict(X)
  15. plt.scatter(X[:,0],X[:,1],c=ml.fit_predict(X))
  16. plt.show()
複製代碼


輸出 array
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,       1, 1, 1, 1, 1, 1, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,       2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2,       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int64)



程式碼
  1. # Scipy
  2. # metric: 距離的計算方式
  3. # method: 群與群之間的計算方式,"single", "complete", "average", "weighted", "centroid", "median", "ward"
  4. import scipy.cluster.hierarchy as sch
  5. dis=sch.linkage(X,metric='euclidean',method='ward')
  6. sch.dendrogram(dis)
  7. plt.title('Hierarchical Clustering')
  8. plt.show()
複製代碼


程式碼
  1. max_dis=5
  2. clusters=sch.fcluster(dis,max_dis,criterion='distance')
  3. clusters
  4. print('clusters',clusters)
  5. plt.scatter(X[:,0],X[:,1],c=clusters)
  6. plt.show()
複製代碼



程式碼
  1. k=5
  2. clusters=sch.fcluster(dis,k,criterion='maxclust')
  3. plt.scatter(X[:,0],X[:,1],c=clusters)
  4. plt.show()
複製代碼


來源

 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-5-6 04:54 , Processed in 0.080800 second(s), 25 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表