V. Clustering Algorithms


Exploratory Data Analysis & Unsupervised Learning

     

Lecturer: Dr. HAS Sothea
..Instructor: Ms. UANN Sreyvi

Resources

1 Introduction & Motivation

1.1 Motivation

Old Faithful dataset (\(272\) rows, \(2\) columns)

Code
import pandas as pd                 # Import pandas package
import seaborn as sns               # Package for beautiful graphs
import plotly.express as px
import matplotlib.pyplot as plt     # Graph management
df0 = pd.read_csv(path_faithful)  # Import it into Python
df0.head(5)                        # Randomly select 4 points
eruptions waiting
0 3.600 79
1 1.800 54
2 3.333 74
3 2.283 62
4 4.533 85

Code
fig0 = px.scatter(df0, x="waiting", y="eruptions", size_max=50)    # Create scatterplot
fig0.update_layout(
    title="Old Faithful data at Yellowstone National Park, US.",
    width=450, height=320)    # Title
fig0.show()
  • Two blocks: shorter wait & eruption, and the longer ones.

More motivations

Marketing: finding groups of customers with similar behavior given a large database of customer data containing their properties and past buying records.

Biology: classification of plants and animals given their features.

Insurance: identifying groups of motor insurance policy holders with a high average claim cost; identifying frauds, identify potential group of customers, etc.

Bookshops: book ordering (recommendation).

City-planning: identifying groups of houses according to their type, value and geographical location.

Internet: document classification; clustering weblog data to discover groups of similar access patterns; topic modeling…

1.2 Introdution

Clustering

Code
df0.head(2)
eruptions waiting
0 3.6 79
1 1.8 54
  • Clustering aims at grouping a set of points in such a way that:
  1. Points within the same group are close/similar, and
  1. Points from different groups are distant.
  • It belongs to the Unsupervised Learning branch of ML.
  • Objective: group data into clusters based on their similarities.
  • Methods: \(K\)-Means, Hierarchical and Spectral Clustering.

2 KMeans Clustering

2.1 KMeans Clustering Theory

Problem setting

  • \(L_2\) loss: \(\ell(\text{x},c)=\|\text{x}-c\|^2=\sum_{j=1}^d(\text{x}_{j}-c_{j})^2.\)
  • Suppose the number of cluster \(K\) is known, we wish to find
    • A set of centroids: \(\color{blue}{{\cal C}}=\{\color{blue}{c_k}:k=1,...,K\}\)
    • A way to assign data \(\to\) cluster (a function) \(\color{red}{q}\) (quantizer):

\[\begin{align*}\color{red}{q}:\mathbb{R}^d&\to\color{blue}{{\cal C}}=\{\color{blue}{c_k}:k=1,...,K\}\\ \text{x}_i&\mapsto \color{red}{q}(\text{x}_i)=\color{blue}{c_k}\text{ for some }k.\end{align*}\]

  • We define Within Sum of Square criterion by:

\[\color{red}{\text{WSS}}(\color{red}{q})=\sum_{i=1}^n\ell(\text{x}_i,\color{red}{q}(\text{x}_i))=\sum_{i=1}^n\|\text{x}_i,\color{red}{q}(\text{x}_i)\|^2.\]

  • Objective: find \(\color{blue}{q^*}\) with lowest WSS: \(\color{red}{\text{WSS}}(\color{blue}{q^*})=\min_{\color{red}{q}\in{\cal Q}}\color{red}{\text{WSS}}(\color{red}{q}).\)

Visualizing WSS

  • Objective: find \(\color{blue}{q^*}\) with lowest WSS: \(\color{red}{\text{WSS}}(\color{blue}{q^*})=\min_{\color{red}{q}\in{\cal Q}}\color{red}{\text{WSS}}(\color{red}{q}).\)

\[\color{red}{\text{WSS}}(\color{red}{q})=\sum_{i=1}^n\ell(\text{x}_i,\color{red}{q}(\text{x}_i))=\sum_{i=1}^n\|\text{x}_i,\color{red}{q}(\text{x}_i)\|^2.\]

  • If \(\color{red}{q}\) maps \(\text{x}_i\) to some centroid \(\color{blue}{c_k}\),
  • For each cluster \(k\in\{1,2,...,K\}\):
    • Within group \(k\): \(\color{red}{\sum_{\text{x}_i\in G_k}\|\text{x}_i-\color{blue}{c_k}\|^2}.\)
  • \(\color{red}{\text{WSS}}(\color{red}{q})=\sum_{k=1}^K\color{red}{\sum_{\text{x}_i\in G_k}\|\text{x}_i-\color{blue}{c_k}\|^2}.\)

Measures the proximity of points within each group.

Basic Identity: TSS, BSS & WSS

For any number of cluster \(K\), \[\color{blue}{\text{TSS}}=\color{green}{\text{BSS}}+\color{red}{\text{WSS}},\] where

  • \(\color{blue}{\text{TSS}}=\sum_{i=1}^n(\text{x}_i-\overline{\text{x}})^2\) and
  • \(\color{green}{\text{BSS}}=\sum_{k=1}^Kn_k(\overline{\text{x}}_k-\overline{\text{x}})^2.\)


  • If codebook \(\color{blue}{\cal C}=\{\color{blue}{c_1,\dots,c_K}\}\) is known, Voronoi partition associated with \(\color{blue}{\cal C}\) is defined by \[\color{green}{S_k}=\{\text{x}_i:\|\text{x}_i-\color{green}{c_k}\|\leq \|\text{x}_i-c_j\|, \forall j\neq k\}.\]

