Choosing Between a Linear Classifier and a Forest on Small Data
Machine LearningModel answerLast updated
Discuss when a regularized linear probabilistic classifier beats a bagged tree ensemble on a small binary task, and how it compares with boosting.
You are building a binary classifier on a small labeled dataset (a few hundred to a few thousand rows). The relationship between features and label may contain some non-linear effects. Your team is deciding between a linear probabilistic model and a tree ensemble.
Answer the following as you would in a technical discussion:
- What is logistic regression, and what loss function does it minimize? Where does that loss come from, and what can you say about its optimization?
- Under what conditions can logistic regression beat a random forest on this kind of problem?
- Explain L1 and L2 regularization for logistic regression. How do they differ in their effect on the learned weights?
- How would you detect overfitting in a logistic regression model, and what would you do to reduce it?
- Compare random forests with gradient boosting in terms of bias, variance, interpretability, and typical use cases.
Give concrete reasoning and trade-offs rather than definitions alone.
Hints
Hint 1
Start from the log-odds being linear in the features, then write the likelihood of Bernoulli labels and take its negative log. Think about whether the resulting surface has one minimum.
Hint 2
For the small-data comparison, count effective parameters and ask which model has more variance. Also consider extrapolation, calibration, sparse high-dimensional inputs, and how a linear model can still capture non-linearity.
Hint 3
For the ensemble comparison, contrast mechanisms: parallel deep trees averaged to cut variance versus sequential shallow trees fit to the remaining error to cut bias. For overfitting, think about train/validation gaps, learning curves, and unstable coefficients.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The core question is whether the bias you accept with a simple model is smaller than the variance you take on with a flexible one. With limited data, variance usually dominates, which favors well-regularized linear models unless there is strong evidence of complex structure.
1. Logistic regression and its loss
Logistic regression assumes the log-odds of the positive class are linear in the features:
log(p / (1 - p)) = w·x + b, so p = sigmoid(w·x + b).
Loss. Treat each label as a Bernoulli draw with probability p_i. Maximizing the likelihood is equivalent to minimizing the negative log-likelihood, the binary cross-entropy (log loss):
L(w) = -(1/n) * sum[ y_i*log(p_i) + (1 - y_i)*log(1 - p_i) ]
Properties worth stating:
- The gradient is
(1/n) * Xᵀ(p - y), "prediction minus label." - The Hessian is
(1/n) * Xᵀ W XwithW = diag(p_i(1 - p_i)), which is positive semidefinite, so the loss is convex. Any local minimum is global, and gradient descent, L-BFGS, or Newton/IRLS converge without sensitivity to initialization. - There is no closed-form solution; fitting is iterative.
- On linearly separable data the unregularized solution does not exist: weights grow without bound as probabilities are pushed to 0 or 1. Regularization fixes this.
- MSE on top of a sigmoid is non-convex and has vanishing gradients when confidently wrong, which is why cross-entropy is used.
2. When logistic regression beats a random forest
- Small n or large p. LR has only p+1 parameters. Trees need many samples per split to choose thresholds reliably, so with few rows forest splits are noisy.
- Near-linear signal in log-odds. LR represents it exactly; trees approximate it with a staircase that needs more data.
- Sparse, high-dimensional features (TF-IDF, one-hot IDs). Regularized LR scales well; random feature subsampling in forests often lands on uninformative columns.
- Extrapolation. Trees are piecewise constant and flat outside the training range; LR continues the trend.
- Calibration. LR optimizes log loss and is typically well calibrated. Forest probabilities tend to be pulled away from 0 and 1 and often need Platt or isotonic calibration.
- Interpretability and compliance. Coefficients are log-odds changes per unit feature, holding others fixed.
- Noisy labels. Deep trees can memorize noise; a penalized linear model is steadier.
Handling the non-linearity. You can keep LR's low variance and still add flexibility: hand-picked interactions, splines, or binned features, all regularized. Then compare against the forest with repeated stratified k-fold CV rather than one split, and look at fold-to-fold spread, not just the mean.
3. L1 and L2 regularization
The objective becomes L(w) + lambda * penalty(w) (in scikit-learn, lambda = 1/C).
| L2 (ridge) | L1 (lasso) | |
|---|---|---|
| Penalty | sum of w_j^2 | sum of abs(w_j) |
| Prior (MAP view) | Gaussian | Laplace |
| Effect | Shrinks all weights smoothly, rarely to exactly 0 | Sets many weights exactly to 0 (sparse model) |
| Geometry | Round constraint region | Diamond with corners on axes, so optimum often sits on a corner |
| Correlated features | Spreads weight across the group, stable | Tends to pick one, can be unstable |
| Optimization | Smooth, strictly convex | Convex, non-differentiable at 0; needs coordinate descent or proximal methods (liblinear, saga) |
Practical notes:
- Both trade a little bias for lower variance and both cure separation.
- Use L1 when you expect few relevant features and want selection; use L2 when many features contribute a little.
- Elastic net blends both: sparsity plus stability with correlated groups.
- Standardize features first, since penalties depend on scale, and do not penalize the intercept.
4. Detecting and reducing overfitting
Detection
- Large gap between training and validation log loss or AUC.
- Learning curves: a gap that narrows with more data suggests high variance; two curves plateauing at poor performance suggest high bias.
- Stratified k-fold CV, repeated with different seeds for small data.
- Very large or sign-flipping coefficients across folds, or convergence warnings, suggest separation or collinearity.
- Overconfident validation predictions near 0 or 1.
Mitigation
- Tune
lambda(and L1 ratio) by CV; use nested CV if you also need an unbiased performance estimate. - Reduce dimensionality through L1, domain-driven selection, removing near-duplicates, or PCA. Be cautious with many polynomial or interaction terms.
- Check for target leakage and fit all preprocessing inside the CV folds (e.g., a Pipeline).
- Collect more data or augment where sensible.
- For imbalance, use class weights instead of oversampling before splitting.
5. Random forest vs. gradient boosting
| Random forest | Gradient boosting | |
|---|---|---|
| Mechanism | Bagging: deep trees trained in parallel on bootstrap samples with random feature subsets, averaged | Boosting: shallow trees added sequentially, each fit to the negative gradient (residual error) of the current ensemble |
| Main effect | Reduces variance (base trees are low bias, high variance) | Reduces bias (base trees are high bias, low variance) |
| Variance of average | rho*sigma^2 + (1 - rho)*sigma^2/B: diversity (low correlation rho) matters | Variance grows if over-boosted; controlled by learning rate, depth, subsampling, early stopping |
| Tuning | Fairly robust defaults, hard to badly overfit by adding trees | More sensitive to hyperparameters; adding rounds can overfit |
| Noise | Fairly tolerant | Can chase noisy labels without regularization |
| Interpretability | Feature importance, partial dependence; individual model is opaque | Same tools, plus SHAP; similarly opaque |
| Typical use | Strong, low-effort baseline; parallel training | Best accuracy on tabular data when tuned; ranking, risk scoring |
Recommendation for this scenario. Start with a regularized LR (with a few engineered non-linear terms) as a baseline, then try a forest and a small, heavily regularized boosted model. Pick using repeated CV on a metric that matches the business need (log loss or AUC, plus calibration). With only a few hundred rows, expect LR to be competitive or better; with thousands of rows and clear interactions, boosting often wins.
Common mistakes
- Saying "trees are always better on tabular data" without considering sample size.
- Forgetting to scale features before L1/L2.
- Tuning hyperparameters and reporting performance on the same CV loop.
- Ignoring calibration when probabilities drive decisions.
- Describing boosting and bagging as the same thing, rather than bias reduction versus variance reduction.