Rapid-Fire ML Fundamentals Check for a Product Recommender
Machine LearningModel answerLast updated
Answer a set of short core machine-learning questions covering models, regularization, evaluation, optimization and ranking, framed around building a product recommendation system.
Context
You are being screened for a role on a team that builds a recommendation system for an online store. The interviewer wants to check how broad and accurate your machine-learning fundamentals are. Each topic below should get a short, precise answer: a definition, the reason it works, and one practical action you would take. Link answers to recommendations where it fits naturally.
Questions
- How do a single decision tree and a random forest differ?
- Compare L1 and L2 regularization. How does each deal with overfitting, and what about underfitting?
- You have one million labeled examples. Would you pick a deep neural network or KNN, and why?
- Is the ROC curve only meaningful for binary classification? Given a list of model scores and true labels, how would you draw one?
- What makes training loss oscillate, and how would you stabilize it?
- Define data drift and explain how you would detect it in production.
- How do convex and non-convex objectives differ?
- In which parts of a neural network do vanishing gradients typically appear, and how do you reduce them?
- As a decision tree gets deeper, how does inference time scale: linear, logarithmic, or exponential?
- Which is more reliable for estimating performance: cross-validation or a single train/test split?
- Summarize the main ideas behind convolutional neural networks.
- Contrast transformer encoders with transformer decoders.
- Describe the k-means algorithm and the assumptions it makes.
- What values can cosine similarity take?
- Is logistic regression generative or discriminative?
- How do you read a confusion matrix, and when would you reach for ensemble methods?
- Compare Naive Bayes and KNN.
- Name regularization techniques other than L1 and L2.
- Gradient boosting machines vs random forests: where is each stronger or weaker?
- What does it mean for a model to be calibrated, and how do you measure it?
- Describe the learning-to-rank problem.
Expectations
Cover definitions, intuition for the math, computational cost, evaluation metrics, and realistic failure modes. Include formulas or short pseudocode where they help.
Hints
Hint 1
For each item, aim for three parts: the definition, the mechanism (why it behaves that way), and a concrete action you would take in practice. Keep each answer to a few sentences.
Hint 2
Several questions hinge on a single distinction: variance vs bias (bagging vs boosting, L2 shrinkage), training cost vs inference cost (KNN vs DNN, tree depth), and discriminative vs generative modeling (logistic regression vs Naive Bayes).
Hint 3
For the ROC question, sort by score, sweep the threshold while handling ties together, and record (FPR, TPR) at each step. For recommendations, remember to split by time or by user to avoid leakage when validating.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
How to approach this
This is a breadth screen, so give short, correct answers with a mechanism and a practical lever. Tie them to recommendations when natural.
Trees, ensembles, regularization
Tree vs random forest. A tree greedily splits on the feature and threshold that most reduce impurity (Gini or entropy for classification, MSE for regression). It is interpretable and fast but high variance. A random forest trains many deep trees on bootstrap samples, considers a random feature subset at each split, and averages or votes. Decorrelated trees cut variance while bias stays about the same. Costs: less interpretability and about T times the inference work. Bonus: out-of-bag error gives a free validation estimate.
L1 vs L2. L1 adds λΣ|wᵢ|. It is non-differentiable at zero, so it drives weights exactly to zero, giving sparsity and implicit feature selection (Laplace prior). L2 adds λΣwᵢ², shrinking all weights smoothly and coping well with correlated features (Gaussian prior). Both reduce overfitting by limiting capacity. Neither cures underfitting; too large a λ causes it, and the remedy is a smaller λ or more capacity. Elastic net mixes both.
Other regularizers. Dropout, early stopping, data augmentation, weight decay (equals L2 under plain SGD but not under Adam, hence AdamW), batch/layer norm, label smoothing, noise injection, max-norm constraints. For trees: max depth, min samples per leaf, row/column subsampling, shrinkage.
GBM vs random forest.
| Gradient boosting | Random forest | |
|---|---|---|
| Training | Sequential, shallow trees fit the negative gradient | Parallel, independent deep trees |
| Mainly reduces | Bias | Variance |
| Accuracy | Often best on tabular data | Strong, usually slightly lower |
| Tuning | Sensitive (learning rate, tree count, depth) | Few knobs |
| Noisy labels | Can overfit | More robust |
Ensembles. Bagging for high-variance base models, boosting for high-bias ones, stacking for diverse models with uncorrelated errors, provided latency and maintenance budgets allow.
Depth and inference time. Inference follows one root-to-leaf path, so it is linear in depth, O(d). For a balanced tree, d ≈ log₂(leaves), so it is logarithmic in size. What grows exponentially is the maximum node count (2ᵈ), affecting memory and training, not per-sample latency.
Model choice and evaluation
DNN vs KNN at 1M samples. Default to the DNN. KNN has no training, but brute-force queries cost O(n·d) and all points must be stored; it also suffers in high dimensions and needs scaling. A DNN pays at training time and has fixed-cost inference. In recommendations the two combine: a two-tower network learns embeddings and approximate nearest-neighbor search (FAISS, ScaNN) retrieves. For low-dimensional tabular data, a GBDT may beat both.
Naive Bayes vs KNN. Naive Bayes is generative and parametric, assumes conditional independence, trains in one pass, works with little data and is strong on text, but its probabilities are poorly calibrated. KNN is lazy and non-parametric, makes few distributional assumptions, but has expensive queries and is sensitive to scaling and irrelevant features.
Logistic regression. Discriminative: it models P(y|x) = σ(wᵀx) directly. Naive Bayes is the generative counterpart.
Confusion matrix. Cells are TP, FP, FN, TN. Precision = TP/(TP+FP), recall = TP/(TP+FN), FPR = FP/(FP+TN), F1 is the harmonic mean of precision and recall. Interpret errors by their business cost, and pick thresholds accordingly.
ROC. Defined for binary problems (TPR vs FPR across thresholds). For multiclass, use one-vs-rest with macro or micro averaging. Plotting from scores:
sort (score, label) by score descending
P = #positives, N = #negatives; tp = fp = 0; points = [(0,0)]
for each distinct score s (handle ties together):
tp += positives at s; fp += negatives at s
points.append((fp/N, tp/P))
AUC = trapezoidal area under points
AUC is the probability a random positive outranks a random negative. With heavy imbalance, also show the precision-recall curve.
Cross-validation vs single split. k-fold is more robust: every sample is validated once and averaging reduces variance, plus you see the spread. It costs k times the compute. For recommendations, use time-based splits for temporal data and group k-fold by user to avoid leakage.
Calibration. Among items predicted at 0.3, about 30% should be positive. Evaluate with reliability diagrams, ECE, Brier score and log loss. Fix with Platt scaling, isotonic regression or temperature scaling on held-out data. It matters when scores feed blending, thresholds or auctions (for example pCTR times bid).
Optimization and deep learning
Convex vs non-convex. Convex: f(λx+(1−λ)y) ≤ λf(x)+(1−λ)f(y), equivalently a positive semi-definite Hessian. Every local minimum is global. Linear/logistic regression and SVMs are convex. Neural-network losses are non-convex, with many local minima and saddles, so initialization, learning rate and stochasticity matter.
Loss oscillation. Causes: learning rate too high, small or noisy batches, unshuffled data, exploding gradients, ill-conditioning. Fixes: lower the learning rate or decay it, warmup, larger batches, gradient clipping, Adam or momentum, normalization, better scaling.
Vanishing gradients. They appear in deep stacks and long recurrent sequences, especially with saturating activations (sigmoid, tanh), where repeated multiplication of small derivatives shrinks the signal in early layers. Mitigate with ReLU-family activations, He/Xavier initialization, batch/layer norm, residual connections, gated units (LSTM/GRU), and gradient clipping for the opposite exploding problem.
CNNs. Local receptive fields with shared weights (convolutions) give translation equivariance and far fewer parameters. Pooling adds invariance and reduces size. Stacked layers build hierarchical features from edges to objects. In e-commerce they are used on product images.
Encoder vs decoder. An encoder uses bidirectional self-attention and produces contextual representations (BERT-style, good for understanding and embeddings). A decoder uses causal masked self-attention and generates tokens autoregressively (GPT-style), and in encoder-decoder models adds cross-attention to the encoder.
Data drift. The input distribution P(x) shifts (covariate drift), or P(y|x) changes (concept drift), or label priors move. Detect with PSI, KS or chi-square tests per feature, embedding-distribution distance, monitoring prediction distributions, and tracking delayed-label metrics. Alert, then retrain or roll back.
Remaining topics
k-means. Initialize k centroids (k-means++), assign points to the nearest centroid, recompute means, repeat until stable. It minimizes within-cluster squared distance and converges to a local optimum. Assumptions: roughly spherical, similarly sized clusters, Euclidean geometry, k known, scaled features. It is sensitive to outliers.
Cosine similarity. Range is [−1, 1]. It is [0, 1] for non-negative vectors such as TF-IDF or counts.
Learning to rank. Given queries (or users) and candidate items with features and relevance labels, learn a scoring function that orders items well. Approaches: pointwise (regress relevance), pairwise (RankNet, hinge on pairs), listwise (LambdaRank/LambdaMART, optimizing NDCG-like metrics). Evaluate with NDCG, MAP, MRR. Beware position bias in click-based labels.
Common mistakes
- Saying L1/L2 fix underfitting.
- Claiming tree inference is exponential in depth.
- Quoting cosine range as [0, 1] universally.
- Using random splits on time-ordered or per-user data.
- Treating raw model scores as probabilities without checking calibration.