Main Lemmas of Kmeans

  • If codebook \(\color{blue}{\cal C}=\{\color{blue}{c_1,\dots,c_K}\}\) is known, Voronoi partition associated with \(\color{blue}{\cal C}\) is defined by \[\color{green}{S_k}=\{\text{x}_i:\|\text{x}_i-\color{blue}{c_k}\|\leq \|\text{x}_i-\color{blue}{c_j}\|, \forall j\neq k\}.\]

  • Given centroids \(\color{blue}{\cal C}\), groups can be defined by computing Voronoi partition or cluster.

Lemma 1: Nearet Neighbor Condition [Linder, T. (2002)]

Given centroids \(\color{blue}{\cal C}\), let \(\color{red}{q}\) be any quantizer and \(\color{blue}{\hat{q}}\) be the quantizer that assigns any observation \(\text{x}_i\) to its closest code-vector (centroid of its Voronoi partition), i.e., \[\color{blue}{\hat{q}}(\text{x}_i)=\arg\min_{\color{blue}{c_k}\in\color{blue}{\cal C}}\|\text{x}_i-\color{blue}{c_k}\|^2\]

Then, one has \[\color{red}{\text{WSS}}(\color{blue}{\hat{q}})\leq \color{red}{\text{WSS}}(\color{red}{q}).\]

  • With \(\color{blue}{\cal C}\xrightarrow{\color{green}{\text{optimal}}}\) assign point to its best cluster \(\color{green}{S_k}\).

Lemma 2: Centroid Condition [Linder, T. (2002)]

Given a partition \(\color{green}{{\cal S}}=\{\color{green}{S_1},\dots,\color{green}{S_K}\}\), let \(\color{red}{q}\) be any quantizer and \(\color{blue}{\hat{q}}\) be the quantizer with Voronoi parition and codebook \(\hat{\color{blue}{\cal C}}=\{\color{blue}{\hat{c}_k}\}\) defined by \[\color{blue}{\hat{c}_k}=\frac{1}{|\color{green}{S_K}|}\sum_{\text{x}_i\in \color{green}{S_K}}\text{x}_i.\]

Then, one has \[\color{red}{\text{WSS}}(\color{blue}{\hat{q}})\leq \color{red}{\text{WSS}}(q).\]

  • With cluster \(\color{green}{\cal S_k}\xrightarrow{\color{green}{\text{optimal}}}\) relocate to a better \(\color{blue}{c_k}\in\color{blue}{\cal C}\).

Summary of the Lemmas

  • Nearet Neighbor Condition: Given codebook \(\color{blue}{\cal C}=\{\color{blue}{c_k}\}\), we know how to assign \(\text{x}_i\mapsto \color{blue}{c_k}\) optimally, therefore find the best Voronoi parition.

  • Centroid Condition: Given a partition \(\color{green}{\cal S}=\{\color{green}{S_k}\}\), we know how to define an optimal codebook \(\color{blue}{\cal C}=\{\color{blue}{c_k}\}\).

  • Q1: How would you design an algorithm?
  • A1: Something like: \(\color{blue}{{\cal C}^1}\overset{\color{green}{\text{NNC}}}{\to}\color{green}{{\cal S}^1}\overset{\color{blue}{\text{CC}}}{\to}\color{blue}{{\cal C}^2}\overset{\color{green}{\text{NNC}}}{\to}\color{green}{{\cal S}_2}...\)
  • This leads to the well-known KMeans clustering algorithm (See: Linder, T. (2002)).

2.2 KMeans Algorithm

  • Given data \({\cal D}=\{\text{x}_1,\dots,\text{x}_n\}\subset\mathbb{R}^d\) and \(K\).
  • Initialization: \(\color{blue}{{\cal C}^{0}}=\{\color{blue}{c_1,\dots,c_K}\}\) (randomly).
  • Cluster Assignment (NNC):

for i = 1,...,n:
…. for k = 1,...,K: \[\text{Assign }\text{x}_i\to \color{green}{S_k}\text{ if }\|\text{x}_i-\color{green}{c_k}\|\leq \|\text{x}_i-c_j\|,\forall j\neq k.\]

  • Centroid Recomputation (CC): From \(\color{green}{\cal S}=\{\color{green}{S_k}\}\) recompute new centroid of each cluster \(k\) by:

\[\color{green}{c_k}=\frac{1}{|\color{green}{S_k}|}\sum_{\text{x}_i\in \color{green}{S_k}}\text{x}_i.\]

  • Alternatively repeat step 2. and 3. until converges.
Code
from sklearn.cluster import KMeans
km = KMeans(n_clusters=4, init='random', max_iter=7, n_init=1, random_state=12)
km = km.fit(df1)
fig_km = go.Figure(go.Scatter(x=df1[:,0], y=df1[:,1], name="Data", mode="markers", 
                   marker=dict(color=[col1[str(j+1)] for j in km.labels_], size=7)))
