Loss, Batch Size, Regularization and Tree Depth: ML Core Review
Machine LearningModel answerLast updated
Four connected ML fundamentals: why log loss suits sigmoid outputs, how batch size shapes training, how L1 and L2 differ, and how leaf size controls bias and variance in trees.
Four Core Ideas Behind Training Supervised Models
Imagine you are explaining the following to a teammate who knows basic ML vocabulary but wants to understand the reasoning. Give a structured answer to each part.
-
Choosing a loss for binary labels. A network ends in a sigmoid and predicts the probability of the positive class. Describe the intuition behind binary cross-entropy. Then explain why it is usually preferred over mean squared error for this setup.
-
Full-batch versus stochastic updates. Compare full-batch gradient descent with stochastic and mini-batch variants. Suppose the training set has 100 million rows. Discuss how picking a batch size of 1, 32, or 10,000 changes convergence speed, memory use, and how well the final model generalizes.
-
Penalizing weights. Explain how L1 and L2 penalties act differently on the learned weight vector. Name a concrete situation in which L1 is the better choice.
-
Tree complexity. For a decision tree, what happens to bias and variance as you raise the minimum number of samples a leaf must contain? Then describe what a leaf looks like, and how the tree behaves, if you let it grow until every leaf holds a single sample.
Use math where it clarifies the point (a gradient, a prior, a variance term), and connect each argument to behavior you would see in practice.
Hints
Hint 1
For part 1, write the gradient of each loss with respect to the pre-activation logit z. Remember that the derivative of the sigmoid is p(1 - p), and check what happens when the prediction is confidently wrong.
Hint 2
For part 2, think of the mini-batch gradient as a noisy but unbiased estimate of the full gradient whose variance shrinks like 1/B. Then weigh updates per epoch, hardware utilization, and memory against that noise.
Hint 3
For parts 3 and 4, picture the constraint shapes (diamond versus circle) and the constant versus proportional shrinkage. For trees, ask how many samples are averaged inside each leaf and how much a single point can change the structure.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
A good answer explains why each technique behaves as it does, not only what it is called. Each section below gives the core argument, a concrete number or formula, and a practical consequence.
1. Cross-entropy versus MSE with a sigmoid output
Setup. The network produces a logit z, the prediction is p = σ(z), and the label is y ∈ {0, 1}.
Intuition. Model the label as Bernoulli with parameter p. The likelihood of one example is p^y (1-p)^(1-y). Its negative log is
L = -[y log p + (1-y) log(1-p)]
So minimizing cross-entropy is maximum likelihood estimation, which is the same as minimizing the KL divergence between the true label distribution and the model's. The loss grows without bound as a confident prediction turns out wrong (-log p → ∞ as p → 0 when y = 1).
Gradient argument. With σ'(z) = p(1-p):
- Cross-entropy:
∂L/∂z = p - y. The gradient is proportional to the error. - MSE,
½(p-y)²:∂L/∂z = (p-y)·p(1-p). The extra factorp(1-p)goes to zero when the sigmoid saturates.
Example. If y = 1 and z = -10, then p ≈ 5e-5. The MSE gradient is roughly -5e-5, so the model learns almost nothing from its worst mistake. The cross-entropy gradient is about -1, a strong corrective signal.
Secondary points. For logistic regression, cross-entropy is convex in the weights, while sigmoid plus MSE is not. MSE also corresponds to Gaussian noise, which is the wrong likelihood for binary targets.
2. Batch gradient descent versus SGD, and batch size
Core difference. Full-batch GD computes the exact gradient over all N rows per update. Stable, but one update costs a full pass. SGD and mini-batch methods use an unbiased estimate from B samples whose variance is about σ²/B, so noise standard deviation falls as 1/√B.
On 100M rows:
| Batch size | Updates per epoch | Convergence | Memory | Generalization |
|---|---|---|---|---|
| 1 | 100M | Very noisy, needs a small learning rate, poor hardware utilization so slow wall-clock | Minimal | Noise can help escape sharp minima but precise convergence is hard |
| 32 | about 3.1M | Good trade-off between noise and progress | Low | Usually generalizes well |
| 10,000 | 10K | Smooth gradients, high throughput per step | High, activations scale with B | Can reach sharper minima and a wider generalization gap unless the learning rate is retuned |
| Full | 1 | One update per pass | Infeasible | Rarely used at this scale |
Points worth adding.
- There is a critical batch size beyond which doubling B no longer halves the number of steps needed. Extra compute is wasted.
- Large batches typically need a scaled learning rate (linear scaling rule), warmup, and sometimes layer-wise optimizers such as LARS or LAMB.
- Gradient noise is an implicit regularizer, with noise scale roughly proportional to
η/B. Changing B changes generalization, not just speed.
3. L1 versus L2 regularization
L2 (ridge), penalty λ‖w‖₂².
- Gradient
2λw: shrinkage proportional to the weight, so big weights shrink strongly and small ones barely move. Weights get small but rarely exactly zero. - Tends to spread weight across correlated features.
- Equivalent to a Gaussian prior (MAP view).
L1 (lasso), penalty λ‖w‖₁.
- Subgradient
λ·sign(w): a constant pull toward zero regardless of size. - The proximal update is soft-thresholding,
w ← sign(w)·max(|w| − ηλ, 0), which produces exact zeros. - Geometrically, the L1 ball is a diamond with corners on the axes, so loss contours often touch it where some coordinates are zero.
- Equivalent to a Laplace prior.
When to choose L1. In high-dimensional, sparse problems where you expect only a small subset of features to matter and want built-in feature selection. A typical case is a linear click-prediction or ranking model over millions of one-hot or hashed features and their crosses. Sparsity shrinks model size, lowers serving cost, and aids interpretability.
Caveat. Among strongly correlated features, L1 picks one somewhat arbitrarily and can be unstable across resamples. Elastic Net (L1 + L2) mitigates this.
4. Leaf size in decision trees
Raising min_samples_leaf increases bias and decreases variance.
- Each leaf averages more points, so predictions are smoother and less sensitive to any single sample (lower variance).
- The tree has fewer splits and cannot isolate small regions, so it may miss fine structure (higher bias).
Fully grown tree (one sample per leaf).
- Each leaf outputs the label of its single training point.
- Training error is zero, except where identical feature vectors carry conflicting labels.
- The tree memorizes noise, acting like a 1-nearest-neighbor rule over axis-aligned boxes.
- Variance is very high: small changes in the data can yield a very different tree.
- Probability estimates are only 0 or 1, so they are poorly calibrated.
This is why random forests grow deep, low-bias trees and then average many of them, using bagging and feature subsampling to cut variance.
Common mistakes
- Saying cross-entropy is "better because it is a classification loss" without the gradient or likelihood argument.
- Claiming smaller batches are always better for generalization, or larger always faster, ignoring hardware utilization and learning-rate retuning.
- Stating that L2 produces exact zeros, or that L1 is always superior for accuracy.
- Mixing up the direction of the bias/variance change when leaf size grows.
Likely follow-ups
- Early stopping: monitor validation loss, checkpoint the best weights, stop after a patience window without improvement, and restore the best checkpoint. For linear models trained by gradient descent it behaves similarly to L2 regularization.
- Overfitting despite strong L2: first rule out leakage, duplicates across splits, and distribution shift. Then consider more data or augmentation, lower capacity, dropout, feature selection, ensembling, and properly cross-validated hyperparameters.
- Learning-rate schedules: because noise scales with
η/B, decaying the learning rate late in training lowers noise much as increasing batch size would, helping the optimizer settle into a minimum.