Sub topic 11
Unsupervised learning: finding structure without labels
This chapter assumes you have read the earlier chapters on features, labels, and supervised learning. You should also be comfortable with NumPy arrays, the mean and variance, and scikit-learn's fit and predict pattern. It introduces the unsupervised setting and its two main tasks. Later chapters cover clustering and dimensionality reduction in more detail.
What changes when labels disappear
In supervised learning, every training example comes with a label, and the model learns a mapping from features to that label. The loss function measures how far a prediction is from the known answer.
In unsupervised learning, the dataset contains only features. There is no column to predict and no answer key. The model is asked to describe the data itself: which examples resemble each other, which directions carry the most variation, and which points look unusual.
This changes three things:
- The goal is looser. "Find structure" has no single correct answer. Several different groupings of the same data can all be reasonable.
- The objective is internal. The training objective is computed from the data and the model alone. K-means, for example, minimizes the squared distance from each point to its cluster center.
- Evaluation is harder. With no ground truth, you cannot compute accuracy on a test set. You judge results by internal measures, by stability, or by whether they are useful for a downstream task.
The main tasks
Unsupervised methods fall into a few families. Clustering and dimensionality reduction are the two this tutorial covers.
| Task | Question it answers | Typical output | Example method |
|---|---|---|---|
| Clustering | Which examples belong together? | A group id for each example | K-means |
| Dimensionality reduction | Can fewer numbers describe each example? | A shorter feature vector per example | PCA |
| Anomaly detection | Which examples do not fit the pattern? | A score or flag per example | Isolation forest |
| Density estimation | How likely is a given example? | A probability model of the data | Gaussian mixture |
A first example: clustering without looking at labels
The iris dataset has species labels, but we can discard them to simulate an unlabeled problem. K-means needs the number of clusters in advance. It starts with k guessed centers, assigns each point to its nearest center, moves each center to the mean of its points, and repeats until the centers stop moving.
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
X, _ = load_iris(return_X_y=True) # the labels are ignored
kmeans = KMeans(n_clusters=3, n_init=10, random_state=0)
kmeans.fit(X)
print(kmeans.labels_[:10])
print(kmeans.cluster_centers_)fit receives only X. There is no y, which is the visible sign that this is unsupervised. The attribute labels_ holds the cluster id of each training example. The cluster_centers_ array has one row per cluster and one column per feature, so each row is a typical example of that group.
Cluster ids are arbitrary. Cluster 0 on one run may be cluster 2 on another. The ids only say which examples share a group, not what the group means.
Judging a result without ground truth
When there is no answer key, you have three options.
Internal measures
These use only the data and the assignments. The silhouette score compares, for each point, its average distance to its own cluster with its average distance to the nearest other cluster. It ranges from -1 to 1, and higher means tighter, better-separated clusters.
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
X, _ = load_iris(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)
for k in range(2, 7):
labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(X_scaled)
print(k, round(silhouette_score(X_scaled, labels), 3))Do not pick k blindly from the highest score. On iris, the best silhouette often appears at k=2, because two of the three species overlap. The score tells you about geometry, not about which grouping serves your purpose.
External checks when some labels exist
Sometimes labels exist but were not used in training, as in a benchmark. Then you can compare clusters to labels with a measure that ignores cluster numbering, such as the adjusted Rand index. A value of 1 means perfect agreement, and a value near 0 means agreement no better than chance.
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
X, y = load_iris(return_X_y=True)
labels = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(X)
print(adjusted_rand_score(y, labels))You should see a value of roughly 0.73. That is good but not perfect, because the versicolor and virginica species overlap in feature space. Plain accuracy would be wrong here, since cluster 0 need not correspond to class 0.
Usefulness
The most honest test is whether the output helps with a real task. Customer segments are useful if the marketing team can act on them. A compressed feature set is useful if a downstream model trained on it performs as well as one trained on the original features.
A second example: compressing features
Dimensionality reduction rewrites each example with fewer numbers while keeping as much information as possible. PCA finds new axes, called principal components, that point in the directions of greatest variance. It then keeps only the first few.
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
X, _ = load_iris(return_X_y=True)
pca = PCA(n_components=2)
X_2d = pca.fit_transform(X)
print(X_2d.shape)
print(pca.explained_variance_ratio_)The shape is (150, 2): 150 examples, now described by 2 numbers instead of 4. The explained_variance_ratio_ array reports the share of total variance each component keeps. For iris, the first component keeps over 90 percent, so two numbers describe the data well. Plotting X_2d is a common way to look at data that has too many features to plot directly.
Common errors
Forgetting to scale features
K-means and PCA both depend on distances or variances. A feature measured in thousands will dominate one measured in fractions, and the structure you find will mostly reflect units. Standardize features first with StandardScaler unless they already share a scale. Iris is a mild case because all four features are in centimeters. A table mixing income and age is not.
Treating clusters as real categories
K-means always returns k clusters, even for data with no group structure at all. Uniform random noise would still be split into k tidy pieces. A cluster is a statement about distances in your chosen features. It is not proof that a natural category exists.
Choosing k by habit
The number of clusters is a modeling decision. Try several values, compare silhouette scores, check that results are stable across random seeds, and inspect the clusters' centers or members. If a group's meaning cannot be described, k is probably wrong or the features are not informative.
Fitting on all the data and calling it generalization
Unsupervised models can still overfit in a loose sense. A model with many clusters can memorize quirks of one sample. To check, fit on one portion of the data and see whether new examples fall into sensible groups with similar properties.
Assuming PCA captures what matters
PCA keeps directions of high variance. Those directions are not necessarily the ones that separate your classes or predict your target. A low-variance direction can be the most informative one. Treat PCA as a way to compress and visualize, and confirm that a downstream task still works.
Using unsupervised output in a pipeline
Unsupervised steps often feed a supervised model. You might reduce 300 features to 20 with PCA before training a classifier, or add a cluster id as a new feature. When you do this, fit the unsupervised step on the training split only, then apply it to the test split with transform or predict. Fitting on the full dataset lets information about the test examples leak into training.
Exercise
Exercise
You run KMeans with nclusters=4 on a customer table with columns "age" (20 to 80) and "annualspend" (0 to 200000). The clusters split almost entirely by spend. Name the likely cause and one fix. Then explain why comparing the cluster ids to a known "plan type" column with plain accuracy would be misleading.
Show answer
The cause is unscaled features. Spend has a far larger numeric range than age, so it dominates the distance calculation. The fix is to standardize both columns first, for example with StandardScaler, then refit. Plain accuracy is misleading because cluster ids are arbitrary: cluster 0 has no fixed relationship to plan type "0" or "basic". A permutation-invariant measure such as the adjusted Rand index compares groupings regardless of how the ids are numbered.