KnowML
FoundationsChapter 02

Classical Supervised ML

Follow five students' hours of study and exam scores as a straight line is fitted, bent, split into decision trees and combined into ensembles. Along the way you'll learn what each classical model decides, how it fails, and why boosted trees still win on tabular data.

⏱ 36 min readAssumes: bias-variance, MLE, cross-entropy (01)
Start reading

Here's a tiny prediction problem. Five students tell you how many hours they studied for an exam, and you know each one's score: 1 hour and 52, 2 hours and 55, 3 hours and 61, 4 hours and 64, 5 hours and 70. A sixth student says they studied for 6 hours, and you're asked to guess the score. You'd probably sketch a trend through the five and read a number off it. That's supervised learning in miniature. You're given training examples, each made of some inputs (called features, here the hours) and a known answer (the label, here the score), and you want a rule that predicts the label for an input you haven't seen.

Chapter 01 gave a three-part recipe for building such a rule: pick a family of functions, pick a loss that scores how wrong a function is on the training data, and adjust its parameters until the loss is small. Every model in this chapter follows that recipe, and what changes is the family: a line, a tree of yes/no questions, a margin, a vote among neighbours. They also arrived in a sensible order, because each one fixed a problem the previous one left open. Linear and logistic regression are fast and easy to interpret but draw only straight boundaries, so nonlinear relationships and interactions between features had to be built by hand. Decision trees (CART, 1984; ID3, 1986) found nonlinear splits on their own, and random forests (Breiman, 2001) and gradient boosting (Friedman, about 1999 to 2001) fixed their instability by averaging many trees or fitting them one after another. XGBoost (Chen and Guestrin, 2016) made boosting fast and regularized, with LightGBM and CatBoost as siblings, and gradient-boosted trees still dominate tabular data, the rows-and-columns kind you'd find in a spreadsheet or a database table, in 2026. That kind of data rarely has the structure that neural networks built for images and text (CNNs and Transformers) exploit.

We'll follow the same path with our five students. First comes the straight line through them and the place where it breaks, then a fix for yes/no answers, then fixes for curves and for overfitting. After that we let the data choose its own splits with decision trees and combine many trees in two different ways. Then come three models that decide differently (support vector machines, nearest neighbours and naive Bayes), and a last section on choosing a metric and avoiding the mistakes that make a model look better than it is.

You've met bias, variance and cross-entropy in chapter 01, and we'll recall each briefly where it matters. If you want a one-sentence answer for an interview, it's this: on tabular data, gradient-boosted trees are still the default that wins competitions and production pipelines. By the end of the chapter you should be able to say why.

01Fitting a line to five students

Let's begin with the simplest rule we could pick, a straight line. Writing it as score = slope × hours + intercept says that the prediction starts at the intercept for zero hours and rises by the slope for each extra hour. Slope and intercept are the parameters, the numbers that fitting gets to choose. To choose them we need a loss. For each student we take the vertical gap between the line and the real score, called the residual, square it so that misses above and below the line both count and big misses count extra, and add the results up. The least-squares line is the one with the smallest total. With more than one feature, say hours studied and hours slept, the line becomes a flat surface called a hyperplane, and the idea stays the same. Predicting a number this way is called regression.

Least squares has a pleasant property: we don't have to search for the answer. Our loss is the sum of squared residuals, , written in matrix form, where holds the features and the coefficients (the slope and intercept, and more of them when there are more features). A gradient tells us how the loss changes as each coefficient moves, and it's zero at the minimum. Setting the gradient with respect to to zero and solving gives the normal equation:

  • X the design matrix, shape (n_examples, n_features) — one row per training example, one column per feature (plus a constant column for the intercept).
  • y the target vector, shape (n_examples,).
  • β̂ the closed-form optimal coefficients — no iteration required, assuming is invertible.

For our five students, has five rows and two columns, the hours and a column of ones that gives the line its intercept. Sometimes can't be inverted, or is too large to invert directly, which happens with many correlated features or more features than examples. Then we minimize the same objective step by step with gradient descent: start from any guess, compute the gradient of the mean squared error (MSE, the average squared residual), , and move a small distance downhill with the usual update . It's the same objective with two ways to reach the minimum.

Here is the closed-form route on the five students. It stacks the hours next to a column of ones, hands both to NumPy's least-squares solver, and uses the fitted slope and intercept to predict each student's score and then the score for 6 hours.

Try it Fit a line to five exam scores with least squares
import numpy as np

hours = np.array([1, 2, 3, 4, 5], dtype=float)       # hours studied
score = np.array([52, 55, 61, 64, 70], dtype=float)  # exam score

X = np.column_stack([hours, np.ones_like(hours)])    # slope and intercept
slope, intercept = np.linalg.lstsq(X, score, rcond=None)[0]
pred = slope * hours + intercept

print(f"score = {slope:.2f} x hours + {intercept:.2f}")
print("predictions:", np.round(pred, 1))
print("mean absolute error:", np.round(np.abs(pred - score).mean(), 2))
print("prediction for 6 hours:", round(slope * 6 + intercept, 1))
The fitted line is score = 4.50 x hours + 46.90. Its predictions land within an average of 0.72 points of the real scores, and it predicts about 73.9 for a student who studies 6 hours. Learning here is choosing the two numbers, slope and intercept, that make the errors smallest.

Read the first line of output as a sentence. Each extra hour adds 4.50 points, and a student who studied nothing would be predicted 46.90. Those predictions, 51.4, 55.9, 60.4, 64.9 and 69.4, sit close to the real 52, 55, 61, 64 and 70, so the average miss is only 0.72 points. For our sixth student, 4.50 × 6 + 46.90 gives the 73.9 we were after.