fig_km.add_trace(go.Scatter(x=km.cluster_centers_[:,0], y=km.cluster_centers_[:,1],
                name="Centroid", mode="markers", marker=dict(color='black', size=15, symbol='star')))
fig_km.update_layout(width=500, height=480, title="KMeans Algorithm in Action")
fig_km.show()

KMeans Algorithm may get stuck

  • Given data \({\cal D}=\{\text{x}_1,\dots,\text{x}_n\}\subset\mathbb{R}^d\) and \(K\).
  • Initialization: \(\color{blue}{{\cal C}^{0}}=\{\color{blue}{c_1,\dots,c_K}\}\) (randomly).
  • Cluster Assignment (NNC):

for i = 1,...,n:
…. for k = 1,...,K: \[\text{Assign }\text{x}_i\to \color{green}{S_k}\text{ if }\|\text{x}_i-\color{green}{c_k}\|\leq \|\text{x}_i-c_j\|,\forall j\neq k.\]

  • Centroid Recomputation (CC): From \(\color{green}{\cal S}=\{\color{green}{S_k}\}\) recompute new centroid of each cluster \(k\) by:

\[\color{green}{c_k}=\frac{1}{|\color{green}{S_k}|}\sum_{\text{x}_i\in \color{green}{S_k}}\text{x}_i.\]

  • Alternatively repeat step 2. and 3. until converges.
Code
from sklearn.cluster import KMeans
km = KMeans(n_clusters=4, init='random', max_iter=7, n_init=1, random_state=11)
km = km.fit(df1)
fig_km = go.Figure(go.Scatter(x=df1[:,0], y=df1[:,1], name="Data", mode="markers", 
                   marker=dict(color=[col1[str(j+1)] for j in km.labels_], size=7)))
fig_km.add_trace(go.Scatter(x=km.cluster_centers_[:,0], y=km.cluster_centers_[:,1],
                name="Centroid", mode="markers", marker=dict(color='black', size=15, symbol='star')))
fig_km.update_layout(width=500, height=480, title="KMeans Algorithm in Action")
fig_km.show()

KMeans Algorithm may get stuck

  • Given data \({\cal D}=\{\text{x}_1,\dots,\text{x}_n\}\subset\mathbb{R}^d\) and \(K\).
  • A solution from KMeans of sklearn.cluster module:
from sklearn.cluster import KMeans
km = KMeans(
    n_clusters=4, 
    n_init=5     # Perform KMeans 5 times
)
km = km.fit(df1) # The best one among the 5

🔑 Perform KMeans algorithm n_init times with different random initializations, the best one (lowest WSS) is taken as the final result.

Q2: The main point is ‘HOW TO FIND A SUITABLE \(K\)’?

Code
fig_km1.show()

2.3 Finding Optimal K

Elbow Method 💪

🔑 \(\color{red}{\text{WSS}}\) decreases as \(K\) increases:

  • \(K=1\Rightarrow \color{red}{\text{WSS}}=\color{blue}{\text{TSS}}\)
  • \(K=n\Rightarrow \color{red}{\text{WSS}}=0\).
  • At the suitable \(K\), \(\color{red}{\text{WSS}}\) starts dropping slower making an elbow.
Code
wss = []
list_k = list(range(1,11))
for k in list_k:
    km = KMeans(n_clusters = k, n_init=2)
    km = km.fit(df1)
    wss.append(km.inertia_)

data_wss = pd.DataFrame({
    'K' : list_k,
    'WSS': wss
})
fig6 = px.line(
    data_wss, x="K", y="WSS", 
    markers="WSS", 
    title="WSS vs Number of cluster (K)")
fig6.add_trace(
    go.Scatter(x=[4,4], y=[0,wss[3]], 
    line=dict(
        color="red", dash="dash"),
        name="Optimal K"))
fig6.update_layout(width=500, height=180)
fig6.show()
Code
from plotly.subplots import make_subplots

list_k = list(range(1, 11))
wss = []
models = {}

for k in list_k:
    # random_state ensures centroids don't initialize randomly each run
    km = KMeans(n_clusters=k, max_iter=100, n_init=2, random_state=42)
    km = km.fit(df1)
    wss.append(km.inertia_)
    models[k] = km

# We will animate K from 2 to 8 (list_k[1:-2])
slider_k = list_k[1:-2]
k_init = slider_k[0] # Starting K (K=2)
km_init = models[k_init]

fig = make_subplots(
    rows=2, cols=1, 
    row_heights=[0.6, 0.4], 
    subplot_titles=("KMeans with different K", "Elbow Curve (WSS)"),
    vertical_spacing=0.2
)

# TRACE 0: Scatter plot points (Row 1)
fig.add_trace(
    go.Scatter(x=df1[:,0], y=df1[:,1], mode='markers', 
               marker=dict(color=km_init.labels_, size=7, colorscale='Viridis'), 
               name='Data points'), 
    row=1, col=1
)

