Skip to main content

Clustering: Unsupervised Learning

K-Means Clustering Visualization

A Different Kind of Problem

So far, all our problems had labels:
  • House prices (we knew the correct price)
  • Spam/not spam (we knew which emails were spam)
  • Customer churn (we knew who churned)
But what if you have data without labels? Real scenarios:
  • Group customers into segments (but you don’t know the segments beforehand)
  • Find patterns in gene expression data
  • Detect anomalies in network traffic
  • Organize documents by topic
This is unsupervised learning. The algorithm finds structure on its own. If supervised learning is like a student taking an exam with an answer key, unsupervised learning is like that same student being handed a box of unlabeled rocks and told to “sort them into groups that make sense.” There’s no right answer — just patterns waiting to be discovered.
Customer Segmentation with Clustering

The Customer Segmentation Problem

Your marketing team wants to send different campaigns to different customer types. But what types exist?
Looking at the scatter plot, you can probably see 3 groups. But how do we find them automatically?

K-Means Clustering

The most popular clustering algorithm. It’s like a game of “hot potato” between cluster centers and data points, where each round brings the centers closer to where they “belong.”

The Algorithm (Simple Version)

  1. Pick K random points as initial cluster centers (like randomly placing K flags on a map)
  2. Assign each point to the nearest center (each person walks to the closest flag)
  3. Update centers to the mean of assigned points (move each flag to the center of its crowd)
  4. Repeat steps 2-3 until nothing changes (the flags stop moving — we’ve converged)
The key insight: this alternating process of “assign then update” is guaranteed to converge, because every step reduces the total within-cluster distance. However, it may converge to a local optimum, not the global one — which is why scikit-learn runs K-Means multiple times (n_init=10 by default) with different random starting positions and keeps the best result.

Using scikit-learn


Choosing K: The Elbow Method

How many clusters should we use?

Silhouette Score: Better Cluster Evaluation

The silhouette score measures how similar a point is to its own cluster vs other clusters. Think of it as asking each data point: “Are you happy in your cluster, or would you rather switch?” s=bamax(a,b)s = \frac{b - a}{\max(a, b)} Where:
  • aa = average distance to points in same cluster (cohesion — “how close am I to my own group?”)
  • bb = average distance to points in nearest other cluster (separation — “how far am I from the next group?”)
Range: -1 (bad) to +1 (good)
  • +1: The point is far from other clusters and close to its own — perfect clustering
  • 0: The point is on the border between two clusters — ambiguous assignment
  • -1: The point is closer to another cluster than its own — likely misassigned

DBSCAN: Density-Based Clustering

K-Means has problems:
  • You must specify K upfront (what if you guess wrong?)
  • Assumes spherical, roughly equal-sized clusters (fails on elongated or ring-shaped groups)
  • Sensitive to outliers (one extreme point can drag a cluster center far from where it should be)
DBSCAN (Density-Based Spatial Clustering) solves all three:
  • Automatically finds the number of clusters based on data density
  • Finds clusters of any shape — rings, crescents, irregular blobs
  • Identifies outliers/noise as points that don’t belong to any cluster
The trade-off: DBSCAN requires you to choose eps (neighborhood radius) and min_samples (minimum density), which can be tricky. And unlike K-Means, DBSCAN struggles when clusters have very different densities — a tight cluster and a sparse cluster might need different eps values.

How DBSCAN Works

  1. For each point, count neighbors within radius eps
  2. If count >= min_samples, it’s a core point
  3. Connect core points that are neighbors
  4. Non-core points near core points are border points
  5. Everything else is noise

Choosing DBSCAN Parameters


Hierarchical Clustering

Builds a tree (dendrogram) of clusters:

Practical Example: Customer Segmentation


Comparison: When to Use What


Connection to Supervised Learning

Clustering can help supervised learning:
Math Connection: Clustering uses distance metrics extensively. Understanding vector similarity helps you choose the right metric.

🚀 Mini Projects

Project 1: Customer Segmentation

Segment e-commerce customers for targeted marketing

Project 2: Image Color Quantization

Compress images using K-Means clustering

Project 3: Anomaly Detection System

Detect outliers using DBSCAN

Project 4: Document Clustering

Organize documents by topic automatically

Project 1: Customer Segmentation

Segment customers based on purchasing behavior for targeted marketing campaigns.

Project 2: Image Color Quantization

Use K-Means to reduce the number of colors in an image (compression).

Project 3: Anomaly Detection System

Use DBSCAN to detect anomalies in network traffic or transaction data.

Project 4: Document Clustering

Automatically organize documents by topic using clustering.

Key Takeaways

No Labels Needed

Clustering finds groups without knowing the answer

K-Means = Centers

Assign to nearest center, update centers, repeat

DBSCAN = Density

Finds arbitrary shapes and identifies noise

Scale Your Data

Distance-based algorithms need scaled features

What’s Next?

You’ve now covered both supervised and unsupervised learning! Let’s dive into the basics of neural networks.

Continue to Module 12: Neural Networks

Learn how artificial neurons work and build your first neural network