scipy.cluster.hierarchy.

average#

scipy.cluster.hierarchy.average(y)[source]#

對壓縮距離矩陣執行平均/UPGMA 連結法。

參數:
yndarray

距離矩陣的上三角部分。pdist 的結果會以這種形式傳回。

回傳值:
Zndarray

包含階層式分群的連結矩陣。 有關其結構的更多資訊,請參閱 linkage

另請參閱

linkage

用於進階建立階層式分群。

scipy.spatial.distance.pdist

成對距離度量

範例

>>> from scipy.cluster.hierarchy import average, fcluster
>>> from scipy.spatial.distance import pdist

首先,我們需要一個玩具資料集來玩玩

x x    x x
x        x

x        x
x x    x x
>>> X = [[0, 0], [0, 1], [1, 0],
...      [0, 4], [0, 3], [1, 4],
...      [4, 0], [3, 0], [4, 1],
...      [4, 4], [3, 4], [4, 3]]

然後,我們從這個資料集取得壓縮距離矩陣

>>> y = pdist(X)

最後,我們可以執行分群

>>> Z = average(y)
>>> Z
array([[ 0.        ,  1.        ,  1.        ,  2.        ],
       [ 3.        ,  4.        ,  1.        ,  2.        ],
       [ 6.        ,  7.        ,  1.        ,  2.        ],
       [ 9.        , 10.        ,  1.        ,  2.        ],
       [ 2.        , 12.        ,  1.20710678,  3.        ],
       [ 5.        , 13.        ,  1.20710678,  3.        ],
       [ 8.        , 14.        ,  1.20710678,  3.        ],
       [11.        , 15.        ,  1.20710678,  3.        ],
       [16.        , 17.        ,  3.39675184,  6.        ],
       [18.        , 19.        ,  3.39675184,  6.        ],
       [20.        , 21.        ,  4.09206523, 12.        ]])

連結矩陣 Z 代表樹狀圖 - 有關其內容的詳細說明,請參閱 scipy.cluster.hierarchy.linkage

我們可以利用 scipy.cluster.hierarchy.fcluster 來查看在給定距離閾值的情況下,每個初始點將屬於哪個群集

>>> fcluster(Z, 0.9, criterion='distance')
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
>>> fcluster(Z, 1.5, criterion='distance')
array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
>>> fcluster(Z, 4, criterion='distance')
array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32)
>>> fcluster(Z, 6, criterion='distance')
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)

此外,scipy.cluster.hierarchy.dendrogram 可以用來產生樹狀圖的繪圖。