Notice how much the coefficients tell us. Each one says how far the prediction moves per unit change in its feature, holding everything else fixed, and that interpretability is the main reason to start here. It also marks the limit. A straight line can't bend, so it can't represent a relationship where the effect of one feature depends on the value of another, unless we build that interaction ourselves as a new column. Before we deal with that, there's probably a more basic problem on your mind. What if the answer we want isn't a number, but pass or fail?

02From a number to a class

Predicting a category instead of a number is called classification. Say a score of 60 or more is a pass. Our five students then have labels fail, fail, pass, pass, pass, and we can write those as 0 and 1. One tempting move is to fit the same straight line to the 0/1 labels and call the prediction a pass whenever the line gives 0.5 or more. That breaks quickly. The line's output is unbounded, so a student who studied a great deal gets a value well above 1, and squared error counts that as a large mistake even though it's the right answer, only more confident. A spam filter shows the same thing: a score of 4.0 for an obvious spam email is penalized exactly as if it were wrong, because squared error has no idea that going above 1 isn't a direction worth pushing.

What we want is a function that takes the line's unbounded output and squeezes it into the range between 0 and 1, where it can be read as a probability. That function is the sigmoid, and putting it after a linear model gives logistic regression:

The linear part, , is unbounded, exactly like linear regression's output. The sigmoid is what squashes it into , so the output reads as a genuine probability, and we choose a cut-off, often 0.5, to turn the probability into a class. With probabilities in play the loss changes too. Chapter 01 worked out that cross-entropy is the maximum-likelihood loss for a class label, and that unlike squared error it doesn't saturate (go flat and stop teaching the model anything) when the model is confidently wrong. We won't re-derive that. We just apply it: fitting and means minimizing the cross-entropy between the predicted probability and the true label, and chapter 01 explains how that loss behaves.

A hard-threshold cousin: the perceptron

There's an older relative of logistic regression that's worth meeting now, because it shows the limit of straight boundaries very clearly. The perceptron (Rosenblatt, 1958) is a single linear classifier: a weighted sum of the inputs plus a constant (the bias), passed through a step function that outputs 0 below a cut-off and 1 above it. It's trained with a simple rule that nudges the weights toward misclassified points. Structurally it's almost identical to logistic regression. It differs in two ways, since its output is a hard 0/1 decision and not a smooth probability, and its update rule isn't derived from a loss gradient the way logistic regression's is.

Minsky and Papert showed in 1969 that a single perceptron can't learn XOR, the function that is 1 when exactly one of its two inputs is 1. It can only separate data that is linearly separable, meaning a straight line (or hyperplane) can put each class on its own side. That limitation is why nobody stopped there. Stack perceptron-like units into layers, replace the step function with a smooth activation, and add backpropagation to train the whole stack, and you have the multilayer perceptron, where chapter 04 (Neural Network Fundamentals) picks up the story directly.

For this chapter, the point is the same one we reached with the straight line. Both linear regression and logistic regression draw boundaries that can't bend, and real relationships often do. To let a line bend cheaply, we can hand it more columns to work with, and that immediately raises a new worry about how far a flexible fit should be trusted.

03Polynomial features and regularization

Giving the line curves

Suppose the extra hours of study help less and less as the night wears on, so the true relationship curves. We can still use linear regression if we add columns that bend: , , or an interaction term that multiplies two features. For the students that could be a column holding hours squared next to the hours column. Linear regression on the expanded set of columns can now fit curves and interactions, and the model is still linear in the parameters, and that's all the closed-form solution from the last section requires.

That fix costs us two things. We now choose by hand which nonlinear terms to add, and high-degree polynomial terms overfit badly, which means they fit the quirks of the training points so closely that they do badly on new ones. Outside the range of the training data the damage is worst, because small differences in the fit near the training points can blow up into huge swings just past the boundary. This hand-built feature engineering is the step that the tree-based models later in the chapter make largely unnecessary.

Penalizing large coefficients

Overfitting doesn't need polynomials. The unpenalized least-squares solution overfits whenever features are correlated or numerous relative to the number of examples. Imagine recording each student's study time twice, once in hours and once in minutes. Those two columns carry the same information, and least squares has no way to prefer one over the other, so it's free to hand them large coefficients that chase noise. A usual remedy is to add a penalty to the loss that grows with the size of the coefficients, so a large coefficient has to earn its place. There are two standard penalties, with (a number we choose) setting how strong the penalty is:

  • λ regularization strength — recovers plain least squares; larger shrinks coefficients harder.
  • Σβⱼ² the L2 (ridge) penalty — smooth, differentiable everywhere, shrinks every coefficient continuously toward zero.
  • Σ|βⱼ| the L1 (lasso) penalty — has a kink at zero for every coefficient, and that is what makes it capable of setting coefficients to exactly zero and not just small. Why that happens is explained just below.

Both shrink coefficients toward zero as grows, but they shrink differently. Ridge, the L2 penalty, shrinks every coefficient smoothly. Lasso, the L1 penalty, can push coefficients all the way to zero, so it performs feature selection as a side effect of fitting. That difference shows up in practice, and it's also one of the most commonly asked interview questions about this chapter.

Why does lasso zero out coefficients when ridge doesn't?

Both penalties can be understood as the same constrained optimization: minimize squared error while the coefficients stay inside some budget region. Each has a different shape. Ridge's constraint, , is a circle (a sphere, in higher dimensions). Lasso's, , is a diamond, with sharp corners sitting exactly on the coordinate axes, and those corners are the points where one or more coefficients are exactly zero.

Now picture the unconstrained least-squares solution as the center of a set of elliptical contours of equal squared error, spreading outward. We get the regularized solution wherever the growing ellipses first touch the budget region. A circle has no corners, so that first contact is, generically, a point on the smooth curve where every coordinate is nonzero, and the coefficients get shrunk but not zeroed. A diamond's corners stick out toward the ellipses and tend to be touched first, and those are exactly the places where some coordinates are zero. So lasso routinely zeroes coefficients out, while ridge, however large gets, almost never does. It's a favourite interview question because you can draw it in a few seconds.

