All Revision Notes

COM6004 Data Mining · Chapter 5

Cluster Analysis: K-means, Hierarchical & DBSCAN

COM6004 · Chapter 5 · Source: COM6004_Chapter_5_Cluster_Analysis.pptx (94 slides) · Cluster Analysis, K-means, Hierarchical Clustering, Cluster Validity, DBSCAN (optional)

Contents · 9 sections

🎯 本講重點 (Learning outcomes)

  • 定義 cluster analysis;分辨 partitional vs hierarchical clusterings,以及 exclusive / fuzzy / partial / heterogeneous 等 distinctions。
  • 認識四種 cluster types:well-separated、center-based、contiguity-based、density-based。
  • 識手計 K-means(assign → update centroid → repeat)同 SSE;理解 initial centroids 問題、K-means++、K-means 嘅 limitations 同 pre/post-processing。
  • 識手做 agglomerative hierarchical clustering(MIN / MAX / Group Average),畫 dendrogram,理解各自優缺點同 time / space complexity。
  • 用 internal measures 評估 clusters:correlation、similarity matrix、SSE(elbow)、cohesion & separation(SSE / SSB)、Silhouette coefficient。
  • DBSCAN(optional):core / border / noise points、algorithm、優缺點、點揀 Eps 同 MinPts。

⭐ 考試必溫 Top-5

  1. K-means 手計 iterations + SSE=∑i∑x∈Cidist2(mi,x)SSE = \sum_i \sum_{x\in C_i} \text{dist}^2(m_i, x)。
  2. Agglomerative clustering 用 MIN / MAX / Group Average 更新 proximity matrix 同畫 dendrogram。
  3. Silhouette coefficient s=(b−a)/max⁡(a,b)s = (b - a)/\max(a, b) 計算同解讀。
  4. K-means limitations(differing sizes、densities、non-globular shapes、outliers)同 initial centroids 問題(P=K!/KKP = K!/K^K,K=10K = 10 時 0.00036)、K-means++。
  5. MIN(處理 non-elliptical shapes,但對 noise 敏感)vs MAX(較唔受 noise 影響,但會打散大 cluster、偏向 globular)vs Group Average(折衷)。

1. What is Cluster Analysis?

ExamSlide 4:Finding groups of objects such that the objects in a group will be similar (or related) to one another and different from (or unrelated to) the objects in other groups.

  • Intra-cluster distances are minimized
  • Inter-cluster distances are maximized

Applications (slide 5):

  • Understanding:Group related documents for browsing、group genes and proteins that have similar functionality、group stocks with similar price fluctuations。
  • Summarization:Reduce the size of large data sets(例:Clustering precipitation in Australia)。

Notion of a Cluster can be Ambiguous (slide 6):同一組點可以睇成 Two Clusters、Four Clusters 或 Six Clusters——"How many clusters?" 冇唯一答案,視乎 granularity 同應用。

2. Types of Clusterings

Slide 7:A clustering is a set of clusters。重要區分:

Partitional ClusteringHierarchical Clustering
定義A division of data objects into non-overlapping subsets (clusters) such that each data object is in exactly one subsetA set of nested clusters organized as a hierarchical tree
表示 (slides 8–9)平面上一組分開嘅 groupsDendrogram(traditional:binary tree;non-traditional:一個 node 可有多個 children)
例子演算法K-means、DBSCANAgglomerative(MIN、MAX、Group Average)、Divisive
🖼️ 圖片內容

Slides 8–9 嘅 partitional clustering 圖同 traditional / non-traditional hierarchical clustering 及 dendrograms 係圖片,請對照原 slide。

2.1 Other Distinctions Between Sets of Clusters (Slide 10)

Distinction說明
Exclusive vs non-exclusiveNon-exclusive clusterings:points may belong to multiple clusters(可以代表 multiple classes 或 'border' points)。
Fuzzy vs non-fuzzyFuzzy clustering:一個 point 以 0 至 1 嘅 weight 屬於每個 cluster;weights must sum to 1。Probabilistic clustering 有類似特性。
Partial vs complete有時只想 cluster 部分 data(例如唔理 noise)。
Heterogeneous vs homogeneousClusters 嘅 sizes、shapes、densities 可以差好遠。

3. Types of Clusters

⭐ 考試重點:四種 cluster 定義 (Slides 11–15)
TypeSlide 定義Slide 圖例
Well-separatedA cluster is a set of points such that any point in a cluster is closer (or more similar) to every other point in the cluster than to any point not in the cluster.3 well-separated clusters
Center-basedAn object in a cluster is closer to the "center" of a cluster than to the center of any other cluster. Center 通常係 centroid(cluster 所有點嘅平均)或 medoid(最 "representative" 嘅實際點)。4 center-based clusters
Contiguity-based(Nearest neighbor / Transitive)A point in a cluster is closer to one or more other points in the cluster than to any point not in the cluster.8 contiguous clusters
Density-basedA cluster is a dense region of points, separated by low-density regions from other regions of high density. Used when the clusters are irregular or intertwined, and when noise and outliers are present.6 density-based clusters
💡 直覺理解

Well-separated 最嚴格(要比所有外面點近過所有內部點)。Center-based 係 K-means 嘅假設(圓形 / globular clusters)。Contiguity 好似「手拉手」嘅鏈條——只要同鄰居近就算同組(MIN / single link 嘅 idea)。Density-based 係 DBSCAN 嘅 idea:密集區就係 cluster,稀疏區係分界或者 noise。

3.1 Characteristics of the Input Data Are Important (Slide 16)

  • Type of proximity or density measure:central to clustering,視乎 data 同 application。
  • 影響 proximity / density 嘅 data characteristics:Dimensionality、Sparseness(curse of dimensionality)、Attribute type、Special relationships in the data(例如 autocorrelation)、Distribution of the data。
  • Noise and Outliers:often interfere with the operation of the clustering algorithm。

Slide 17:本 chapter 主要講 K-means clustering 同 Hierarchical clustering(另附 DBSCAN optional)。

