6  Organizing the Toy Box

Unsupervised Learning, Clustering, and Dimensionality Reduction

🐾 Evergreen Chapter: Core mathematics and theory do not expire. Last verified: 2026-02-24

Prerequisites: Chapter 5 Technical Keywords: Unsupervised Learning, K-Means Clustering, Hierarchical Clustering, DBSCAN, Gaussian Mixture Models (GMM), Anomaly Detection, Silhouette Score


In Chapter 5, Pixel went to Kitty Training School. The human stood over him, holding up toys and providing the exact answers: “This is a mouse. This is a ball. This is a laser pointer.” Because the human provided the labels (y), the optimization engine knew exactly how to correct the kitten’s mistakes. This was Supervised Learning.

But what happens when the human leaves the room?

Pixel is left alone with a massive box of 1,000 completely unknown objects. There are no labels. No right or wrong answers. No loss function telling him he made a mistake.

Yet, as a curious kitten, Pixel doesn’t just stare at the pile. He starts batting things around. He notices that some objects are soft and fuzzy. He piles those together. He notices some objects are hard, round, and roll away when smacked. He pushes those into a different corner. He finds a few objects that smell like catnip and guards them fiercely.

Without any human supervision, Pixel has discovered the hidden structure of the data. This is Unsupervised Learning.


6.1 The Goal: Finding Hidden Structure

In Unsupervised Learning, we only have Features (X). We have no Labels (y).

Our goal is not to predict a specific answer, but to answer questions like:

  • “How is this data organized?”
  • “Which data points are similar to each other?”
  • “Are there any data points that don’t belong here at all?”

The most common way to organize unlabelled data is Clustering—grouping similar items together so that items in the same pile are more similar to each other than to items in other piles.

Let’s look at the algorithms Pixel uses to organize his toy box.


6.2 K-Means Clustering: The Center of Gravity

Pixel decides he wants to organize the 1,000 toys into exactly 3 piles (K=3). He doesn’t know what the piles will represent yet, he just knows he wants 3 of them.

Here is the K-Means algorithm:

  1. Initialization: Pixel randomly drops 3 special “magnet toys” (called Centroids) into the room.
  2. Assignment: Every regular toy in the room looks at the 3 magnets and slides over to the one it is closest to (using mathematical distance, like Euclidean distance from Chapter 1). We now have 3 rough piles.
  3. Update: Pixel looks at Pile 1. He calculates the exact physical center of that pile (the mean) and moves Magnet 1 to that new center. He does the same for Magnets 2 and 3.
  4. Repeat: Because the magnets moved, some toys might now be closer to a different magnet. The toys re-assign themselves. The magnets move again.

Math Translation: min vs argmin

You will see argmin and argmax constantly in Machine Learning.

  • min() asks: “What is the shortest distance to the magnet?” (Example answer: 2 inches).
  • argmin() asks: “Which magnet is the shortest distance away?” (Example answer: Magnet number 3). Arg stands for “argument” (the input). We do not care about the numerical distance; we care about which pile the kitten belongs to.

This loop repeats until the magnets stop moving. The piles are stable.

Pixel looks at the results. Pile 1 is entirely round objects (balls). Pile 2 is soft objects (plushies). Pile 3 is crunchy things (crinkle balls). He discovered the categories entirely on his own!

Catastrophic Failure: Choosing the Wrong K

K-Means is incredibly fast, but it has a fatal flaw: you have to tell it how many piles (K) to make before it starts. If Pixel’s toys naturally fall into 5 categories, but he forces K=2, the algorithm will awkwardly smash balls and plushies together into a massive, meaningless super-pile.

How do we choose K? We use the Elbow Method. We run the algorithm for K=1, 2, 3... 10 and plot the tightness of the piles (inertia). When the graph stops dropping sharply and bends like an elbow, we’ve found the optimal number of clusters.

Rosetta Stone

Kitten World Math/Concept Python (scikit-learn)
“The 3 magnet toys” Centroids (\mu_k) kmeans.cluster_centers_
“Assign toys to magnets” \arg\min \|x_i - \mu_k\|^2 kmeans.labels_
“Run the algorithm” Lloyd’s Algorithm KMeans(n_clusters=3).fit(X)

K-means clustering illustrated with centroids

K-Means Magnets

6.3 Hierarchical Clustering: The Family Tree of Toys

