Ensembles & Unsupervised Learning
P5.ml-methods.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Supervised Learning Algorithms
Where next?
Later in ML Methods
This module unlocks
Go up a level
P5.ml-methods.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Supervised Learning Algorithms
Later in ML Methods
This module unlocks
Go up a level
A single decision tree, met at the end of the previous module, is fragile: grow it freely and it memorises the training set, prune it hard and it misses real structure. The way out is not a better tree but many trees, and the two ways of combining them behave very differently, because training models independently and averaging them cancels their noise, while training them in sequence so each corrects its predecessor's mistakes chips away at systematic error. The second half of the module then drops the labels altogether and asks how to find natural groups in unlabeled data, and how to compress hundreds of features into a few directions before distance stops meaning anything. Every one of those ideas is reduced to a small worked computation you can follow line by line, at the level of detail an ml-engineer interview will test.
Framing. Bagging attacks variance, boosting attacks bias; clustering and PCA are the unsupervised workhorses. Each step turns the slogan into numbers you can follow.
Bagging trains high-variance learners in parallel on bootstrap samples and averages them (variance down, bias unchanged); random forests add per-split feature subsampling to decorrelate the trees. Boosting fits weak learners sequentially, each on the previous ensemble's errors — gradient boosting fits each new tree to the negative gradient (the residuals for squared error), reducing bias.
Worked example — one gradient-boosting round on residuals. Targets y = [12, 20, 18]; the current ensemble predicts [10, 20, 15]. The next tree learns the residuals, and we add a shrunk step with learning rate 0.1:
residuals = y - pred = [ 2, 0, 3] new_tree ~ fit(residuals) ≈ [ 2, 0, 3] pred += 0.1 * new_tree = [10.2, 20.0, 15.3] # nudged toward y; repeat for the next tree
Each round chases the leftover error, so boosting drives bias down and can overfit without the shrinkage (learning rate) and early stopping. Bagging, by contrast, would train those trees independently and average — no residual chasing, just variance reduction.
Interview-depth machine learning for the ml-engineer track: ensemble methods (bagging, boosting, random forests, gradient boosting), clustering (k-means, hierarchical, DBSCAN), and the curse of dimensionality with PCA — assumptions, trade-offs, and the 'why it matters' framing.
Bagging (bootstrap aggregating) trains many high-variance learners in parallel, each on a different bootstrap sample (sample-with-replacement) of the data, then averages their predictions (or majority-votes for classification):
Because the base learners are (near) unbiased but noisy, averaging reduces variance without inflating bias. Random forests are bagging on decision trees plus per-split feature subsampling — at each split only a random subset of features is considered — which decorrelates the trees so their averaged variance drops further.
Boosting instead fits weak learners sequentially, each one correcting the previous ensemble's errors:
Boosting reduces bias and can drive training error very low, so it can overfit if left unregularised. Random forests are parallel, robust, and low-maintenance; gradient boosting machines (XGBoost / LightGBM) are usually more accurate on tabular data but need careful tuning of the learning rate, tree depth, and early stopping.
Why it matters. This is the classic bias–variance lever: reach for bagging / random forests to kill variance, reach for boosting to kill bias — and know that GBMs win most tabular Kaggle competitions precisely because staged bias reduction plus shrinkage is so effective.
k-means minimises the within-cluster sum of squares via Lloyd's algorithm (alternate: assign each point to its nearest centroid, then recompute centroids):
You must specify k up front; it assumes roughly spherical, equal-size clusters, is sensitive to initialisation (use k-means++ seeding), and is scale-dependent so features must be standardised.
Hierarchical (agglomerative) clustering builds a dendrogram by repeatedly merging the closest clusters under a linkage rule (single, complete, average, Ward). No k is needed upfront — you cut the tree at the height that gives the clusters you want.
DBSCAN is density-based: with parameters eps (neighbourhood
radius) and minPts, it grows clusters from dense cores, finds
arbitrarily shaped clusters, needs no k, and explicitly labels
low-density points as outliers/noise. Its weakness is varying
density — a single global eps struggles when clusters have very
different densities.
Choosing k: the elbow method (plot inertia / within-cluster SS vs k and look for the bend), the silhouette score (how well each point sits in its cluster vs the next-nearest, in [−1, 1] — higher is better), and the gap statistic (compare inertia against a null reference distribution).
Why it matters. Picking the wrong algorithm silently distorts results: k-means will happily split one banana-shaped cluster in two, while DBSCAN handles it but demands density tuning — and without a principled k (silhouette / elbow) the whole unsupervised story is unfalsifiable.
In high dimensions data becomes sparse, distances concentrate (the nearest and farthest neighbours become almost equidistant, so 'nearest' loses meaning), and volume grows exponentially with the number of dimensions — so the sample size needed to cover the space blows up. This curse of dimensionality degrades neighbourhood- and distance-based methods (kNN, k-means, kernel density) and inflates overfitting risk because there are far more ways to fit noise.
PCA (principal component analysis) fights back by projecting the data onto its top principal components — the orthogonal directions of maximum variance, which are the leading eigenvectors of the covariance matrix (equivalently the top singular vectors of the centred data; the P2 Mathematics pillar develops the eigen-decomposition and SVD behind this):
Keeping the first d components retains most of the variance (the explained-variance ratio is the kept eigenvalues' share of the total, Σᵢ≤d λᵢ / Σᵢ λᵢ) while collapsing the rest, which reduces dimensionality, denoises, and speeds up downstream models. The costs: components are linear combinations of features so they lose interpretability, PCA assumes linear structure and that variance = signal, and it requires standardised inputs.
Why it matters. Almost every high-dimensional pipeline (embeddings, images, genomics) leans on dimensionality reduction to stay tractable and generalisable — PCA is the linear baseline that non-linear methods (t-SNE, UMAP, autoencoders) are measured against.
Rigorous references for ensembles and unsupervised learning.
| Type | Resource |
|---|---|
| Book | Hastie, Tibshirani & Friedman, The Elements of Statistical Learning — bagging, boosting, PCA |
| Book | James et al., An Introduction to Statistical Learning — trees, clustering, PCA |
| Paper | Chen & Guestrin, XGBoost: A Scalable Tree Boosting System |
| Paper | Ester et al., A Density-Based Algorithm for Discovering Clusters (DBSCAN) |
| In-app | P5.ml-methods.01 — Supervised Learning Algorithms, for the trees these ensembles are built from |
| In-app | P2 Mathematics pillar — the eigen-decomposition and SVD foundations behind PCA |
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
Off by default. The mentor always gets your file; this only decides whether your own copy stays here. Copies live in this browser only - they do not follow you to another device, and clearing site data removes them.
A scratch console for this page's ideas — ungraded, nothing you run here is recorded.
Scratch console
A scratch console with the scientific stack (pandas, numpy, scikit-learn). Runs on the server — no network, resource-limited and measured.
Output appears here.
Loading your notes...