30 Mins

5. Unsupervised Learning: Clustering

K-Means Clustering: Objective Function, Centroids, and Inertia

Unsupervised learning operates on unlabeled data, where the goal is to discover underlying patterns, groupings, or structures without a target response variable. K-Means is one of the most widely used clustering algorithms. It partitions a dataset of N observations into K distinct, non-overlapping clusters. The algorithm operates iteratively to assign each data point to its closest cluster representative, known as a centroid.

The optimization mechanism of K-Means centers around minimizing an objective function known as Inertia, or the Within-Cluster Sum of Squares (WCSS). Let C_k be the set of points in the k-th cluster, and mu_k be the centroid of that cluster. Inertia is defined mathematically as the sum over all clusters of the squared Euclidean distances between each point x in C_k and the centroid mu_k. By minimizing this objective, the algorithm maximizes the similarity of points within each individual cluster.

The step-by-step execution of the algorithm proceeds as follows: First, K initial centroids are selected, either randomly or via smart initialization heuristics like KMeans++. Second, in the assignment step, each data point is mapped to the nearest centroid. Third, in the update step, the centroids are recomputed as the mean coordinates of all data points assigned to that cluster. This assignment and update cycle repeats iteratively until the centroids stop changing significantly, or until a predefined maximum number of iterations is reached.

Operator Note: Because K-Means relies heavily on calculating Euclidean distances between points, it is extremely sensitive to scale. Always scale your features using standard techniques (like StandardScaler) before running K-Means to prevent variables with larger numerical ranges from dominating the distance calculations.
Python 3
import numpy as np
from sklearn.cluster import KMeans

# Generate random mock data representing 3 separate customer spending behaviors
np.random.seed(42)
cluster1 = np.random.normal(loc=20, scale=2, size=(30, 2))
cluster2 = np.random.normal(loc=50, scale=3, size=(30, 2))
cluster3 = np.random.normal(loc=80, scale=2, size=(30, 2))
X = np.vstack([cluster1, cluster2, cluster3])

# Run K-Means with 3 clusters
kmeans = KMeans(n_clusters=3, random_state=42, n_init='auto')
kmeans.fit(X)

print(f"Centroids:\n{kmeans.cluster_centers_}")
print(f"Inertia (Within-Cluster Sum of Squares): {kmeans.inertia_:.4f}")

Selecting Optimal Clusters: The Elbow Method and Silhouette Score

Since K-Means requires the programmer to define the number of clusters (K) beforehand, selecting the optimal K is a critical hyperparameter tuning challenge. Two main diagnostics are used to address this: the Elbow Method and the Silhouette Score. The Elbow Method involves plotting Inertia against a range of K values. As K increases, Inertia naturally decreases because clusters become smaller and tighter. The optimal K is selected at the 'inflection point' or elbow of the curve, after which the rate of decrease in Inertia slows down significantly.

The Silhouette Score offers a complementary approach by measuring how similar an object is to its own cluster (cohesion) compared to other clusters (separation). The silhouette coefficient for a single sample is calculated as (b - a) / max(a, b), where a is the mean distance to other points in the same cluster, and b is the mean distance to the points in the nearest neighboring cluster. The score ranges from -1 to +1, where a high value indicates that the object is well-matched to its own cluster and poorly matched to neighboring clusters.

The table below highlights the trade-offs and utility of both evaluation approaches:

Operator Note: An elbow is not always sharp and clear in real-world messy datasets. Combining the Elbow Method with the Silhouette Score provides a more rigorous quantitative justification for your final cluster count selection.
Python 3
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

# Create synthetic clustered dataset
np.random.seed(10)
X = np.concatenate([
    np.random.normal(15, 3, (50, 2)),
    np.random.normal(40, 5, (50, 2)),
    np.random.normal(70, 4, (50, 2))
])

# Evaluate different cluster numbers
results = []
for k in range(2, 6):
    kmeans = KMeans(n_clusters=k, random_state=42, n_init='auto')
    labels = kmeans.fit_predict(X)
    inertia = kmeans.inertia_
    sil = silhouette_score(X, labels)
    results.append(f"K={k} | Inertia: {inertia:.1f} | Silhouette Score: {sil:.3f}")

