Unsupervised Learning: Clustering
7 min read
Unsupervised Learning: Clustering 🌀
Welcome to the fascinating world of Unsupervised Learning! In this corner of machine learning, we're like detectives dropped into a room full of unlabelled items. Our job? To find patterns, group similar things together, and make sense of the chaos without any prior hints. This is what we call clustering.
The Problem: Imagine you have a massive pile of socks, all jumbled up. You need to sort them, but you don't have any predefined categories like "work socks" or "gym socks". You'd naturally start pairing them up based on color, size, and fabric. That's clustering in a nutshell! We're trying to group data points that are similar to each other.
K-Means Clustering: Grouping Similar Data Points 🎯
The Problem it Solves: You have a dataset, and you want to partition it into a specific number of groups, or "clusters". For instance, a marketing team might want to segment customers into distinct groups to tailor their campaigns.
What is K-Means?
K-Means is an algorithm that groups data into a predefined number of clusters (the "K" in K-Means). It does this by trying to find cluster centers, or "centroids," that are representative of each group.
How it Works (Under the Hood):
- Choose K: You decide how many clusters you want to create.
- Initialize Centroids: The algorithm randomly picks K data points to be the initial centroids. Think of these as the starting "capitals" of your clusters.
- Assign to Clusters: Each data point is assigned to the nearest centroid.
- Update Centroids: The centroids are recalculated by taking the mean of all data points assigned to their cluster. The capital moves to the center of its "country".
- Repeat: Steps 3 and 4 are repeated until the centroids no longer move significantly.
A Fun Fact: The "K" in K-Means is a bit of a celebrity. Choosing the right 'K' is a crucial and often debated step in the process!
Example in scikit-learn:
from sklearn.cluster import KMeans
import numpy as np
# Sample data
X = np.array([[1, 2], [1, 4], [1, 0],
[10, 2], [10, 4], [10, 0]])
# Initialize and fit the model
kmeans = KMeans(n_clusters=2, random_state=0, n_init="auto").fit(X)
# Get the cluster labels and centroids
print(kmeans.labels_)
# Output: [1 1 1 0 0 0]
print(kmeans.cluster_centers_)
# Output:
# [[10. 2.]
# [ 1. 2.]]In this example, we created two clusters from our sample data. The labels_ attribute tells us which cluster each data point belongs to, and cluster_centers_ gives us the coordinates of the centroids.
Evaluating Clusters: Silhouette Score and the Elbow Method 🧐
The Problem it Solves: After running a clustering algorithm like K-Means, you need to know how well it performed. Did it create meaningful clusters?
1. The Elbow Method: 🦾
This method helps you choose the optimal number of clusters (K). It works by plotting the within-cluster sum of squares (WCSS) for different values of K. WCSS is the sum of the squared distance between each point and its centroid in a cluster.
As you increase the number of clusters, the WCSS will decrease. The "elbow" of the plot is the point where the rate of decrease sharply changes. This point is a good indication of the optimal number of clusters.
Example in scikit-learn:
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# ... (your data X)
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()The inertia_ attribute in scikit-learn's KMeans model conveniently provides the WCSS value.
2. Silhouette Score: 👤
The Silhouette Score measures how similar a data point is to its own cluster compared to other clusters. The score ranges from -1 to 1.
- 1: The data point is far away from the neighboring clusters.
- 0: The data point is on or very close to the decision boundary between two neighboring clusters.
- -1: The data point is assigned to the wrong cluster.
A higher average Silhouette Score indicates better-defined clusters.
Example in scikit-learn:
from sklearn.metrics import silhouette_score
# ... (your fitted kmeans model and data X)
labels = kmeans.labels_
score = silhouette_score(X, labels)
print(f"Silhouette Score: {score}")You can calculate the silhouette score for different numbers of clusters and choose the one with the highest score.
Hierarchical Clustering and Dendrograms 🌳
The Problem it Solves: What if you don't know the number of clusters beforehand? Or what if your data has a nested structure, like a family tree? This is where hierarchical clustering comes in.
What is Hierarchical Clustering?
It's a clustering method that builds a hierarchy of clusters. There are two main approaches:
- Agglomerative (Bottom-up): Starts with each data point as its own cluster and merges the closest pairs of clusters until only one cluster is left.
- Divisive (Top-down): Starts with all data points in one cluster and recursively splits them into smaller clusters.
Dendrograms: Visualizing the Hierarchy
A dendrogram is a tree-like diagram that records the sequence of merges or splits. It allows you to see the relationship between clusters and helps in deciding the optimal number of clusters by cutting the dendrogram at a certain height. The height of the lines in a dendrogram represents the distance at which clusters were merged.
Example in scikit-learn and scipy:scikit-learn provides AgglomerativeClustering, but to visualize the dendrogram, we often use scipy.
from scipy.cluster.hierarchy import dendrogram, linkage
from matplotlib import pyplot as plt
import numpy as np
# Sample data
X = np.array([[1, 2], [2, 1], [4, 5], [5, 4], [8, 9], [9, 8]])
# Perform hierarchical clustering
linked = linkage(X, 'ward')
# Plot the dendrogram
plt.figure(figsize=(10, 7))
dendrogram(linked,
orientation='top',
labels=range(1, len(X) + 1),
distance_sort='descending',
show_leaf_counts=True)
plt.show()This will generate a dendrogram that visually represents how the data points are clustered.
DBSCAN: Density-Based Spatial Clustering 密度
The Problem it Solves: What if your clusters are not nicely spherical like K-Means assumes? What if they have irregular shapes, and there's noise in your data?
What is DBSCAN?
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is a clustering algorithm that groups together points that are closely packed together, marking as outliers points that lie alone in low-density regions. This makes it great for discovering clusters of arbitrary shape and handling noise.
How it Works (The Gist):
DBSCAN has two key parameters: eps (epsilon) and min_samples.
eps: The maximum distance between two samples for one to be considered as in the neighborhood of the other.min_samples: The number of samples in a neighborhood for a point to be considered as a core point.
The algorithm starts with an arbitrary point and finds all its neighbors within eps. If it has enough neighbors (more than min_samples), a new cluster is started. It then expands the cluster by finding the neighbors of these neighbors, and so on. Points that are not part of any cluster are considered noise.
A Funny Exaggeration: Think of DBSCAN as a party planner. It looks for crowded areas (eps and min_samples) to set up a dance floor (a cluster). Anyone standing too far away from the crowd is considered an awkward wallflower (noise).
Example in scikit-learn:
from sklearn.cluster import DBSCAN
import numpy as np
# Sample data
X = np.array([[1, 2], [2, 2], [2, 3],
[8, 7], [8, 8], [25, 80]])
# Initialize and fit the model
dbscan = DBSCAN(eps=3, min_samples=2).fit(X)
# Get the cluster labels (-1 indicates noise)
print(dbscan.labels_)
# Output: [ 0 0 0 1 1 -1]In this example, the last point is labeled as -1, indicating that DBSCAN considers it to be noise.
Installation and Setup 🚀
To get started with scikit-learn, you'll need to have Python, NumPy, and SciPy installed. The easiest way to install scikit-learn is using pip:
pip install -U scikit-learnIt's highly recommended to use a virtual environment to avoid potential conflicts with other packages.
For Windows:
python -m venv sklearn-env
sklearn-env\Scripts\activate
pip install -U scikit-learnFor macOS and Linux:
python3 -m venv sklearn-env
source sklearn-env/bin/activate
pip install -U scikit-learnReferences 📚
- scikit-learn Documentation:
- Clustering: https://scikit-learn.org/stable/modules/clustering.html
- K-Means: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html
- Silhouette Score: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.silhouette_score.html
- Hierarchical Clustering: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html
- DBSCAN: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html
- Installation Guide: https://scikit-learn.org/stable/install.html
Challenge
You are given a 2D dataset named X.
Your task is to determine the optimal number of clusters for this dataset using the K-Means algorithm and evaluate it using the Silhouette Score. After finding the best number of clusters, you will perform the final clustering.
Complete the following steps:
- Define a range of potential cluster numbers to test, from
k=2tok=10(inclusive). - Iterate through this range. In each iteration:
a. Initialize aKMeansmodel with the current number of clusters (k). For reproducibility, setrandom_state=42andn_init='auto'.
b. Fit the model to the datasetX.
c. Predict the cluster labels for the data.
d. Calculate thesilhouette_scorefor the current clustering and store it. - After the loop, identify the number of clusters (
k) that resulted in the highest Silhouette Score. Store this optimal value in a variable namedoptimal_k. - Finally, instantiate a new
KMeansmodel usingoptimal_kclusters (again withrandom_state=42andn_init='auto'). - Fit this final model to the dataset
Xand store the resulting cluster labels in a variable namedfinal_labels.
Expected result
Your final code should correctly implement the loop to find the best number of clusters and then create the final model. The following variables must be correctly defined and populated:
optimal_k: An integer representing the number of clusters that yielded the highest Silhouette Score from the tested range.final_kmeans_model: An instance ofsklearn.cluster.KMeansthat has been fitted to the dataXusingoptimal_kclusters.final_labels: A NumPy array containing the final cluster assignments for each data point inXfrom thefinal_kmeans_model.