Cheat sheet · Module 2
Cheat sheet: trees, ensembles and classical models
Machine Learning · Cheat sheet · Trees, ensembles and classical models
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 (equal to ), entropy . 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 (entropy gain 0.2781).
- For 0/1 labels Gini is , 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 for in 0 to 10, a tree predicts 20.0 at , 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 ). 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_leafof 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 trees with variance and pairwise correlation : . More trees shrink only the second term; is a floor. Independent trees give , identical trees gain nothing.
- To go below the floor, make the trees less alike: random feature subsets per split. This lowers 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 . 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 with a shallow tree fitted to the negative gradient of the loss at the current prediction.
- Squared error: the negative gradient is the residual . Log loss with : it is . Any differentiable loss gives a recipe.
- Worked example: , stumps, : 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 rows.
- Small is high variance (1-NN scores perfectly on its own training data), large blurs boundaries. Choose 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 , 0.91 at 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 : inertia always falls, so look for an elbow and a silhouette peak, in . 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, chosen by cutting; single linkage follows chains) and DBSCAN (dense regions, flags noise as -1;
epsis crucial; oneepsstruggles with different densities).
PCA: centre, covariance , eigen-decomposition, ratio = eigenvalue over the sum, project .
- Worked example: has eigenvalues 3 and 1 (vectors and ), ratios 3/4 and 1/4. Dropping a component leaves a squared error of 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 . The margin width is ; hinge loss is zero past margin 1, so only points near or past the boundary shape the fit.
- Low : smooth surface, wide margin, many points inside it. High : 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 is added: 0.604 to 0.978).
- Not scale invariant. Kernel
SVCfit time grows between and times the number of features;LinearSVCscales almost linearly. Probabilities need an extra, expensive step.
Naive Bayes: , assuming features are independent given the class, so about numbers per class.
- Without smoothing, one unseen word zeroes a class. Laplace smoothing () 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
transformfor 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
| Model | Reach for it when | Breaks when | Scaling needed? |
|---|---|---|---|
| Regularised linear or logistic | Baseline, coefficient story, speed | Strongly curved boundary | Yes |
| k-NN | Small data, few meaningful columns | Many columns, large , strict latency | Yes |
| Linear SVM | Many sparse columns, medium to large | You need probabilities | Yes |
| Kernel SVM | Medium data, curved boundary | Very large | Yes |
| Naive Bayes | Text, tiny data, a baseline in minutes | You need trustworthy probabilities | Gaussian: no |
| Trees and ensembles | Mixed-type tabular data | Extrapolation, tiny data | No |
Quick answers
- Why do more trees not fix a forest? The floor does not depend on ; 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 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 from inertia alone.