FOUNDATIONS · ML RAPID REVIEW

ML fundamentals — a textbook progression

ML-fundamentals rounds at top companies are conversational and probing — interviewers keep asking "why?" until they find your floor, and they lean hard on feature selection and Bayes/overlap reasoning. This page is a course, not a Q&A dump: it walks the theory in the order the books do (Hastie ESL / Bishop PRML) — the learning problem, Bayes error, the bias–variance decomposition, regularization, then models, evaluation, RecSys, and finally probe chains tying the theory back to the interview.

6 parts · 19 chapters Theory-first with derivations RecSys-flavored Math renders (KaTeX)
TL;DR

Everything in this round reduces to a few ideas: error decomposes into irreducible (Bayes) + bias² + variance (Part I); you trade bias for variance with capacity and regularization; you pick a model to match the regime and the data (Parts II–III); you measure with the right metric and calibrate (Part IV); and at Reddit you apply it to retrieval + ranking (Part V). The interview's favorite question — two overlapping class distributions — is just Bayes error in disguise (Part VI). Be able to derive, not recite, and survive three "why?"s on any answer.

01
PART I · FOUNDATIONS

The learning problem: loss, risk, generalization

025507510000.20.40.6Learning curves: training vs true risktraining-set size nexpected errorirreducible (Bayes) errorgeneralization gaptest / true risktraining error
More data shrinks the generalization gap: training error rises and test error falls until both hit the irreducible Bayes error. The gap, not the training error, is what regularization and more data attack.

Supervised learning assumes data $(x,y)$ drawn i.i.d. from an unknown joint distribution $P(x,y)$. We pick a hypothesis $f$ from a class $\mathcal{F}$ to minimize the expected risk under a loss $L$:

$$ R(f) = \mathbb{E}_{(x,y)\sim P}\big[L(y, f(x))\big]. $$

We never know $P$, so we minimize the empirical risk on $n$ samples (ERM — empirical risk minimization):

$$ \hat R(f) = \frac{1}{n}\sum_{i=1}^{n} L(y_i, f(x_i)). $$

The whole game is the generalization gap $R(f) - \hat R(f)$: training error is optimistic, and the gap grows with model capacity and shrinks with data. Everything downstream — regularization, validation, the bias–variance tradeoff — is about controlling that gap.

Loss functions and what they assume

TaskLossImplied noise model
RegressionSquared error $(y-\hat y)^2$Gaussian noise → mean is optimal
Regression (robust)Absolute / HuberLaplace / heavy tails → median is optimal
ClassificationCross-entropy $-\sum_c y_c\log \hat p_c$Bernoulli/Categorical → calibrated probabilities
RankingPairwise / listwise (BPR, LambdaMART)Order matters, not absolute score
Why cross-entropy, not MSE, for classification
Cross-entropy is the negative log-likelihood of the Bernoulli/Categorical model, so its minimizer is the true class probability. Its gradient w.r.t. the logits is the clean $\hat p - y$. MSE-through-a-sigmoid multiplies the gradient by $\sigma'(z)$, which vanishes when the unit saturates → slow learning and worse calibration.

The loss is a modeling choice. "Which model?" in the interview always starts here: clarify the task (regression / classification / ranking), the label, and the cost of each error type — that fixes the loss before you pick an architecture.

02
PART I · FOUNDATIONS

Bayes optimal classifier & Bayes error

-4-2024Class overlap & the Bayes thresholdfeature xclass Aclass BthresholdBayes error012345600.10.20.30.40.5Bayes error vs separationseparation Δ/σBayes error R*Δ/σ=2.8 → R*≈0.08
The shaded overlap is the irreducible Bayes error. It depends only on the separation in units of noise: $R^*=\Phi(-\Delta/2\sigma)$. A single threshold can't remove it — only a feature that raises $\Delta/\sigma$ can.

The lowest error any model can achieve is the Bayes error — the error of the Bayes optimal classifier, which predicts the most probable class given $x$:

