Unsupervised Learning: k-Means Clustering and PCA
Group unlabeled data with the k-means algorithm, choose the number of clusters, and reduce many features to a few with principal component analysis.
Welcome back!
Step 1 of 13Learn
Finding groups nobody labeled
An online store has purchase histories for 200,000 customers but no labels saying what kind of customer each one is. The marketing team wants to tailor campaigns. Clustering finds groups of similar customers automatically.
k-means is the classic clustering algorithm. You choose k, the number of clusters, and it repeats two simple steps:
- Initialize: place k centroids (cluster centers), for example at k randomly chosen data points.
- Assign: put each point in the cluster of its nearest centroid.
- Update: move each centroid to the mean of the points assigned to it.
- Repeat steps 2 and 3 until assignments stop changing.
k-means is trying to minimize the within-cluster sum of squares: the total squared distance from each point to its cluster's centroid. Each assign-and-update round can only lower this number or leave it unchanged, so the algorithm always converges, usually within a few dozen rounds.
The result for the store might be four groups: frequent small-basket shoppers, occasional big spenders, discount hunters who buy only during sales, and customers who bought once and never returned. Interpreting the clusters is the human part: k-means finds groups, but people have to look at the centroids and decide what each group means and whether it's useful.
Practical cautions:
- Scale features first, since k-means uses distances.
- Results depend on the starting centroids. Run it several times with different initializations and keep the best; smarter initialization (k-means++) is standard in libraries.
- k-means assumes roughly round, similarly sized clusters. For long, curved or very uneven clusters, density-based methods such as DBSCAN or hierarchical clustering can do better.
Step 2 of 13Practice · Put in order
Put the steps of the k-means algorithm in order.
Drag the items, or use the arrow buttons, to put them in order.
- Move each centroid to the mean of its assigned points
- Repeat assignment and update until assignments stop changing
- Choose k and place k initial centroids
- Assign every point to its nearest centroid
Step 3 of 13Diagram
The k-means loop
Tap a shape with to see more.
- Assign points
Each point joins its nearest centroid.
- Move centroids
Each centroid moves to the mean of its points.
- Check change
If assignments did not change, the algorithm has converged.
Step 4 of 13Practice · Code challenge
Write nearestCentroid(point, centroids) that returns the index of the centroid closest to the point (by Euclidean distance). Points and centroids are arrays of numbers. If two are equally close, return the lower index.
nearestCentroid([1, 1], [[0, 0], [5, 5]])nearestCentroid([4, 6], [[0, 0], [5, 5]])nearestCentroid([10, 0], [[0, 0], [5, 5], [9, 1]])nearestCentroid([2, 2], [[0, 0], [4, 4]])
Step 5 of 13Learn
How many clusters?
k-means needs you to choose k, and the data doesn't come with an answer key. Common approaches:
The elbow method. Run k-means for k = 1, 2, 3, … and plot the within-cluster sum of squares (often called inertia) against k. Inertia always decreases as k grows, since with k equal to the number of points every point is its own cluster and inertia is zero. Look for the elbow: the k after which adding clusters gives only small improvements.
The silhouette score. For each point, compare how close it is to its own cluster with how close it is to the nearest other cluster. Scores range from −1 to 1; higher averages mean better-separated clusters. Choose the k with the highest average silhouette.
Usefulness. Often the deciding factor. A marketing team may be able to run four distinct campaigns but not eleven. Clusters must also be stable (similar when you rerun on a new sample) and interpretable.
A healthy dose of skepticism helps. Clustering algorithms will always return clusters, even in data with no real group structure. If you feed k-means uniformly random points with k = 5, it will happily produce five clusters. Checking stability across samples and asking whether the clusters predict anything useful, such as different responses to a campaign, guards against finding patterns that aren't there.
Other unsupervised tasks include anomaly detection (finding points that don't fit any normal pattern, used for fraud and equipment monitoring) and association rules (discovering items often bought together).
Step 6 of 13Practice · Chart
An elbow plot
Tap the elbow: the k after which extra clusters barely help.
Tap the point that answers the question, then press Check.
| Item | Inertia |
|---|---|
| k=1 | 5,200 |
| k=2 | 2,600 |
| k=3 | 1,500 |
| k=4 | 700 |
| k=5 | 620 |
| k=6 | 570 |
| k=7 | 540 |
Step 7 of 13Practice · Choose one
Inertia for k-means is 1,000 at k = 2, 400 at k = 3, 330 at k = 4, 300 at k = 5 and 285 at k = 6. Using the elbow method, which k is the most reasonable choice?
Step 8 of 13Learn
PCA: fewer dimensions, most of the information
Datasets often have many features, some of them redundant: height in inches and height in centimeters, or dozens of survey questions that all measure the same underlying attitude. Principal component analysis (PCA) finds a smaller set of new features that keep most of the information.
The idea in pictures: imagine data points in two dimensions forming a long, tilted cloud. PCA finds the direction along which the points are most spread out, the direction of maximum variance, and calls it the first principal component. The second component is the direction of the next-most variance, at a right angle to the first. With more features, PCA continues, producing components ordered by how much variance each explains.
Keeping the first few components and dropping the rest reduces dimensionality. For example, 50 correlated survey features might be summarized by 5 components that together explain 90% of the variance.
Uses:
- Visualization: project high-dimensional data onto 2 components to plot it.
- Speed and noise reduction: fewer features for a downstream model, and dropping low-variance components can filter noise.
- Handling correlated features: components are uncorrelated by construction.
Cautions:
- Standardize first. Otherwise features with large units dominate the variance.
- Components are harder to interpret: each is a weighted mix of the original features.
- Variance is not the same as relevance: a low-variance direction might still be the one that predicts your target. PCA ignores labels entirely.
- As with all preprocessing, fit PCA on training data only.
Step 9 of 13Practice · Chart
Variance explained by each principal component
Tap the first component at which you keep at least 90% of the variance.
Tap the bar that answers the question, then press Check.
Step 10 of 13Practice · Work it out
PCA on a dataset gives components that explain 45%, 25%, 15%, 8%, 4% and 3% of the variance. What is the smallest number of components needed to keep at least 85% of the variance?
Step 11 of 13Note
Step 12 of 13Practice · Match the pairs
Match each technique to what it does.
Tap an answer, then tap the place where it belongs (or drag it there).
- k-means
- Elbow method
- Silhouette score
- PCA
- Anomaly detection
Step 13 of 13Practice · True or false
If k-means returns five clean-looking clusters, the data must contain five real natural groups.
Lesson complete!