We can see the same thing in numbers. It builds 60 examples with 8 features, of which only features 0, 4 and 6 matter (their true coefficients are 3, -2 and 1.5), and makes column 3 a near-copy of column 0, like our hours and minutes. Ridge has a closed-form solution that looks like the normal equation with lam added to the diagonal. Lasso has none, so the loop fits one coefficient at a time. The line with max(abs(rho) - lam / 2, 0.0) is the diamond's corner in code: once a feature's pull on the fit drops below lam / 2, its coefficient snaps to exactly zero.

Try it Fit the same data with ridge and lasso and compare the coefficients
import numpy as np
rng = np.random.default_rng(0)

n, d, lam = 60, 8, 12.0
X = rng.normal(size=(n, d))
X[:, 3] = X[:, 0] + 0.05 * rng.normal(size=n)   # a near-duplicate
beta = np.array([3., 0., 0., 0., -2., 0., 1.5, 0.])
y = X @ beta + 0.5 * rng.normal(size=n)

# Ridge is smooth everywhere, so there is no kink to land on.
ridge = np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y)

# Lasso has no closed form. The max(., 0) below IS the diamond's
# corner: once a feature's pull drops under lam/2, it snaps flat.
lasso = np.zeros(d)
for _ in range(400):
    for j in range(d):
        rho = X[:, j] @ (y - X @ lasso + X[:, j] * lasso[j])
        pull = max(abs(rho) - lam / 2, 0.0)
        lasso[j] = np.sign(rho) * pull / (X[:, j] @ X[:, j])

print("X", X.shape, " truly nonzero:", np.flatnonzero(beta).tolist())
print("ridge:", np.round(ridge, 3) + 0.)
print("lasso:", np.round(lasso, 3) + 0.)
print("exactly 0.0  ->  ridge", int((ridge == 0).sum()),
      " lasso", int((lasso == 0).sum()))
Last line: ridge 0 exact zeros, lasso 5. Lasso's three surviving coefficients are at indices 0, 4, 6, the three that were ever real. Columns 0 and 3 are near-duplicates by construction: ridge splits the credit between them, 1.292 and 1.255, while lasso gives one of them 2.813 and the other nothing. Ridge's coefficients on the useless features (such as -0.081, 0.054 and 0.015) are tiny, but tiny still means you ship all eight features and compute all eight at inference time. This is the practical difference the diamond's corners buy you.

Start with the last line, which counts exact zeros: none for ridge, five for lasso. Lasso kept exactly the three coefficients that were ever real. Then compare columns 0 and 3. Ridge splits the credit between the near-duplicates, and lasso gives one of them 2.813 and the other nothing. Ridge's coefficients on the useless features are tiny, but tiny isn't zero, and you'd still have to collect all eight features and compute with them at inference time, the moment a trained model makes a prediction. Penalties keep a linear model honest. They don't make it find a nonlinear pattern, though, and for that we need a different kind of model.

04Decision trees

Hand-built columns work, but they ask us to guess the shape of the relationship before we've seen it. A decision tree lets the data say where the structure is. It repeatedly asks the single best yes/no question about one feature, splits the training data into two purer groups, and then does the same inside each group. For our students the best first question is "did you study at most 2.5 hours?", because everyone on the yes side failed and everyone on the no side passed. Each final group is called a leaf, and it predicts the majority class among its training examples (or, for a numeric target, their mean). The tree's function shape is a set of axis-aligned rectangular regions, rectangles whose sides line up with the feature axes.

What does "best" question mean? We want the split that makes the two groups as pure as possible, meaning each group holds mostly one class, and two measures of impurity dominate:

  • Information gain. The drop in entropy, , where is the fraction of the group in class . Literally how much less uncertain you are about the class label after the split.
  • Gini impurity. , the probability that two randomly drawn examples from the node would be misclassified if you labeled them according to the node's class distribution.

For our five students, the group before any split holds two fails and three passes, so its Gini impurity is 1 − (0.4² + 0.6²) = 0.48. After the 2.5-hour split both groups are pure and the impurity is 0. Both measures are saying "how mixed is this group", just with different curvature, and in practice they usually produce very similar trees. Gini is marginally cheaper to compute, since it has no logarithm, and is the default in most libraries, and you'll probably never see the choice change a tree's structure or accuracy meaningfully. Trees are also greedy: at each step a tree tries every candidate split on every feature and takes the one that's best right now, without looking ahead.

Left alone, a tree keeps splitting until every leaf is pure. With five tidy students that's harmless, but with hundreds of noisy ones it means memorizing individual training points, including their noise. Pruning is the fix, and it comes in two forms. One is to stop early, with a maximum depth, a minimum number of samples per leaf, or a minimum impurity decrease required to accept a split. Or we can grow the full tree and then cut back branches whose removal doesn't hurt performance on held-out data, meaning examples the tree wasn't trained on (cost-complexity pruning). Either way the goal is the same, to trade a little training accuracy for a tree that generalizes.

Pruning helps, but a single tree stays a low-bias, high-variance model. In the language of chapter 01, it can represent almost any function shape, yet small changes to the training data produce very different splits, especially near the root. Change one student's score and the best first question can move. If one tree is unstable, what happens if we train many and let them vote?

05Averaging many trees: bagging and random forests

Combining many models' predictions gives what's called an ensemble, and averaging is the standard cure for variance. If we had many independent, unbiased estimates of the same quantity, their average would have lower variance than any one of them, without moving its bias. We have a problem, though: only one training set, and trees trained on the same data come out the same. We work around that with a bootstrap resample, a new training set made by drawing rows from the original with replacement. Draw five students from our five with replacement and some students turn up twice while others don't turn up at all, so each resample gives a slightly different tree. Bagging (bootstrap aggregating) trains one tree per resample and averages their predictions, or lets them vote for classification, where each tree casts one vote and the majority class wins.

