Cheat sheet · Module 2

Cheat sheet: trees, ensembles and classical models

Machine Learning · Cheat sheet · Trees, ensembles and classical models

Open the moduleModule quiz

The pattern: every method here is a cheap bet. Trees bet that axis-aligned questions can carve up the data, ensembles that averaging or stagewise correction beats one model, k-NN that close points share labels, k-means that clusters are balls, PCA that spread is importance, the SVM that a wide margin generalises, naive Bayes that features speak independently. Know the bet and you know how each one fails.

Tree splits: a tree tries every feature and threshold and keeps the split with the largest gain, the parent’s impurity minus the size-weighted impurity of the children.

  • Gini 1−∑kpk21-\sum_k p_k^2 (equal to ∑kpk(1−pk)\sum_k p_k(1-p_k)), entropy −∑kpklog⁡2pk-\sum_k p_k\log_2 p_k. A pure node scores 0; a 50/50 node scores 0.5 (Gini) or 1 bit (entropy). Regression trees use target variance, and a leaf predicts the mean.
  • By hand: a 5/5 node split into (4, 1) and (1, 4) has Gini gain 0.5−0.32=0.180.5-0.32=0.18 (entropy gain 0.2781).
  • For 0/1 labels Gini is 2p(1−p)2p(1-p), twice the label variance, so squared-error splitting picks the same cut.
  • Greedy: the tree never looks ahead, and an optimal tree is NP-complete to find. On XOR either feature alone has gain 0, so a learner that needs positive gain stops at the root.
  • Boundaries are axis-aligned staircases; predictions are piecewise constant, so trees extrapolate badly (trained on y=2xy=2x for xx in 0 to 10, a tree predicts 20.0 at x=15x=15, a line 30.0).

Controlling a single tree: an unlimited tree reaches 1.000 training accuracy even on noisy labels, so it has memorised the noise.

  • Controls: max_depth, min_samples_leaf, cost-complexity pruning (minimise R(T)+α∣T∣R(T)+\alpha|T|). Choose them on validation data.
  • In the lesson’s noisy circle (best possible accuracy 0.85), validation accuracy peaked near depth 4 (0.763) and fell for no limit (0.715); min_samples_leaf of 10 or 20 did better (0.778, 0.780).
  • Small data changes can give a completely different tree: a single deep tree has high variance.

Bagging and random forests: bootstrap samples (rows drawn with replacement), deep trees, average or vote.

  • Variance of an average of BB trees with variance σ2\sigma^2 and pairwise correlation ρ\rho: ρσ2+1−ρBσ2\rho\sigma^2+\frac{1-\rho}{B}\sigma^2. More trees shrink only the second term; ρσ2\rho\sigma^2 is a floor. Independent trees give σ2/B\sigma^2/B, identical trees gain nothing.
  • To go below the floor, make the trees less alike: random feature subsets per split. This lowers ρ\rho but raises each tree’s variance and bias, so features per split is a hyperparameter (in the lesson’s example, all-features bagging beat the 2-of-6 forest on bias plus variance, 0.583 against 0.656).
  • Averaging leaves bias unchanged, so use deep, low-bias trees.
  • Out-of-bag: a row is missed by a bootstrap sample with probability (1−1/n)n→1/e≈0.368(1-1/n)^n\to1/e\approx0.368. Predict each row with the trees that never saw it for a validation score with nothing held out (oob_score=True). It is right on average and noisy on a small set.

Gradient boosting: start from a constant, then Fm=Fm−1+η hmF_m=F_{m-1}+\eta\,h_m with hmh_m a shallow tree fitted to the negative gradient of the loss at the current prediction.

  • Squared error: the negative gradient is the residual y−Fy-F. Log loss with p=σ(F)p=\sigma(F): it is y−py-p. Any differentiable loss gives a recipe.
  • Worked example: y=(1,3,2,6,7,9)y=(1,3,2,6,7,9), stumps, η=1/2\eta=1/2: MSE falls from 74/9 = 8.22 to 26/9 = 2.89 to 25/18 = 1.39 in two rounds.
  • Smaller learning rate needs more rounds. The number of rounds is a regularisation setting: choose it by early stopping on held-out data, not training loss, which only falls. Row subsampling gives stochastic gradient boosting.
  • Bagging cuts variance with deep trees in parallel; boosting cuts bias with shallow trees in sequence and can overfit if run too long or too fast.