# TRACE 1: Centroids (Row 1)
fig.add_trace(
    go.Scatter(x=km_init.cluster_centers_[:,0], y=km_init.cluster_centers_[:,1],
               name="Centroids", mode="markers", 
               marker=dict(color='red', size=15, symbol='star')), 
    row=1, col=1
)

# TRACE 2: Static Elbow Line (Row 2)
fig.add_trace(
    go.Scatter(x=list_k, y=wss, mode='lines+markers', 
               line=dict(color='blue'), name='WSS'), 
    row=2, col=1
)

# TRACE 3: Moving Red Dot for current K on Elbow curve (Row 2)
fig.add_trace(
    go.Scatter(x=[k_init], y=[wss[k_init-1]], mode='markers', 
               marker=dict(
                color='red', size=12, 
                symbol='circle-open', 
                line=dict(width=3)), 
               name='Current K'), 
    row=2, col=1
)


frames = []
for k in slider_k: 
    km = models[k]
    
    # We update Traces 0, 1, and 3. Trace 2 (the WSS line) stays static.
    frame = go.Frame(
        data=[
            # Update Trace 0 (Scatter Colors)
            go.Scatter(marker=dict(color=km.labels_, size=7, colorscale='Viridis')),
            # Update Trace 1 (Centroids)
            go.Scatter(x=km.cluster_centers_[:,0], y=km.cluster_centers_[:,1]),
            # Update Trace 3 (Red dot on Elbow)
            go.Scatter(x=[k], y=[wss[k-1]], marker=dict(
                color=['green' if k==4 else 'red'][0],
                size = [15 if k==4 else 12][0]))
        ],
        name=str(k),
        traces=[0, 1, 3] # This tells Plotly exactly which traces to update
    )
    frames.append(frame)

fig.frames = frames
animation_settings = {"frame": {"duration": 600, "redraw": True}, "mode": "immediate", "transition": {"duration": 0}}

fig.update_layout(
    width=400, height=450,
    showlegend=False,
    updatemenus=[{
        "buttons": [
            {
                "args": [None, animation_settings],
                "label": "Play",
                "method": "animate"
            },
            {
                "args": [[None], {"frame": {"duration": 0, "redraw": False}, "mode": "immediate"}],
                "label": "Stop",
                "method": "animate"
            }
        ],
        "type": "buttons",
        "showactive": False,
        "x": 0, "y": 1.1,
        "pad": {"r": 10, "t": 10}
    }],
    sliders=[{
        "active": 0,
        "currentvalue": {"prefix": "K: "},
        "pad": {"t": 20},
        "steps": [{
            "label": str(k),
            "method": "animate",
            "args": [[str(k)], animation_settings]
        } for k in slider_k]
    }]
)

# Fix axis ranges so they don't jump around during animation
fig.update_xaxes(range=[df1[:,0].min()-2, df1[:,0].max()+2], row=1, col=1, title_text="X1")
fig.update_yaxes(range=[df1[:,1].min()-2, df1[:,1].max()+2], row=1, col=1, title_text="X2")
fig.update_xaxes(title_text="Number of clusters (K)", row=2, col=1)
fig.update_yaxes(title_text="WSS", row=2, col=1)

fig.show()

Silhouette Coefficients

  • Elbow method may fail on real data due to unclear pattern!
  • If \(\color{blue}{\text{x}_i}\) belongs to cluster \(\color{green}{k}\)-th, we define
    • \(a(\color{blue}{i})=\frac{1}{|\color{green}{S_k}|-1}\sum_{j\neq i}\|\text{x}_j-\color{blue}{\text{x}_i}\|^2\): measures how close \(\color{blue}{\text{x}_i}\) to other members within the same cluster.
    • \(b(\color{blue}{i})=\min_{j\neq \color{green}{k}}\frac{1}{|S_j|}\sum_{\text{x}\in S_j}\|\text{x}-\color{blue}{\text{x}_i}\|^2\): measures how close \(\color{blue}{\text{x}_i}\) to other members of the nearest cluster.
  • Silhouette value for the data point \(\color{blue}{\text{x}_i}\) is defined by: \[-1\leq s(\color{blue}{i})=\frac{b(\color{blue}{i})-a(\color{blue}{i})}{\max\{a(\color{blue}{i}),b(\color{blue}{i})\}}\leq 1.\]
    • \(s(\color{blue}{i})\approx 1:\) \(\color{blue}{\text{x}_i}\) is well-clustered within its cluster and distant from other groups.
    • \(s(\color{blue}{i})\approx -1:\) \(\color{blue}{\text{x}_i}\) is distant from other members of its cluster and should belong to the nearest group.
  • Silhouette Coefficient for a given \(K\) is \(\tilde{s}(K)=1/n\sum_{i=1}^ns(i).\)
  • Optimal number of cluster \(\color{red}{K^*}=\arg\max_{K_\min\leq \color{blue}{k}\leq K_\max}\{\tilde{s}(\color{blue}{k})\}.\)
Code
from sklearn.metrics import silhouette_score, silhouette_samples
km = KMeans(n_clusters=4, max_iter=100, n_init=2)
km = KMeans(n_clusters=4, max_iter=100, n_init=2, random_state=42)
km = km.fit(df1)
clusters = km.labels_
silhouette_avg = silhouette_score(df1, clusters)
sample_silhouette_values = silhouette_samples(df1, clusters)

