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.
Why can naively computing the sigmoid or softmax overflow for large logits, and how does the log-sum-exp trick fix it? What guardrails would you build into a production ML library to avoid this?
Sample Answer
Direct answer
Naive softmax or sigmoid computation calls exp() on raw logits, and if any logit is large (a few hundred or more, easily reached with unnormalized network outputs or a diverging training run), exp() overflows to infinity in floating point; when that happens in both the numerator and denominator of softmax, you get an inf / inf = NaN, silently poisoning the loss and every gradient downstream. The log-sum-exp trick fixes this by subtracting the maximum logit before exponentiating, which provably gives the exact same mathematical result while keeping every intermediate value in a safe numeric range.
Structured elaboration
Why overflow happens. IEEE 754 double-precision floats overflow to inf above roughly 1.8×10308, but exp(x) reaches that threshold once x is only around 709; single precision (float32, the common default in ML) overflows around x≈88. Logits in the hundreds or thousands are entirely plausible from an untrained or diverging model, or simply from unnormalized linear-layer outputs before a softmax, so this isn't a contrived edge case.
Why it specifically breaks softmax. Softmax computes softmax(z)k=∑jezjezk. If the logits are all large (say all near 1000), every ezj overflows to inf, and the result is inf / inf, which IEEE 754 defines as NaN, not an error you can catch and not a value close to the correct answer. Symmetrically, if the logits are all very negative (say all near -1000), every ezj underflows to exactly 0.0, and you get 0/0, again NaN.
The log-sum-exp identity that fixes it. For any constant m, log∑jezj=m+log∑jezj−m, and picking m=maxjzj guarantees every exponent zj−m≤0, so every exp() call is now bounded between 0 and 1, never overflowing. Applying the same shift inside softmax itself, softmax(z)k=∑jezj−mezk−m, gives the mathematically identical result (the e−m factor cancels between numerator and denominator) while keeping every intermediate value numerically safe.
A subtler failure mode: log-probabilities, not just softmax itself. Even after stabilizing softmax with the max-subtraction trick, if you then separately compute log(softmax_output) for a cross-entropy loss, a genuinely correct but very small probability (from a large negative logit) can underflow to an exact 0.0, and log(0.0) = -inf, a real, silent failure rather than an imprecise approximation. The fix is the same idea applied one level up: compute cross-entropy for class k=logsumexp(z)−zk directly, never materializing the intermediate probability at all, which is both more accurate and cheaper (one less division and log per element).
Production guardrails. (1) Always call a library's built-in logsumexp / stable softmax (scipy.special.logsumexp, torch.logsumexp, torch.nn.functional.log_softmax) rather than hand-rolling exp and log calls; these are the actual guardrail, not a coding-style preference. (2) Assert or log when raw logits exceed a sanity threshold (say ∣z∣>50) before they reach any exponential, since that's usually itself a symptom of a diverging training run or an unnormalized upstream computation, worth catching early rather than papering over downstream. (3) Prefer computing losses via the identity above (never materializing an intermediate probability that could underflow to exact zero) rather than composing separately-correct softmax and log calls.
Worked example
import numpy as np
logits = np.array([1000.0, 1001.0, 999.0])
def softmax_naive(z):
e = np.exp(z)
return e / np.sum(e)
def softmax_stable(z):
shifted = z - np.max(z)
e = np.exp(shifted)
return e / np.sum(e)
def logsumexp_naive(z):
return np.log(np.sum(np.exp(z)))
def logsumexp_stable(z):
m = np.max(z)
return m + np.log(np.sum(np.exp(z - m)))
Running this (float64, verified): softmax_naive(logits) returns [nan, nan, nan], since every exp() call overflowed to inf first, giving inf/inf. softmax_stable(logits) returns [0.2447, 0.6652, 0.0900], which matches scipy.special.softmax(logits) exactly (max absolute difference 0.0). logsumexp_naive(logits) returns inf (the log of an already-overflowed infinity), while logsumexp_stable(logits) correctly returns 1001.408, matching scipy.special.logsumexp(logits) exactly.
The subtler failure is just as concrete and just as reproducible:
def sigmoid_naive(z):
return 1.0 / (1.0 + np.exp(-z))
def log_sigmoid_stable(z):
return np.minimum(z, 0) - np.log1p(np.exp(-np.abs(z)))
z = np.array([-1000.0])
s = sigmoid_naive(z) # [0.0], the correct limiting value
naive_log = np.log(s) # [-inf], a real divide-by-zero
stable_log = log_sigmoid_stable(z) # [-1000.0], exact
sigmoid_naive(-1000) correctly underflows to exactly 0.0 (that's the right limiting value, not an error itself), but np.log of that 0.0 then returns -inf, a real RuntimeWarning: divide by zero, not just an imprecise number. log_sigmoid_stable(-1000) instead returns exactly -1000.0, matching the asymptotic identity $\log\sigma(z) \to z$ as $z \to -\infty$ exactly. Both forms agree to machine precision at moderate logit values like $z=-5,0,5$ (verified: naive and stable give the identical [-5.00672, -0.69315, -0.00672] there), so the stable form costs nothing in the well-behaved regime and only pays off exactly where it's needed.
Trade-offs & pitfalls
- The max-subtraction trick is mathematically exact, not an approximation; there's no accuracy-versus-safety trade-off to weigh, which is exactly why every production ML library implements it as the default, not an opt-in flag.
- Don't stabilize softmax alone and assume you're safe; a naive
log()applied afterward to the (now-correct) softmax output can still underflow-then-log-of-zero if any resulting probability rounds to exactly0.0in floating point. Compute cross-entropy via the directlogsumexp(z) - z_kidentity instead of composing separately-stabilized pieces. - Sanity-checking raw logit magnitude is a cheap, high-value guardrail: a logit of 1000 is very rarely legitimate model output, it's almost always a symptom of an upstream bug (missing normalization, a learning-rate-driven divergence, or accidentally feeding pre-activation values where post-activation ones were expected), worth surfacing immediately rather than silently absorbing.
- These stability tricks matter more, not less, in mixed-precision or float16 training, where the safe range for
exp()is far narrower than float64, and where accumulation of many "successfully" masked overflow/underflow events over a training run's many steps is exactly the kind of failure that's hard to trace back to its root cause after the fact.
You suspect the relationship between a feature and the target isn't linear. How would you use polynomial features or interaction terms with linear regression, and how do you keep that from blowing up variance and overfitting as you add degree?
Sample Answer
Direct answer
Add polynomial terms (x, x^2, x^3, ...) or interaction terms (x1*x2) as new columns and fit ordinary linear regression on the expanded feature set. The model stays linear in its parameters, so it keeps the same fitting machinery and interpretability, but as you raise the degree the parameter count grows and, with a fixed number of data points, you can eventually have as many parameters as data points, at which point the model can memorize the training data and generalizes badly.
Structured elaboration
Why it still works as linear regression: linear regression only requires linearity in the parameters, not the raw inputs. Feeding it phi(x) = [1, x, x^2, ...] lets it fit curves while remaining ordinary linear regression under the hood.
Parameter growth: a degree-d polynomial on one feature adds d terms; with p original features and all pairwise interactions, the interaction count grows like O(p^2), and a full degree-d expansion across p features grows combinatorially.
Effect on bias and variance: low degree underfits (high bias, misses real curvature) but has low variance. Higher degree lowers bias but variance grows quickly, because more parameters are being estimated from the same amount of data, and the added polynomial columns are highly correlated with each other (x and x^2 move together for x > 0), which is the same instability mechanism as ordinary multicollinearity.
Controls:
- Cross-validate the degree instead of picking it by training error.
- Standardize or use an orthogonal polynomial basis to reduce numerical correlation between terms.
- Apply ridge or lasso on top of the expanded features so unnecessary high-degree terms shrink toward zero.
- Prefer splines when only certain regions of x are nonlinear, since local basis functions don't oscillate far from the data the way a single high-degree global polynomial can. (This oscillation near the edges of the fitted range, worse at higher degree, is known as Runge's phenomenon.)
Worked example
Fit y from x with only n = 3 points: x = [0, 1, 2], y = [1, 3, 2].
A degree-1 fit (a line, 2 parameters) via least squares gives intercept 1.5 and slope 0.5:
y^=1.5+0.5x
giving predictions [1.5, 2.0, 2.5] and a sum of squared errors of 1.5, an honest approximation that doesn't pass through every point.
A degree-2 fit (a parabola, 3 parameters, exactly matching the 3 data points) solves exactly:
y^=1+3.5x−1.5x2
giving predictions [1.0, 3.0, 2.0], a perfect match, sum of squared errors = 0. That zero error is not evidence of a better model, it's evidence that zero degrees of freedom are left: with as many parameters as data points, the parabola threads exactly through every point, including whatever noise those points happen to contain, and there is no held-out data left to check whether it generalizes. In practice this parabola would swing wildly if evaluated between or beyond the three fitted points.
Trade-offs & pitfalls
Chasing training R^2 by raising the degree without cross-validation is the classic trap this example illustrates directly. Interaction terms without polynomial terms should still be checked for multicollinearity using VIF (variance inflation factor: how much a term's coefficient variance is inflated by its correlation with the other predictors, with values above roughly 5-10 flagged as concerning), since x1*x2 correlates with both x1 and x2 individually. Extrapolating a polynomial fit outside the training range is especially dangerous because polynomial curvature can diverge quickly. High-degree polynomial design matrices are also numerically unstable to compute directly (they resemble ill-conditioned Vandermonde matrices); centering and scaling x, or using an orthogonal polynomial basis, mitigates this on top of the statistical fix.
Derive the normal-equation closed-form solution for OLS linear regression. What's its computational and memory complexity, when does it become numerically unstable, and when would you prefer gradient descent or a regularized method instead in production?
Sample Answer
Direct answer
OLS finds the coefficient vector that minimizes squared error; setting the gradient of that loss to zero gives the normal equation, solved by a matrix inversion. It costs O(np^2 + p^3) time and needs the design matrix and a p x p matrix in memory, becomes unstable when X^T X is ill-conditioned (near-collinear features or p close to n), and in production you typically move to gradient descent for very large n or p, or to a regularized method when features are correlated or p is large relative to n.
Structured elaboration
Derivation
L(β)=(y−Xβ)⊤(y−Xβ)
∇βL=−2X⊤y+2X⊤Xβ
X⊤Xβ=X⊤y⟹β^=(X⊤X)−1X⊤y
Complexity
Forming X⊤X costs O(np^2); inverting the p x p result costs O(p^3); total time is O(np^2 + p^3). Memory needs the n x p design matrix (O(np)) plus the p x p Gram matrix (O(p^2)).
Numerical instability
When columns of X are highly correlated (or p approaches n), X^T X becomes near-singular and its condition number blows up, so small floating-point errors get amplified hugely when inverted. Forming X^T X explicitly squares the condition number of X itself, which is why production-grade solvers avoid that step: QR decomposition factors X directly into an orthogonal matrix times a triangular one, and SVD factors X into rotation-scale-rotation components, and both let you solve for beta by operating on X itself rather than on the squared, worse-conditioned X^T X.
When to prefer gradient descent or a regularized method
| Situation | Prefer |
|---|---|
| p is large (thousands+), cubic inversion cost is prohibitive | Gradient descent / SGD, O(np) per epoch, streams data |
| Data doesn't fit in memory | Gradient descent, out-of-core, mini-batches |
| Multicollinearity or p > n | Ridge (adds lambda I, always invertible) |
| Need automatic feature selection | Lasso / Elastic Net |
Worked example
Take x = [1, 2, 3, 4], y = [3, 5, 6, 9], with an intercept column added: X = [[1,1],[1,2],[1,3],[1,4]].
X⊤X=(4101030),X⊤y=(2367)
Solving X⊤Xβ=X⊤y gives β^=(1.0, 1.9), i.e. intercept 1.0, slope 1.9. Predictions are [2.9, 4.8, 6.7, 8.6], residuals are [0.1, 0.2, -0.7, 0.4], and the sum of squared residuals is 0.7. This is the full pipeline the derivation above describes, applied to four real numbers, not just the symbolic form.
Trade-offs & pitfalls
Defaulting to the normal equation regardless of p size breaks down (or gets slow) as p grows into the thousands; forming X^T X directly rather than using QR/SVD hurts numerical accuracy because it squares the condition number; not centering or scaling features before inverting can create instability purely from mismatched feature scales; and confusing "needs regularization" with a universal requirement rather than a fix specifically for rank-deficiency or multicollinearity is a common overcorrection.
Explain principal component analysis (PCA): what it optimizes, how the principal components are computed, and how you would decide how many components to keep.
Sample Answer
Direct answer
PCA re-describes your data using a new set of axes, chosen so that the data's variance (how spread out the points are) is captured as efficiently as possible: the first axis points in the single direction the data varies the most, the second is the direction of next-most variation while staying perpendicular ("orthogonal") to the first, and so on. These new axes are called principal components, ranked from most to least variance explained. Equivalently, it finds the rank-k linear subspace that minimizes reconstruction error (the sum of squared distances between the original points and their projections). The components are computed from the eigenvectors of the (centered) data's covariance matrix (a matrix summarizing how every pair of features varies together; eigenvectors are the special directions a matrix only stretches, never rotates, and the amount of stretch along each one tells you how much variance that direction captures), or equivalently and more stably, from the singular value decomposition (SVD) of the centered data matrix. How many to keep is decided by looking at explained variance (a scree plot or a cumulative variance threshold) or, when there is a downstream task, by tuning it like any other hyperparameter.
Structured elaboration
What PCA optimizes. For centered data X∈Rn×d, PCA seeks a unit vector v1 that maximizes the variance of the projected data:
v1=arg∥v∥=1maxVar(Xv)=arg∥v∥=1maxvTCvwhere C=n−11XTX is the sample covariance matrix. Each subsequent component maximizes the same objective subject to being orthogonal to all previous components. This turns out to be exactly the eigenvector problem Cvi=λivi, so the components are the eigenvectors of C and the variance each one explains is its eigenvalue λi.
Two equivalent ways to compute it.
| Route | Steps | When to prefer |
|---|---|---|
| Covariance eigendecomposition | Center X, form C=n−11XTX, eigendecompose C | Conceptually simplest; fine for small, well-scaled, low-dimensional data |
| SVD of centered data | Center X, factor X=UΣVT; V's columns are the components, and λi=σi2/(n−1) | Numerically preferred: never explicitly forms XTX, so it avoids squaring the data's condition number (a measure of how much small input errors get amplified by a matrix operation; squaring it means rounding error gets amplified much more), and it works directly even when features outnumber samples |
Required preprocessing. Centering (subtracting the feature means) is mandatory: without it, the "variance" PCA maximizes is contaminated by the mean, and the first component just points toward the centroid. Scaling (standardizing to unit variance) is a judgment call: scale when features are in different units or have arbitrarily different variances (a feature measured in dollars will dominate one measured in fractions of a percent); skip it when the relative variance across features is itself meaningful, such as pixel intensities on a shared scale.
Choosing the number of components. Three practical approaches, in increasing order of rigor:
- Cumulative explained variance: keep the smallest k such that ∑i=1kλi/∑i=1dλi passes a target such as 90-95%.
- Scree plot elbow: plot eigenvalues in descending order and stop where the marginal drop flattens out.
- Downstream validation: if PCA is a preprocessing step, treat k as a hyperparameter and pick it by cross-validated performance of the model that consumes the components, since the variance-based cutoff is a proxy, not the actual objective.
Worked example
Take four 2D points: (1,2),(3,3),(5,6),(7,7). The mean is (4,4.5), so the centered points are (−3,−2.5),(−1,−1.5),(1,1.5),(3,2.5).
The covariance matrix (dividing by n−1=3):
C=(20/36617/3)≈(6.6676.0006.0005.667)Its trace is 37/3≈12.333 and its determinant is 16/9≈1.778. For any 2x2 matrix, its eigenvalues are exactly the roots of its characteristic polynomial (the equation you get by requiring det(C−λI)=0, i.e. the values of λ that make C−λI singular, which for a 2x2 matrix works out to λ2−tr(C)λ+det(C)=0). Solving that quadratic here gives eigenvalues λ1≈12.187 and λ2≈0.146 (they sum to the trace, 12.333, as they must). The explained variance ratios are:
λ1+λ2λ1≈0.988,λ1+λ2λ2≈0.012So the first principal component, pointing roughly along direction (0.736,0.677), already captures about 98.8% of the variance in this data, which makes sense: the four points lie almost exactly on a line. This is the mechanical content behind "keep components until you hit 90-95% cumulative variance": here a single component clears that bar.
Trade-offs & pitfalls
- PCA only captures linear structure. Data on a curved manifold (a spiral, for example) will need many linear components to approximate what a nonlinear method (kernel PCA, a UMAP embedding, an autoencoder) captures in two or three dimensions.
- "High variance" is a proxy for "important," not a guarantee. A low-variance direction can still be exactly the one that separates classes in a supervised problem; PCA has no way to know that because it never looks at labels.
- Skipping centering, or scaling when you shouldn't (or not scaling when you should), silently changes which directions look like they carry the most variance and is one of the most common practical mistakes.
- Components are linear combinations of every input feature, so they are harder to explain to a stakeholder than the original features; if interpretability matters more than compression, feature selection or sparse PCA is often the better tool for the job.
Show why averaging n identically-distributed estimators with pairwise correlation rho reduces variance. What does the formula tell you about the value of adding more, less-correlated trees to an ensemble?
Sample Answer
Direct answer
Averaging M identically distributed estimators with pairwise correlation ρ reduces variance to σ2[1+(M−1)ρ]/M, which shrinks toward σ2/M (the ideal 1/M reduction) only as ρ→0, and never drops below ρσ2 no matter how large M gets. This is the formal reason why adding more trees to an ensemble helps only to the extent those trees are decorrelated; past a point, more correlated trees buy you almost nothing.
Structured elaboration
Setup. Let f1,…,fM be M base estimators, each with Var(fi)=σ2 and pairwise correlation ρ between any two distinct estimators (so Cov(fi,fj)=ρσ2 for i=j). Form the ensemble average:
fˉ=M1i=1∑MfiDerivation. Using the variance of a sum:
Var(fˉ)=M21Var(i=1∑Mfi)Expanding the variance of the sum into variance and covariance terms (there are M variance terms and M(M−1) ordered covariance pairs, or equivalently M(M−1)/2 unordered pairs counted twice):
Var(i∑fi)=i∑Var(fi)+i=j∑Cov(fi,fj)=Mσ2+M(M−1)ρσ2Substituting back:
Var(fˉ)=M2Mσ2+M(M−1)ρσ2=Mσ2[1+(M−1)ρ]Interpreting the limits.
| Case | Result | Meaning |
|---|---|---|
| ρ=0 | Var(fˉ)=σ2/M | Full averaging benefit: variance shrinks proportionally to the number of independent estimators |
| ρ=1 | Var(fˉ)=σ2 | No benefit at all: perfectly correlated estimators carry no new information over one estimator |
| M→∞ (fixed ρ>0) | Var(fˉ)→ρσ2 | A nonzero variance floor set entirely by the correlation; adding more trees beyond this point yields diminishing, then negligible, returns |
Why this matters for ensemble design. The formula says variance reduction has two separate levers: M (how many estimators) and ρ (how correlated they are), and they interact multiplicatively, not additively, in a way that makes ρ the dominant term once M is even moderately large, since the (M−1)ρ term grows with M while the 1 stays fixed. This is exactly the mechanism random forests exploit deliberately: bootstrap resampling (bagging) and random feature subsampling at each split are both aimed at reducing ρ between trees, not just at generating M trees, because past some point, more trees at the same ρ barely move the needle while decorrelating the trees further keeps paying off.
Worked example
With σ2=1 and M=10, compare three correlation levels:
ρ=0:Var(fˉ)=101+9(0)=101=0.10 ρ=0.2:Var(fˉ)=101+9(0.2)=101+1.8=102.8=0.28 ρ=0.5:Var(fˉ)=101+9(0.5)=101+4.5=105.5=0.55Going from ρ=0 to ρ=0.2 nearly triples the variance (0.10 to 0.28, a factor of 2.80) for the same M=10; going further to ρ=0.5 nearly doubles it again (0.28 to 0.55, a factor of 1.96, just under double). At ρ=0.5 and M→∞, the variance floor is ρσ2=0.5, meaning even an infinite ensemble at that correlation level can never do better than half the single-estimator variance, a ceiling that no amount of additional trees can break through. This is the quantitative version of "diversity matters as much as ensemble size."
Trade-offs and pitfalls
- The derivation assumes identically distributed, unbiased estimators with a single shared pairwise correlation ρ; real trees in a random forest are not perfectly exchangeable (different bootstrap samples and feature subsets induce varying pairwise correlations), so the formula is a useful first-order approximation, not an exact description of a fitted forest.
- A common wrong turn is treating M (number of trees) as the only lever for variance reduction and cranking it up indefinitely; past the point where (M−1)ρ dominates the 1 in the numerator, additional trees have rapidly diminishing marginal value, and the better investment is usually a change that reduces ρ (deeper feature subsampling, more aggressive bootstrap diversity) rather than more trees at the same settings.
- This decomposition assumes each fi is unbiased for the target; if the base learners are biased (e.g. systematically underfit), averaging reduces variance exactly as derived but does nothing about the bias term, so total error (bias-squared plus variance) can still be dominated by a bias floor the formula doesn't address.
- The formula also assumes the training data behind each fi can be treated as giving rise to this fixed correlation structure; if trees are trained on strongly dependent resamples of the same small dataset (e.g. very small n relative to tree complexity), the effective ρ can be higher than intuition suggests, which is part of why bagging's benefit is more pronounced with larger, more diverse training sets.
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.