4. K-means Clustering

Slide 19:

  • Partitional clustering approach
  • Number of clusters, K, must be specified
  • Each cluster is associated with a centroid (center point)
  • Each point is assigned to the cluster with the closest centroid
  • The basic algorithm is very simple:
⭐ 考試重點:Basic K-means Algorithm
1: Select K points as the initial centroids.
2: repeat
3:     Form K clusters by assigning all points to the closest centroid.
4:     Recompute the centroid of each cluster.
5: until The centroids don't change
🖼️ 圖片內容

Slide 19 嘅 algorithm 框同 slides 20–21 嘅 K-means iteration 動畫圖係圖片;上面 algorithm 係教科書標準版本,請對照原 slide。

4.1 K-means Details (Slide 22)

  • Initial centroids are often chosen randomly → clusters produced vary from one run to another。
  • Centroid is (typically) the mean of the points in the cluster。
  • 'Closeness' is measured by Euclidean distance, cosine similarity, correlation, etc.
  • K-means will converge for common similarity measures mentioned above。
  • Most of the convergence happens in the first few iterations;stopping condition 常改為 'Until relatively few points change clusters'。
  • ExamComplexity is O(n×K×I×d)O(n \times K \times I \times d):n = number of points,K = number of clusters,I = number of iterations,d = number of attributes。

4.2 Worked example:1-D K-means(自擬)

⭐ 考試重點:手計 K-means

Points:2, 3, 4, 10, 11, 12, 20, 25, 30;K=2K = 2;initial centroids c1=2c_1 = 2,c2=12c_2 = 12。

Iteration 1:assign 去最近 centroid:

  • C1C_1 (c=2c = 2):{2, 3, 4}(例如 4:|4−2| = 2 < |4−12| = 8)
  • C2C_2 (c=12c = 12):{10, 11, 12, 20, 25, 30}(例如 10:|10−2| = 8 > |10−12| = 2)
  • Update:c1=(2+3+4)/3=c_1 = (2+3+4)/3 = 3;c2=(10+11+12+20+25+30)/6=108/6=c_2 = (10+11+12+20+25+30)/6 = 108/6 = 18

Iteration 2(c1=3c_1 = 3, c2=18c_2 = 18):

  • 10:|10−3| = 7 < |10−18| = 8 → C1C_1;11:8 > 7 → C2C_2
  • C1={2,3,4,10}C_1 = \{2, 3, 4, 10\};C2={11,12,20,25,30}C_2 = \{11, 12, 20, 25, 30\}
  • Update:c1=19/4=c_1 = 19/4 = 4.75;c2=98/5=c_2 = 98/5 = 19.6

Iteration 3(c1=4.75c_1 = 4.75, c2=19.6c_2 = 19.6):

  • 11:|11−4.75| = 6.25 < 8.6 → C1C_1;12:7.25 < 7.6 → C1C_1
  • C1={2,3,4,10,11,12}C_1 = \{2, 3, 4, 10, 11, 12\};C2={20,25,30}C_2 = \{20, 25, 30\}
  • Update:c1=42/6=c_1 = 42/6 = 7;c2=75/3=c_2 = 75/3 = 25

Iteration 4(c1=7c_1 = 7, c2=25c_2 = 25):assignment 冇變 → centroids 冇變 → converged。

SSE = C1C_1:(2−7)2+(3−7)2+(4−7)2+(10−7)2+(11−7)2+(12−7)2=25+16+9+9+16+25=100(2-7)^2 + (3-7)^2 + (4-7)^2 + (10-7)^2 + (11-7)^2 + (12-7)^2 = 25+16+9+9+16+25 = 100;C2C_2:(20−25)2+0+(30−25)2=50(20-25)^2 + 0 + (30-25)^2 = 50 → SSE=150SSE = 150。

每次 iteration 嘅 SSE(用 update 後 centroid 計):348 → 307.95 → 150,單調下降。

import numpy as np
from sklearn.cluster import KMeans
X = np.array([2, 3, 4, 10, 11, 12, 20, 25, 30]).reshape(-1, 1)
km = KMeans(n_clusters=2, init=np.array([[2], [12]]), n_init=1).fit(X)
km.labels_, km.cluster_centers_, km.inertia_      # inertia_ = SSE = 150

4.3 Evaluating K-means Clusters: SSE (Slide 23)

Most common measure is Sum of Squared Error (SSE):每個 point 嘅 error = 佢同最近 cluster(centroid)嘅距離;將 errors 平方再加總:

SSE=∑i=1K∑x∈Cidist2(mi,x)SSE = \sum_{i=1}^{K} \sum_{x \in C_i} \text{dist}^2(m_i, x)

xx 係 cluster CiC_i 入面嘅 data point,mim_i 係 cluster CiC_i 嘅 representative point。可以證明令 SSE 最細嘅 mim_i 就係 cluster 嘅 center (mean)。

  • Given two sets of clusters, we prefer the one with the smallest error。
  • ExamOne easy way to reduce SSE is to increase K(K=nK = n 時 SSE=0SSE = 0!所以唔可以單靠 SSE 揀 K)。
  • A good clustering with smaller K can have a lower SSE than a poor clustering with higher K。

Slide 24 "Two different K-means Clusterings":同一組 original points,可以得到 Optimal Clustering 或 Sub-optimal Clustering——取決於 initial centroids。

4.4 Importance of Choosing Initial Centroids (Slides 25–31)

Slides 25–26 圖示:好嘅 initial centroids 幾個 iterations 就搵到 optimal;差嘅 initial centroids 會卡喺 sub-optimal(local minimum)。

ExamSlide 27:如果有 K 個 'real' clusters,揀到每個 cluster 各一個 initial centroid 嘅機會好細,K 越大越細。如果每個 cluster 大小都係 n:

P=number of ways to select one centroid from each clusternumber of ways to select K centroids=K! nK(Kn)K=K!KKP = \frac{\text{number of ways to select one centroid from each cluster}}{\text{number of ways to select } K \text{ centroids}} = \frac{K!\,n^K}{(Kn)^K} = \frac{K!}{K^K}