# 3. Plotly Silhouette Plot
fig = go.Figure()
y_lower = 10

# Lists to hold the positions and text for the Y-axis labels
y_tick_vals = []
y_tick_text = []

for k in range(km.n_clusters):
    # Aggregate the silhouette scores for samples belonging to cluster k, and sort them
    ith_cluster_silhouette_values = sample_silhouette_values[clusters == k]
    ith_cluster_silhouette_values.sort()
    
    size_cluster_k = ith_cluster_silhouette_values.shape[0]
    y_upper = y_lower + size_cluster_k
    
    # Generate the Y coordinates for this cluster
    y_range = np.arange(y_lower, y_upper)
    
    # Equivalent to ax1.fill_betweenx()
    fig.add_trace(
        go.Scatter(
            x=ith_cluster_silhouette_values,
            y=y_range,
            mode='lines',
            fill='tozerox',   # Fills the area from the curve to the X=0 axis
            name=f'Cluster {k+1}',
            line=dict(width=0.5) 
        )
    )
    
    # Calculate the center of the cluster on the Y-axis to place the label
    y_tick_vals.append(y_lower + 0.5 * size_cluster_k)
    y_tick_text.append(str(k + 1))
    
    # Compute the new y_lower for the next plot
    y_lower = y_upper + 10

# Equivalent to ax1.axvline()
fig.add_trace(
        go.Scatter(
            x=[silhouette_avg] * 2,
            y=[0, df1.shape[0]],
            mode='lines',
            name='Ave coef',
            line=dict(width=1.5, color='red', dash='dash')
        )
    )

# Update layout
fig.update_layout(
    title="Silhouette plot for 4 clusters",
    xaxis_title="Silhouette coefficients",
    yaxis_title="Cluster label",
    width=270, 
    height=250,
    showlegend=False
)

fig.show()
Code
sc_av = []
for k in range(2,10):
  kmeans = KMeans(n_clusters=k, n_init=3)
  clusters = kmeans.fit_predict(df1)
  sc_av.append(silhouette_score(df1, clusters))
sc_df = pd.DataFrame({'k' : range(2, 10),
                      'Silhouette coef' : sc_av})
fig6 = px.line(data_frame=sc_df, x='k', y='Silhouette coef', markers='Silhouette Coef')
fig6.add_trace(go.Scatter(x=[4,4],y=[np.min(sc_av), np.max(sc_av)],  line=dict(dash="dash"), name=r"$K^*$"))
fig6.update_layout(width=270, height=230, title = "Silhouette coef vs K")
fig6.show()

KMeans Summary

  • KMeans involves two alternative processes:

    • Cluster assignment: \(\color{blue}{\cal C}=\{\color{blue}{c_k}\}\to \color{green}{\cal S}=\{\color{green}{S_k}\}\).
    • Centroid recomputation: \(\color{green}{\cal S}=\{\color{green}{S_k}\}\to\color{blue}{\cal C}=\{\color{blue}{c_k}\}\).
  • The algorithm may get stuck if it started from a bad initialization. Increasing n_init may solves this problem.

  • A suitable number of cluster \(K\) may be estimated using:

    • Elbow method: Find the elbow of \(\color{red}{\text{WSS}}\) vs \(K\) curve.
    • Silhouette coefficient: find \(K\) that maximizes this coef.
  • Real-world data may require one to prioritize interpretable \(K\) over above criteria!

3 Hierarchical clustering

3.1 Agglomerative clustering

  • It doesn’t require the prior knowledge of \(K\).
  • Let \({\cal D}=\{\text{x}_1,\dots, \text{x}_n\}\) be the data points.

Agglomerative clustering

  • Start: Each point belongs to its own cluster (\(K=n\)).
  • Merging: Pairs of clusters are merged as we move up.
  • End: All points are in one cluster.
  • At each step, \(\color{red}{\text{WSS}}\) is recorded.
  • It’s the reverse process of Elbow method: \(K\) decreases, the sudden jump in \(\color{red}{\text{WSS}}\) indicates the suitable \(K\).
  • Q4: But how to link clusters together?
  • A4: We need tools AKA “Linkages”.
Linkage Formula
Single Linkage \(d_{\text{SL}}(A, B) = \min \{ \|a, b\|^2 : a \in A, b \in B \}\)
Complete Linkage \(d_{\text{CoL}}(A, B) = \max \{ \|a, b\|^2 : a \in A, b \in B \}\)
Average Linkage \(d_{\text{AL}}(A, B) = \frac{1}{|A||B|} \sum_{a \in A} \sum_{b \in B} \|a, b\|^2\)
Centroid Linkage \(d_{\text{CeL}}(A, B) = \|\bar{a}, \bar{b}\|^2\) where \(\bar{a}\) and \(\bar{b}\) are centroids of clusters \(A\) and \(B\), respectively.
Ward’s Linkage \(d_{\text{WL}}(A, B) = \sqrt{\frac{|A||B|}{|A| + |B|} \| \bar{a} - \bar{b} \|^2}\)

  • Ward’s linkage is design to merge clusters that leads to the least increment in WSS.