for r in results:
    print(r)

Density-Based Clustering: DBSCAN, eps, and min_samples

While K-Means assumes spherical and convex clusters, real-world data often exhibits complex, non-linear shapes. DBSCAN (Density-Based Spatial Clustering of Applications with Noise) resolves this issue by grouping points based on spatial density rather than centroid proximity. It excels at finding clusters of arbitrary shapes and is robust to noise, identifying outlier points automatically.

The behavior of DBSCAN is governed by two key hyperparameters: eps (epsilon) and min_samples. The eps parameter defines the maximum distance radius for a point's neighborhood. The min_samples parameter represents the minimum number of data points that must reside within this radius for a region to be considered dense. Based on these thresholds, points are classified as Core points (dense neighborhood), Border points (located within a core point's neighborhood but not having enough neighbors themselves), or Noise points (neither core nor border).

DBSCAN does not require you to specify the number of clusters in advance. However, tuning eps and min_samples is vital. If eps is set too small, most points will be treated as noise; if set too large, separate clusters will merge into a single entity.

Operator Note: DBSCAN represents noise points using the label -1. This makes it an excellent algorithm for anomaly and outlier detection alongside conventional cluster analysis tasks.
Python 3
import numpy as np
from sklearn.cluster import DBSCAN

# Generate a synthetic dataset with clusters and noise points
np.random.seed(42)
cluster1 = np.random.normal(0, 1, (20, 2))
cluster2 = np.random.normal(10, 1, (20, 2))
noise = np.random.uniform(-5, 15, (5, 2))
X = np.vstack([cluster1, cluster2, noise])

# Initialize and fit DBSCAN with an eps radius of 2.0 and min_samples of 4
dbscan = DBSCAN(eps=2.0, min_samples=4)
dbscan.fit(X)

print("Cluster Labels assigned (outliers marked as -1):")
print(dbscan.labels_)

Executing Clustering: Extracting Labels and Cluster Centers

After fitting a clustering model to your data, you must extract and analyze the resulting configurations. In scikit-learn, clustering algorithms provide key attributes once fitting is completed. For centroid-based algorithms like KMeans, the primary outputs of interest are the cluster labels assigned to each input sample and the coordinates of the cluster centers.

The .labels_ attribute is a 1D array of integers of size equal to the number of input rows. It details the precise cluster assignment (ranging from 0 to K-1) for each instance. Outliers in DBSCAN are represented by a value of -1. The .cluster_centers_ attribute is a 2D array of shape (n_clusters, n_features) representing the coordinate matrix of the calculated centroids. By mapping these attributes back to the original pandas DataFrame, you can construct cluster profiles, aggregate characteristics, and interpret the physical meaning of each subgroup.

Analyzing these extracted centroids helps interpret user behaviors or feature distributions. For instance, in customer segmentation, a high average spending combined with high income maps to a 'premium user' profile.

Operator Note: Use pandas .groupby(Cluster_Label).mean() to quickly aggregate and profile your data features across all clusters immediately after retrieving the labels.
Python 3
import pandas as pd
from sklearn.cluster import KMeans

# Create synthetic raw customer metrics
data = {
    'Annual_Income_k': [15, 16, 17, 70, 72, 75, 110, 115, 120],
    'Spending_Score': [80, 85, 78, 45, 50, 48, 90, 85, 95]
}
df = pd.DataFrame(data)

# Fit KMeans
model = KMeans(n_clusters=3, random_state=42, n_init='auto')
df['Cluster_Label'] = model.fit_predict(df)

# Retrieve cluster centers (centroids)
centroids = model.cluster_centers_

print("Enriched DataFrame:")
print(df)
print("\nExtracted Centroids (Income vs Spending):")
for idx, cent in enumerate(centroids):
    print(f"Cluster {idx}: Income={cent[0]:.1f}k, Spending Score={cent[1]:.1f}")

Knowledge Check

Ready to test your understanding of 5. Unsupervised Learning: Clustering?

Back