例如 K=10K = 10:P=10!/1010=3,628,800/10,000,000,000=P = 10!/10^{10} = 3{,}628{,}800 / 10{,}000{,}000{,}000 = 0.00036。(K=3K = 3:3!/27 = 0.222;K=5K = 5:120/3125 = 0.0384。)

有時 initial centroids 會自己 readjust 去「正確」位置,有時唔會。Five pairs of clusters 例子(10 clusters,slides 28–31):

  • Slides 28–29:Starting with two initial centroids in one cluster of each pair of clusters → 每對 clusters 有兩個 centroids,結果可以正確分開。
  • Slides 30–31:Starting with some pairs of clusters having three initial centroids, while others have only one → 有一個 centroid 嘅嗰對 clusters 會被合併成一個,有三個 centroids 嘅會將一個 cluster 錯誤切開。
🖼️ 圖片內容

Slides 20–21、24–31 嘅 K-means iteration 圖、optimal / sub-optimal clustering 同 10-cluster 例子全部係圖片,請對照原 slide。

4.5 Solutions to Initial Centroids Problem (Slide 32)

  • Multiple runs:有幫助,但 probability is not on your side(K 大時要好多次);揀 SSE 最細嗰次。
  • Sample and use hierarchical clustering to determine initial centroids。
  • Generate a larger number of clusters and then perform a hierarchical clustering(merging the clusters)。
  • Select more than k initial centroids and then select among these initial centroids(e.g., select most widely separated)。
  • Use some strategy to select the k initial centroids:K-means++ is a robust way of doing this selection。

4.6 K-means++ (Slide 33)

比 random initialization 慢,但 very consistently produces better results in terms of SSE;保證 approximation ratio O(log⁡k)O(\log k) in expectation。

⭐ 考試重點:K-means++ 步驟
  1. Select an initial point at random to be the first centroid。
  2. For k−1k - 1 steps:
    • For each of the N points xix_i,搵佢同目前已選 centroids C1,…,CjC_1, \dots, C_j 嘅 minimum squared distance:d(xi)=min⁡j∥xi−Cj∥2d(x_i) = \min_j \|x_i - C_j\|^2。
    • Randomly select a new centroid by choosing a point with probability proportional to d(xi)/∑id(xi)d(x_i) / \sum_i d(x_i)。
  3. End For
💡 Worked example(自擬)

Points:0, 1, 5, 6, 10。第一個 centroid 隨機揀咗 0。

Squared distance to nearest centroid:0, 1, 25, 36, 100 → 總和 162。

揀第二個 centroid 嘅概率:0 → 0;1 → 1/162 = 0.006;5 → 25/162 = 0.154;6 → 36/162 = 0.222;10 → 100/162 = 0.617。

即係越遠嘅點越大機會被揀,令 centroids 自然分散,但仍有隨機性(唔會一定揀 outlier)。

4.7 Limitations of K-means (Slides 34–40)

⭐ 考試重點:K-means limitations

K-means has problems when clusters are of differing:

  • Sizes(slide 35:大 cluster 被切開,部分分去細 cluster)
  • Densities(slide 36:密嘅細 clusters 同疏嘅大 cluster 被錯誤劃分)
  • Non-globular shapes(slide 37:例如兩個半月形 / 環形,K-means 只會切成兩半圓)

K-means has problems when the data contains outliers(mean 被拉走;SSE 用平方,outlier 影響更大)。One possible solution is to remove outliers before clustering。

Overcoming K-means Limitations (slides 38–40):One solution is to find a large number of clusters such that each of them represents a part of a natural cluster. But these small clusters need to be put together in a post-processing step.

💡 直覺理解

K-means 用 centroid + Euclidean distance,等於假設每個 cluster 係「大小相若嘅圓球」,而 cluster 之間嘅分界係兩個 centroids 嘅垂直平分線。任何違反呢個假設嘅情況(大細唔同、密度唔同、形狀唔係圓)都會出錯。

4.8 Pre-processing and Post-processing (Slide 41)

Pre-processingPost-processing
  • Normalize the data(attributes scale 唔同會令 distance 偏向某 attribute)
  • Eliminate outliers
  • Eliminate small clusters that may represent outliers
  • Split 'loose' clusters, i.e., clusters with relatively high SSE
  • Merge clusters that are 'close' and that have relatively low SSE

5. Hierarchical Clustering

Slide 43:Produces a set of nested clusters organized as a hierarchical tree;can be visualized as a dendrogram——a tree like diagram that records the sequences of merges or splits(y 軸係 merge 時嘅距離)。

Strengths (slide 44):

  • Do not have to assume any particular number of clusters:any desired number of clusters can be obtained by 'cutting' the dendrogram at the proper level。
  • They may correspond to meaningful taxonomies:例如 biological sciences 嘅 animal kingdom(slide notes:Vertebrates → Mammals(Primates、Rodents、Carnivores)、Birds、Reptiles、Fish;Invertebrates → Arthropods、Mollusks、Annelids)。

5.1 Agglomerative vs Divisive (Slide 45)

Agglomerative(bottom-up)Divisive(top-down)
Start with the points as individual clusters;at each step, merge the closest pair of clusters until only one cluster (or k clusters) left Start with one, all-inclusive cluster;at each step, split a cluster until each cluster contains an individual point (or there are k clusters)

Traditional hierarchical algorithms use a similarity or distance matrix,merge or split one cluster at a time。

5.2 Agglomerative Clustering Algorithm (Slides 46–50)

⭐ 考試重點:Algorithm
1. Compute the proximity matrix
2. Let each data point be a cluster
3. Repeat
4.     Merge the two closest clusters
5.     Update the proximity matrix
6. Until only a single cluster remains

Key operation is the computation of the proximity of two clusters:different approaches to defining the distance between clusters distinguish the different algorithms。