Linkage impacts

Code
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.cluster import AgglomerativeClustering
import seaborn as sns
import numpy as np
import plotly.figure_factory as ff

# 2. Define our iteration parameters
methods = ['single', 'complete', 'average', 'ward']
ks = [3, 4, 5, 6]
titles = [
    "Single Linkage", "Complete Linkage", "Average Linkage", "Ward's Linkage",
    "K = 3", "K = 4", "K = 5", "K = 6"
]

# 3. Create the 2x4 Subplot Grid
fig = make_subplots(
    rows=2, cols=4, 
    subplot_titles=titles,
    vertical_spacing=0.15,
    horizontal_spacing=0.05
)

# 4. Loop through the methods and Ks to populate the grid
for i, (method, k) in enumerate(zip(methods, ks)):
    col = i + 1  # Plotly columns are 1-indexed

    # Create a standalone dendrogram figure
    dendro_fig = ff.create_dendrogram(
        df1, 
        linkagefun=lambda x: linkage(x, method=method)
    )
    
    # Extract the line traces from the standalone figure and add them to our subplot
    for trace in dendro_fig.data:
        trace.showlegend = False
        fig.add_trace(trace, row=1, col=col)
    
    # Hide the X-axis ticks (mimics axs[0,c].set_xticks([]))
    fig.update_xaxes(showticklabels=False, row=1, col=col)

    clust = AgglomerativeClustering(n_clusters=k).fit_predict(df1)
    
    scatter_trace = go.Scatter(
        x=df1[:, 0], 
        y=df1[:, 1], 
        mode='markers',
        marker=dict(
            color=clust, 
            colorscale='Rainbow', # discrete-like continuous scale 
            size=7,
            line=dict(width=0.5, color='white')
        ),
        showlegend=False
    )
    fig.add_trace(scatter_trace, row=2, col=col)

# 5. Update Layout for a clean look
fig.update_layout(
    height=400, 
    width=950, 
    plot_bgcolor='rgba(0,0,0,0)',  # Transparent background
    showlegend=False
)

# Add grids to scatter plots for better readability
fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='lightgray', row=2)
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='lightgray', row=2)

fig.show()
  • Single linkage doesn’t show clear cut-off for \(K\) compared to other linkages.
  • Ward’s linkage show the clearest jump in WSS.

4 Spectral Clustering

4.1 Motivation

  • Not all clusters are Convex.
  • KMeans and Hierarchical clustering algorithms often struggle with non-convex cluster structures.
Code
np.random.seed(0) 
theta = np.linspace(0, 2*np.pi, 100) 
r1 = 1 + 0.2 * np.sin(4 * theta) 
r2 = 2 + 0.2 * np.sin(4 * theta) 
r3 = 0.5 * np.linspace(0.1, 5, 100)
x1 = r1 *np.cos(theta) - 3
y1 = r1 * np.sin(theta) # + np.random.normal(0, 0.3, 100)
x2 = r2 * np.cos(theta) - 3
y2 = r2 * np.sin(theta) #+ np.random.normal(0, 0.3, 100)
x3 = r3 * np.cos(theta) + 3.25
y3 = r3 * np.sin(theta) #+ np.random.normal(0, 0.3, 100)
x4 = r3 * np.cos(theta - np.pi) +  2.75
y4 = r3 * np.sin(theta - np.pi) #+ np.random.normal(0, 0.3, 100)
data = np.vstack((np.concatenate([x1, x2, x3, x4]), np.concatenate([y1, y2, y3, y4]))).T 
# Create a DataFrame
df = pd.DataFrame(data, columns=['x', 'y']) 
df['cluster'] = ['A'] * 100 + ['B'] * 100 + ['C'] * 100 + ['D'] * 100
# Plot using Plotly 
fig = px.scatter(df, x='x', y='y', title='Data with Non-Convex Clusters') 
fig.update_layout(width=450, height=220)
fig.show()
Code
# Kmeans
km1 = KMeans(n_clusters=4)
km1 = km1.fit(data)
# Hierarchical
Agg_clust = AgglomerativeClustering(n_clusters=4).fit_predict(data)

from plotly.subplots import make_subplots
fig7 = make_subplots(rows=2, cols=1, subplot_titles=("KMeans clustering", "Hierarchical clustering"))
fig7.add_trace(
    go.Scatter(x=df['x'], y=df['y'], mode="markers", 
    marker=dict(color=km1.labels_), showlegend=False),
    row=1, col=1
)

fig7.add_trace(
    go.Scatter(x=df['x'], y=df['y'], mode="markers", 
    marker=dict(color=Agg_clust), showlegend=False),
    row=2, col=1
)

fig7.update_layout(height=450, width=450)
fig7.show()

Motivation

  • Not all clusters are Convex.
  • KMeans and Hierarchical clustering algorithms often struggle with non-convex cluster structures.
Code
fig.show()
Code
from sklearn.cluster import SpectralClustering
from sklearn.metrics import pairwise_kernels
def gaussian_similarity(X, sigma): 
    return pairwise_kernels(data, metric='rbf', gamma=1/(2*sigma**2))