What if Pixel doesn’t want to guess K in advance? What if he wants to see exactly how all the toys relate to each other, from the bottom up?

He uses Agglomerative Hierarchical Clustering:

  1. Start by treating every single toy as its own tiny pile (1,000 piles).
  2. Find the two toys that are most identical in the whole room and glue them together into a slightly bigger pile (999 piles).
  3. Find the next two closest piles and glue them together.
  4. Repeat this until every toy in the room is glued into one massive, towering mountain of toys.

As Pixel does this, he draws a map called a Dendrogram—a family tree of the toys.

Looking at the tree, he can see that the “Feather Wand” and the “Fuzzy Mouse” were glued together very early (they are highly related). He can see that the “Loud Vacuum Cleaner” wasn’t glued to anything else until the very end (it is fundamentally different from everything else).

If the human wants 4 distinct categories, they just take a pair of scissors and cut the tree horizontally at the branch level that yields 4 trunks.

Analogy

K-Means is dropping magnets and hoping for the best. Hierarchical Clustering is carefully building a family tree from the leaves down to the root.


6.4 DBSCAN: Finding the Weird Shapes

K-Means has a hidden assumption: it favors roughly spherical clusters (circles on a 2D floor), and Hierarchical Clustering’s cluster shapes depend on the chosen linkage criterion (Ward or complete linkage favors compact blobs, whereas single linkage can trace elongated chains).

But imagine the toys are arranged on the floor in the shape of a massive smile, with two eyes above it. K-Means will completely fail to group the “smile” together. It will just chop the floor into rigid, geometric slices.

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) doesn’t care about the center of a pile. It only cares about density—how closely packed the toys are.

  1. Pixel picks a random toy.
  2. He draws a small circle around it (radius \epsilon).
  3. If there are enough toys inside that circle (say, at least 4), he declares it a “Core Point” and starts a new cluster.
  4. He then expands the cluster outward through neighboring Core Points (border points with fewer neighbors still join the cluster, but do not expand it further), like a puddle of spilled milk spreading across the floor.
  5. The puddle snakes and bends, perfectly capturing the “smile” shape!

If Pixel finds a toy that has zero neighbors within its circle, he doesn’t force it into a cluster. He labels it as Noise (an Outlier).

Analogy

DBSCAN is like a contagion of playfulness. If a toy is close enough to an active toy, it joins the game. If a toy is isolated in the corner, it is ignored entirely.


6.5 Gaussian Mixture Models (GMM): Fuzzy Boundaries

K-Means is harsh. A toy is either 100% in Pile 1, or 100% in Pile 2. There is no in-between.

But what if Pixel has a toy that is a fuzzy ball with a small bell inside? It’s halfway between the “Plushie” pile and the “Noisy” pile.

A Gaussian Mixture Model (GMM) uses Probability (Chapter 2). Instead of dropping hard magnets, Pixel drops multiple Gaussian Distributions (bell curves) over the room.

The algorithm calculates: “This toy has a 70% probability of belonging to the Plushie distribution, and a 30% probability of belonging to the Noisy distribution.”

This is called Soft Clustering. It is mathematically more complex, but much more realistic for messy, real-world data where categories overlap.


6.6 Anomaly Detection: “What is the Cucumber Doing Here?”

While organizing his toys, Pixel finds a long, green, terrifying object. It doesn’t roll. It isn’t fuzzy. It doesn’t make noise. It is completely unlike anything else in the room. It is a cucumber the human accidentally dropped.

Pixel leaps straight into the air in terror. He has just performed Anomaly Detection.

In Unsupervised Learning, Anomaly Detection is the process of identifying data points that deviate so significantly from the normal clusters that they arouse suspicion.

  • In DBSCAN, anomalies are the points labeled as “Noise.”
  • In a GMM, an anomaly is a point with an unusually low overall mixture log-density (gmm.score_samples(X)), not a low posterior component-membership probability (since component responsibilities always sum to 100%, even a distant cucumber gets assigned ~100% to whichever bell curve is least far away).
  • Isolation Forests are an algorithm specifically built for this: they randomly slice the data room until every point is isolated. Normal toys take many slices to isolate because they are packed together. The cucumber, sitting alone in the corner, is isolated on the very first slice.