Slides 47–50:Starting situation(每點一個 cluster + proximity matrix)→ intermediate situation(clusters C1…C5)→ 要 merge 最近嘅 C2 同 C5 → merge 後問題:"How do we update the proximity matrix?"(C2 ∪ C5 嗰行 / 列要重新計)。

5.3 How to Define Inter-Cluster Distance (Slides 51–55)

⭐ 考試重點:四種定義
方法定義公式
MIN (Single Link)兩個 clusters 中最近嗰對點嘅距離(determined by one pair of points, i.e., by one link in the proximity graph)d(Ci,Cj)=min⁡p∈Ci,q∈Cjd(p,q)d(C_i, C_j) = \min_{p \in C_i, q \in C_j} d(p, q)
MAX (Complete Linkage)兩個 clusters 中最遠嗰對點嘅距離(determined by all pairs of points)d(Ci,Cj)=max⁡p∈Ci,q∈Cjd(p,q)d(C_i, C_j) = \max_{p \in C_i, q \in C_j} d(p, q)
Group Average兩 clusters 之間所有 pairwise proximity 嘅平均d(Ci,Cj)=∑p∈Ci∑q∈Cjd(p,q)∣Ci∣×∣Cj∣d(C_i, C_j) = \dfrac{\sum_{p \in C_i}\sum_{q \in C_j} d(p, q)}{|C_i| \times |C_j|}
Distance Between Centroids兩個 centroids 之間嘅距離d(Ci,Cj)=d(mi,mj)d(C_i, C_j) = d(m_i, m_j)
🖼️ 圖片內容

Slides 56–65 嘅六點例子(點坐標、distance matrix、nested clusters 圖同 dendrograms for MIN / MAX / Group Average)係圖片,擷取不到具體數值;以下 worked example 用自擬 distance matrix。

5.4 Worked example:MIN / MAX / Group Average(自擬)

五點 a–e 嘅 distance matrix:

abcde
a026109
b20598
c65045
d109403
e98530
⭐ 考試重點:逐步 merge

Step 1(三種方法都一樣):最細距離 d(a,b)=2d(a, b) = 2 → merge {a, b} at height 2。

Step 2:更新 {a,b} 同其他點:

  • MIN:d({ab},c)=min⁡(6,5)=5d(\{ab\}, c) = \min(6, 5) = 5;d({ab},d)=min⁡(10,9)=9d(\{ab\}, d) = \min(10, 9) = 9;d({ab},e)=min⁡(9,8)=8d(\{ab\}, e) = \min(9, 8) = 8
  • MAX:d({ab},c)=max⁡(6,5)=6d(\{ab\}, c) = \max(6, 5) = 6;d({ab},d)=10d(\{ab\}, d) = 10;d({ab},e)=9d(\{ab\}, e) = 9
  • Avg:d({ab},c)=5.5d(\{ab\}, c) = 5.5;d({ab},d)=9.5d(\{ab\}, d) = 9.5;d({ab},e)=8.5d(\{ab\}, e) = 8.5

剩低最細係 d(d,e)=3d(d, e) = 3 → merge {d, e} at height 3(三種方法都係)。

Step 3:而家 clusters = {a,b}, c, {d,e}:

d(c,{de})d(c, \{de\})d({ab},c)d(\{ab\}, c)d({ab},{de})d(\{ab\}, \{de\})Merge
MINmin(4, 5) = 45min(10,9,9,8) = 8c + {d,e} at 4
MAXmax(4, 5) = 56max(10,9,9,8) = 10c + {d,e} at 5
Avg(4+5)/2 = 4.55.5(10+9+9+8)/4 = 9c + {d,e} at 4.5

Step 4:最後 merge {a,b} 同 {c,d,e}:

  • MIN:min(6, 10, 9, 5, 9, 8) = 5
  • MAX:max(…) = 10
  • Avg:(6+10+9+5+9+8)/6 = 47/6 = 7.83

Dendrogram(MIN):a–b @2,d–e @3,c–{de} @4,{ab}–{cde} @5。
Dendrogram(MAX):a–b @2,d–e @3,c–{de} @5,{ab}–{cde} @10。
如果 cut 成 2 clusters:三種方法都得 {a, b} 同 {c, d, e}。

MIN dendrogram(高度 = merge 距離)
 5 ┤       ┌─────┴─────┐
 4 ┤       │        ┌──┴──┐
 3 ┤       │        │   ┌─┴─┐
 2 ┤    ┌──┴──┐     │   │   │
   └────a─────b─────c───d───e──
from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.spatial.distance import squareform
D = [[0,2,6,10,9],[2,0,5,9,8],[6,5,0,4,5],[10,9,4,0,3],[9,8,5,3,0]]
for m in ["single", "complete", "average"]:      # MIN, MAX, Group Average
    print(m, linkage(squareform(D), method=m))
dendrogram(linkage(squareform(D), "single"), labels=list("abcde"))

5.5 MIN (Single Link): Strength & Limitations (Slides 56–59)

  • Strength:Can handle non-elliptical shapes(slide 58:six clusters,可以沿住鏈狀 / 彎曲形狀連埋一齊)。
  • Limitation:Sensitive to noise(slide 59:noise points 可以喺兩個 clusters 之間「搭橋」,令佢哋被 chain 埋一齊——chaining effect)。

5.6 MAX (Complete Linkage): Strength & Limitations (Slides 60–63)

  • Strength:Less susceptible to noise(slide 62)。
  • Limitations:Tends to break large clusters;Biased towards globular clusters(slide 63)。

5.7 Group Average (Slides 64–66)

  • Proximity of two clusters is the average of pairwise proximity between points in the two clusters。
  • Need to use average connectivity for scalability since total proximity favors large clusters(所以要除以 ∣Ci∣×∣Cj∣|C_i| \times |C_j|)。
  • Compromise between Single and Complete Link。
  • Strengths:Less susceptible to noise and outliers。Limitations:Biased towards globular clusters。