Library defaults (documented, not a ranking): XGBoost eta 0.3, max_depth 6, max_bin 256, with L2 (lambda) and L1 (alpha) penalties. LightGBM grows leaf-wise, which may overfit small data, so keep num_leaves small. Scikit-learn’s histogram boosting uses up to 255 bins plus one for missing values.

Tabular practice

  • A defensible default: regularised linear baseline, then gradient-boosted trees with early stopping, then a shallow tree or scorecard if every decision must be explained. Compare on the same folds with equal tuning effort.
  • Trees win on irregular signals and lose on a line: with a linear signal least squares scored validation MSE 1.050 against 1.516 for boosting.
  • Evidence for trees on medium tabular data (a 2022 benchmark of 45 datasets) is strong, not settled; pretrained tabular models (TabPFN) report wins on up to about 10,000 rows.
  • Impurity importance comes from training statistics and favours many-valued features: it gave about 75% of the credit to pure-noise columns. Use permutation importance on held-out data. With correlated features each copy looks less important than it is; permute them together or keep one per cluster. Neither method is causal.
  • Missing values: learn a side for them (scikit-learn trees, histogram boosting, XGBoost); mean filling can hide a missingness signal. Categoricals: use native support or cross-fitted target encoding; one-hot on a 50,000-level category makes 50,000 sparse columns.

k-NN: stores the data; a query compares with all nn rows.

  • Small kk is high variance (1-NN scores perfectly on its own training data), large kk blurs boundaries. Choose kk on validation data.
  • Scale first: a column in large units dominates Euclidean distance. A noise column multiplied by 100 dropped 5-NN from 0.950 to 0.530, below the 0.607 of always answering “outside”.
  • Curse of dimensionality: nearest and farthest distances converge (ratio 0.04 at d=2d=2, 0.91 at d=1000d=1000 for random data). Irrelevant columns do the same damage.

k-means: minimise inertia, the within-cluster sum of squared distances. Lloyd’s loop: assign each row to its nearest centre, move each centre to its rows’ mean, repeat until nothing changes.

  • Each step can only lower the inertia, so it converges, but to a local optimum. Use k-means++ seeding (probability proportional to squared distance) and several restarts, keeping the lowest inertia. In the lesson, k-means++ raised good runs from 72% to 87% but its worst run still ended at 2.4 times the best.
  • Choosing kk: inertia always falls, so look for an elbow and a silhouette peak, s=(b−a)/max⁡(a,b)s=(b-a)/\max(a,b) in [−1,1][-1,1]. Add stability across restarts and usefulness for the decision.
  • Fails on: non-convex shapes (two rings: purity 0.522), unscaled columns (0.520 raw, 0.970 standardised), outliers (one far point took a cluster alone in 30 of 30 datasets).
  • Alternatives: hierarchical clustering (merge tree, kk chosen by cutting; single linkage follows chains) and DBSCAN (dense regions, flags noise as -1; eps is crucial; one eps struggles with different densities).

PCA: centre, covariance Σ=1n−1Xc⊤Xc\Sigma=\frac1{n-1}X_c^{\top}X_c, eigen-decomposition, ratio = eigenvalue over the sum, project Z=XcVkZ=X_cV_k.

  • Worked example: Σ=(2112)\Sigma=\begin{pmatrix}2&1\\1&2\end{pmatrix} has eigenvalues 3 and 1 (vectors (1,1)(1,1) and (1,−1)(1,-1)), ratios 3/4 and 1/4. Dropping a component leaves a squared error of (n−1)(n-1) times the dropped eigenvalue.
  • Pick components by cumulative explained variance (such as 90% or 95%), but the better test is whether the downstream validation score survives. Fit on training data only.
  • Misleads: units (a column with standard deviation 1,000 took 0.999998 of the variance), signal in a quiet direction (PC1 alone scored 0.508, PC2 alone 1.000, since PCA never sees labels), curved structure, and dense components that are hard to read.

