什麼是 scipy 叢集層次?如何將層次聚類轉換為平面聚類?
scipy.cluster.hierarchy 模組提供了分層聚類及其型別的函式,例如凝聚聚類。它有各種程式,我們可以用這些程式來 −
將分層聚類轉換為平面聚類。
實現凝聚聚類。
在層次結構上計算統計資料
將平面聚類視覺化。
檢查兩個平面叢集分配的同構性。
繪製叢集。
程式 scipy.cluster.hierarchy.fcluster 用於將分層聚類剪下為平面聚類,它們作為結果獲取原始資料點分配到單個叢集。讓我們藉助以下示例來理解這個概念 −
示例
#Importing the packages from scipy.cluster.hierarchy import ward, fcluster from scipy.spatial.distance import pdist #The cluster linkage method i.e., scipy.cluster.hierarchy.ward will generate a linkage matrix as their output: A = [ [0, 0], [0, 1], [1, 0], [0, 3], [0, 2], [1, 4], [3, 0], [2, 0], [4, 1], [3, 3], [2, 3], [4, 3] ] X = ward(pdist(A)) print(X)
輸出:
[[ 0. 1. 1. 2. ] [ 2. 7. 1. 2. ] [ 3. 4. 1. 2. ] [ 9. 10. 1. 2. ] [ 6. 8. 1.41421356 2. ] [11. 15. 1.73205081 3. ] [ 5. 14. 2.081666 3. ] [12. 13. 2.23606798 4. ] [16. 17. 3.94968353 5. ] [18. 19. 5.15012714 7. ] [20. 21. 6.4968857 12. ]]
以上輸出中接收的矩陣 X 表示樹狀圖。在這個樹狀圖中,第一個和第二個元素是每一步合併的兩個叢集。這些叢集之間的距離由上述樹狀圖的第三個元素給出。第四個元素提供了新叢集的大小。
#Flatting the dendrogram by using fcluster() where the assignation of the original data points to single clusters mostly depend on the distance threshold t. fcluster(X, t=1.5, criterion='distance') #when t= 1.5
輸出:
array([6, 6, 7, 4, 4, 5, 1, 7, 1, 2, 2, 3], dtype=int32)
示例
fcluster(X, t=0.9, criterion='distance') #when t= 0.9
輸出:
array([ 9, 10, 11, 6, 7, 8, 1, 12, 2, 3, 4, 5], dtype=int32)
示例
fcluster(X, t=9, criterion='distance') #when t= 9
輸出:
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
廣告