sigma = 0.7
affinity_matrix = gaussian_similarity(data, sigma)
# Spectral Clustering
sc = SpectralClustering(n_clusters=4,
        affinity="nearest_neighbors",
        eigen_solver="arpack",
        assign_labels='discretize')
labels = sc.fit_predict(affinity_matrix)

fig8 = go.Figure(go.Scatter(x=df['x'], y=df['y'], mode="markers", 
    marker=dict(color=labels), showlegend=False))
fig8.update_layout(height=200, width=450, title="Spectral Clustering")
fig8.show()
  • Q3: How and why does it work?

  • A3: It relies on Laplacian of Graph Theory: rearranges and pulls strongly connected points into tighter and denser groups.

Read: Luxburg (2007)

Graph Laplacian

  • Ex: Social media can be represented by a graph.

\[W=\begin{bmatrix} & A & B & \dots & G \\ A & w_{11} & w_{12} & \dots & w_{17} \\ B & w_{21} & w_{22} & \vdots & w_{27} \\ \vdots & \vdots &\vdots &\ddots &\vdots\\ G & w_{71} & w_{72} & \dots & w_{77} \end{bmatrix} \]

  • \(W\) is called adjacency matrix of the graph \({\cal G}=\{W, E\}\) where \(E=\{A,B,...,G\}\).

  • Degree of node \(i\)-th: \(d_i=\sum_{ij}^nw_{ij}\).

  • Degree matrix: \(D=\text{diag}(d_1,\dots,d_n)\).

  • Unnormalized Laplacian: \[L=D-W\]
  • Normalized Laplacian:
    • \(L_{\text{sym}}=D^{-1/2}LD^{-1/2}\)
    • \(L_{\text{rw}}=D^{-1}L.\)
  • These laplacian matrices capture the connectivity of the graph \(\cal G\).
  • The number of connected components of \(\cal G\) is related to eigenvalues / vectors of these matrices.

Graph Laplacian

Number of connected components [Wang (2016)]

Let \(\cal G\) be an undirected graph with non-negative weights. Then the multiplicity \(k\) of the eigenvalue \(0\) of both \(L_{\text{rw}}\) and \(L_{\text{sym}}\) equals to the number of connected components \(G_1,...,G_k\) in the graph.

  • For \(L_{\text{rw}}\), the eigenspace of \(0\) is spanned by the indicator vectors \(\mathbb{1}_{G_i}\) of those components.
  • For \(L_{\text{sym}}\), the eigenspace of \(0\) is spanned by the vectors \(D^{1/2}\mathbb{1}_{G_i}\).

\[L=\begin{bmatrix} [L_1] & 0 & 0 & \dots & 0 \\ 0 & [L_2] & 0 & \dots & 0 \\ 0 & 0 & 0 & \ddots & 0\\ 0 & 0 & 0 & \dots & [L_k] \end{bmatrix}.\]

Normalized Spectral Clustering

Algorithm [Wang (2016)]

  • Inputs:
    • Similarity matrix \(S\in\mathbb{R}^{n\times n}\), e.g., \(s(i,j)=e^{-\|\text{x}_i-\text{x}_j\|^2/(2\sigma^2)}\)
    • Number of clusters \(K\).
  • Compute \(W\) from \(S\) (e.g., \(W_{ij}=s(i,j)\) for Gaussian case).
  • Compute unnormalized laplacian \(L\).
  • Compute the first \(K\) generalized eigenvectors \(u_1,\dots, u_K\) of \(L\) corresponding to eigenvalues: \(0=\lambda_0<\lambda_1\leq \lambda_2\leq \dots\leq \lambda_K\).
  • Let \(U=[u_1|\dots |u_K]\) be the matrix with eigenvector columns \(u_j\).
  • Perform KMeans clustering on \(U\) to obtain clusters: \(C_1,\dots,C_K\).
  • Return final clusters \(A_k\) from indices of \(C_k\) i.e., \(A_k=\{j:\tilde{x}_j\in C_k\}\).

Summary

  • In some case, connection between data can be represented by a graph.
  • Laplacian of the graph captures connectivity within it.
  • The eigenvectors corresponding to the smallest non-zero eigenvalues capture the “smoothest” variations in the graph. These variations reflect the most significant and coherent groups of connected nodes, which correspond to the clusters.
  • Clustering structure or connected components within the graph are clearly revealed within this matrix.
  • Therefore, clustering this eigenvector matrix leads to connected component clusters.

More Examples

To explore: DBSCAN, HDBSCAN, OPTICS…

4.2 Applications

Image segmentation

Code
from skimage import data
image = data.astronaut()
plt.imshow(image[:,:,1])
plt.axis('off')
plt.show()