$$ f^*(x) = \arg\max_{c} P(y=c \mid x), \qquad R^* = \mathbb{E}_x\Big[\,1 - \max_c P(y=c\mid x)\,\Big]. $$

This error is irreducible: it comes from genuine overlap between the classes (the same $x$ can yield different $y$), not from a weak model. No amount of data or capacity removes it — only better features that separate the classes can.

The two-Gaussian case (this is the interview's overlap question)

One feature $x$, two equally-likely classes with $x\mid A \sim \mathcal{N}(\mu_A,\sigma^2)$, $x\mid B \sim \mathcal{N}(\mu_B,\sigma^2)$, $\mu_B>\mu_A$. The Bayes classifier thresholds where the densities cross, $t=\tfrac{\mu_A+\mu_B}{2}$, and the Bayes error is the overlap area:

$$ R^* = \Phi\!\left(-\frac{\Delta}{2\sigma}\right), \qquad \Delta = \mu_B-\mu_A, $$

with $\Phi$ the standard normal CDF. The point every interviewer wants: error depends on the separation in units of noise, $\Delta/\sigma$. More overlap (small $\Delta/\sigma$) → higher irreducible error → a single threshold cannot fix it; you need a feature that raises $\Delta/\sigma$. With unequal priors or asymmetric costs, the optimal threshold shifts off the midpoint toward the rarer/cheaper class.

Connect it to the ROC curve
Sliding the threshold traces the ROC curve; the Bayes-optimal point is where slope = ratio of priors×costs. AUC measures separability across all thresholds — high exactly when $\Delta/\sigma$ is large. This bridges Bayes error (ch2) to metrics (ch10).
Q. The classes overlap in the middle. What does that tell you and what do you do?
It tells you there is irreducible (Bayes) error on this feature — the overlap is genuinely ambiguous, so no threshold drives error to zero. A threshold is still a reasonable rule (1-D, ordered conditionals), placed by the cost of FP vs FN, not at the geometric middle by default. The real lever is better/more features that reduce overlap (raise $\Delta/\sigma$ in the joint space). "It's linearly separable, pick a threshold" is the answer that fails this round.
03
PART I · FOUNDATIONS

The bias–variance decomposition

24681000.250.50.751Bias²–variance decompositionmodel capacity →expected erroroptimaltotalbias²variancenoise24681000.250.50.751What you observe: train vs testmodel capacity →errorunderfitoverfittesttrain
Capacity trades bias for variance: $\mathbb{E}[(y-\hat f)^2]=\text{bias}^2+\text{variance}+\sigma^2$. Test error is the U-shaped sum; training error keeps falling, which is exactly why it can't pick capacity.
00.511.522.5300.250.50.751Double descent (modern over-parameterization)capacity (params / n)test errorinterpolation thresholdclassical U2nd descenttesttrain
Beyond the classical bias–variance U, test error spikes at the interpolation threshold (parameters ≈ samples, where training error first hits 0) and then descends again deep in the over-parameterized regime — the reason huge networks that can memorize the data still generalize.

For squared-error regression, fix $x$ with $y = g(x) + \varepsilon$, $\mathbb{E}[\varepsilon]=0$, $\mathrm{Var}(\varepsilon)=\sigma^2$. Let $\hat f$ be trained on a random dataset $D$. The expected test error decomposes exactly:

$$ \mathbb{E}_{D,\varepsilon}\big[(y-\hat f(x))^2\big] = \underbrace{\sigma^2}_{\text{irreducible}} + \underbrace{\big(g(x)-\mathbb{E}_D[\hat f(x)]\big)^2}_{\text{bias}^2} + \underbrace{\mathbb{E}_D\big[(\hat f(x)-\mathbb{E}_D[\hat f(x)])^2\big]}_{\text{variance}}. $$
Derive it (the cross-term vanishes)

Let $\bar f=\mathbb{E}_D[\hat f(x)]$. Write $y-\hat f = (y-g) + (g-\bar f) + (\bar f-\hat f)$ and square. $\mathbb{E}[(y-g)^2]=\sigma^2$; $(g-\bar f)^2$ is deterministic = bias²; $\mathbb{E}[(\bar f-\hat f)^2]$ = variance. Cross terms vanish: $\varepsilon\perp\hat f$ so $\mathbb{E}[(y-g)(\cdot)]=0$, and $\mathbb{E}_D[\bar f-\hat f]=0$ by definition of $\bar f$.

Capacity moves you along the tradeoff: more flexibility ⇒ bias↓, variance↑; total error is U-shaped. The moves: more data cuts variance (not bias); regularization raises bias to cut variance; ensembling targets one term.

Bagging vs boosting in one line
Bagging (Random Forest) averages many high-variance, low-bias trees → cuts variance. Boosting (GBM/XGBoost) fits weak, high-bias learners to the residual sequentially → cuts bias. Hence RF is robust out-of-the-box while boosting needs regularization to avoid overfitting.

Double descent: past the interpolation threshold, very over-parameterized models can have decreasing test error again — the U-curve is the underparameterized half of a double-descent curve. One sentence; don't over-claim.

04
PART I · FOUNDATIONS

Capacity, overfitting & regularization

w₁w₂OLS (unpenalised)L2: small but ≠0L1: w₁=0 (sparse)Constraint geometry-2-101200.511.52Penalty shape → sparsityweight wpenaltyL1: |w|L2: w²L1 slope is constant → drives weights to exactly 0
Regularization shrinks the solution to where a loss contour first touches the constraint ball. The L1 diamond has corners on the axes, so the optimum often lands at $w_i=0$ (sparse); the smooth L2 circle shrinks every weight but zeroes none.

Overfitting = low train, high test = high variance (fit noise). Underfitting = high train and test = high bias. Diagnose with a learning curve: a large persistent train/val gap ⇒ variance ⇒ regularize / more data; both curves high and close ⇒ bias ⇒ more capacity/features.

Q. Train accuracy 0.91, test 0.85 — what's going on and what do you do?
A ~6-pt gap ⇒ overfitting / variance. Leverage order: (1) more data; (2) regularization — L2/L1, dropout, weight decay; (3) reduce capacity / fewer features; (4) early stopping; (5) augmentation; (6) ensembling. First rule out leakage or train/test distribution shift. If both numbers were low and close, it'd be bias → add capacity/features.

L2 vs L1 — geometry and the Bayesian reading

Ridge (L2) adds $\lambda\lVert w\rVert_2^2$; Lasso (L1) adds $\lambda\lVert w\rVert_1$.

Capacity control without changing the model: early stopping limits effective capacity; and $\lambda$ is tuned by cross-validation (ch10), never on the training set.

05
PART I · FOUNDATIONS

MLE, MAP & the Bayesian view

-2-101234Prior × likelihood → posteriorparameter θprior meanMLEMAPposteriorlikelihoodprior
MLE maximises the likelihood alone; MAP multiplies in the prior, so the estimate is the MLE shrunk toward the prior mean (here 0). A Gaussian prior = L2; a Laplace prior = L1. As $n\to\infty$ the likelihood dominates and MAP → MLE.

Maximum likelihood picks parameters making the data most probable; MAP adds a prior and is exactly MLE + a regularizer:

$$ \hat\theta_{\text{MLE}} = \arg\max_\theta \sum_i \log p(x_i\mid\theta), \qquad \hat\theta_{\text{MAP}} = \arg\max_\theta \Big[\sum_i \log p(x_i\mid\theta) + \log p(\theta)\Big]. $$

Logistic regression worked example. The Bernoulli likelihood gives cross-entropy; MAP with a Gaussian prior gives L2-regularized logistic regression, with gradient $X^\top(\hat p - y) + 2\lambda w$ — the data term pulls predictions toward labels, the prior shrinks weights. Fully Bayesian inference keeps the whole posterior $p(\theta\mid D)$ (predictive uncertainty); MAP is the point-estimate shortcut.

The thread that ties Part I together
Loss = negative log-likelihood (ch1). Regularization = a prior (ch5). Generalization error = irreducible (ch2) + bias² + variance (ch3), controlled by capacity + prior strength (ch4). Move fluidly between these views and the fundamentals round is yours.
06
PART II · CLASSICAL MODELS

Linear / logistic regression & GLMs

-6-303600.250.50.751Logistic linkz = wᵀx + bP(y=1 | x)decision boundary z=000.250.50.751012345Cross-entropy (log) losspredicted probability p− log lossy = 1y = 0confident & wrong → huge loss
Logistic regression squashes the linear score through $\sigma(z)=1/(1+e^{-z})$. It is fit with cross-entropy $-[y\log p+(1-y)\log(1-p)]$, which is convex and punishes confident mistakes far more than the squared error would.

Start every "which model?" answer with the simplest thing that could work, then justify added complexity by the bias–variance regime.

07
PART II · CLASSICAL MODELS

Trees & ensembles (bagging, boosting)

0246Bagging: averaging cuts variancextruthavg of 6individual05010015020000.20.40.6Boosting: add weak learners# trees (rounds)errorearly stoptesttrain
Bagging (random forest) averages high-variance, low-bias trees → variance drops, bias unchanged. Boosting (GBDT/XGBoost) adds shallow trees that fit the residual → bias drops round by round, but test error eventually creeps up, so you early-stop.

A single decision tree is low-bias, high-variance and captures interactions automatically — but overfits. Ensembles fix the variance or the bias (the bias–variance lens from ch3):

Bagging / Random ForestBoosting / GBM, XGBoost
BuildsMany deep trees in parallel on bootstrapped samples (+ feature subsampling)Shallow trees sequentially, each fit to the gradient of the loss (residual)
AttacksVariance (averaging decorrelated trees)Bias (additively reducing residual error)
Overfit riskLow; more trees never hurtsHigher; needs learning-rate, depth, subsample, L1/L2 regularization, early stopping
Key knobsn_trees, max_featureslearning_rate, n_estimators, max_depth, reg_lambda/alpha, subsample
Why GBDTs dominate tabular ranking
They model feature interactions and nonlinearities without manual engineering, handle mixed/scaled features, and are robust to outliers/monotone transforms. At Reddit-scale ranking the trunk may be a DNN/DLRM (ch14), but GBDTs remain the strong tabular baseline and a common first ranker. Feature importance via gain or, better, permutation/SHAP (ch17).
08
PART II · CLASSICAL MODELS

SVM / kernels, k-NN, clustering, PCA

02468100510SVM: maximum-margin separatorx₁x₂margin02468100510PCA: max-variance directionsx₁x₂PC1PC2
SVM picks the separator with the widest margin; only the support vectors (circled, on the margin) define it. PCA rotates to the orthogonal directions of greatest variance — keep PC1/PC2, drop the rest to reduce dimensions.

SVM maximizes the margin between classes; the kernel trick replaces inner products $x_i^\top x_j$ with $k(x_i,x_j)$ to learn nonlinear boundaries in an implicit high-dim space (RBF → infinite-dim). Powerful on small/medium data; scales poorly (kernel matrix is $O(n^2)$), so logistic regression / GBDTs win at scale.

k-NN: no training; predict by the $k$ nearest neighbors. $k$ is a direct bias–variance knob: small $k$ = low bias/high variance (jagged boundary), large $k$ = high bias/smooth. Curse of dimensionality kills it in high dim (everything is far).

Unsupervised: clustering & dimensionality reduction

09
PART III · DEEP LEARNING

Backprop, activations, init, normalization, optimizers

-4-2024-101Activation functionszsigmoidtanhReLUleaky-4-202400.250.50.751…and their gradientszf '(z)σ' ≤ 0.25saturation → vanishing gradient
Sigmoid and tanh saturate: their derivative collapses toward 0 for large |z|, so gradients vanish through deep stacks (note $\sigma'\le 0.25$). ReLU keeps a gradient of 1 wherever it is active — which is why deep nets default to ReLU-family units.
-8-4048-404Optimizers on an ill-conditioned lossw₁ (flat direction)w₂ (steep)SGD (zig-zags)+ momentumAdam (rescaled)
When curvature is uneven, plain SGD zig-zags across the steep direction while crawling along the flat one. Momentum averages successive gradients to damp the oscillation and accelerate down the valley; Adam/RMSProp rescale each coordinate by its own gradient history, taking near-straight steps to the minimum.

Backprop is the chain rule on the computation graph: a forward pass caches activations, a backward pass propagates $\partial L/\partial \cdot$ from output to input, reusing shared subexpressions (it computes vector–Jacobian products, never the full Jacobian).

Activations & the vanishing gradient

Sigmoid's derivative is $\sigma'(z)=\sigma(z)(1-\sigma(z))\le 0.25$, and it saturates to $\approx 0$ for large $|z|$. Stack many layers and the product of small derivatives drives early-layer gradients to zero — training stalls. ReLU ($\max(0,z)$) has derivative 1 on the positive side, so gradients flow; cost is "dying ReLU" (stuck at 0) → Leaky ReLU / GELU fix it. This is why deep nets needed ReLU + good init + normalization to train at all.

Initialization & normalization

Optimizers & regularization

SGD → +momentum (velocity) → Adam (per-parameter adaptive LR via 1st/2nd moment estimates with bias correction) → AdamW (decoupled weight decay — the correct way to L2-regularize adaptive optimizers). Regularize with weight decay, dropout (randomly zero activations at train time ≈ ensembling thinned subnetworks; scale at test), early stopping, and augmentation. LR schedule (warmup + cosine) matters as much as the optimizer.

Q. Your deep net's loss plateaus immediately. Diagnose.
Check, in order: LR (too high → diverge/NaN, too low → no progress); initialization + activations (vanishing gradients with sigmoid/poor init); normalization (add BN/LN); dead ReLUs (large negative bias); data issues (unnormalized inputs, wrong labels); and whether the loss/gradient is even connected (bug). State a hypothesis and the one experiment that tests it.
10
PART IV · EVALUATION

Metrics: ROC/PR, NDCG, cross-validation

00.250.50.75100.250.50.751ROC (AUC = 0.86)false-positive ratetrue-positive rateoperating ptchance00.250.50.75100.250.50.751Precision–recallrecallprecisionbase rate π=0.25
ROC/AUC is threshold-free and prevalence-independent — AUC is P(score⁺ > score⁻). On rare-positive problems it looks rosy, so report the PR curve too: precision sags toward the base rate $\pi$, which ROC hides.

From the confusion matrix: precision $=\tfrac{TP}{TP+FP}$ (of what you flagged, how much was right), recall $=\tfrac{TP}{TP+FN}$ (of what's real, how much you caught), F1 = harmonic mean. The threshold trades precision for recall — pick it by the cost of FP vs FN (ties back to ch2's cost-shifted threshold).

MetricUse whenPitfall
AccuracyBalanced classes, symmetric costsUseless under imbalance (99% by predicting majority)
ROC-AUCRanking quality, threshold-free, balanced-ishOver-optimistic under heavy imbalance
PR-AUCRare positives (fraud, spam, click)Baseline = positive rate, not 0.5
NDCG / MAP / MRRRanked lists (feed, search)Need graded relevance + position discount

NDCG rewards relevant items near the top via a logarithmic position discount:

$$ \text{DCG@k} = \sum_{i=1}^{k} \frac{2^{\text{rel}_i}-1}{\log_2(i+1)}, \qquad \text{NDCG@k}=\frac{\text{DCG@k}}{\text{IDCG@k}}. $$

Cross-validation done right

k-fold averages out variance in the estimate; stratified k-fold preserves class ratios (essential for imbalance); time-series splits (train past → test future) for any temporal data — random splits leak the future. The cardinal sin is leakage: any preprocessing/feature-selection/target-encoding fit on the full data before splitting inflates CV scores. Fit transforms inside the fold.

11
PART IV · EVALUATION

Calibration

00.250.50.75100.250.50.751Before: over-confidentpredicted probabilityobserved frequencyper-bin gapperfect00.250.50.75100.250.50.751After calibrationpredicted probabilityobserved frequencyPlatt / isotonic / temperature
A model can rank well yet be mis-calibrated: a reliability diagram plots predicted vs observed rate. The per-bin gap between the two, averaged and weighted by how many predictions fall in each bin, is the expected calibration error ($\text{ECE}=\sum_m \tfrac{|B_m|}{n}\,|\text{acc}(B_m)-\text{conf}(B_m)|$). Platt scaling, isotonic regression or temperature scaling bend the curve back onto the diagonal — essential when the probability itself is used (ads bidding, thresholds).

Discrimination (AUC) asks "can you rank positives above negatives?"; calibration asks "when you say 0.7, does it happen 70% of the time?" A model can rank perfectly yet be badly calibrated. Diagnose with a reliability diagram (predicted vs observed frequency per bin) and ECE (expected calibration error).

Why top companies care
Calibration is the glue for multi-task ranking and ads bidding: a final score that linearly combines $p(\text{click}), p(\text{upvote}), p(\text{comment})$ only makes sense if each head is calibrated; one miscalibrated head dominates the blend. Recalibrate per-segment and re-fit when the logging policy shifts.
12
PART IV · EVALUATION

Statistics & A/B testing

-3036Type I / II error & powertest statisticcritical zααβH₀H₁05010015020000.250.50.751Power vs sample sizesamples per arm npower = 1 − β80% power at n≈69
An A/B test trades off two errors: α (reject a true H₀, the red tail) and β (miss a real effect). Power = 1−β rises with sample size and effect size — fix α=0.05 and power=0.8, then solve for the sample size you need before launching. (CUPED cuts variance → more power for the same n.)

Reddit is product/experimentation-heavy; expect this even in an ML round.

13
PART V · RECSYS

Retrieval, two-tower, negative sampling

USER TOWERITEM TOWERuser / context featuresMLPMLPembed u (d)item / post featuresMLPMLPembed v (d)score = u · vcosine / dotTrained with in-batch negatives + logQ correction; serve items from an ANN index on v.
The two-tower retrieval model: independent towers map user and item to the same $d$-dim space; relevance is a dot product. Item embeddings are precomputed into an ANN index, so retrieval is a fast nearest-neighbour lookup. Train with in-batch negatives and a logQ correction for sampling bias.

Industrial recsys is a funnel: retrieval/candidate-generation (millions → hundreds, high recall, cheap) → ranking (hundreds → ordered, rich features) → re-ranking (diversity, business rules). The bias–variance/serving tradeoff lives here: retrieval must be sub-linear, ranking can be expensive per item.

Two-tower: a user tower and an item tower produce embeddings; relevance = dot product. Item embeddings are precomputed and indexed for ANN (HNSW / IVF-PQ) so retrieval is milliseconds over billions. (Standard industry retrieval; confirmed at Reddit specifically in the notification retrieval stage.)

Negative sampling — the crux of two-tower training

14
PART V · RECSYS

Ranking models & multi-task

MMoE — all experts sharedinputE1E2E3gate Agate Btower → CTRtower → CVRPLE — shared + task-specificinputA-specsharedB-specgate Agate Btower → CTRtower → CVR
Multi-task ranking shares a backbone across objectives (CTR, CVR, dwell). MMoE gives every task a soft gate over a shared pool of experts. PLE adds task-specific experts alongside the shared ones, which reduces negative transfer when objectives conflict.
15
PART V · RECSYS

Position bias & counterfactual evaluation

1357900.250.50.751Position biasrank position kprobabilitytrue relevance (flat)examined p(k)observed CTR00.250.50.751IPS de-biasingpositionestimated relevancek=1k=2k=3k=4k=5raw CTRCTR / p(k)
Top results get clicked more regardless of relevance because they are examined more. Observed CTR = relevance × examination $p(k)$. Dividing each click by its propensity $p(k)$ (inverse-propensity scoring) recovers the flat true relevance — the basis of counterfactual learning-to-rank.

Logged ranking data is biased: top items get clicked because they're on top, not (only) because they're relevant. Naively training on it makes the model mimic the old ranker.

16
PART VI · APPLIED PROBE CHAINS

The overlap-distributions chain

This is Reddit's most-reported ML-fundamentals sequence (1Point3Acres + darkinterview). It's a single thread that walks from "what model?" down to a mini design — and it's all the Part-I theory applied. Cross-link: real question #12. The interviewer gives hints and follows your reasoning, so narrate.

  1. "Given feature $x$ and label $y\in\{A,B\}$, how would you model it?" → Clarify it's binary classification; start with a baseline (logistic regression), state you'd add complexity only if the data demands it. Mention you'd look at the class-conditional distributions of $x$ first.
  2. They show two overlapping normals. → "The overlap is irreducible Bayes error on this feature (ch2): the same $x$ produces both labels there, so no decision rule drives error to zero." Give $R^*=\Phi(-\Delta/2\sigma)$ and the $\Delta/\sigma$ intuition. Do not stop at "linearly separable, pick a threshold" — that's the failing answer.
  3. "How do you predict points in the overlap?" → Output a probability, not a hard label; place the threshold by the cost of FP vs FN (and the class prior), not the geometric midpoint. If you must hard-classify, you'll be wrong $R^*$ of the time there — that's expected.
  4. "How would you reduce the error?" → Not by tuning the threshold — by adding features that separate the classes (raise $\Delta/\sigma$ in the joint space). This is the line they're listening for, and it leads straight into feature selection (ch17).
  5. "Now $x$ has 1000 features, not 1 — what's the same, what changes, what's new?" → Same: Bayes error, bias–variance, the probabilistic framing. Changes: distances concentrate (curse of dimensionality), variance/overfitting risk rises → need regularization + feature selection; visualization breaks. New: feature interactions and correlations matter; multicollinearity; you can now actually separate classes a single feature couldn't.
  6. "Train acc 0.91, test 0.85 — what's wrong?" → Overfitting / variance (ch4): regularize, more data, fewer features, early stopping; rule out leakage/shift first.
  7. "Design a model to predict post popularity." → A mini design: define the label (early-velocity vs final score; classification "will it hit top-K?" vs regression on log-score), pick features (author/subreddit history, early engagement, content embeddings, time-of-day), watch leakage (no post-publication signals for an at-publish prediction), use a temporal split + PR-AUC/NDCG, and handle cold start. Tie back: it's the same loss → model → eval → bias-variance loop.
17
PART VI · APPLIED PROBE CHAINS

Feature selection (probed hard)

0153045600.60.70.80.9Validation score vs # featuresnumber of features keptvalidation scorepeak ≈ 23 featurestoo few → underfit (bias)too many → noise features add variance (overfit)
More features help until the marginal signal is gone; past the peak, irrelevant features add variance and the validation score declines. This is why teams probe feature selection (filter / wrapper / L1 / importance) hard — the curve, not raw feature count, is the goal.

Reddit interviewers repeatedly steer the fundamentals round to "how do you choose features?" Have a structured answer.

18
PART VI · APPLIED PROBE CHAINS

The ML-practitioner notebook (#13)

The senior MLE phone screen is often a live notebook: Post Click Prediction — features are hours spent reading category A/B/C + the current post category; label is click. Cross-link: real question #13. They allow Googling syntax; they care about workflow + reasoning, not memorized APIs.

  1. Load & inspect: JSON → DataFrame; check dtypes, the label balance, missingness. (Reported data is clean and roughly balanced.)
  2. Prepare: one-hot the categorical current_post_category; train/test split with stratify; standardize for linear models.
  3. Baseline → models: DummyClassifier (sanity floor) → Logistic Regression (fast, interpretable) → Random Forest (nonlinear interactions) → XGBoost (stronger). The progression itself is the signal.
  4. Metric choice: justify by the product goal — accuracy if balanced + symmetric cost; ROC-AUC for ranking quality; PR-AUC if positives are rare; F1 for a precision/recall balance.
  5. "With more time?": cross-validation, hyperparameter tuning, threshold tuning, interaction features (reading-profile × current-category), calibration, error analysis by category.

Be ready for the follow-ups: "why this model / why not that one / what's the tradeoff?" — answer through the bias–variance lens (ch3) and the data size/shape.

19
PART VI · APPLIED PROBE CHAINS

Rapid-fire probes (grouped)

Short Q&A to drill recall — grouped by the part they test, so they reinforce the progression.

Q (I). Why does cross-entropy beat MSE for classification?
CE is the NLL of the Bernoulli/Categorical model → minimizer is the true probability; gradient is the clean $\hat p-y$. MSE-through-sigmoid adds a vanishing $\sigma'(z)$ factor → slow learning + worse calibration.
Q (I). What is irreducible error and can you reduce it?
Bayes error / label noise $\sigma^2$ — the overlap of class-conditionals. Not reducible by model or data; only by better features that separate the classes.
Q (I). L1 vs L2 — which gives sparsity and why?
L1: the diamond ball's corners on the axes + a constant-magnitude gradient soft-threshold weights to exactly 0 → sparsity. L2 shrinks proportionally, rarely to 0. As priors: L1=Laplace, L2=Gaussian.
Q (II). When do trees beat logistic regression?
Nonlinear boundaries + automatic feature interactions + mixed/unscaled tabular features + robustness to outliers. Logistic wins on linearly-separable, high-dim sparse, very-large-scale, and when you need calibrated probabilities cheaply.
Q (II). How do you choose k in k-means?
Elbow (inertia), silhouette, gap statistic, or a downstream task metric; plus domain constraints. No single right answer — justify by the objective.
Q (III). Why did deep nets need ReLU?
Sigmoid derivative $\le 0.25$ and saturates → vanishing gradients in deep stacks. ReLU's derivative is 1 on the positive side → gradients flow. Plus good init (He) + normalization.
Q (III). BatchNorm vs LayerNorm?
BN normalizes per-feature across the batch (batch-dependent, awkward at small batch/inference); LN normalizes per-example across features (batch-independent → transformers).
Q (IV). AUC is 0.92 but the model is "bad" in production — how?
AUC measures ranking, not calibration; predicted probabilities can be systematically off → bad thresholds/bids/blends. Or it's the wrong metric (imbalance → use PR-AUC), or offline/online mismatch (selection bias).
Q (IV). p-value 0.04 — what does it mean?
If $H_0$ were true, data this extreme occurs 4% of the time. It is not the probability the null is true, nor the effect size. Check power, multiple testing, and practical significance.
Q (V). Why does logQ correction help in-batch negatives?
Popular items show up as in-batch negatives more often, so the model over-penalizes them. Subtracting $\log Q(i)$ debiases the logit so popular items aren't under-ranked at serving.
Q (V). PLE vs MMoE?
MMoE shares all experts via per-task gates; PLE adds task-specific experts so conflicting tasks don't suffer the "seesaw" from shared-gradient interference. Reach for PLE when tasks conflict.
Q (V). Why can a 5-up/0-down comment beat a 100-up/40-down one?
Reddit ranks comments by the lower bound of a Wilson confidence interval on the upvote ratio — it treats votes as a statistical sample, so high-ratio-low-volume can outrank high-volume-lower-ratio. (Hot posts use the log+time-decay formula instead.)