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.
The business cares much more about catching fraud than avoiding false alarms. Which evaluation metrics and model-selection approach would you use, and how would you pick the operating threshold?
Sample Answer
Direct answer
When missing fraud is much more expensive than a false alarm, optimize for recall while tracking precision as the cost of that recall, and pick the operating threshold by turning the business's cost asymmetry into an explicit expected-cost calculation rather than defaulting to 0.5. Precision-recall AUC (not ROC-AUC) is the right curve to compare models on, since it's sensitive to exactly the trade-off the business cares about.
Metrics and model selection
- Precision-recall curve, not ROC. With fraud rates typically well under 5%, ROC-AUC can look strong even for a mediocre model because the false-positive-rate denominator (all legitimate transactions) is huge. Precision and recall are both computed against the small positive class, so the PR curve directly shows the trade-off you're navigating.
- Fβ score with β>1 if you want a single tuning number that weights recall above precision; β can be derived from the cost ratio (shown below), rather than guessed.
- Report an operational number alongside the statistical one: at your chosen threshold, how many transactions per day get flagged for review, since that's a capacity constraint the fraud team actually lives with, not just a modeling detail.
- Calibrate probabilities before treating the model's output as a probability for cost calculations: a raw model score can rank transactions correctly (higher score means more likely fraud) while still being a bad probability estimate, so you fit a small correction on top of it, either Platt scaling (fits a logistic curve mapping raw scores to calibrated probabilities) or isotonic regression (fits a non-decreasing step function instead, more flexible but needs more data). An uncalibrated score can still rank well while being useless for "expected cost" math.
Choosing the operating threshold from cost
Define Cfn as the cost of a missed fraud and Cfp as the cost of investigating a false alarm. For a given threshold t, the expected cost on a validation set is:
ExpectedCost(t)=Cfn⋅FN(t)+Cfp⋅FP(t)Sweep t across the range of predicted scores, compute FN(t) and FP(t) at each point from the confusion matrix, and pick the t∗ that minimizes expected cost. If the business instead states a hard floor ("we must catch at least 90% of fraud"), find the lowest threshold that meets that recall and, among thresholds satisfying it, minimize false positives or expected cost. The two approaches usually point to a similar region of the curve; the cost-floor version is often easier to defend to stakeholders because it's phrased as their constraint, not a modeling choice.
Worked example: two thresholds, real costs
Take a validation set of 1,000 transactions with 20 true fraud cases (2%), and set Cfn=500 (average loss per missed fraud) and Cfp=5 (cost of a wasted investigation).
Threshold A (looser): 15 true positives, 50 false positives, 5 false negatives.
recall=2015=0.75,precision=6515=0.231 ExpectedCostA=500(5)+5(50)=2,500+250=2,750Threshold B (stricter): 10 true positives, 10 false positives, 10 false negatives.
recall=2010=0.50,precision=2010=0.50 ExpectedCostB=500(10)+5(10)=5,000+50=5,050Even though threshold B looks better by the usual "balanced" precision/recall instinct (both at 0.50), it is nearly twice as expensive in real terms, because at this cost ratio (Cfn/Cfp=100) each additional missed fraud is far more expensive than dozens of false alarms. Threshold A, the looser one, is the better operating point given these costs. This is the concrete argument for computing expected cost directly instead of eyeballing precision and recall.
Trade-offs and pitfalls
- Getting Cfn and Cfp from stakeholders is the actual hard part; a threshold derived from made-up costs is precise-looking but not more correct than a guess, so treat those numbers as an explicit, revisitable assumption, not a constant.
- Investigator capacity is a real constraint the expected-cost formula ignores: a threshold that's optimal on paper but floods the fraud team with more alerts than they can review in a day isn't actually deployable; incorporate a capacity constraint (e.g. review at most k cases/day, rank by score) rather than a pure threshold.
- Fraud labels are frequently delayed (a chargeback shows up weeks later) or incomplete (undetected fraud is recorded as legitimate); training and evaluating against those labels understates the true false-negative rate, so periodically revisit performance as labels mature.
- Thresholds drift: as fraud patterns and the legitimate-transaction mix change over time, a fixed threshold's expected cost changes with it. Recompute periodically rather than treating threshold selection as a one-time decision.
A product manager asks you to explain what the coefficients from your logistic regression mean. How do you explain odds ratios and feature impact to someone without a stats background?
Sample Answer
Direct answer
Explain it in two layers: first, a plain-language sentence about direction and rough size ("holding everything else equal, one more support ticket in the last 30 days roughly multiplies a customer's odds of churning by 1.5"), then, if they want more, the odds-ratio mechanics behind that sentence. The key translation step a PM needs is going from a coefficient (which lives on the log-odds scale, not intuitive to anyone) to an odds ratio (a multiplier, more intuitive) to an approximate change in probability at their specific baseline rate (the only thing that actually maps to "how big a deal is this").
Structured elaboration
Why coefficients aren't directly readable. Logistic regression models log(1−pp)=β0+β1x1+⋯+βnxn, the log-odds, as a linear function of the features. A coefficient βj is the change in log-odds per one-unit increase in xj, holding other features fixed. Nobody, including most data scientists on first encounter, has good intuition for what "log-odds increased by 0.4" feels like, so the raw coefficient is the wrong unit to hand a PM.
Step 1: convert to an odds ratio. Exponentiating gives ORj=eβj, the odds ratio: exactly how much the odds (not the probability) get multiplied by a one-unit increase in xj. This is already more intuitive ("odds go up by 50%") but "odds" is still not the same thing as "probability", and conflating them is the single most common mistake in explaining this to a non-technical audience.
Step 2: convert odds ratio to an approximate probability change at a specific baseline. Odds and probability relate by odds=1−pp, so the same odds ratio produces a very different probability change depending on the baseline rate: a 50% odds increase moves an 8% baseline probability to roughly 11.5%, but the same 50% odds increase would move a 50% baseline probability all the way to 60%. This baseline-dependence is exactly why you should never say "50% higher odds" and let a stakeholder silently substitute "50% higher probability", the two are only close to each other when the baseline probability is very small.
A concrete script for the PM conversation: "Right now, about 8 out of 100 customers churn. For every extra support ticket in the last 30 days, a customer's chance of churning goes up to roughly 11 or 12 out of 100, holding everything else about them the same. It's not a huge jump for one ticket, but it compounds: several tickets in a row push that number up faster than you'd guess from a straight line, because we're modeling odds, not probability, directly."
Worked example
Suppose βj=0.4 for "number of support tickets in the last 30 days", and the baseline churn probability at the average customer's other feature values is p0=0.08.
- Odds ratio: e0.4≈1.492.
- Baseline odds: 1−0.080.08=0.08696.
- New odds after a one-unit increase: 0.08696×1.492≈0.12972.
- New probability: 1+0.129720.12972≈0.1148, i.e. about 11.5%.
So one extra ticket moves this customer from an 8.0% to an 11.5% chance of churning, a 3.5 percentage-point increase (verified by computing it two independent ways: through the odds transformation above, and directly by shifting the logit by 0.4 and re-applying the sigmoid, both give 0.1148). Note this is a local approximation around this specific baseline; the same coefficient produces a different percentage-point shift for a customer starting at, say, a 40% baseline churn probability, which is exactly why "the effect" has to be quoted relative to a stated starting point rather than as one universal number.
Trade-offs & pitfalls
- Never say "the odds went up 50%, so the probability went up 50%"; that's only approximately true when the baseline probability is very small (well under 10%), and it's flatly wrong otherwise.
- Always anchor the explanation to a real baseline rate the PM already has intuition for ("our typical customer", "our highest-risk segment") rather than quoting the odds ratio in the abstract.
- "Holding everything else equal" is doing real work in this sentence and is worth saying out loud: if support tickets are correlated with tenure or plan type, a PM might otherwise misread the coefficient as the total observed effect of tickets in the raw data, not the effect isolated from those other features.
- Coefficients only describe correlational structure inside a fitted model, not causation; if the eventual decision is "let's proactively call customers with many tickets to prevent churn", that's a causal claim the model alone doesn't license, worth flagging explicitly before a business decision is made on it.
Explain logistic regression for binary classification: the sigmoid, how outputs map to probabilities and log-odds, how you get from a probability to a class label, and what its main limitations are (e.g. a linear decision boundary).
Sample Answer
Direct answer
Logistic regression predicts a probability by taking a linear combination of the features, called the score, and squashing it through the sigmoid function into the range (0, 1). That probability is converted to a class label by comparing it to a threshold, usually 0.5. Its central limitation is that the decision boundary it can draw is always linear in whatever features you give it, so it fails on problems where the true separation between classes is curved unless you engineer non-linear features yourself.
The sigmoid and probabilities
The model first computes a linear score from the features:
z=w0+w1x1+w2x2+⋯+wnxnThen it maps that score to a probability with the sigmoid function:
p=σ(z)=1+e−z1The sigmoid squashes any real number into (0, 1): very negative z pushes p toward 0, very positive z pushes p toward 1, and z=0 gives exactly p=0.5.
Log-odds: the other way to read the same model
Solving the sigmoid equation for z shows that logistic regression is linear regression on the log-odds (logit) of the outcome, not on the probability itself:
log(1−pp)=zThis is the useful interpretive lens: a one-unit increase in xi multiplies the odds 1−pp by ewi, holding everything else fixed. It is also why the model has no closed-form solution for the weights, coefficients are fit by maximizing the likelihood (equivalently minimizing cross-entropy loss), which is convex in the weights, so gradient descent or Newton's method reliably converges to the global optimum.
From probability to a label
Once you have p, you compare it to a threshold t (0.5 by default) and predict the positive class if p≥t. The threshold is a separate decision from fitting the model: moving it trades precision for recall, and the right value depends on the relative cost of false positives versus false negatives in the application, not on anything the training procedure chose for you.
Main limitations
- Linear decision boundary. In the raw feature space, the set of points where p=0.5 is a straight line (or hyperplane in higher dimensions). If the true classes are separated by a curve, logistic regression cannot represent that unless you add polynomial or interaction features, or switch to a model that learns non-linear boundaries natively (trees, kernel SVM).
- Sensitive to multicollinearity. Highly correlated features make individual coefficient estimates unstable, even though the model's overall predictions can still be fine.
- Assumes the log-odds are linear in the features, not that the raw relationship between a feature and the outcome is linear, a distinction that is easy to misstate in an interview.
Worked example: from score to label
Suppose a model produces the score z=1.2 for a given input. The predicted probability is:
p=σ(1.2)=1+e−1.21=0.7685Converting to odds: 1−pp=0.23150.7685=3.32, meaning the model considers the positive class about 3.3 times more likely than the negative class for this input. At the default threshold of 0.5, since 0.7685≥0.5, the predicted label is 1. If the deployment threshold were instead 0.8 (say, to control false positives), this same input would be labeled 0 despite the model being fairly confident, which is exactly why threshold choice is a separate lever from model fit.
Trade-offs and pitfalls
- Coefficients are only directly comparable across features if those features are on the same scale; a common junior mistake is reading raw coefficient magnitude as "feature importance" on unstandardized data.
- Regularization (L1 or L2 penalty on the weights) trades a small amount of bias for lower variance and, with L1, can zero out irrelevant features, but it also shrinks the coefficients you'd otherwise use for odds-ratio interpretation.
- Logistic regression gives well-calibrated probabilities when the model is close to correctly specified, which is part of why it stays a strong baseline even when a more flexible model wins on raw accuracy.
- The linear-boundary limitation is a feature as much as a bug: it is what makes the model fast, interpretable, and hard to overfit with a small feature set, which is exactly the trade a tree ensemble or kernel method gives up.
What's the practical difference between linear regression and logistic regression: what kind of target each models, their core assumptions, and how you'd evaluate each?
Sample Answer
Direct answer
Linear regression models a continuous numeric target as a linear function of the features and is evaluated with error-magnitude metrics like RMSE or MAE and R-squared. Logistic regression models the probability of a binary (or multiclass) outcome via a sigmoid applied to a linear function, and is evaluated with classification metrics like AUC, precision and recall, and calibration measures, not R-squared.
Structured elaboration
| Linear regression | Logistic regression | |
|---|---|---|
| Target | Continuous, unbounded (price, temperature) | Categorical (binary, or multinomial with extensions) |
| Model form | y^=β0+β1x1+⋯+βpxp | P(y=1∣x)=1+e−(β0+β1x1+⋯+βpxp)1 |
| Fitting loss | Squared error (maximum likelihood under a Gaussian-noise assumption) | Log-loss / cross-entropy (maximum likelihood under a Bernoulli assumption) |
| Core assumptions | Linear relationship, independent residuals, homoscedastic (constant variance), roughly normal residuals for inference | Linear relationship between features and the log-odds, independent observations, no severe class separation |
| Evaluation | RMSE / MAE, R-squared, residual diagnostics (residuals vs fitted, QQ plot) | AUC-ROC, precision / recall / F1 at a threshold, log-loss, calibration (reliability diagram, Brier score) |
What linear in the log-odds means concretely: logistic regression is still a linear model, just linear in log-odds space rather than in probability space; the sigmoid squashes that unbounded linear combination into a valid [0,1] probability.
Worked example
Suppose a fitted logistic regression's linear combination (log-odds) at a particular input works out to 0.5. Converting to a probability via the sigmoid:
P(y=1∣x)=1+e−0.51=0.6225
A linear regression producing that same raw score of 0.5 would report it directly as the predicted value, no transform needed, valid across the whole real line and directly comparable to the actual target's units (dollars, degrees, and so on). The logistic regression's 0.5 log-odds, by contrast, isn't itself a probability, it's not even bounded to [0,1], it has to pass through the sigmoid to become the interpretable 0.6225 probability of the positive class.
Trade-offs & pitfalls
R-squared isn't meaningful for logistic regression the way it is for linear regression, some pseudo-R-squared variants exist but don't carry the same fraction-of-variance-explained interpretation, reporting plain R-squared for a classifier is a common tell that someone copy-pasted a linear-regression evaluation template onto a classification problem. Conversely, using a plain linear regression to predict a 0/1 target directly (the linear probability model) can produce predicted probabilities outside [0,1] and violates the constant-variance assumption by construction, since the variance of a Bernoulli outcome depends on its mean, logistic regression exists specifically to fix both problems.
What's cross-validation, and why do you use it? How does k-fold differ from stratified k-fold, and what goes wrong if you use plain random k-fold on time-dependent data?
Sample Answer
Direct answer
Cross-validation estimates how a model will perform on unseen data by repeatedly holding out different slices of the training set, fitting on the rest, and averaging the validation scores, which gives a much more reliable estimate than a single train/test split. Stratified k-fold is the same idea but forces each fold to preserve the overall class proportions, which matters for imbalanced classification. Plain random k-fold on time-dependent data is actively wrong: it can put future observations in the training fold and past observations in the validation fold, letting the model implicitly learn from the future and inflating your validation scores in a way that won't hold up in production.
k-fold vs. stratified k-fold
k-fold: split the data into k roughly equal, randomly-assigned folds. Train on k−1 folds, validate on the remaining one, repeat k times so every fold serves as validation exactly once, then average the k scores. This gives both a mean performance estimate and a sense of variance across folds.
Stratified k-fold: the same procedure, but folds are constructed so each one has (approximately) the same class distribution as the full dataset. Plain random k-fold does not guarantee this, and on an imbalanced dataset a small, unlucky fold can end up with very few or zero positive examples, making that fold's precision/recall undefined or wildly noisy.
Worked example: why stratification matters, with an explicit fold assignment
Take 10 labeled examples with an 8:2 class split, where the positives happen to be examples 9 and 10 (a realistic scenario: data is often collected or sorted in a way that clusters similar rows, e.g. by signup date or by a batch ID):
labels=[0,0,0,0,0,0,0,0,1,1]A naive unshuffled 5-fold split done as contiguous blocks of 2 (fold 1 = examples 1-2, fold 2 = examples 3-4, ..., fold 5 = examples 9-10) puts both positives in fold 5 and zero positives in every other fold. Folds 1 through 4 can't report a meaningful precision or recall (no positives to find), and fold 5's score is based on a validation set that's 100% positive, an unrepresentative extreme in both directions. Stratified 5-fold instead constructs each fold to contain roughly 0.2 positives per fold on average (in practice, one fold gets one positive, the rest are handled by scikit-learn's allocation rule so the 2 positives are spread as evenly as the count allows), so every fold's score is at least computable and representative of the true 20% rate.
Time-dependent data: what goes wrong with random k-fold
If rows are ordered in time (say, January through December), random k-fold shuffles them across folds without regard to date. A given fold's training set can then contain December data while its validation set contains June data, meaning the model is evaluated on "predicting the past" using information from "the future" that would never have been available at prediction time in production. This inflates validation metrics, sometimes substantially, because the model can pick up on trends, seasonality, or even data-leakage artifacts (like a feature that encodes a later processing step) that won't be available at actual inference time.
The fix is a time-aware split: forward-chaining (expanding-window) or rolling-window cross-validation, where every validation fold's data is strictly later in time than everything in its training fold, mirroring how the model will actually be used.
Trade-offs and pitfalls
- Larger k (more folds) means each fold is smaller and more training data is used each round (lower bias in the estimate), but the folds are more correlated with each other and it costs more compute; k=5 or k=10 is the usual default trade-off, and k=n (leave-one-out) is only practical for very small datasets.
- Stratification fixes class-proportion imbalance across folds but does nothing for other kinds of dependence, like multiple rows belonging to the same user; that needs
GroupKFoldso a given user's rows never span both the training and validation fold. - Time-aware CV and stratified CV solve different problems and aren't automatically compatible; if you have a time-dependent, imbalanced classification problem, you generally need a custom split that respects both the time ordering and per-fold class representation.
- Cross-validation gives you an estimate of generalization error for model selection, but the final reported number should still come from a held-out test set that was never touched during CV, since repeatedly tuning against CV folds can itself overfit to those folds.
Unlock Full Question Bank
Get access to all 31 Classical Machine Learning Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.