⭐ 考試重點:比較表
LinkageStrengthLimitation
MIN (single)Non-elliptical shapesSensitive to noise & outliers (chaining)
MAX (complete)Less susceptible to noiseBreaks large clusters;biased towards globular
Group AverageLess susceptible to noise & outliers(折衷)Biased towards globular

5.8 Time and Space Requirements (Slide 67)

  • O(N2)O(N^2) space since it uses the proximity matrix(N = number of points)。
  • O(N3)O(N^3) time in many cases:there are N steps and at each step the size N2N^2 proximity matrix must be updated and searched。
  • Complexity can be reduced to O(N2log⁡(N))O(N^2 \log(N)) time with some cleverness。

對比 K-means 嘅 O(n⋅K⋅I⋅d)O(n\cdot K\cdot I\cdot d),hierarchical clustering 對大 data sets 慢好多。

5.9 Problems and Limitations (Slide 68)

  • Once a decision is made to combine two clusters, it cannot be undone(greedy)。
  • No global objective function is directly minimized(唔似 K-means minimize SSE)。
  • Different schemes have problems with one or more of:sensitivity to noise and outliers;difficulty handling clusters of different sizes and non-globular shapes;breaking large clusters。

6. Cluster Validity

Slide 70:Supervised classification 有 accuracy、precision、recall 等 measures。Cluster analysis 嘅對應問題係:點樣評估 clusters 嘅 "goodness"?但 "clusters are in the eye of the beholder"! 咁點解仲要評估?

  • To avoid finding patterns in noise(K-means 喺 random data 上都會「搵到」K 個 clusters!)
  • To compare clustering algorithms
  • To compare two sets of clusters
  • To compare two clusters

6.1 Different Aspects of Cluster Validation (Slide 71)

  1. Determining the clustering tendency of a set of data, i.e., distinguishing whether non-random structure actually exists in the data。
  2. Comparing the results of a cluster analysis to externally known results, e.g., to externally given class labels(external index)。
  3. Evaluating how well the results of a cluster analysis fit the data without reference to external information(use only the data → internal index)。
  4. Comparing the results of two different sets of cluster analyses to determine which is better。
  5. Determining the 'correct' number of clusters。

For 2, 3, and 4, we can further distinguish whether we want to evaluate the entire clustering or just individual clusters。

6.2 Measures of Cluster Validity Via Correlation (Slides 72–73)

兩個 matrices:

  • Proximity Matrix
  • Ideal Similarity Matrix:每個 data point 一行一列;entry = 1 if the pair belongs to the same cluster,0 if different clusters。

計兩個 matrices 嘅 correlation。因為 matrices 係 symmetric,只需要計 n(n−1)/2n(n-1)/2 個 entries。High correlation 表示同一 cluster 嘅點互相接近。Not a good measure for some density or contiguity-based clusters.

⚠️ 留意符號

如果用 distance matrix(而唔係 similarity),好 clustering 嘅 correlation 會係負數(同 cluster → ideal = 1 而 distance 細)。教科書例子(slide 73)兩個 data sets 嘅 correlation 分別約 −0.92(清晰 clusters)同 −0.58(random data)——數字以 slide 圖為準。

6.3 Using Similarity Matrix for Cluster Validation (Slides 74–76)

Order the similarity matrix with respect to cluster labels and inspect visually. 好嘅 clustering 會見到對角線上有清晰嘅高相似度方塊。Clusters in random data are not so crisp(slides 75–76:DBSCAN、K-means、Complete Link 喺 random data 上嘅方塊都模糊)。

🖼️ 圖片內容

Slides 73–78、80–81、83 嘅 similarity matrix 圖、SSE curves、histogram 同 cohesion / separation 圖係圖片,請對照原 slide。

6.4 Internal Measures: SSE (Slides 77–78)

Internal Index:used to measure the goodness of a clustering structure without respect to external information,例如 SSE。

  • SSE is good for comparing two clusterings or two clusters(average SSE)。
  • Can also be used to estimate the number of clusters:畫 SSE vs K 曲線,搵 "knee / elbow"(SSE 急跌之後變平嘅位置)。
  • Clusters in more complicated figures aren't well separated(slide 78:SSE curve for a more complicated data set,elbow 未必明顯)。
sse = [KMeans(n_clusters=k, n_init=10, random_state=0).fit(X).inertia_ for k in range(1, 11)]
plt.plot(range(1, 11), sse, "o-"); plt.xlabel("K"); plt.ylabel("SSE")   # 搵 elbow

6.5 Framework for Cluster Validity (Slides 79–81)

  • Need a framework to interpret any measure:例如 evaluation measure = 10,係 good、fair 定 poor?
  • Statistics provide a framework:The more "atypical" a clustering result is, the more likely it represents valid structure in the data。
  • 將 index 值同 random data / random clusterings 嘅 index 值比較;if the value of the index is unlikely, then the cluster results are valid。(較複雜、較難理解。)
  • 比較兩組 cluster analyses 時 framework 較唔需要,但仍有「兩個 index 值嘅差是否 significant」嘅問題。

Statistical Framework for SSE (slide 80):例子:compare SSE of 0.005 against three clusters in random data。Histogram 顯示 500 組 random data(每組 100 點,x、y 分佈於 0.2–0.8)分成 3 clusters 嘅 SSE——random data 嘅 SSE 遠大於 0.005,所以 SSE=0.005SSE = 0.005 嘅 clustering 好 "atypical" → 代表真實結構。

Statistical Framework for Correlation (slide 81):同樣將 ideal similarity / proximity matrix 嘅 correlation 同 random data 比較。

6.6 Internal Measures: Cohesion and Separation (Slides 82–84)

  • Cluster Cohesion:measures how closely related are objects in a cluster(例:SSE)。
  • Cluster Separation:measure how distinct or well-separated a cluster is from other clusters(例:squared error between clusters)。
⭐ 考試重點:SSE (WSS) 同 SSB (BSS)

Cohesion is measured by the within cluster sum of squares (SSE):

SSE=WSS=∑i∑x∈Ci(x−mi)2SSE = WSS = \sum_i \sum_{x \in C_i} (x - m_i)^2