Trees from bagging are still more alike than they should be. If one feature is unusually predictive, nearly every bootstrap sample picks it as the very first split, so the trees end up structurally similar near the root and make correlated errors. Random forests add one more ingredient to break this up: at every split, each tree may only consider a random subset of the features. A tree that can't see the dominant feature at some split is forced to find another good question, and the trees become more diverse.

Why does adding more trees eventually stop helping?

Correlated errors don't average away, and there's a formula for how much is left. If trees each have variance and average pairwise correlation , the variance of their average works out to

Its second term shrinks toward zero as you add trees. The first term, , doesn't depend on at all, so it's a floor that no number of extra trees can get you below. What lowers the floor is a smaller , and that's what random feature subsampling does: by occasionally hiding the dominant feature from a tree, it makes different trees discover different splits. It is the only lever that keeps helping as grows.

Bagging and random forests are good at what they do, removing variance. But averaging has a limit that no number of trees can lift. If every tree is wrong in the same direction, the average is wrong in that direction too. To attack that kind of error, we have to go the opposite way.

06Boosting: fixing what's left over

Boosting starts from the opposite end of the bias-variance spectrum. Instead of averaging many strong, independent, high-variance trees, it chains many weak, high-bias trees (often just a few levels deep, and sometimes stumps, trees with a single split) one after another. Each new tree is trained to predict what the current ensemble still gets wrong. For regression with squared-error loss, the loop goes like this:

  1. Start simple. An initial prediction , often just the mean of the target.
  2. Compute the residual for every training example, .
  3. Fit a new small tree to predict that residual, and not the original target.
  4. Add a shrunk version of that tree's prediction to the running total, , where (the learning rate) is typically small, 0.01 to 0.3.
  5. Recompute the residual against the new, better prediction, and repeat.

Fitting trees to residuals like this is the idea behind gradient boosting. Let's run the first round on our five students, which is probably the clearest way to see the loop. Their scores average 60.4, so predicts 60.4 for everyone, and the residuals are −8.4, −5.4, 0.6, 3.6 and 9.6. Splitting those residuals after 2 hours of study does best. It gives the first two students a correction of −6.9, the average of their residuals, and the other three a correction of +4.6. With we add 30% of each correction, so students 1 and 2 are now predicted 58.33 and the others 61.78. The first student's residual has shrunk from −8.4 to −6.33, and the next tree will go after what's left. Each round the remaining error gets a little smaller, and each tree only has to solve the much easier problem of predicting that leftover. Taking only a fraction of each correction keeps every step cautious.

This diagram puts the loop beside bagging from the last section, so you can compare the shapes. On the left, bagging trains its trees at once, on different data and different feature subsets, and averages them. On the right, boosting trains one tree at a time, each fitting the previous total's error.

Bagging vs. boosting — two different fixes for the same instability
Bagging — parallel, independent Boosting — sequential, corrective Training data Bootstrap A Bootstrap B Bootstrap C Tree A (few feats) Tree B (few feats) Tree C (few feats) Average / majority vote Prediction Start: F₀ = mean(y) Tree 1 fits r₀ = y − F₀ F₁ = F₀ + η·Tree1 Tree 2 fits r₁ = y − F₁ F₂ = F₁ + η·Tree2 ⋯ repeat, often hundreds of rounds F = Σ η·Treeᵢ Prediction
Left: bagging trains many trees at once, on different data and different feature subsets, then averages — variance goes down because independent errors cancel. Right: boosting trains one tree at a time, each one fitting only the error the previous total got wrong, and adds a shrunk copy of it to a running sum — bias goes down because the ensemble keeps correcting its own mistakes. Different axis, different mechanism, both fixing the same underlying instability of a single tree.

Why the two are different moves

It's tempting to file bagging and boosting together as two flavors of "combine a bunch of trees", but they attack opposite ends of the bias-variance tradeoff. Bagging starts from strong, low-bias, high-variance learners (deep, largely unpruned trees) and averages many independent copies. Averaging is a variance-reduction operation and does almost nothing for bias: if every tree is systematically wrong in the same direction, the average reproduces that error. That's also why random feature subsampling matters so much for bagging, since it keeps the trees' errors decorrelated enough for averaging to keep paying off as you add more of them.

Boosting starts from weak, high-bias, low-variance learners and chains them, each one aimed at the error the current ensemble hasn't explained yet. That's a bias-reduction operation, and the ensemble's capacity grows with every round, so it can fit relationships that no single weak learner could capture alone. Its cost shows up when you stop regularizing. Unless you rein it in, boosting keeps driving training error toward zero by fitting whatever is left, including noise. Typical restraints are a small learning rate, limited tree depth, early stopping (halting once the error on held-out data stops improving), and row and column subsampling, where each tree sees only a random part of the data. Adding more trees to a random forest almost never hurts, while adding more rounds to an unregularized boosted model eventually does.

We can test that claim directly. In this experiment bagging and boosting get the same ingredient, 30 stumps, on 200 noisy points from a sine curve. The function stump tries 19 candidate thresholds and keeps the one with the smallest squared error, predicting the mean on each side. Bagging fits 30 stumps on bootstrap resamples and averages them. Boosting starts at the mean of y and, 30 times, fits a stump to y - F and adds 0.3 of its prediction to F. Then we print how much the bagged stumps disagree with each other, and the MSE of a single stump, the bagged average and the boosted sum.

Try it Give bagging and boosting the same 30 stumps and compare
import numpy as np
rng, n = np.random.default_rng(0), 200
x = np.sort(rng.random(n))
y = np.sin(4 * x) + 0.1 * rng.normal(size=n)   # the target curve