SVM: objective 12w⊤w+C∑imax⁡(0,1−yif(xi))\tfrac12w^{\top}w+C\sum_i\max(0,1-y_if(x_i)). The margin width is 2/∥w∥2/\lVert w\rVert; hinge loss is zero past margin 1, so only points near or past the boundary shape the fit.

  • Low CC: smooth surface, wide margin, many points inside it. High CC: narrow margin, fits training points harder, more risk of fitting noise.
  • A kernel gives the effect of lifted features without building them (a disc becomes linearly separable once x12+x22x_1^2+x_2^2 is added: 0.604 to 0.978).
  • Not scale invariant. Kernel SVC fit time grows between n2n^2 and n3n^3 times the number of features; LinearSVC scales almost linearly. Probabilities need an extra, expensive step.

Naive Bayes: P(y∣x)∝P(y)∏jP(xj∣y)P(y\mid x)\propto P(y)\prod_jP(x_j\mid y), assuming features are independent given the class, so about dd numbers per class.

  • Without smoothing, one unseen word zeroes a class. Laplace smoothing (α=1\alpha=1) fixes it.
  • Classification needs only the larger score, so correlated features can leave accuracy intact while probabilities inflate. Copying every feature 3 times kept accuracy at 0.800 and raised confidence to 0.928; copying one feature 20 times dropped accuracy to 0.650. Do not trust its probabilities.

Beyond k-means and PCA

  • Gaussian mixture with EM: soft assignments, covariance per component, local optimum, starts from k-means in scikit-learn; BIC can choose the number of components.
  • Isolation Forest: random splits isolate anomalies in fewer steps, so a short average path length marks an anomaly. Outlier detection (dirty training data) differs from novelty detection (clean training data).
  • t-SNE is for visualisation: not convex, seed-dependent, global structure not preserved, no transform for new rows. Do not ship island labels as features. UMAP can transform new data but can create false tears in clusters.

Choosing a classical model

ModelReach for it whenBreaks whenScaling needed?
Regularised linear or logisticBaseline, coefficient story, speedStrongly curved boundaryYes
k-NNSmall data, few meaningful columnsMany columns, large nn, strict latencyYes
Linear SVMMany sparse columns, medium to large nnYou need probabilitiesYes
Kernel SVMMedium data, curved boundaryVery large nnYes
Naive BayesText, tiny data, a baseline in minutesYou need trustworthy probabilitiesGaussian: no
Trees and ensemblesMixed-type tabular dataExtrapolation, tiny dataNo

Quick answers

  • Why do more trees not fix a forest? The ρσ2\rho\sigma^2 floor does not depend on BB; decorrelate the trees instead.
  • Bagging or boosting? Bagging averages deep trees to cut variance; boosting adds shallow trees stagewise to cut bias.
  • Boosting training loss keeps falling but validation rises: early stopping on validation; to go lower, shrink the rate and allow more rounds.
  • Why does k-means give different results each run? Non-convex inertia, so local optima; use k-means++ and restarts.
  • Which clustering for curved regions and noise? DBSCAN.
  • Why not keep only the top PCA components? PCA ranks by variance, not by label signal.
  • What does a high SVM CC do? Narrower margin, fewer points inside it, more risk of fitting noise.

Traps

“More trees always help” (not below the correlation floor) · “more boosting rounds always help” · picking rounds by training loss · reading impurity importance as truth · trusting a tree to extrapolate a trend · mean-filling when missingness carries signal · one-hot on a huge category · unscaled columns in k-NN, k-means, PCA or SVM · reading t-SNE islands as segments · trusting naive Bayes probabilities · choosing kk from inertia alone.