Anomaly Detection is heavily used in the real world for Fraud Detection (credit card transactions) and Predictive Maintenance (sensor readings on a factory machine acting strangely before it explodes).


6.7 Unsupervised Evaluation: The Silhouette Score

Pixel organized his toys into 3 piles. But how do we know if these piles are actually good? In Supervised Learning, we just check the true labels to find the MSE or Accuracy. But here, there are no labels!

To evaluate pile quality mathematically, we score two things: 1. Cohesion: Are the toys in Pile A packed tightly together? 2. Separation: Is Pile A far away from Pile B?

The Silhouette Score combines these into a single number between -1 and 1 for every single data point:

  • +1: The kitten did perfectly. The toy is perfectly in the center of its own tight pile, far from any other pile.
  • 0: The toy is sitting exactly on the border between two piles. Pixel is confused.
  • -1: The toy was thrown into the completely wrong pile.

If the average Silhouette Score of all toys is close to +1, the clusters are excellent. If it’s near zero or negative, the clusters are overlapping messes, and maybe Pixel chose the wrong number of piles (K)!


6.8 Removing the Training Wheels

The Real Engineering

We used magnets and toys to explain Clustering. In a production pipeline, K-Means is an expectation-maximization algorithm minimizing within-cluster sum of squares. DBSCAN relies on epsilon-neighborhoods and minimum points to find dense regions, allowing it to ignore noise. ‘Anomaly Detection’ is how credit card companies flag fraudulent transactions. Unsupervised learning is notoriously hard to evaluate because there’s no ground truth, which is why mathematical heuristics like the Silhouette Score are critical.

6.9 Paws and Reflect: Chapter Quiz

Work through these conceptually before checking the answers.

  1. You have a dataset of customer locations. They live in a dense, snaking line along a major river, and a few isolated farmers live miles away in the desert. Which algorithm is best: K-Means or DBSCAN?

  2. True or False: In Unsupervised Learning, you split your data into X_{train} and y_{train}.

  3. You run K-Means on a dataset and it creates 3 distinct piles. Are you guaranteed that these piles correspond to real, meaningful categories (like “Dog”, “Cat”, “Bird”)?

  4. Why might a bank prefer a Gaussian Mixture Model (GMM) over K-Means when clustering customer risk profiles?

Reveal answers
  1. DBSCAN. It excels at finding non-circular, snaking shapes based on density, and it will correctly identify the isolated farmers as outliers/noise rather than forcing them into a cluster.
  2. False! There is no y (Labels) in Unsupervised Learning. You only have X.
  3. No! Unsupervised algorithms just group data by mathematical similarity. It is up to the human to look at the piles afterward and decide if the grouping actually makes sense in the real world.
  4. Because GMM provides probabilities (Soft Clustering). A customer might be 60% “Low Risk” and 40% “Medium Risk”, which is far more useful to a bank than a hard, absolute categorization.

6.10 Chapter 6 Summary

You’ve learned how an AI finds hidden structures when left entirely alone:

  • Unsupervised Learning: Finding patterns in data (X) without human labels (y).
  • K-Means: Grouping data into K rigid piles by finding the center of gravity (Centroids).
  • Hierarchical Clustering: Building a family tree (Dendrogram) from the bottom up to see how all data relates.
  • DBSCAN: Finding snaking, weirdly shaped clusters based purely on how densely packed the points are, while ignoring isolated noise.
  • Gaussian Mixture Models (GMM): Using probability curves to create “Soft Clusters” where points can belong partially to multiple groups.
  • Anomaly Detection: Finding the terrifying cucumbers—the data points that belong to no cluster at all.

Pixel has organized the living room. He has learned to predict the human’s actions (Chapter 5) and understand his toys (Chapter 6).

But how good is he, really? We are about to give him his report card. It is time for Evaluation. 🐈📝


AI Safety Thread: Chapter 6

The Illusion of Objectivity: It is a common myth that Unsupervised Learning is “unbiased” because humans didn’t provide any labels. This is completely false. The AI groups data based on the features you chose to give it. If you ask an algorithm to cluster job applicants, and one of the features is “Zip Code,” the algorithm will quietly cluster people by race and socioeconomic status (because historically, zip codes correlate heavily with these). The AI isn’t objective; it is perfectly reflecting the structural biases encoded in the geometry of the data you gave it.


Next: Chapter 7: Kitty Report Card →