def stump(xs, rs, grid):     # depth-1 tree: one split, two means
    best = (np.inf, None)
    for t in np.quantile(xs, np.linspace(.05, .95, 19)):
        L = xs <= t
        a, b = rs[L].mean(), rs[~L].mean()
        sse = ((rs - np.where(L, a, b)) ** 2).sum()
        if sse < best[0]:
            best = (sse, np.where(grid <= t, a, b))
    return best[1]

# Bagging: 30 stumps on bootstrap resamples, averaged in parallel.
bag = np.array([stump(x[i], y[i], x)
                for i in rng.integers(0, n, (30, n))])

# Boosting: 30 stumps in series, each fitting what is left over.
F = np.full(n, y.mean())
for _ in range(30):
    F = F + 0.3 * stump(x, y - F, x)

print("bag members", bag.shape, " they disagree by",
      round(bag.std(0).mean(), 3))
for tag, p in [("one stump", stump(x, y, x)),
               ("bagged x30", bag.mean(0)), ("boosted x30", F)]:
    print(f"{tag:12s} MSE {((y - p) ** 2).mean():.4f}")
Thirty stumps averaged take MSE from 0.0903 to 0.0807. Chain the same thirty stumps instead of averaging them and they reach 0.0156, roughly six times better, with no extra parameters. That first printed line explains why: the 30 bagged members disagree with each other by only 0.065 on average, so there was hardly any variance for averaging to remove. A stump is already a low-variance model and its error is almost all bias, and that's the error boosting attacks.

Look at the disagreement figure first. The 30 bagged stumps differ from each other by only 0.065 on average, so there was hardly any variance for averaging to remove, and the bagged MSE moves only from 0.0903 to 0.0807. A stump is already a low-variance model, and its error is almost all bias. That's the error boosting goes after, and the same 30 stumps chained in series reach 0.0156. Averaging pays only when the base learner has high variance, so bagging is paired with deep, unpruned trees and boosting with shallow ones.

Here's the contrast in one table. Its overfitting and noise rows follow from what we just saw: a forest's averaging dilutes noisy points, while a boosted model treats noise as one more residual to chase.

Bagging (random forests)Boosting (gradient boosting / XGBoost)
Primary effectReduces varianceReduces bias
Base learnersDeep, low-bias, high-variance treesShallow, high-bias, low-variance trees
TrainingParallel — every tree is independentSequential — each tree depends on the last
Overfitting risk from adding more treesLow — more trees rarely hurtReal — needs learning rate, depth limits, early stopping
Sensitivity to label noiseRobust — averaging dilutes noisy pointsHigher — will keep trying to fit noise as "residual"
ExamplesRandom Forest, Extra TreesAdaBoost, Gradient Boosting, XGBoost, LightGBM, CatBoost

Boosting is the one that gets shipped, and the next question is how it was made fast and robust enough to dominate real pipelines.

07XGBoost, LightGBM and CatBoost

XGBoost (Chen & Guestrin, 2016) didn't reinvent gradient boosting so much as engineer it properly. Three changes carried the weight:

  • A regularized objective that penalizes tree complexity directly, in addition to shrinkage.
  • Native missing-value handling, learning a default split direction so imputation (filling gaps with a substitute value) is not required.
  • Systems-level optimization (parallel split-finding, cache-aware access patterns) to make it fast at scale.

LightGBM and CatBoost are later, actively used siblings. LightGBM is optimized for speed on very large datasets via histogram-based splitting, and CatBoost for datasets with many categorical features, meaning columns whose values are labels such as a merchant name or a country. All three are gradient boosting underneath and differ in engineering.

Why do tree ensembles still beat neural networks on tabular data?

Interviewers probably like this one because deep learning has won nearly everywhere else, and the answer comes in three parts that all point the same way. The first is that tabular features usually have no structure for a neural network to exploit. Every architecture carries an inductive bias, an assumption about the data built into its shape. A CNN's convolution assumes that nearby pixels are related, and a Transformer's attention assumes that tokens form a meaningful sequence. Column order in a spreadsheet is arbitrary, so those biases have nothing to grab onto.

The second is that trees handle mixed feature types and missing values natively. A categorical column, a numeric column and a sparsely populated column all just become "is this value above, below or equal to some threshold". No embedding table (a learned vector for each category) or imputation pipeline is required.

The third is that boosting's sequential error-correction suits the data these problems usually present: a moderate number of features with complex but relatively low-order interactions, exactly what a shallow tree can carve out a few splits at a time. Trees aren't the only way to carve up a space, though, and three older models do it differently.

08Margins, neighbours and probabilities

A tree chops the feature space into boxes. We could instead ask which boundary leaves the widest gap between the classes, what the nearest training examples did, or how likely the observed features are under each class. Each question gives one of the remaining models in the toolkit.

Support vector machines

Take our pass/fail students on a line of hours. Any boundary between 2 and 3 hours separates them, so which one should we pick? A support vector machine (SVM) uses margin maximization: among all the lines (or hyperplanes) that separate two classes, pick the one that leaves the widest possible street between the boundary and the nearest point of either class. For our students that's a boundary at 2.5 hours, and the nearest points, the students at 2 and 3 hours, are the support vectors. They're the only points that determine where the boundary sits, so the student who studied 5 hours could move a little and nothing would change, so the model depends on far fewer points than it looks.

When classes aren't linearly separable, the soft-margin formulation allows some points to sit inside the margin or even on the wrong side, penalized by a cost. That gives a tunable tradeoff between a wide margin and a few tolerated mistakes. For boundaries that need to curve, the kernel trick lets an SVM stay with linear machinery. Plainly stated, a kernel function computes the similarity two points would have if you had projected them into some higher-dimensional space (for instance, adding columns like the squares of the features), without ever forming that projection. The SVM optimization only ever needs dot products between points (multiply two vectors entry by entry and add the products), never their raw coordinates in that space, so you can substitute a kernel function for the dot product and get the effect of a much richer feature space at the computational cost of the original one.

