Classical Machine Learning Algorithms Questions
Foundational non-deep-learning models and when to reach for each. Covers linear and logistic regression, decision trees and ensemble methods (random forests, gradient boosting), support vector machines, k-nearest neighbors, and clustering, including their assumptions, strengths, and failure modes. Focuses on algorithm selection and the numerical and implementation considerations behind these workhorse models.
What is nested cross-validation, and why do you need it when you're doing both feature selection or hyperparameter tuning and estimating generalization error? Walk through the outer/inner loop structure and the computational cost of doing it properly.
Sample Answer
Direct answer
Nested cross-validation is two CV loops in one: an outer loop that estimates how well the whole modeling pipeline generalizes, and an inner loop, run entirely inside each outer training fold, that picks hyperparameters or features. You need it whenever the same data is used both to tune the model and to report its performance, because tuning on the same data you evaluate on leaks information and inflates the reported score.
Structured elaboration
Why plain k-fold CV is not enough here. If you run k-fold CV once to pick the best hyperparameters (by, say, taking the config with the highest mean CV score) and then report that same mean CV score as your generalization estimate, you have used the test folds to make a selection decision, so the reported number is optimistically biased. The gap grows with the size of the hyperparameter search space: the more configurations you try, the more likely one of them fits the validation folds' noise, not just signal.
Outer/inner structure.
- Outer loop (Kouter folds): each outer fold is held out entirely and touched only once, at the very end, purely for scoring. It never influences any modeling decision.
- Inner loop (Kinner folds, run on the outer-training portion only): performs the hyperparameter search or feature selection, using its own train/validation splits. Whatever it selects (say, the config with the best mean inner-validation score) is refit on the full outer-training set.
- The refit model is then scored once on the untouched outer-test fold. Averaging that score across all outer folds gives an unbiased estimate of how well "the pipeline, including its tuning procedure" generalizes.
- Any preprocessing that looks at the target (target encoding, feature selection by correlation with y, scaling parameters) must be fit only on the current inner-training data, never on the inner-validation or outer-test data, or the same leakage reappears one level down.
Computational cost. Every hyperparameter configuration gets fit Kinner times per outer fold just to be scored, then the winner gets refit once more on the full outer-training set. Total model fits:
total fits=Kouter×(G×Kinner+1)where G is the number of hyperparameter configurations evaluated. This is roughly Kinner times more expensive than a single k-fold search (precisely Kinner+1/G), which is why nested CV is usually reserved for the final reported generalization number rather than for every exploratory tuning pass.
Worked example
Suppose Kouter=5, Kinner=3, and a grid search over G=10 hyperparameter configurations.
total fits=5×(10×3+1)=5×31=155Compare that to a single (non-nested) k-fold grid search used just to pick hyperparameters, at G×K=10×5=50 fits, with no separately reported unbiased generalization estimate. Nested CV costs about 155/50≈3.1× more fits here, and the ratio grows directly with Kinner: doubling Kinner to 6 gives 5×(10×6+1)=305 fits, roughly double, because the inner search dominates the total.
Trade-offs & pitfalls
- Nested CV answers "how good is this tuning procedure, on average," not "what hyperparameters should I ship." The winning configuration can differ across outer folds; for deployment, refit once on the full dataset using the inner-loop procedure (or the single most frequently selected configuration) after nested CV has validated that the procedure is trustworthy.
- Under a tight compute budget, replace grid search with randomized or Bayesian search in the inner loop to shrink G without shrinking the search space explored, or reduce Kinner to 3 (a common compromise, since the inner loop only needs to rank configurations relatively, not report a final number).
- Skipping the inner loop and just using a single train/val split inside each outer fold is a cheaper approximation, but reintroduces some tuning variance into the outer score; it is a reasonable trade-off for very expensive models, not for cheap ones where full nested CV is affordable.
- The single most common implementation bug: fitting a preprocessing step (scaler, target encoder, feature selector) once on the whole dataset before either loop starts. That silently defeats the entire point of nesting.
Describe how a support vector machine works: maximizing the margin, what support vectors are, the soft-margin parameter C, and how the kernel trick lets you get non-linear decision boundaries. When would you reach for an SVM?
Sample Answer
Direct answer
A support vector machine finds the decision boundary that maximizes the margin, the distance to the closest training points of each class, rather than just any boundary that separates the classes. Those closest points are the support vectors, they're the only points that determine where the boundary sits. The soft-margin parameter C controls how much the model tolerates points that violate the margin, and the kernel trick lets the same margin-maximizing idea draw non-linear boundaries by implicitly working in a higher-dimensional feature space without ever computing the mapping explicitly.
Maximizing the margin
For linearly separable data, SVM solves for a hyperplane w⋅x+b=0 that maximizes the distance between itself and the nearest point of either class, subject to correctly classifying every point:
w,bmin21∥w∥2s.t.yi(w⋅xi+b)≥1 ∀iThe margin width works out to ∥w∥2, so minimizing ∥w∥ is exactly maximizing the margin. Only the points that sit exactly on the margin boundary (where the constraint is tight, yi(w⋅xi+b)=1) affect the solution, these are the support vectors; every other point could be moved or removed without changing the boundary at all.
Soft margin: the C parameter
Real data is rarely perfectly separable, so slack variables ξi≥0 let points violate the margin (or even end up on the wrong side), at a cost:
w,b,ξmin21∥w∥2+Ci∑ξis.t.yi(w⋅xi+b)≥1−ξi, ξi≥0Large C penalizes margin violations heavily, pushing toward a narrower margin that fits the training data closely (lower bias, higher variance, more prone to overfitting on noisy points). Small C tolerates more violations for a wider, smoother margin (higher bias, lower variance). C is exactly the regularization strength knob, analogous to the inverse of λ in ridge regression.
The kernel trick
A linear kernel only draws a straight decision boundary in the original feature space. The kernel trick replaces the dot product xi⋅xj used throughout the SVM optimization with a kernel function K(xi,xj) that computes the dot product as if the data had been mapped into a higher-dimensional space, without ever materializing that mapping. The RBF (Gaussian) kernel is the common non-linear choice:
K(x,x′)=exp(−γ∥x−x′∥2)where γ controls how localized each point's influence is: large γ means only very nearby points affect the boundary (complex, wiggly boundaries, risk of overfitting), small γ means influence extends further (smoother boundaries, risk of underfitting).
When to reach for an SVM
- Small-to-medium datasets where training cost scales acceptably (naive SVM training is roughly O(n2) to O(n3), which gets painful past tens of thousands of rows).
- High-dimensional, sparse data (text with TF-IDF features) with a linear kernel, since SVMs handle the "many features, comparatively few samples" regime well and a linear kernel keeps training fast.
- Cases where you specifically want the margin-maximizing boundary's generalization property and can afford to tune C (and γ, for RBF) via cross-validation.
Worked example: computing an actual margin
Take the simplest separable case, one feature, positive-class points at x=1 and x=2, negative-class points at x=−1 and x=−2. The support vectors are the closest points of each class to the boundary: x=1 (positive) and x=−1 (negative). Solving the constraint equations at equality for these two support vectors, w(1)+b=1 and w(−1)+b=−1, gives:
w=1.0,b=0.0so the decision boundary is at x=0 and the margin width is:
margin=∥w∥2=1.02=2.0The points at x=±2 play no role in this solution at all, only the two closest points (x=±1) determined w and b, which is the concrete illustration of "only support vectors matter."
Trade-offs and pitfalls
- SVMs are not scale-invariant: features must be standardized before fitting, since the margin (a Euclidean-distance-based concept) is dominated by whichever feature happens to have the largest raw numeric range otherwise.
- C and γ (for RBF) need to be tuned together, not independently; a grid search over both on a log scale, validated by cross-validation, is standard, since their effects interact (a very large C with a very large γ can both push toward overfitting simultaneously).
- Kernel SVMs don't naturally produce calibrated probabilities; if you need probability outputs, that requires an extra calibration step (Platt scaling) on top of the raw decision function.
- For very large or very high-dimensional dense datasets, kernel SVM training cost becomes a real constraint; a linear SVM, or switching to a tree ensemble or a linear model with engineered non-linear features, is often more practical than trying to scale a kernel SVM.
At a high level, how does gradient boosting build its ensemble? Walk through fitting sequential base learners to residuals or gradients, and what learning_rate, n_estimators, and base-learner complexity each control.
Sample Answer
Direct answer
Gradient boosting builds its ensemble one small step at a time: start from a simple baseline prediction, look at where that prediction is still wrong (the residual, or more generally the gradient of the loss), fit a new weak learner to predict that error, and add a shrunk version of it to the running prediction. Repeat, and each new learner nudges the ensemble a little closer to the targets. learning_rate controls the size of each nudge, n_estimators controls how many nudges you take, and base-learner complexity controls how much each individual nudge is allowed to represent.
Structured elaboration
The sequential fitting process.
- Initialize the ensemble with a simple constant prediction, typically the mean of the target for regression with squared-error loss.
- Compute how wrong the current ensemble is for every training example: for squared-error loss this is literally the residual yi−F(xi); for other losses it's the negative gradient of the loss with respect to the current prediction (a "pseudo-residual"), which reduces to the ordinary residual as a special case for squared error.
- Fit a new weak learner (almost always a shallow decision tree) to predict those residuals/gradients from the input features.
- Scale the new learner's output by
learning_rateand add it to the running prediction: Fm(x)=Fm−1(x)+learning_rate×hm(x). - Repeat steps 2 to 4 for
n_estimatorsrounds.
What each hyperparameter controls.
learning_ratescales how much each tree's correction actually moves the ensemble. A smaller learning rate (e.g., 0.05) means each step is conservative, so mistakes get corrected more gradually and the model is less likely to overreact to any single tree's idiosyncrasies, at the cost of needing more trees to reach the same overall fit.n_estimatorsis how many correction rounds you run. With a small learning rate you need more rounds to converge; with a large learning rate, few rounds can already overfit, since large corrections applied repeatedly can chase noise in the residuals.- Base-learner complexity (tree depth, or number of leaves) controls how much structure each individual correction step is allowed to capture. Very shallow trees (even single-split "stumps") are common because they're weak enough that many small, well-regularized corrections tend to generalize better than a few large, complex ones; deeper trees per step converge in fewer rounds but risk overfitting each individual correction to training-set noise.
These three interact: a smaller learning rate paired with shallower trees and more estimators is the classic "slow and steady" regularized recipe; the total model capacity is roughly the product of how many trees you fit, how expressive each one is, and how much each one is allowed to contribute.
Worked example
Toy regression with three training targets y=[3,5,9]. Initialize F0 as the mean: F0=(3+5+9)/3=17/3≈5.667 for every example. The residuals against this baseline:
r=y−F0=[3−5.667, 5−5.667, 9−5.667]=[−2.667, −0.667, 3.333]Suppose the first weak learner, fit to these residuals, predicts exactly h1=[−2.667,−0.667,3.333] (a tree that perfectly memorizes 3 training points, for illustration). With learning_rate = 0.1, the update is:
Compare to the true targets [3,5,9]: the squared error before this step was (−2.667)2+(−0.667)2+(3.333)2=7.11+0.44+11.11=18.66; after this one small step it's (3−5.400)2+(5−5.600)2+(9−6.000)2=5.76+0.36+9.00=15.12, a modest improvement from a single conservative step, exactly the "many small nudges" behavior the learning rate is designed to produce. A larger learning rate of 1.0 applied to the same h1 would move F1 all the way to [3,5,9] (perfect fit) in a single step, which is precisely why aggressive learning rates with expressive base learners overfit fast: the model has no room left to generalize beyond memorizing this exact training set.
Trade-offs & pitfalls
- Fitting sequentially to residuals means each tree depends on every tree before it; there's no natural row/column-level parallelism across boosting rounds the way there is within bagging, though modern implementations parallelize the split-finding within each individual tree.
- Too large a learning rate with too many estimators overfits fast, since large corrections applied repeatedly chase noise; too small a learning rate with too few estimators underfits, since the ensemble never fully closes the gap to the targets. Early stopping on a validation set is the standard practical guardrail against picking a bad n_estimators for a given learning rate.
- Shallow base learners (stumps or depth 2-3 trees) are usually preferred over deep ones specifically because gradient boosting already gets its expressiveness from stacking many weak learners; giving each individual learner too much capacity removes the regularizing benefit of the "many small steps" approach.
- This description covers first-order gradient boosting; modern implementations like XGBoost also use second-order (Hessian) information to compute better per-leaf updates, which changes the details of step 3 and 4 but not the overall sequential structure described here.
How would you handle class imbalance specifically for a tree-ensemble model: class weighting, balanced subsampling, focal loss, or resampling? What are the tradeoffs for training stability and production deployment?
Sample Answer
Direct answer
For tree ensembles specifically, class weighting is usually the right first move: it's simple, requires no change to the training data, and both random forests and gradient boosting frameworks support it natively (class_weight, scale_pos_weight). Balanced subsampling and resampling change what data each tree actually sees and can help further, but at the cost of discarding majority-class information or duplicating minority-class examples; focal loss is a more surgical tool for boosting frameworks when the imbalance is compounded by many "easy" majority examples drowning out gradient signal from hard ones.
Structured elaboration
| Method | Mechanism | Training stability | Production deployment |
|---|---|---|---|
| Class weighting | Scale the loss contribution of each class (class_weight='balanced', scale_pos_weight) | Stable; no data duplication, same effective sample size | Simple, no preprocessing pipeline to maintain, easy to A/B different weight schemes without retouching data |
| Balanced subsampling | Draw each tree's bootstrap sample with equal counts from each class (random forest's balanced_subsample) | Reduces majority-class information per tree, can raise per-tree variance | Reproducible if seeded; changes what the forest "sees" but not the model artifact's shape |
| Resampling (SMOTE / undersampling) | Change the training set composition before training: duplicate/synthesize minority examples or drop majority examples | Oversampling risks overfitting duplicated points; undersampling discards real majority-class signal, raising variance | Adds a preprocessing step that must be version-controlled and reproduced identically at retrain time; SMOTE's synthetic points can look unrealistic in high-dimensional or categorical-heavy feature spaces |
| Focal loss | Down-weight well-classified ("easy") examples in the loss so gradient signal concentrates on hard, often minority, examples | Adds a tuning parameter (focusing parameter γ); can overfit noisy minority examples if γ too aggressive | Requires a custom objective in gradient boosting frameworks (not always a one-line config flag); complicates probability calibration since the loss no longer directly targets calibrated likelihoods |
Why class weighting is the default starting point for tree ensembles. It leaves the training data itself untouched, so there's no risk of the duplication-driven overfitting that oversampling introduces, or the information loss from undersampling. Both bagged and boosted tree frameworks support it as a first-class option, so it's a one-parameter change rather than a new pipeline step. The main risk is that extreme weight ratios can make optimization noisy: a rare class weighted very heavily can cause a boosting model to overfit the handful of minority examples it does see, since each of their gradient contributions is now large.
When to reach further. If class weighting alone still leaves the model insensitive to the minority class (common under severe imbalance, e.g. beyond roughly 100:1), balanced subsampling or targeted resampling can help by directly changing what fraction of each tree's or boosting round's training signal comes from each class, rather than just reweighting a fixed dataset. Focal loss is worth reaching for specifically when the problem isn't just "too few minority examples" but "too many easy majority examples burying the gradient signal from the hard cases," which plain class weighting doesn't address, since it reweights by class label alone, not by how hard an individual example currently is to classify.
Worked example
Take a dataset with 10,000 negative examples and 500 positive examples (a 20:1 imbalance ratio). For gradient boosting's scale_pos_weight, the standard recommendation is the ratio of negative to positive counts:
For scikit-learn's class_weight='balanced' scheme, each class's weight is wc=nclasses×ncntotal. With ntotal=10,500, nclasses=2:
Note the two schemes give different numbers (20 vs. 10.5 for the positive class) because they normalize differently, scale_pos_weight is a raw ratio applied only to the positive class in a binary boosting objective, while class_weight='balanced' normalizes both classes' weights to average to 1 across the dataset; mixing up which convention a given library expects is a common, silent source of over- or under-weighting in practice.
Trade-offs & pitfalls
- Class weighting changes what the model optimizes for but not what data it sees; if the minority class has very few examples in absolute terms (say, under a few dozen), no amount of reweighting compensates for the model simply never having encountered enough variety in that class to learn robust patterns from it.
- Oversampling (including SMOTE) evaluated with plain k-fold CV is a common leakage trap: if resampling happens before the train/validation split, synthetic or duplicated minority points can leak into the validation fold, inflating the reported score; resampling must happen only inside each fold's training portion.
- Whatever imbalance-handling method is used during training, predicted probabilities are no longer calibrated to the true class balance (they now reflect the reweighted/resampled training distribution), so a separate threshold-tuning or recalibration step (e.g., Platt scaling or isotonic regression against a held-out set with the true class balance) is usually needed before deploying probability outputs to a business rule.
- Prefer the simplest method that closes the gap: class weighting first, escalate to subsampling or resampling only if weighting alone underperforms on the metric that matters (typically AU-PR or F-beta for imbalanced problems, not raw accuracy), and reserve focal loss for cases where the hard-example-mining behavior specifically, not just class rebalancing, is the diagnosed problem.
For a 100k-row, 200-feature tabular dataset with high-cardinality categoricals, how would you decide between a gradient boosting model and a neural network with embeddings? Compare expected sample complexity, training and inference cost, and how each handles categorical features and missingness.
Sample Answer
Direct answer
For a 100k-row, 200-feature tabular dataset with high-cardinality categoricals, I'd default to gradient boosting (LightGBM/CatBoost) over a neural network with embeddings, because GBMs typically reach strong accuracy on data of this size with less tuning, handle missingness and mixed scales natively, and have native categorical handling that avoids the embedding-design and data-volume concerns a neural net brings. A neural net becomes the better choice mainly when the dataset is substantially larger, the categoricals carry rich learnable semantics worth sharing across tasks, or the model needs to plug into an end-to-end differentiable pipeline.
Structured elaboration
| Dimension | Gradient boosting (GBM) | Neural net with embeddings |
|---|---|---|
| Sample complexity | Reaches strong performance with 100k rows; greedy splits are sample-efficient for tabular structure | Often needs meaningfully more data than 100k to reliably beat a well-tuned GBM; 100k is borderline |
| Training cost | Fast on CPU for this size; boosting rounds × tree depth sets the cost | Needs more epochs, benefits from GPU; cost scales with layer width/depth and batch size |
| Inference cost | Lightweight ensemble of shallow trees, generally fast on CPU | Can be fast on GPU/TPU but may be heavier on CPU without quantization |
| Categorical handling | Native (CatBoost/LightGBM handle high-cardinality categoricals directly, e.g. via ordered target statistics) | Needs learned embeddings; requires choosing embedding sizes and enough data per category to learn them well |
| Missingness | Handled natively by most implementations | Requires explicit imputation or a missingness-indicator design |
| Feature engineering burden | Low; robust to mixed scales and some redundant features out of the box | Higher; benefits from careful normalization and explicit design for interactions |
| Interpretability | Feature importances and SHAP values are standard tooling | Weaker by default; needs integrated-gradients or similar attribution methods |
Why sample size at 100k matters. Neural nets, and embeddings for high-cardinality categoricals in particular, need enough examples per category to learn a meaningful representation. With 200 features and 100k rows, a high-cardinality categorical (say, 5,000 distinct values) may only have on the order of 20 examples per category on average, not much for a network to learn a useful embedding vector from scratch, whereas a tree-based split on that same categorical (using target statistics) is a much lower-variance way to extract signal from a similarly sparse per-category sample.
When the neural net does start to win. As data grows well past 100k, embeddings get enough examples per category to learn genuinely useful representations, sometimes capturing similarity structure between categories (e.g. two product SKUs behaving similarly) that a GBM's per-feature splits don't naturally exploit. A neural net is also the better choice when there's a reason to want a differentiable end-to-end pipeline (e.g. joint training with another neural component, or transfer of learned embeddings to a related task), independent of which model wins on raw accuracy.
Worked example
Suppose one of the 200 features is a "merchant ID" categorical with 5,000 distinct values across the 100k rows. With even distribution across categories, that's 100,000/5,000=20 rows per merchant on average. A tree-based split using target statistics (e.g. the historical target rate for that merchant, computed with appropriate regularization/smoothing to avoid leakage) reduces this to a single informative numeric feature per split candidate, requiring only enough examples per category to estimate a stable rate, not enough to fit a multi-dimensional embedding vector. An embedding of size, say, 16 for that same categorical has 16 free parameters per category to learn, i.e. 5,000×16=80,000 parameters for that one feature alone, competing for signal against only 20 rows per category; that parameter count relative to available data per category is the concrete reason embeddings are data-hungry in exactly the regime this question describes.
Trade-offs and pitfalls
- GBMs can plateau in accuracy once real interaction structure gets very deep or the categorical semantics matter (e.g. two rarely co-occurring categories that behave similarly); a neural net with shared embeddings can sometimes capture that structure a tree-based split cannot.
- Ensembling a GBM and a neural net sometimes captures complementary error patterns and outperforms either alone, but that's a meaningfully larger engineering and maintenance surface for a modest accuracy gain, worth it only when the accuracy gain is validated and the maintenance cost is acceptable.
- A common wrong turn is reaching for embeddings because "neural nets are more powerful" in the abstract, without checking whether the per-category sample size actually supports learning a useful embedding; at 100k rows with high-cardinality categoricals, that assumption often doesn't hold.
- The right first step in almost every case is to fit the GBM as a fast baseline; if it saturates and the use case justifies the added complexity (larger expected future data volume, need for a differentiable pipeline), only then invest in the neural net path.
Unlock Full Question Bank
Get access to all Classical Machine Learning Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.