Separation is measured by the between cluster sum of squares:

SSB=BSS=∑i∣Ci∣ (m−mi)2SSB = BSS = \sum_i |C_i|\,(m - m_i)^2

∣Ci∣|C_i| 係 cluster ii 嘅 size,mim_i 係 cluster centroid,mm 係全部 data 嘅 overall mean。SSE+SSB=SSE + SSB = 常數(Total Sum of Squares, TSS)。

Worked example(一維 points 1, 2, 4, 5;overall mean m=3m = 3):

  • K=1K = 1:SSE=(1−3)2+(2−3)2+(4−3)2+(5−3)2=4+1+1+4=SSE = (1-3)^2 + (2-3)^2 + (4-3)^2 + (5-3)^2 = 4+1+1+4 = 10;SSB=4×(3−3)2=SSB = 4 \times (3-3)^2 = 0;Total = 10
  • K=2K = 2:clusters {1, 2}(m1=1.5m_1 = 1.5)同 {4, 5}(m2=4.5m_2 = 4.5):SSE=0.25+0.25+0.25+0.25=SSE = 0.25+0.25+0.25+0.25 = 1;SSB=2(3−1.5)2+2(4.5−3)2=4.5+4.5=SSB = 2(3-1.5)^2 + 2(4.5-3)^2 = 4.5 + 4.5 = 9;Total = 10 ✓

好嘅 clustering:SSE 細(cohesion 高)、SSB 大(separation 高)。

🖼️ 圖片內容

Slide 82 嘅 SSE / SSB 公式同 slide 83 嘅數值例子係圖片;上面公式同例子係教科書標準內容(slide 文字 "Where |Ci| is the size of cluster i" 與之吻合),請對照原 slide。

Proximity graph based approach (slide 84):Cluster cohesion is the sum of the weight of all links within a cluster;cluster separation is the sum of the weights between nodes in the cluster and nodes outside the cluster。

6.7 Internal Measures: Silhouette Coefficient (Slide 85)

Silhouette coefficient combines ideas of both cohesion and separation,可以用於 individual points、clusters 同 clusterings。

⭐ 考試重點:Silhouette 計法

對一個 individual point ii:

  • a = average distance of ii to the points in its cluster(cohesion)
  • b = min (average distance of ii to points in another cluster)(對每個其他 cluster 計平均距離,取最細)
s=b−amax⁡(a,b)s = \frac{b - a}{\max(a, b)}

Typically between 0 and 1;the closer to 1 the better(理論範圍 −1 至 1;負數表示該點可能分錯 cluster)。可以計一個 cluster 或成個 clustering 嘅 average silhouette coefficient。

💡 Worked example(用 §5.4 distance matrix,clustering = {a, b}、{c, d, e})

Point a:a=d(a,b)=2a = d(a, b) = 2;b=avg(d(a,c),d(a,d),d(a,e))=(6+10+9)/3=8.33b = \text{avg}(d(a,c), d(a,d), d(a,e)) = (6+10+9)/3 = 8.33;s=(8.33−2)/8.33=s = (8.33 - 2)/8.33 = 0.76

Point c:a=avg(d(c,d),d(c,e))=(4+5)/2=4.5a = \text{avg}(d(c,d), d(c,e)) = (4+5)/2 = 4.5;b=avg(d(c,a),d(c,b))=(6+5)/2=5.5b = \text{avg}(d(c,a), d(c,b)) = (6+5)/2 = 5.5;s=(5.5−4.5)/5.5=s = (5.5 - 4.5)/5.5 = 0.18(c 喺兩個 clusters 之間,silhouette 低)

Point d:a=(4+3)/2=3.5a = (4+3)/2 = 3.5;b=(10+9)/2=9.5b = (10+9)/2 = 9.5;s=6/9.5=s = 6/9.5 = 0.63

如果某點 a>ba > b(離自己 cluster 比另一 cluster 更遠),s 會係負數 → 應考慮重新分配。

from sklearn.metrics import silhouette_score, silhouette_samples
silhouette_samples(D, labels=[0,0,1,1,1], metric="precomputed")   # 每點 s
silhouette_score(X, km.labels_)                                     # 整體平均

7. Density Based Clustering: DBSCAN (Optional)

Slide 86:Clusters are regions of high density that are separated from one another by regions of low density。

⭐ 考試重點(optional 部分仍可能考概念):DBSCAN 定義 (Slide 87)
  • Density = number of points within a specified radius (Eps)
  • Core point:has at least a specified number of points (MinPts) within Eps(counts the point itself);these are points at the interior of a cluster
  • Border point:is not a core point, but is in the neighborhood of a core point
  • Noise point:any point that is not a core point or a border point

Slides 88–89 例子圖:MinPts = 7 示意;Eps = 10, MinPts = 4 時 original points 被標記為 core、border、noise。

7.1 DBSCAN Algorithm (Slide 90)

Form clusters using core points, and assign border points to one of its neighboring clusters:

  1. Label all points as core, border, or noise points。
  2. Eliminate noise points。
  3. Put an edge between all core points within a distance Eps of each other。
  4. Make each group of connected core points into a separate cluster。
  5. Assign each border point to one of the clusters of its associated core points。
💡 Worked example(自擬,一維)

Points:1, 2, 3, 4, 8, 9, 20;Eps = 1.5,MinPts = 3(包括自己)。

  • 1:Eps 內有 {1, 2} = 2 點 → 唔係 core;但 2 係 core 且 |1−2| ≤ 1.5 → border
  • 2:{1, 2, 3} = 3 → core
  • 3:{2, 3, 4} = 3 → core
  • 4:{3, 4} = 2 → 唔係 core;鄰近 core 3 → border
  • 8:{8, 9} = 2;9:{8, 9} = 2;兩者都唔係 core,亦冇 core 鄰居 → noise
  • 20:{20} → noise