k-nearest neighbors and the curse of dimensionality

k-nearest-neighbors (k-NN) defers almost all of its work to prediction time. To classify a new point, it finds the closest training points and lets them vote, so there's no training phase to speak of. Suppose a new student studied 2.8 hours and we set . The three closest students are those at 3, 2 and 4 hours, who passed, failed and passed, so the vote says pass. Because is the only dial, k-NN is a clean lens for bias-variance intuition.

  • Small (like ) lets the prediction follow every quirk of the single nearest point. Low bias, high variance, a decision boundary that snakes around individual noisy examples.
  • Large averages over many neighbors, smoothing the boundary out, which gives higher bias and lower variance. In the extreme where equals the whole training set, the prediction collapses to always guessing the majority class.

Our students have one feature, so "closest" is easy. Real problems have many, and that's where the curse of dimensionality breaks k-NN. As the number of dimensions (features) grows, the volume of the space grows so much faster than the data filling it that distances between points stop being informative. For many common distance metrics, the ratio between the distance to the nearest neighbor and the distance to the farthest converges toward 1, so everything ends up roughly equidistant from everything else. "Nearest" stops meaning "similar" and starts meaning "arbitrary".

We can watch it happen. The code scatters 500 random points in a unit cube, picks one random query point, and measures the distance from the query to every point. For each number of dimensions it prints the nearest and farthest distance and their ratio, and the last line prints the array shapes so you can follow what the arrays hold.

Try it Watch nearest and farthest converge as dimensions pile up
import numpy as np
rng = np.random.default_rng(0)

n = 500                          # 500 points, one query, unit cube
print("    d   nearest  farthest    ratio")
for d in [2, 5, 20, 100, 1000, 10000]:
    P = rng.random((n, d))       # (500, d) the "training set"
    q = rng.random(d)            # (d,)     the point to classify
    dist = np.linalg.norm(P - q, axis=1)    # (500,) one per point
    lo, hi = dist.min(), dist.max()
    print(f"{d:5d} {lo:9.3f} {hi:9.3f} {lo / hi:8.3f}")

print("\nshapes on the last row: P", P.shape, " q", q.shape,
      " dist", dist.shape)
The ratio column only moves one way. At d=2 the nearest point sits at 0.024 of the farthest distance, so "nearest" means something. By d=10000 the ratio is 0.967, which makes the closest of 500 points barely 3% nearer than the most distant one. The nearest distance itself climbs from 0.030 to 40.210 while the gap to the farthest hardly widens, because every point has drifted out to roughly the same radius. Nothing is broken: a unit cube in 10,000 dimensions looks like this, and it is why k-NN stops carrying signal long before you notice it has.

The ratio column only moves one way. In 2 dimensions the nearest point is a small fraction of the farthest distance, so a vote among nearest neighbors carries meaning. By 10,000 dimensions the closest of 500 points is barely 3% nearer than the most distant one. This is why k-NN usually needs dimensionality reduction (squeezing many features into a few, as chapter 03 covers) or a learned lower-dimensional representation first. Without one, it's only useful on a small, carefully chosen feature set.

Naive Bayes

The third question needs a different example, so let's switch from students to emails. Naive Bayes applies Bayes' theorem (see chapter 01), which turns "how likely are these words if the email is spam" into "how likely is spam given these words", with one deliberate simplification. It assumes every feature is conditionally independent of every other feature, given the class, so once you know the class, one word tells you nothing about another. That assumption is almost always technically false. In a document, the word "loan" and the word "interest" are obviously not independent given the class "finance".

Why does a false independence assumption still work?

Classification only needs the correct class to come out on top, and it doesn't need a calibrated probability, one that matches how often emails with those words are in fact spam. The independence assumption does distort the probability values, but it tends to distort them in a similar, consistent direction across classes. So the ranking between classes survives even when the magnitudes don't. Add that naive Bayes is cheap and stable to fit on high-dimensional, sparse bag-of-words features (a vector of word counts that ignores word order), and you have a strong, fast baseline.

We now have a dozen models, and picking one is only half the job. The other half is checking it honestly, which is easy to get wrong.

09Leakage, metrics and choosing a model

Data leakage

The most common way a model looks great offline and fails in production is data leakage: information that wouldn't be available at real prediction time ends up influencing training. Two concrete examples show how it creeps in. The first is fitting a scaler (which rescales features to a common range) or an imputer on the entire dataset before splitting it into train and test sets. The training statistics have already seen information from the test rows, which quietly inflates validation performance. The second is including a feature that's only populated after the outcome is already known. A "days since last late payment" column will look like an extremely strong predictor of default in historical data, but it isn't available at the moment you'd need to make the prediction.

The fix is mechanical discipline. Fit every preprocessing step only on the training fold, inside the cross-validation loop and never before it. (Cross-validation splits the data into several folds, trains on all but one and tests on the one left out, and rotates.) And audit every feature for whether it could plausibly exist at prediction time.

Choosing a metric

Even with clean data, a model's score depends on what you count as a mistake. For classification, call the class you're hunting for (fraud, disease, a defect) the positive class. The basic measures are:

  • Precision. Of the things I flagged positive, how many were.
  • Recall. Of the things that were positive, how many did I catch.
  • ROC-AUC. Ranking quality across all thresholds (the cut-offs that turn probabilities into yes/no), and a reasonable default.
  • PR-AUC. Precision-recall AUC, which ignores true negatives (the negatives the model correctly leaves alone) entirely.