Code
image_gray = image[:,:,1].reshape(-1,1)
_, ax = plt.subplots(2, 2, figsize=(6, 4.2))
for k in range(2, 6):
    km_image = KMeans(n_clusters=k)
    km_image_fit = km_image.fit(image_gray)
    image_compressed = np.array([np.mean(image_gray[km_image_fit.labels_==i]) for i in range(k)])
    image_seg = np.zeros_like(km_image_fit.labels_)
    for i in range(k):
        image_seg[km_image_fit.labels_ == i] = image_compressed[i]

    image_reshaped = image_seg.reshape(image.shape[0], image.shape[1])
    ax[(k-2)//2,(k-2)%2].imshow(image_reshaped, cmap='gray')
    ax[(k-2)//2,(k-2)%2].set_title(f"K = {k}")
    ax[(k-2)//2,(k-2)%2].axis('off')
plt.axis('off')
plt.tight_layout()
plt.show()

Satellite Image Segmentation

Customer Segmentation: Credit Card

Gender Age Annual Income (k$) Spending Score (1-100)
0 Male 19 15 39
1 Male 21 15 81
2 Female 20 16 6
3 Female 23 16 77
4 Female 31 17 40
  • Q4: What should you do in preprocessing step?

  • A4: Exclude Gender, remove missing, duplicated values, scaling…

Customer Segmentation: Credit Card (cont.)

Missing values:
    Gender  Age  Annual Income (k$)  Spending Score (1-100)
0       0    0                   0                       0
  • Optimal \(K=\) 4 by Elbow method and \(K=\) 6 by Silhouette coefficient method.

Can you interpret each group?

Code
column_colors = ['#636EFA', '#EF553B', '#00CC96', '#AB63FA']
titles = [va if i == 0 else "" for i in range(4) for va in data.columns]
fig = make_subplots(
    rows=4, 
    cols=4, 
    subplot_titles=titles,
    vertical_spacing=0.08, 
    horizontal_spacing=0.05
)

for i in range(opt_k):
    cluster_mask = km_opt.labels_ == i
    
    for j, va in enumerate(data.columns):
        row = i + 1
        col = j + 1
        subset = data.loc[cluster_mask, va]
        current_color = column_colors[j % len(column_colors)]
        
        if va == "Gender":
            prop = subset.value_counts(normalize=True)
            trace = go.Bar(
                x=prop.index,
                y=prop.values, 
                text=prop.values,
                marker_color=current_color,
                texttemplate="%{text:.2f}",
                textposition="outside",
                showlegend=False)
        else:
            mean_val = subset.median()
            fig.add_shape(
                type="line",
                x0=mean_val, x1=mean_val,
                y0=0, y1=1,
                yref="y domain",
                row=row, col=col,
                line=dict(color="black", width=2, dash="dash"))
            trace = go.Histogram(
                x=subset,
                marker_color=current_color,
                showlegend=False)
        fig.add_trace(trace, row=row, col=col)
        if j == 0:
            fig.update_yaxes(title_text=f'Cluster {i+1}', row=row, col=col)

fig.update_layout(
    height=450,
    width=900,
    plot_bgcolor='white'
)

fig.update_xaxes(showline=True, linewidth=1, linecolor='black')
fig.update_yaxes(showline=True, linewidth=1, linecolor='black')

fig.show()

How about now?

Code
titles = [va if i == 0 else "" for i in range(4) for va in data.columns]

fig = make_subplots(
    rows=4, 
    cols=4, 
    subplot_titles=titles,
    vertical_spacing=0.08, 
    horizontal_spacing=0.05
)

for i in range(opt_k):
    cluster_mask = km_opt.labels_ == i
    
    for j, va in enumerate(data.columns):
        row = i + 1
        col = j + 1
        current_color = column_colors[j % len(column_colors)]
        subset = data.loc[cluster_mask, va]
        
        if va == "Gender":
            prop = subset.value_counts(normalize=True)
            
            trace = go.Bar(
                x=prop.index,
                y=prop.values,
                text=prop.values,
                marker_color=current_color,
                texttemplate="%{text:.2f}",
                textposition="outside",
                showlegend=False)
        else:
            mean_val = subset.median()
            fig.add_shape(
                type="line",
                x0=mean_val, x1=mean_val,
                y0=0, y1=1,
                yref="y domain",
                row=row, col=col,
                line=dict(color="black", width=2, dash="dash"))
            trace = go.Histogram(
                x=subset,
                marker_color=current_color,
                showlegend=False)
        fig.add_trace(trace, row=row, col=col)
        if j > 0:
            fig.update_xaxes(
                range=[np.min(data[va]), np.max(data[va])], 
                row=row, col=col)

        if j == 0:
            fig.update_yaxes(title_text=f'Cluster {i+1}', row=row, col=col)

fig.update_layout(
    height=450,
    width=900,
    plot_bgcolor='white'
)

# Apply a clean grid and axes borders to match seaborn's default style
fig.update_xaxes(showline=True, linewidth=1, linecolor='black')
fig.update_yaxes(showline=True, linewidth=1, linecolor='black')

fig.show()

With 6 clusters

Summary

  • Clustering is a key technique in the unsupervised learning branch of machine learning.
  • It plays a crucial role in tasks involving the organization and segmentation of data based on their similarities.
  • It can be applied in various fields such as market segmentation, image processing, and anomaly detection.
  • There are numerous clustering algorithms available, each suited to different types of data and purposes. Examples include KMeans, Hierarchical Clustering, DBSCAN, and Spectral Clustering.
  • Interpreting clustering results can be challenging but is an essential step to ensure the validity and usefulness of the clusters identified.

🥳 Yeahhhh….









Let’s Party… 🥂