Core 2 同 3 距離 1 ≤ Eps → 連埋做一個 cluster;border 1、4 加入 → Cluster = {1, 2, 3, 4};Noise = {8, 9, 20}。
如果 MinPts 改為 2,8 同 9 都會變 core,形成第二個 cluster {8, 9}——結果對參數好敏感。

7.2 When DBSCAN Works / Does NOT Work Well (Slides 91–92)

Works wellDoes NOT work well
  • Can handle clusters of different shapes and sizes
  • Resistant to noise
  • Varying densities(slide 92:MinPts = 4,Eps = 9.92 vs 9.75 結果差好遠——一個 Eps 唔能夠同時適合密同疏嘅 clusters)
  • High-dimensional data(curse of dimensionality 令 density 定義失效)

7.3 Determining Eps and MinPts (Slide 93)

  • Idea:for points in a cluster, their k-th nearest neighbors are at close distance;noise points have the k-th nearest neighbor at farther distance。
  • So, plot sorted distance of every point to its k-th nearest neighbor(k-distance plot);曲線急升嘅 "knee" 位置就係 Eps 嘅好選擇,k 就做 MinPts。
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import DBSCAN
k = 4
dist, _ = NearestNeighbors(n_neighbors=k).fit(X).kneighbors(X)
plt.plot(np.sort(dist[:, -1]))                  # k-distance plot,搵 knee → Eps
labels = DBSCAN(eps=1.5, min_samples=3).fit_predict(np.array([1,2,3,4,8,9,20]).reshape(-1,1))
# labels: [0 0 0 0 -1 -1 -1]   (-1 = noise)
⭐ 考試重點:三種方法總比較
K-meansAgglomerative HierarchicalDBSCAN
TypePartitional, center-basedHierarchical (nested)Partitional, density-based
要預設K唔使(cut dendrogram);要揀 linkageEps、MinPts
ShapesGlobular onlyMIN:任意;MAX / Avg:globular任意形狀同大小
Noise / outliers敏感MIN 敏感;MAX / Avg 較 robustResistant(標記為 noise)
ComplexityO(n⋅K⋅I⋅d)O(n\cdot K\cdot I\cdot d)O(N2)O(N^2) space,O(N3)O(N^3) time(教科書:O(N2)O(N^2),有 index 可更快)
主要弱點Initial centroids、sizes、densities、shapesMerge 唔可以 undo;冇 global objectiveVarying densities、high-dimensional

自我測驗 Self-test

Q1. Points:1, 2, 6, 7, 8, 15;K=2K = 2;initial centroids 1 同 8。做 K-means 直到收斂,並計最終 SSE。

Iter 1:C1={1,2}C_1 = \{1, 2\}(2:|2−1| = 1 < 6),C2={6,7,8,15}C_2 = \{6, 7, 8, 15\}(6:5 > 2)→ c1=1.5c_1 = 1.5,c2=36/4=9c_2 = 36/4 = 9。
Iter 2:6:|6−1.5| = 4.5 > |6−9| = 3 → C2C_2;assignments 冇變 → converged。
SSE=(1−1.5)2+(2−1.5)2+(6−9)2+(7−9)2+(8−9)2+(15−9)2=0.25+0.25+9+4+1+36=SSE = (1-1.5)^2 + (2-1.5)^2 + (6-9)^2 + (7-9)^2 + (8-9)^2 + (15-9)^2 = 0.25 + 0.25 + 9 + 4 + 1 + 36 = 50.5。
(如果 K=3K = 3 用 {1,2}、{6,7,8}、{15},SSE=0.5+2+0=2.5SSE = 0.5 + 2 + 0 = 2.5,明顯好啲——15 係 outlier 拉走咗 centroid。)

Q2. 點解唔可以揀令 SSE 最細嘅 K?應該點揀?

因為 SSE 隨 K 增加而下降,K=nK = n 時 SSE=0SSE = 0,所以「最細 SSE」永遠揀最大 K。應用 SSE vs K 曲線搵 elbow / knee,或用 silhouette coefficient、或同 random data 比較(statistical framework)。

Q3. 有 5 個大小相同嘅真實 clusters,隨機揀 5 個 initial centroids,每個 cluster 剛好一個嘅概率係幾多?

P=K!/KK=5!/55=120/3125=P = K!/K^K = 5!/5^5 = 120/3125 = 0.0384。(K=10K = 10 時只有 0.00036。)

Q4. Distance matrix(p1p_1–p4p_4):d12=1d_{12} = 1, d13=4d_{13} = 4, d14=5d_{14} = 5, d23=3d_{23} = 3, d24=6d_{24} = 6, d34=2d_{34} = 2。用 MIN 同 MAX 做 agglomerative clustering,寫出每步 merge 嘅高度。

Step 1:merge {p1, p2} @1。
MIN:d({12},3)=min⁡(4,3)=3d(\{12\}, 3) = \min(4, 3) = 3;d({12},4)=min⁡(5,6)=5d(\{12\}, 4) = \min(5, 6) = 5;d(3,4)=2d(3, 4) = 2 → merge {p3, p4} @2;最後 d({12},{34})=min⁡(4,5,3,6)=3d(\{12\}, \{34\}) = \min(4, 5, 3, 6) = 3 → @3。
MAX:d({12},3)=4d(\{12\}, 3) = 4;d({12},4)=6d(\{12\}, 4) = 6;d(3,4)=2d(3, 4) = 2 → merge {p3, p4} @2;最後 max(4, 5, 3, 6) = 6 → @6。
Group Average 最後一步 = (4+5+3+6)/4 = 4.5。

Q5. 比較 MIN 同 MAX linkage 嘅優缺點。

MIN:可以處理 non-elliptical shapes,但對 noise / outliers 敏感(chaining effect)。MAX:較唔受 noise 影響,但傾向打散大 clusters,同偏向 globular clusters。Group Average 係兩者折衷(less susceptible to noise,但 biased towards globular)。

Q6. 用 Q4 嘅 distance matrix,clustering = {p1, p2}、{p3, p4}。計 p2 同 p3 嘅 silhouette coefficient。