The tradeoff between precision and recall is a business decision as much as a modeling one. ROC-AUC can look deceptively good under severe class imbalance, because it's partly driven by the true-negative rate, the share of real negatives the model gets right. When negatives vastly outnumber positives, even a mediocre model racks up a huge number of easy true negatives. PR-AUC focuses on how well the model does specifically on the positive class, which makes it the honest choice whenever positives are rare: fraud, disease screening, defect detection.

For regression, the choice is about how much a big miss should hurt:

  • MAE. Penalizes every error linearly, so it's robust to outliers but gives no extra urgency to large mistakes.
  • MSE / RMSE. Penalizes errors quadratically, so a few large errors dominate the loss. (RMSE is the square root, back in the original units.) Appropriate when big mistakes are disproportionately costly, risky when a few noisy outliers shouldn't be allowed to dominate training.
  • Huber loss. It is the compromise: quadratic for small errors and linear beyond a threshold, giving you MSE's smooth gradient near zero without MSE's outlier sensitivity far from it.
  • MAPE. Mean absolute percentage error reports error as a percentage of the true value. Easy to communicate, but it behaves badly, or is undefined, when the true value is near zero.

Matching the model to the data

That leaves the question we started with, which model to reach for. Structured, tabular data (spreadsheets, transaction logs, customer records) is where trees almost always win, usually with less tuning and less data than a neural net would need, because a boosted tree's inductive biases match what that data looks like. Unstructured data with real spatial or sequential structure (images, text, audio, video) is where deep nets win. Convolution and attention are inductive biases built for exactly that structure, and trees have no mechanism to exploit it. So the honest interview answer is not that deep learning is more advanced. It's that you match the inductive bias to the structure present in the data.

10Summary

  1. Every model here is a function family, a loss and a fit. The students' line, a tree, a margin and a neighbour vote are different families with the same recipe from chapter 01.
  2. Least squares has a closed form, and a line can't bend. The normal equation gives the best line in one step, and gradient descent reaches the same answer when it can't be used. The coefficients are readable, but interactions have to be built by hand.
  3. Logistic regression squeezes a line through a sigmoid. The output reads as a probability, cross-entropy is the loss, and the perceptron is its hard-threshold ancestor that can't learn XOR, which is where chapter 04 takes over.
  4. Penalties keep flexible fits honest. Ridge shrinks every coefficient, and lasso zeroes some out, because the diamond-shaped budget region has corners on the axes where the error contours tend to touch it first.
  5. A decision tree asks one yes/no question at a time. It picks splits by Gini impurity or entropy, needs pruning to stop memorizing noise, and stays unstable even then.
  6. Bagging averages trees to cut variance. Random feature subsets lower the correlation between trees, which matters because the floor can't be averaged away.
  7. Boosting chains weak trees on residuals to cut bias. Each round adds a shrunk tree fitted to what's left, and without a small learning rate, depth limits or early stopping it ends up fitting noise.
  8. Gradient-boosted trees win on tabular data. XGBoost, LightGBM and CatBoost made boosting fast and regularized, and the data has no spatial or sequential structure for neural networks to exploit, while trees handle mixed types and missing values natively.
  9. SVMs, k-NN and naive Bayes decide differently. An SVM maximizes the margin and uses kernels for curves, k-NN trades bias against variance through and breaks in high dimensions, and naive Bayes ranks classes correctly even though its independence assumption is false.
  10. Leakage and metrics fool you more often than models do. Fit preprocessing inside the training fold, drop features that don't exist at prediction time, and use PR-AUC when positives are rare.
  11. Match the inductive bias to the structure of the data. Trees for tables, convolution and attention for images, text and audio.

11Build this

Boosting is easy to state and easy to misremember as "average a lot of trees". Watching a stack of stumps eat a residual, one stump at a time, is what makes the sequential part stick.

Project Watch residuals shrink, one stump at a time ~3 hours · NumPy

Fit a one-dimensional curve with depth-1 trees, written from the five-step loop in section 06. One input feature, one output, a few hundred noisy points. Small enough to plot the ensemble's prediction over the target after any round you like. That turns "each tree fits what the last total got wrong" from a sentence into a picture.

  1. Generate the data: a few hundred points from a smooth curve with a couple of bends, plus Gaussian noise. Hold a third of them out.
  2. Write the stump by hand. Scan every candidate split threshold on the single feature, keep the one that minimizes squared error, and predict the mean of each side. That is the whole weak learner, with no library call.
  3. Run the loop from section 03. Start at the mean of the target, compute residuals, fit a stump to those residuals, add times its prediction to the running total, repeat. Use .
  4. Plot two things at rounds 1, 5, 20, and a few hundred: the ensemble's prediction over the target, and a histogram of the residuals.
  5. Plot training and held-out squared error against round number, on the same axes, all the way out.
  6. Now remove the learning rate. Set and rerun every plot above.
You'll know it worked when the staircase tightens onto the curve. Round 1 is a single step function that barely resembles the target. A few hundred rounds in, the prediction is tracking the bends, and the residual histogram has pulled in around zero from both sides. No individual stump was ever shown the curve. Each one only ever saw what the previous total left behind.
What the breakage teaches. At the first stump swallows most of the residual in one bite, and the ensemble stops being a slow accumulation of weak corrections. Watch for training error dropping faster while held-out error turns back upward. That gap is the overfitting risk section 06 gives boosting and not bagging. It is why a small learning rate heads the list of ways to rein boosting in. It is also the noise-sensitivity row of the table in section 06, happening in front of you. With no shrinkage, the later stumps are fitting the noise you added in step 1. By then it is most of what is left.

Where this runs in production

A typical fraud or credit-risk pipeline built on XGBoost has three moving parts:

  • Engineer features from transaction and account history. Aggregations over recent activity, velocity features like "transactions in the last hour," categorical merchant and device fields.
  • Train a gradient-boosted tree model on these features.
  • Evaluate it knowing the positive class, actual fraud, is a small minority of all transactions.

Because positives are rare, ROC-AUC can look reassuringly high while the model is still missing most of the fraud that matters. It's partly propped up by the huge number of easy true negatives. PR-AUC is the honest metric here, because it only credits the model for how well it finds and ranks the rare positive cases.

Class imbalance itself is usually handled with a combination of three levers: class weighting (XGBoost's scale_pos_weight), threshold tuning against the actual business cost of a false positive (blocking a legitimate purchase) versus a false negative (missing real fraud), and sometimes resampling.

Leakage is easy to introduce by accident in a pipeline like this, and a feature derived from data only available after a chargeback is filed is a textbook example. Every preprocessing and feature-engineering step needs to be fit strictly inside the training fold, and audited for whether it could exist at the moment a real prediction has to be made.

12Interview questions

BeginnerWhy can't you just threshold a linear regression's output to do classification?

Linear regression's output is unbounded and its loss (squared error) has no notion that "more positive than 1" or "more negative than 0" isn't a meaningful direction — a very confidently correct prediction still gets penalized for being far from the label. Logistic regression fixes this by passing the linear output through a sigmoid, bounding it into (0,1) so it reads as a probability, and pairing it with cross-entropy loss, which is the correct maximum-likelihood loss for a class label and doesn't have that saturation problem.

BeginnerWhat happens to bias and variance as you increase k in k-nearest-neighbors?

Small k follows the nearest point(s) closely — low bias, high variance, a jagged decision boundary sensitive to individual noisy points. Large k averages over more neighbors — higher bias, lower variance, a smoother boundary. At the extreme, k equal to the whole training set just always predicts the majority class: maximum bias, minimum variance.

BeginnerEntropy/information gain vs. Gini impurity for splitting a tree — does the choice actually matter?

Both measure how mixed a node's class distribution is — entropy via , Gini via — just with slightly different curvature. In practice they usually produce very similar trees. Gini is marginally cheaper (no logarithm) and is the default in most libraries, but the choice rarely changes accuracy meaningfully.

IntermediateWhy does lasso produce sparse solutions and ridge doesn't?

Both are equivalent to minimizing squared error subject to a budget constraint on the coefficients — ridge's constraint region is a circle/sphere, lasso's is a diamond with corners sitting exactly on the coordinate axes, where one or more coefficients equal zero. The regularized solution sits wherever the growing elliptical error contours first touch that region's boundary. A smooth circle has no corners, so contact generically happens where every coordinate is nonzero — coefficients shrink but rarely hit exactly zero. A diamond's corners are much more likely to be the first point of contact, which is exactly why lasso routinely zeroes coefficients out and ridge essentially never does.

IntermediateBagging vs. boosting — what's actually different about how they reduce error?

Bagging averages many independent, high-variance, low-bias trees trained in parallel on bootstrap resamples — it's a variance-reduction move, and does little for bias. Boosting chains many weak, high-bias, low-variance trees sequentially, each one fit to the previous ensemble's residual error — it's a bias-reduction move. That difference is also why they carry different overfitting risk: adding more trees to a random forest rarely hurts, but adding more rounds to an unregularized boosted model eventually starts fitting noise.

IntermediateWhy does random feature subsampling in a random forest help beyond what bootstrapping alone gives you?

Bootstrapping alone still tends to produce correlated trees, because a strongly predictive feature gets chosen as the top split in nearly every bootstrap sample. The variance of an average of trees works out to , where is the average pairwise correlation between trees — the second term vanishes as you add trees, but the floor doesn't. Random feature subsampling lowers directly, by occasionally hiding the dominant feature and forcing trees to find genuinely different splits — that's the only lever that keeps paying off as you add more trees.

IntermediateWhat is data leakage, and how does it typically sneak into a pipeline?

Leakage is when information that wouldn't be available at real prediction time ends up influencing training, making offline metrics look better than production performance will actually be. Two common patterns: fitting a scaler or imputer on the full dataset before splitting into train/test, so training statistics have already "seen" test data; and including a feature that's only populated after the outcome is known — like a payment-history field that only exists once a default has already occurred. The fix is fitting every preprocessing step only inside the training fold of the cross-validation loop, and auditing every feature for whether it could plausibly exist at prediction time.

DeepExplain the kernel trick in an SVM in one or two sentences.

A kernel function computes the similarity two points would have if you projected them into a higher-dimensional feature space, without ever actually forming that projection — since the SVM optimization only ever needs dot products between points, substituting a kernel for the dot product gets you the effect of a much richer, nonlinear feature space at the computational cost of the original one.

DeepWhy do gradient-boosted trees still beat deep neural networks on most tabular data problems?

Tabular features usually have no spatial or sequential structure for a neural net's inductive biases (convolution, attention) to exploit — column order is arbitrary. Trees handle mixed feature types and missing values natively, without an embedding table or imputation pipeline. And boosting's sequential, greedy error-correction is a strong structural fit for the moderate-feature-count, relatively low-order-interaction structure tabular problems tend to have. None of that changes for unstructured data — images, text, audio — which is exactly where deep nets do win, because that data actually has the spatial/sequential structure those inductive biases were built for.

DeepYour fraud model has a great ROC-AUC but the fraud team says it's missing most real fraud. What's going on?

ROC-AUC is measured against the true-negative rate too, and when the positive class (fraud) is a small fraction of all transactions, a model can rack up a huge number of easy true negatives and post a high ROC-AUC while still doing poorly on the positive class specifically. PR-AUC ignores true negatives and directly measures precision and recall on the positive class, which is the honest metric under severe imbalance — it would likely be revealing the exact gap the fraud team is describing.

13Go deeper

●Now write it yourself

Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.

Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.