p2:a=d(p2,p1)=1a = d(p_2, p_1) = 1;b=avg(d23,d24)=(3+6)/2=4.5b = \text{avg}(d_{23}, d_{24}) = (3 + 6)/2 = 4.5;s=(4.5−1)/4.5=s = (4.5 - 1)/4.5 = 0.778。
p3:a=d(p3,p4)=2a = d(p_3, p_4) = 2;b=avg(d31,d32)=(4+3)/2=3.5b = \text{avg}(d_{31}, d_{32}) = (4 + 3)/2 = 3.5;s=(3.5−2)/3.5=s = (3.5 - 2)/3.5 = 0.429。

Q7. 一維 points 2, 4, 10, 12,clusters {2, 4} 同 {10, 12}。計 SSE、SSB 同 total,並驗證 SSE+SSB=TSSSSE + SSB = TSS。

Overall mean = 7;m1=3m_1 = 3,m2=11m_2 = 11。SSE=1+1+1+1=SSE = 1+1+1+1 = 4;SSB=2(7−3)2+2(11−7)2=32+32=SSB = 2(7-3)^2 + 2(11-7)^2 = 32 + 32 = 64;TSS=25+9+9+25=68=4+64TSS = 25+9+9+25 = 68 = 4 + 64 ✓。

Q8. DBSCAN:定義 core、border、noise point。點解 DBSCAN 處理唔到 varying densities?

Core:Eps 半徑內(包括自己)有 ≥ MinPts 點;Border:唔係 core 但喺某 core point 嘅 Eps neighborhood 內;Noise:既唔係 core 亦唔係 border。因為成個 data set 只用一組 Eps / MinPts:Eps 細到可以分開密 clusters 時,疏 cluster 嘅點會變 noise;Eps 大到可以容納疏 cluster 時,相鄰嘅密 clusters 會被合併。

Q9. 列出 K-means 嘅 pre-processing 同 post-processing 步驟。

Pre:normalize the data;eliminate outliers。Post:eliminate small clusters(可能係 outliers);split loose clusters(high SSE);merge close clusters with relatively low SSE。

Q10. Hierarchical clustering 嘅 space 同 time complexity?有咩主要限制?

O(N2)O(N^2) space(proximity matrix);O(N3)O(N^3) time(N 步,每步更新 / 搜尋 N2N^2 matrix),聰明實作可減到 O(N2log⁡N)O(N^2 \log N)。限制:merge 決定唔可以 undo;冇直接 minimize global objective function;唔同 linkage 有 noise 敏感、處理唔到唔同大小 / non-globular、打散大 cluster 等問題。

一頁總結 Cheat sheet

⭐ 考前速記
  • Cluster analysis:組內相似(intra ↓)、組間唔同(inter ↑);用途 understanding、summarization;cluster 數目 ambiguous。
  • Partitional(non-overlapping,每點一個 cluster)vs Hierarchical(nested,dendrogram);exclusive / non-exclusive、fuzzy(weights sum to 1)、partial / complete、heterogeneous / homogeneous。
  • Cluster types:well-separated、center-based(centroid / medoid)、contiguity-based(transitive)、density-based(irregular + noise)。
  • K-means:揀 K 個 initial centroids → assign to closest → recompute mean → repeat until no change。O(n⋅K⋅I⋅d)O(n\cdot K\cdot I\cdot d)。Random init → 每次結果唔同。
  • SSE = ∑∑dist2(mi,x)\sum\sum \text{dist}^2(m_i, x);mean 令 SSE 最細;增加 K 一定減 SSE。
  • Initial centroids:P(每 cluster 一個) = K!/KKK!/K^K(K=10K = 10 → 0.00036);solutions:multiple runs、hierarchical on sample、多啲 clusters 再 merge、揀多過 k 再揀 widely separated、K-means++(prob ∝D(x)2\propto D(x)^2,O(log⁡k)O(\log k))。
  • K-means limitations:differing sizes、densities、non-globular shapes、outliers → 用多啲 clusters 再 post-process merge;pre(normalize、remove outliers)、post(remove small、split high-SSE、merge close low-SSE)。
  • Hierarchical:唔使預設 K(cut dendrogram)、可對應 taxonomy;agglomerative(merge closest)vs divisive(split)。
  • Linkage:MIN(closest pair;non-elliptical ✓、noise ✗)、MAX(farthest pair;noise ✓、breaks large、globular bias)、Group Average(∑d/(∣Ci∣∣Cj∣)\sum d / (|C_i||C_j|);折衷)、Centroid distance。
  • Complexity:O(N2)O(N^2) space、O(N3)O(N^3) time(可到 O(N2log⁡N)O(N^2 \log N));merge 唔可以 undo、冇 global objective。
  • Validity:避免喺 noise 搵 pattern;aspects:clustering tendency、external labels、internal(只用 data)、比較兩組、揀 K。
  • Correlation:ideal similarity matrix(同 cluster = 1)vs proximity matrix,計 n(n−1)/2n(n-1)/2 entries;唔適合 density / contiguity clusters。Similarity matrix 按 label 排序睇方塊;random data 唔 crisp。
  • SSE vs K 搵 elbow;statistical framework:同 random data 嘅 index 分佈比較(SSE 0.005 例子)。
  • Cohesion = SSE (WSS);Separation = SSB=∑∣Ci∣(m−mi)2SSB = \sum |C_i|(m - m_i)^2;SSE+SSB=SSE + SSB = 常數(1,2,4,5 例:K=1K=1 → 10 + 0;K=2K=2 → 1 + 9)。
  • Silhouette:a = 同 cluster 平均距離;b = 最近其他 cluster 嘅平均距離;s=(b−a)/max⁡(a,b)s = (b - a)/\max(a, b);越近 1 越好。
  • DBSCAN:Eps、MinPts(包括自己);core / border / noise;連接 Eps 內嘅 core points 成 clusters,border 歸附近 core 嘅 cluster;✓ 任意形狀大小、resistant to noise;✗ varying densities、high-dimensional;k-distance plot 揀 Eps。