The Machine Learning Field Guide
A working-knowledge reference spanning classical ML algorithms and their math, data preprocessing and feature engineering, deep learning architectures, time series and NLP, model selection, the Python library landscape, cloud platform implementation, and the questions you're actually likely to be asked.
Foundations & Core Concepts
The vocabulary, statistics and evaluation machinery every algorithm-specific section assumes you already know.
Before any algorithm, an interviewer (and a good practitioner) cares about whether you understand why a model works, not just how to call .fit(). This part covers the vocabulary and statistical machinery that every algorithm-specific section later will assume you know.
The Machine Learning Taxonomy
| Paradigm | Definition | Examples |
|---|---|---|
| Supervised learning | Learn a mapping f(x) → y from labeled pairs (x, y). Split into regression (continuous y) and classification (categorical y). | Linear regression, logistic regression, random forests, gradient boosting, neural nets |
| Unsupervised learning | Learn structure in x with no labels — grouping, compression, density estimation. | K-Means, PCA, DBSCAN, GMM, autoencoders |
| Semi-supervised learning | Small labeled set + large unlabeled set; propagate labels or use unlabeled data to regularize. | Label propagation, pseudo-labeling, consistency regularization |
| Self-supervised learning | Labels are generated automatically from the data itself (a "pretext task"), then the learned representation is reused. | Masked language modeling (BERT), contrastive learning (SimCLR), next-token prediction (GPT) |
| Reinforcement learning | An agent learns a policy by interacting with an environment to maximize cumulative reward. | Q-learning, policy gradients, PPO |
| Online / incremental learning | Model updates continuously as new data arrives, rather than a single batch fit. | SGD-based estimators, River library, bandits |
A very common opener is "walk me through the types of machine learning." Structure your answer around the table above, then immediately pivot to a concrete example for each — interviewers reward specificity over definitions.
Bias–Variance Tradeoff
For a model that predicts ŷ(x) trained on a random training set, the expected squared error at a point x decomposes as:
E[(y − ŷ)²] = Bias(ŷ)² + Var(ŷ) + σ² (irreducible noise)- Bias — error from wrong assumptions in the model (e.g., fitting a line to a curve). High bias → underfitting.
- Variance — error from sensitivity to the specific training set (e.g., a deep unpruned tree that memorizes noise). High variance → overfitting.
- Irreducible error (σ²) — noise inherent to the data-generating process; no model can remove it.
Model complexity trades one for the other: as you add flexibility (more polynomial degrees, deeper trees, more neurons), bias falls and variance rises. The goal is the complexity that minimizes their sum on unseen data, not on training data. Techniques to manage this tradeoff: regularization (reduces variance, may add bias), ensembling (bagging reduces variance; boosting reduces bias), more training data (reduces variance without touching bias), and feature engineering (can reduce bias by giving the model the right signal).
"High training error and high validation error" → underfitting (high bias): get a more expressive model or better features. "Low training error, high validation error" → overfitting (high variance): regularize, get more data, simplify, or ensemble.
Regularization
Regularization adds a penalty to the loss function that discourages complexity, trading a little bias for a large reduction in variance.
L(θ) = Loss(θ) + λ · Penalty(θ)| Type | Penalty | Effect |
|---|---|---|
| L2 (Ridge / weight decay) | λΣθᵢ² | Shrinks all weights smoothly toward zero; keeps all features; handles multicollinearity well. |
| L1 (Lasso) | λΣ|θᵢ| | Drives some weights exactly to zero → automatic feature selection; not smooth at 0, can be unstable with correlated features. |
| Elastic Net | λ₁Σ|θᵢ| + λ₂Σθᵢ² | Combines both; good when features are correlated and you still want sparsity. |
| Dropout (NNs) | Randomly zero activations during training | Prevents co-adaptation of neurons; acts like an implicit ensemble. |
| Early stopping | Stop training when validation loss stops improving | Implicit regularization; cheap and effective for iterative learners (boosting, NNs). |
| Max depth / min samples leaf (trees) | Structural constraint | Limits tree variance directly. |
Overfitting, Underfitting & Learning Curves
A learning curve plots training and validation error against training-set size (or epoch/boosting round). Diagnostic patterns:
- Both curves converge to a high error, close together → underfitting. More data won't help; you need a more expressive model or better features.
- Large persistent gap between low training error and higher validation error → overfitting. More data, regularization, or simplification will help.
- Gap that's shrinking as training set grows but hasn't plateaued → more data will keep helping.
Cross-Validation & Data Splitting
| Method | How it works | Best for |
|---|---|---|
| Hold-out split | Single train/validation/test split (e.g., 60/20/20) | Large datasets where a single split is already statistically stable; fastest iteration |
| k-Fold CV | Split into k folds, train on k−1, validate on the remaining fold, rotate, average metrics | Small/medium datasets; general-purpose model comparison (k=5 or 10 typical) |
| Stratified k-Fold | k-Fold but preserves class proportions per fold | Classification, especially with class imbalance |
| Leave-One-Out (LOOCV) | k = n; each fold is a single sample | Very small datasets; computationally expensive, high variance estimate |
| Group k-Fold | Ensures samples from the same group (e.g., same patient, same user) never span train and validation | Data with natural groupings — prevents leakage |
| TimeSeriesSplit (walk-forward) | Expanding/rolling window; validation fold is always after the training fold in time | Any temporally ordered data — using future data to predict the past is leakage |
| Nested CV | Outer loop for unbiased performance estimate, inner loop for hyperparameter tuning | When you need both model selection AND an unbiased estimate of generalization error (common in research / small-N settings) |
Fitting scalers, encoders, imputers, or feature-selectors on the full dataset before splitting leaks information from validation/test into training. Always fit preprocessing inside the CV loop (e.g., via sklearn.pipeline.Pipeline) so each fold only sees its own training data.
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipe = Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression(max_iter=1000))])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, X, y, cv=cv, scoring="roc_auc")
print(scores.mean(), scores.std())
Evaluation Metrics
Regression metrics
| Metric | Formula | Notes |
|---|---|---|
| MAE | (1/n)Σ|yᵢ − ŷᵢ| | Robust to outliers; same units as y; not differentiable at 0 |
| MSE | (1/n)Σ(yᵢ − ŷᵢ)² | Penalizes large errors heavily; sensitive to outliers; differentiable everywhere |
| RMSE | √MSE | Same units as y; most commonly reported |
| MAPE | (100/n)Σ|(yᵢ−ŷᵢ)/yᵢ| | Scale-independent %, but undefined/unstable near y=0 |
| R² (coefficient of determination) | 1 − SS_res/SS_tot | Fraction of variance explained; can be negative for a bad model; not comparable across different y-scales/datasets |
| Adjusted R² | 1 − (1−R²)(n−1)/(n−p−1) | Penalizes adding useless predictors; use when comparing models with different feature counts |
Classification metrics
Confusion matrix: TP, FP, FN, TN
Accuracy = (TP+TN) / (TP+TN+FP+FN)
Precision = TP / (TP+FP) — "of predicted positives, how many were right"
Recall (TPR)= TP / (TP+FN) — "of actual positives, how many did we catch"
Specificity = TN / (TN+FP)
F1 = 2·Precision·Recall / (Precision+Recall)
Fβ = (1+β²)·Precision·Recall / (β²·Precision+Recall) — weight recall β× more when β>1
| Metric | Use when |
|---|---|
| Accuracy | Classes are balanced and errors are equally costly. Misleading under imbalance (99% accuracy on a 99:1 dataset by predicting the majority class). |
| Precision | False positives are expensive (e.g., flagging a legitimate transaction as fraud, spam filter blocking real email). |
| Recall | False negatives are expensive (e.g., missing a cancer diagnosis, missing actual fraud). |
| F1 / Fβ | Need a single number balancing precision and recall, typically under class imbalance. |
| ROC-AUC | Ranking quality across all thresholds, roughly balanced classes. Probability that a random positive is ranked above a random negative. |
| PR-AUC (Average Precision) | Severe class imbalance — ROC-AUC can look deceptively good when negatives vastly outnumber positives; PR-AUC is more informative there. |
| Log loss / cross-entropy | You care about calibrated probabilities, not just the final label. |
| Cohen's Kappa | Agreement corrected for chance — useful comparing to a baseline or across annotators. |
| Matthews Correlation Coefficient (MCC) | Single balanced metric that works well even under strong imbalance; uses all four confusion-matrix cells. |
ROC curves plot TPR vs FPR across thresholds; PR curves plot Precision vs Recall. Always pick the threshold using the validation set and a metric that reflects real business cost (e.g., maximize F2 if missing positives is twice as costly as a false alarm) — 0.5 is not a law of nature.
Statistical Foundations Interviewers Probe
- p-value — probability of observing data at least as extreme as what you saw, assuming the null hypothesis is true. It is not the probability the null is true, and it is not the probability your finding is due to chance.
- Confidence interval — a range that would contain the true parameter in, e.g., 95% of repeated samples; it is a statement about the procedure, not "95% probability the true value is in this interval" (that's the Bayesian credible interval interpretation).
- Type I / Type II error — false positive (rejecting a true null, rate α) vs false negative (failing to reject a false null, rate β); statistical power = 1 − β.
- Central Limit Theorem — the sampling distribution of the mean of i.i.d. samples approaches normal as n grows, regardless of the population's distribution — the theoretical basis for most parametric tests and confidence intervals.
- A/B testing — randomize units to control/treatment, define a pre-registered primary metric, compute a test statistic (two-sample t-test / z-test for means, chi-square or z-test for proportions), and check statistical AND practical significance. Watch for: peeking (inflates false-positive rate — use sequential testing methods if you must monitor continuously), novelty effects, network effects/interference between units, and multiple-comparison inflation when testing many metrics (control with Bonferroni or Benjamini-Hochberg FDR correction).
- Maximum Likelihood Estimation (MLE) — choose parameters θ that maximize the probability of the observed data: θ̂ = argmax Π P(xᵢ|θ). Many "cost functions" are just negative log-likelihoods in disguise — e.g., minimizing MSE under linear regression is equivalent to MLE under a Gaussian-noise assumption; minimizing log-loss is MLE under a Bernoulli/categorical assumption.
- Bayesian vs Frequentist — frequentist treats parameters as fixed unknowns and data as random; Bayesian treats parameters as random variables with a prior, updated via Bayes' rule into a posterior: P(θ|D) ∝ P(D|θ)P(θ).
- Correlation vs causation — correlation measures association; causal claims need either a randomized experiment or causal-inference assumptions (unconfoundedness, instrumental variables, difference-in-differences, regression discontinuity, etc.).
"How would you design an A/B test to measure X?" is one of the most common Senior DS interview questions. Structure: (1) define the metric and minimum detectable effect, (2) power analysis to size the sample, (3) randomization unit and guardrail metrics, (4) analysis plan and statistical test, (5) how you'd handle novelty/network effects and peeking.
Data Preprocessing & Feature Engineering
The stage that determines more of a model's final performance than algorithm choice — and a favorite interview area.
In practice this stage determines more of a model's final performance than algorithm choice. It's also a favorite interview area because it reveals whether you've actually shipped models, not just fit them in a notebook.
Missing Data
| Strategy | When to use | Caveats |
|---|---|---|
| Listwise deletion | Missingness is rare (<5%) and Missing Completely At Random (MCAR) | Loses data, can bias results if not truly MCAR |
| Mean/median/mode imputation | Quick baseline, tree models with monotonic tolerance | Shrinks variance, distorts relationships between features, ignores that missingness itself may be informative |
| K-Nearest-Neighbors imputation | Moderate dataset size, features are correlated | Expensive at scale; sensitive to feature scaling |
| Multiple Imputation by Chained Equations (MICE) | Statistical inference matters (need honest uncertainty), moderate missingness | Slower, more complex to implement/validate |
| Model-based (e.g., regress feature on others) | Missingness has structure explainable by other features | Can leak target info if not careful |
| Missing indicator + impute | Missingness itself is predictive (e.g., "income not disclosed") | Add a binary flag column alongside the imputed value |
| Native handling (XGBoost/LightGBM/CatBoost) | Tree-boosting models | These learn an optimal default split direction for missing values — often the best option, no imputation needed |
Always fit imputers on the training fold only (via Pipeline) to avoid leakage, and check the MCAR / MAR (Missing At Random) / MNAR (Missing Not At Random) mechanism before choosing a strategy — MNAR (e.g., high earners refusing to disclose salary) can bias any naive imputation.
Feature Scaling
| Method | Formula | Use with |
|---|---|---|
| Standardization (Z-score) | (x − μ) / σ | Linear/logistic regression, SVM, PCA, KNN, neural nets — anything distance- or gradient-based |
| Min-Max scaling | (x − min) / (max − min) | Neural nets with bounded activations, image pixel data, when you need a fixed [0,1] range |
| Robust scaling | (x − median) / IQR | Data with outliers |
| Log / Box-Cox / Yeo-Johnson transform | log(x), power transforms | Right-skewed data (income, counts); stabilizes variance, makes distribution closer to normal |
| None needed | — | Tree-based models (decision trees, random forest, gradient boosting) are invariant to monotonic feature transforms |
Categorical Encoding
| Method | Best for | Watch out for |
|---|---|---|
| One-hot encoding | Low-cardinality nominal features, linear models | Dimensionality explosion with high cardinality; drop one column to avoid the dummy-variable trap in linear models |
| Ordinal encoding | Features with a true order (e.g., "low/medium/high") | Imposes false numeric distance if there is no real order |
| Target/mean encoding | High-cardinality categoricals (zip code, user ID) with tree/linear models | High leakage risk — must be computed with out-of-fold/cross-validated statistics, plus smoothing toward the global mean for rare categories |
| Frequency/count encoding | High cardinality, quick baseline | Collides categories with equal frequency |
| Hashing trick (feature hashing) | Very high cardinality, streaming/online learning | Hash collisions; not human-interpretable |
| Embeddings (learned) | Very high cardinality categoricals in neural nets (e.g., product IDs) | Needs enough data per category to learn a useful embedding |
| Native categorical support | CatBoost (best-in-class ordered target encoding built in), LightGBM (native split on category) | Still worth understanding what happens under the hood |
Feature Engineering
- Interaction terms — products/ratios of existing features (e.g., BMI = weight/height²) that linear models can't discover on their own but tree ensembles can approximate through splits.
- Polynomial features — degree-2/3 expansions for linear models to capture curvature; watch combinatorial blow-up in feature count.
- Binning/discretization — convert continuous to categorical (equal-width, equal-frequency/quantile, or supervised binning via decision-tree splits); helps linear models capture non-linearity, can help interpretability.
- Datetime features — extract hour/day-of-week/month/is_weekend/is_holiday, cyclical encoding via sin/cos of the period (e.g.,
sin(2π·hour/24)) so midnight and 11pm are close in feature space, time-since-last-event. - Text features — length, punctuation counts, TF-IDF, embeddings (see Part 9).
- Domain aggregation features — rolling/expanding statistics per group (e.g., customer's 30-day average spend), lag features for time series.
- Dimensionality reduction as feature engineering — PCA components, autoencoder bottleneck as compact features feeding a downstream model.
Feature Selection
| Family | Methods | Notes |
|---|---|---|
| Filter methods | Correlation threshold, chi-square test, mutual information, variance threshold | Fast, model-agnostic, ignores feature interactions |
| Wrapper methods | Recursive Feature Elimination (RFE), forward/backward selection | Model-aware, expensive (retrains repeatedly), risk of overfitting the selection to the validation set |
| Embedded methods | Lasso coefficients, tree feature importances, permutation importance | Selection happens as part of training — efficient and usually the best tradeoff |
| SHAP-based selection | Drop features with near-zero mean |SHAP value| | More reliable than impurity-based importance, especially with correlated/high-cardinality features |
Default tree "feature importance" (mean decrease in impurity) is biased toward high-cardinality and continuous features. Prefer permutation importance or SHAP for anything you'll report externally.
Handling Class Imbalance
| Technique | How | Notes |
|---|---|---|
| Class weights | class_weight="balanced" in sklearn, scale_pos_weight in XGBoost | Cheapest first thing to try — reweights the loss, no data duplication |
| Random oversampling | Duplicate minority-class rows | Risk of overfitting to duplicated points |
| Random undersampling | Drop majority-class rows | Throws away data/information |
| SMOTE (Synthetic Minority Oversampling) | Generate synthetic minority points by interpolating between a point and its k nearest minority neighbors | Can create unrealistic samples in noisy/high-dimensional space; must be applied only within the training fold |
| ADASYN | Like SMOTE but generates more synthetic samples for minority points that are harder to classify | Same leakage caveat as SMOTE |
| Threshold moving | Keep the model as-is, choose a decision threshold from the precision-recall curve that matches business cost | Often the simplest, most robust fix — no resampling needed |
| Anomaly-detection framing | Treat extreme imbalance (e.g., 1:10,000 fraud) as one-class/anomaly detection instead of binary classification | See Isolation Forest / One-Class SVM in Part 6 |
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline as ImbPipeline
from sklearn.ensemble import RandomForestClassifier
pipe = ImbPipeline([
("smote", SMOTE(random_state=42)), # only resamples the training fold
("clf", RandomForestClassifier(n_estimators=300, random_state=42)),
])
pipe.fit(X_train, y_train) # SMOTE never touches X_test
Data Leakage — the #1 Silent Model Killer
- Target leakage — a feature that encodes the outcome (e.g., "date account was closed" when predicting churn).
- Train/test contamination — scaling, imputing, encoding, or selecting features on the full dataset before splitting.
- Temporal leakage — using information not yet available at prediction time (e.g., a "current balance" feature computed after the event you're predicting).
- Group leakage — related rows (same patient, same household) split across train and test, letting the model "cheat" via entity-specific patterns rather than generalizable ones.
"Tell me about a time a model performed great in validation but failed in production" is a near-universal senior DS question — leakage is the single most common root cause to reference, alongside train/serve skew (features computed differently online vs offline) and distribution shift.
Linear Models
The interpretable, statistically well-understood workhorse baselines — and the strong sanity check before reaching for anything more complex.
Linear models are the workhorse baseline of ML: fast, interpretable, well-understood statistically, and a strong sanity check before reaching for anything more complex.
Linear Regression (Ordinary Least Squares)
Idea: model y as a linear combination of features: ŷ = θ₀ + θ₁x₁ + … + θₚxₚ.
Cost function
J(θ) = (1/2n) Σᵢ (ŷᵢ − yᵢ)² (Mean Squared Error, optionally ×½ for a clean gradient)Closed-form solution (Normal Equation): θ = (XᵀX)⁻¹Xᵀy. Equivalent to Maximum Likelihood Estimation under the assumption that residuals are i.i.d. Gaussian with constant variance.
Key assumptions (the classic "LINE")
- Linearity of the relationship between X and y
- Independence of residuals
- Normality of residuals (needed for valid inference/CIs, not for point predictions)
- Equal variance of residuals (homoscedasticity)
- No perfect multicollinearity (needed for a unique solution)
When to use
Baseline for any regression task; when interpretability and statistical inference (coefficients, p-values, confidence intervals) matter as much as predictive accuracy; small-to-medium n relative to p; when the true relationship is plausibly linear or can be made linear via transforms.
Limitations
Sensitive to outliers (squared loss); assumes linearity; unstable coefficients under multicollinearity (variance inflation); can't capture interactions/non-linearity without manual feature engineering; normal equation is O(p³), doesn't scale to very high-dimensional X (use gradient descent or SGD instead).
Example use cases
Housing price prediction from square footage/rooms/location, demand forecasting from price/promotions, economic modeling, any setting where a business needs to explain "for every +1 unit of X, y changes by θ".
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
model = LinearRegression()
model.fit(X_train, y_train)
preds = model.predict(X_test)
print("RMSE:", mean_squared_error(y_test, preds, squared=False))
print("R2:", r2_score(y_test, preds))
print(dict(zip(X_train.columns, model.coef_))) # interpretability
# statsmodels gives p-values, CIs, full inferential summary
import statsmodels.api as sm
X_sm = sm.add_constant(X_train)
sm.OLS(y_train, X_sm).fit().summary()
Ridge Regression (L2)
Cost function
J(θ) = (1/2n) Σ(ŷᵢ − yᵢ)² + λ Σθⱼ²When to use: many correlated features (multicollinearity inflates OLS coefficient variance — ridge shrinks and stabilizes them), p close to or greater than n, you want all features retained but shrunk. Limitations: doesn't perform feature selection (coefficients shrink toward but rarely hit exactly zero); λ needs tuning via CV; features should be standardized first since the penalty is scale-sensitive. Use cases: genomics (thousands of correlated predictors), econometrics with multicollinear regressors.
from sklearn.linear_model import RidgeCV
model = RidgeCV(alphas=[0.01, 0.1, 1.0, 10.0, 100.0], cv=5).fit(X_train, y_train)
Lasso Regression (L1)
Cost function
J(θ) = (1/2n) Σ(ŷᵢ − yᵢ)² + λ Σ|θⱼ|When to use: you suspect only a subset of features truly matter and want automatic, embedded feature selection (sparse solutions). Limitations: with groups of correlated features, Lasso arbitrarily picks one and zeroes the rest (unstable selection); can underperform Ridge predictively when most features carry some signal; not differentiable at 0 (solved via coordinate descent / LARS, not closed form). Use cases: high-dimensional sparse problems (text with bag-of-words features, genomics), building a parsimonious, explainable model for stakeholders.
from sklearn.linear_model import LassoCV
model = LassoCV(cv=5, random_state=42).fit(X_train, y_train)
selected = X_train.columns[model.coef_ != 0]
Elastic Net
J(θ) = (1/2n) Σ(ŷᵢ − yᵢ)² + λ₁ Σ|θⱼ| + λ₂ Σθⱼ²When to use: features are correlated AND you still want sparsity — combines Ridge's stability under correlation with Lasso's selection. Two hyperparameters to tune (overall λ and the L1/L2 mixing ratio). Good default when unsure between Ridge and Lasso.
from sklearn.linear_model import ElasticNetCV
model = ElasticNetCV(l1_ratio=[.1, .5, .9, 1], cv=5).fit(X_train, y_train)
Polynomial Regression
Still a linear model in its parameters — apply a polynomial feature expansion (x, x², x³, x₁x₂, …) then fit ordinary/regularized linear regression. Lets a linear model capture curvature and interactions at the cost of exploding feature count (combinatorial with degree and original feature count) and higher overfitting risk — always pair with regularization and CV to pick the degree.
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import Ridge
model = make_pipeline(PolynomialFeatures(degree=3), Ridge(alpha=1.0))
model.fit(X_train, y_train)
Logistic Regression
Idea: models the log-odds of the positive class as a linear function of x, squashed through the sigmoid function.
P(y=1|x) = σ(θᵀx) = 1 / (1 + e^(−θᵀx))Cost function — binary cross-entropy / log loss
J(θ) = −(1/n) Σ [ yᵢ log(ŷᵢ) + (1−yᵢ) log(1−ŷᵢ) ] + λ·penalty(θ)This is the negative log-likelihood under a Bernoulli model — logistic regression is MLE for a linear log-odds model. Optimized via gradient descent / L-BFGS / coordinate descent (no closed form).
Multiclass extension
Softmax / multinomial logistic regression generalizes to K classes: P(y=k|x) = e^(θₖᵀx) / Σⱼe^(θⱼᵀx), trained with categorical cross-entropy. (One-vs-Rest is an older alternative.)
When to use
Binary/multiclass classification baseline; when you need calibrated probabilities and interpretable odds ratios (e^θ); linearly (or near-linearly) separable classes; low-latency production scoring; credit scoring and other regulated domains that require explainability.
Limitations
Assumes a linear decision boundary in log-odds space; struggles with complex non-linear boundaries unless you engineer interaction/polynomial features; sensitive to outliers and multicollinearity; needs enough events-per-variable (rule of thumb ≥10 positive cases per predictor) for stable coefficients.
Example use cases
Credit default prediction, churn prediction, medical diagnosis (odds ratios are directly interpretable), click-through-rate baseline models, marketing response modeling.
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, roc_auc_score
clf = LogisticRegression(penalty="l2", C=1.0, class_weight="balanced", max_iter=1000)
clf.fit(X_train, y_train)
proba = clf.predict_proba(X_test)[:, 1]
print(roc_auc_score(y_test, proba))
print(classification_report(y_test, clf.predict(X_test)))
odds_ratios = dict(zip(X_train.columns, __import__("numpy").exp(clf.coef_[0])))
sklearn's C is the inverse of regularization strength (C = 1/λ) — smaller C means stronger regularization, the opposite of the λ used in most textbook notation.
Linear & Quadratic Discriminant Analysis (LDA / QDA)
Idea: generative classifiers — model each class's feature distribution as multivariate Gaussian, then apply Bayes' rule to get P(y|x). LDA assumes all classes share one covariance matrix Σ (giving a linear decision boundary); QDA lets each class have its own Σₖ (giving a quadratic boundary).
P(y=k|x) ∝ P(x|y=k)·P(y=k), P(x|y=k) = N(x; μₖ, Σ)When to use: Gaussian-ish class-conditional features, more classes than logistic regression handles gracefully, small-n settings where the generative model's stronger assumptions help (lower variance than logistic regression when assumptions hold). LDA also doubles as a supervised dimensionality-reduction technique (project onto the directions that best separate classes). Limitations: sensitive to non-Gaussian features and outliers; QDA needs more data per class to estimate each covariance matrix reliably. Use cases: face recognition (Fisherfaces), marketing segmentation, bankruptcy prediction.
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
lda = LinearDiscriminantAnalysis(n_components=2) # also usable for dim. reduction
X_reduced = lda.fit_transform(X_train, y_train)
Instance-Based, Margin-Based, Probabilistic & Tree Models
KNN, SVMs, Naive Bayes and Decision Trees — the algorithm family that sets up everything Part 5's ensembles build on.
K-Nearest Neighbors (KNN)
Idea: no training phase ("lazy learning") — to predict a new point, find the k closest points in the training set (by a distance metric) and aggregate their labels (majority vote for classification, mean/median for regression).
Distance metrics
Euclidean: d(x,x') = √Σ(xᵢ−x'ᵢ)² | Manhattan: Σ|xᵢ−x'ᵢ| | Minkowski: (Σ|xᵢ−x'ᵢ|ᵖ)^(1/p) | Cosine: 1 − (x·x')/(‖x‖‖x'‖)When to use
Small-to-medium datasets, low-dimensional feature space, decision boundary is highly irregular/non-linear and you have no strong prior on its shape, recommender-system-style similarity lookups, quick baseline before investing in a parametric model.
Limitations
Curse of dimensionality — in high dimensions all points become roughly equidistant, so distance loses meaning; computationally expensive at inference (O(n) per query naively, mitigated with KD-trees/Ball-trees/approximate nearest neighbor libraries like FAISS/Annoy for large n); requires feature scaling (unscaled features with large ranges dominate the distance); sensitive to irrelevant features and to class imbalance (majority class dominates the vote — use distance-weighted voting to help); no interpretable model artifact, must keep the training data around.
Choosing k
Small k → low bias, high variance (sensitive to noise); large k → high bias, smoother boundary. Tune via CV; using odd k avoids ties in binary classification.
Example use cases
Recommendation systems (item/user similarity), anomaly detection (distance to nearest neighbors), image recognition baselines, imputation (KNNImputer).
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15, weights="distance"))
model.fit(X_train, y_train)
Support Vector Machines (SVM / SVR)
Idea: find the hyperplane that maximizes the margin between classes. Only the closest points ("support vectors") determine the boundary.
Objective (soft-margin, primal form)
min_θ (1/2)‖θ‖² + C·Σᵢ max(0, 1 − yᵢ(θᵀxᵢ+b)) ← hinge loss + L2 regularizationC trades off margin width vs. misclassification tolerance: large C → narrow margin, fits training data tightly (low bias, high variance); small C → wide margin, more tolerant of misclassification (higher bias, lower variance).
The kernel trick
SVMs can learn non-linear boundaries without explicitly computing high-dimensional feature maps φ(x), by replacing the dot product xᵀx' with a kernel function K(x,x') = φ(x)ᵀφ(x').
| Kernel | Formula | Use for |
|---|---|---|
| Linear | xᵀx' | High-dimensional sparse data (text), when classes are linearly separable |
| Polynomial | (γxᵀx' + r)^d | Feature interactions up to a known degree |
| RBF / Gaussian | exp(−γ‖x−x'‖²) | Default general-purpose non-linear kernel; γ controls how far a single training point's influence reaches |
| Sigmoid | tanh(γxᵀx' + r) | Behaves like a shallow neural net; rarely the best choice |
When to use
Medium-sized datasets (training is O(n²)–O(n³), doesn't scale well past ~100k rows without approximation), high-dimensional data with a clear margin (text classification with linear kernel is a classic strong baseline), when you need a robust boundary maximizing margin rather than just minimizing training error.
Limitations
Doesn't scale well to large n; no direct probability output (Platt scaling required, and it's an approximation); sensitive to feature scaling; kernel/C/γ selection requires careful grid search; harder to interpret than linear models or trees.
SVR (regression variant)
Instead of a hard margin, SVR fits a tube of width ε around the regression line and only penalizes points outside it (ε-insensitive loss) — good when you're indifferent to small errors and want a sparse solution robust to outliers beyond ε.
Example use cases
Text/document classification, image classification (pre-deep-learning era), bioinformatics (gene expression classification with few samples, many features), handwriting recognition.
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
pipe = make_pipeline(StandardScaler(), SVC(kernel="rbf", probability=True))
grid = GridSearchCV(pipe, {"svc__C": [0.1,1,10,100], "svc__gamma": ["scale", 0.01, 0.1, 1]},
cv=5, scoring="roc_auc", n_jobs=-1)
grid.fit(X_train, y_train)
Naive Bayes
Idea: apply Bayes' theorem with the (naive) assumption that features are conditionally independent given the class.
P(y|x₁,…,xₚ) ∝ P(y) · Π P(xᵢ|y)| Variant | P(xᵢ|y) model | Use for |
|---|---|---|
| GaussianNB | Normal distribution per feature/class | Continuous features approximately Gaussian |
| MultinomialNB | Multinomial (counts) | Text classification with word counts / TF-IDF |
| BernoulliNB | Bernoulli (binary presence/absence) | Binary/sparse features (word present or not) |
| ComplementNB | Adjusted multinomial | Imbalanced text classification — often outperforms MultinomialNB there |
When to use
Text classification (spam filtering, sentiment, topic classification) — the independence assumption is "wrong" but the model still ranks documents well; extremely fast to train (closed-form parameter estimates, no iterative optimization) and score, works well with limited training data, strong baseline before trying anything fancier.
Limitations
The independence assumption is almost always violated in reality (words in a sentence are correlated), which can bias the actual probability estimates even when the classification decision is still often correct; struggles when features are highly correlated; zero-frequency problem — an unseen feature/class combination gives zero probability unless you use Laplace/additive smoothing.
Example use cases
Spam detection, sentiment analysis, real-time prediction at massive scale (recommendation pre-filtering), medical diagnosis baseline.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
model = make_pipeline(TfidfVectorizer(stop_words="english"), MultinomialNB(alpha=1.0))
model.fit(train_texts, train_labels) # alpha = Laplace smoothing
Decision Trees (CART)
Idea: recursively split the feature space into regions by choosing, at each node, the feature/threshold that maximizes "purity gain" in the children.
Splitting criteria
Gini impurity: Gini = 1 − Σₖ pₖ²
Entropy: H = −Σₖ pₖ log₂(pₖ)
Information Gain = H(parent) − Σ (nⱼ/n)·H(childⱼ)
Regression (variance reduction): minimize Σ (yᵢ − ȳ_node)² within each resulting leaf
Gini and entropy usually produce similar trees in practice; Gini is slightly cheaper (no log) and is sklearn's default.
When to use
Need a fully interpretable, visualizable model (can literally draw the decision path); mixed feature types without scaling; non-linear relationships and interactions the tree discovers automatically; as the base learner for ensembles (Random Forest, Gradient Boosting) — rarely used alone in production because of variance.
Limitations
High variance — small data changes can produce a very different tree (this is exactly what bagging exploits); prone to overfitting without pruning/depth limits; axis-aligned splits struggle with diagonal decision boundaries; biased toward features with more levels/splits; greedy algorithm (locally optimal splits, not globally optimal tree).
Regularization / pruning controls
max_depth, min_samples_split, min_samples_leaf, max_leaf_nodes, min_impurity_decrease, and cost-complexity pruning (ccp_alpha) — post-hoc pruning that removes subtrees that don't improve validation performance enough to justify the extra complexity.
Example use cases
Credit approval rules that must be explained to regulators/customers, medical triage decision support, any setting demanding an auditable "if-then" model.
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt
tree = DecisionTreeClassifier(max_depth=4, min_samples_leaf=20, criterion="gini", random_state=42)
tree.fit(X_train, y_train)
plot_tree(tree, feature_names=X_train.columns, class_names=list(map(str, tree.classes_)), filled=True)
plt.show()
"Why does a single decision tree overfit, and how do ensembles fix it?" — answer with the bias-variance framing: a deep tree has low bias but very high variance; Random Forest averages many decorrelated high-variance trees to cancel out variance (bagging), while boosting builds shallow high-bias trees sequentially, each correcting the previous ensemble's residual error (reducing bias).
Ensemble Methods
Bagging, boosting and stacking reduce error through different mechanisms — one of the most-asked conceptual distinctions in senior DS interviews.
Ensembles combine multiple "weak" or diverse models to produce a stronger one. The three families — bagging, boosting, and stacking — reduce error via different mechanisms, and this distinction is one of the most-asked conceptual questions in senior DS interviews.
Bagging reduces variance by averaging independent, high-variance models trained on bootstrap samples. Boosting reduces bias by sequentially fitting models to the errors of the current ensemble. Stacking learns how to combine heterogeneous models optimally.
Random Forest
Idea: train many decision trees, each on (a) a bootstrap sample of the rows and (b) a random subset of features considered at each split, then average (regression) or majority-vote (classification) their predictions.
ŷ = (1/M) Σₘ Tₘ(x) (regression) | ŷ = mode{T₁(x), …, T_M(x)} (classification)Randomizing both rows (bagging) and the candidate feature subset at each split (typically √p for classification, p/3 for regression) decorrelates the trees — this is the key extra trick beyond plain bagging, and it's what makes averaging effective (averaging correlated estimators reduces variance far less than averaging independent ones).
Out-of-bag (OOB) error
Each tree only sees ~63% of rows (bootstrap sampling with replacement); the other ~37% ("out-of-bag") can be used as a free internal validation set — no separate holdout needed to get an unbiased error estimate.
When to use
Strong, low-effort baseline for tabular data; robust to outliers and irrelevant features; minimal preprocessing (no scaling needed, handles mixed types); naturally provides feature importances; parallelizable (trees are independent).
Limitations
Less accurate than well-tuned gradient boosting on most tabular benchmarks; large model size (hundreds of trees) — slower inference and more memory than a single boosted ensemble of comparable accuracy; can still overfit noisy data with too-deep trees; extrapolates poorly outside the range of training data (piecewise-constant predictions).
Example use cases
Fraud detection, general tabular classification/regression baselines, feature importance / exploratory driver analysis, remote sensing / land-cover classification.
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(
n_estimators=500, max_features="sqrt", min_samples_leaf=3,
oob_score=True, n_jobs=-1, random_state=42
)
rf.fit(X_train, y_train)
print("OOB accuracy:", rf.oob_score_)
importances = dict(zip(X_train.columns, rf.feature_importances_))
AdaBoost
Idea: fit weak learners (typically depth-1 "stumps") sequentially; after each round, up-weight the misclassified samples so the next learner focuses on them; combine learners via a weighted vote where more accurate learners get more say.
αₘ = ½ ln((1−errₘ)/errₘ) ← learner weight, higher for more accurate learners
F(x) = sign( Σₘ αₘ hₘ(x) )
When to use: clean, low-noise datasets, binary classification with weak but better-than-random base learners. Limitations: very sensitive to noisy data and outliers (they keep getting up-weighted); has been largely superseded by gradient boosting variants in practice. Use cases: face detection (Viola-Jones used a boosted cascade), historically important, now mostly of conceptual/interview interest.
from sklearn.ensemble import AdaBoostClassifier
model = AdaBoostClassifier(n_estimators=200, learning_rate=0.5, random_state=42).fit(X_train, y_train)
Gradient Boosting Machines (GBM)
Idea: a generalization of AdaBoost — fit each new weak learner (usually a shallow tree) to the negative gradient of the loss function with respect to the current ensemble's predictions ("functional gradient descent"). For squared-error loss the negative gradient is simply the residual (y − ŷ), so intuitively: "fit a tree to the errors, add it in, repeat."
F₀(x) = argmin_c Σ L(yᵢ, c)
Fₘ(x) = F_{m−1}(x) + ν · hₘ(x), where hₘ fits the pseudo-residuals rᵢ = −∂L(yᵢ,F(xᵢ))/∂F(xᵢ)
ν (learning rate / shrinkage) controls how much each tree contributes; smaller ν needs more trees but generalizes better (classic bias-variance-tuned-by-two-knobs setup: n_estimators × learning_rate).
When to use
The single strongest general-purpose algorithm for structured/tabular data in industry and competitions; when you have time/compute to tune carefully and squeeze out accuracy.
Limitations
Sequential — can't parallelize across trees (only within each tree's build); more hyperparameters to tune than Random Forest (learning rate, n_estimators, max_depth, subsample, colsample); more prone to overfitting if not regularized (early stopping essential); slower to train than a Random Forest at equal tree count.
Example use cases
Click-through-rate prediction, credit risk scoring, ranking (search relevance), Kaggle-style structured-data competitions, insurance claim prediction.
from sklearn.ensemble import GradientBoostingClassifier
model = GradientBoostingClassifier(n_estimators=300, learning_rate=0.05,
max_depth=3, subsample=0.8, random_state=42)
model.fit(X_train, y_train)
XGBoost / LightGBM / CatBoost — the Gradient Boosting Family
All three implement regularized, engineering-optimized gradient boosting; the differences matter in interviews and in practice.
| Library | Key innovation | Best for |
|---|---|---|
| XGBoost | Second-order (Newton) gradient boosting with an explicit regularized objective (L1+L2 on leaf weights), built-in handling of sparse/missing values (learns default split direction), histogram & exact split-finding options. | General-purpose default; extremely well-supported, battle-tested in production and competitions. |
| LightGBM | Histogram-based binning for speed, leaf-wise (best-first) tree growth instead of level-wise (deeper, often more accurate trees per leaf budget but higher overfitting risk on small data), Gradient-based One-Side Sampling (GOSS) and Exclusive Feature Bundling (EFB) for speed on large/high-dimensional data. Native categorical feature support. | Very large datasets, many features, speed-constrained training pipelines. |
| CatBoost | Ordered target statistics for categorical encoding (avoids leakage/target-shift without manual encoding), symmetric ("oblivious") trees that resist overfitting and speed inference, strong defaults out of the box. | Data with many high-cardinality categorical features, when you want great results with minimal tuning. |
Regularized objective (XGBoost): Obj = Σᵢ L(yᵢ, ŷᵢ) + Σₘ Ω(hₘ), Ω(h) = γT + ½λΣⱼwⱼ²
(T = number of leaves, w = leaf weights — penalizes both tree size and large leaf outputs)
Key shared hyperparameters
n_estimators/num_boost_round, learning_rate, max_depth (or num_leaves in LightGBM), subsample/bagging_fraction (row sampling), colsample_bytree/feature_fraction (column sampling), reg_alpha/reg_lambda (L1/L2), min_child_weight/min_data_in_leaf, plus early_stopping_rounds against a validation set.
Limitations (shared)
Many hyperparameters — tuning requires structure (see Part 10); less interpretable than a single tree (mitigate with SHAP); not naturally suited to unstructured data (images/text/audio) where deep learning dominates; leaf-wise growth (LightGBM) can overfit small datasets without depth limits.
Example use cases
Any serious tabular ML problem: fraud detection, pricing/demand forecasting, credit risk, ranking, propensity modeling — the default first-and-often-last algorithm to try after linear baselines.
import xgboost as xgb
model = xgb.XGBClassifier(
n_estimators=1000, learning_rate=0.03, max_depth=5,
subsample=0.8, colsample_bytree=0.8, reg_lambda=1.0,
eval_metric="auc", early_stopping_rounds=50, n_jobs=-1
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=100)
# LightGBM
import lightgbm as lgb
lgb_model = lgb.LGBMClassifier(n_estimators=1000, num_leaves=63, learning_rate=0.03)
lgb_model.fit(X_train, y_train, eval_set=[(X_val, y_val)],
callbacks=[lgb.early_stopping(50)])
# CatBoost — pass categorical columns directly, no manual encoding needed
from catboost import CatBoostClassifier
cb = CatBoostClassifier(iterations=1000, learning_rate=0.03, depth=6, verbose=100)
cb.fit(X_train, y_train, cat_features=cat_col_indices, eval_set=(X_val, y_val))
Stacking & Voting
Voting: combine predictions of several different model types by simple (hard) majority vote or (soft) averaged predicted probabilities — no training involved in the combination step, just averaging. Works best when base models are individually strong and make uncorrelated errors.
Stacking: train a "meta-learner" (often a simple linear/logistic model) on the out-of-fold predictions of several base models, learning the optimal way to combine them. Must use out-of-fold predictions for the meta-training set (never predictions from models trained on the same rows) to avoid leakage.
When to use
Squeezing out the last few percent of performance (common in competitions); combining models with complementary strengths (e.g., a linear model + a tree ensemble + a neural net); when inference-time compute budget allows running several models.
Limitations
Added complexity and latency in production; harder to debug/interpret; diminishing returns and risk of overfitting the meta-learner if base models are highly correlated or the stacking set is small.
from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
import xgboost as xgb
stack = StackingClassifier(
estimators=[("rf", RandomForestClassifier(n_estimators=300)),
("xgb", xgb.XGBClassifier(n_estimators=300))],
final_estimator=LogisticRegression(),
cv=5, stack_method="predict_proba"
)
stack.fit(X_train, y_train)
Unsupervised Learning
Clustering, dimensionality reduction, anomaly detection and association rule mining — finding structure with no labels.
Clustering
K-Means
Idea: partition n points into k clusters by iteratively (1) assigning each point to its nearest centroid and (2) recomputing centroids as the mean of assigned points, until convergence (Lloyd's algorithm).
J = Σₖ Σ_{x∈Cₖ} ‖x − μₖ‖² (within-cluster sum of squares, WCSS / inertia)This is a non-convex objective solved via coordinate-descent-style local optimization (guaranteed to decrease J each iteration, but only converges to a local minimum) — hence n_init (multiple random restarts) and smart initialization (k-means++, which spreads initial centroids apart probabilistically) matter a lot in practice.
Choosing k
Elbow method — plot inertia vs. k, look for the diminishing-returns bend. Silhouette score — measures how similar a point is to its own cluster vs. the next-nearest cluster, range [−1,1], higher is better; doesn't require a "true" k, more principled than the elbow method. Gap statistic — compares WCSS to that of a null reference distribution.
When to use
Roughly spherical, similarly-sized clusters; fast, scalable clustering on large n (near-linear); customer/market segmentation, image color quantization, initializing other algorithms.
Limitations
Must specify k in advance; assumes convex/isotropic clusters (fails on elongated, nested, or unequal-density clusters); sensitive to outliers (squared distance) and to feature scale (always standardize first); sensitive to initialization without k-means++; struggles in high dimensions (distance concentration, same curse-of-dimensionality issue as KNN).
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score
Xs = StandardScaler().fit_transform(X)
km = KMeans(n_clusters=5, init="k-means++", n_init=10, random_state=42).fit(Xs)
print("silhouette:", silhouette_score(Xs, km.labels_))
DBSCAN (Density-Based Spatial Clustering)
Idea: groups points that are densely packed together (at least min_samples neighbors within radius eps), and marks low-density points as noise/outliers. Core points, border points, and noise points emerge naturally from the density structure — no need to pre-specify the number of clusters.
When to use
Arbitrarily-shaped, non-convex clusters (crescents, rings); when the dataset contains real noise/outliers you want automatically excluded rather than forced into a cluster; unknown number of clusters.
Limitations
Struggles with clusters of varying density (a single global eps can't fit both dense and sparse clusters well — HDBSCAN relaxes this by using a hierarchy of densities); sensitive to eps/min_samples choice; can be slow in high dimensions without spatial indexing.
Example use cases
Geospatial clustering (e.g., clustering GPS pings into "places visited"), anomaly detection, clustering irregularly shaped clusters in scientific data.
from sklearn.cluster import DBSCAN
db = DBSCAN(eps=0.5, min_samples=5).fit(Xs)
n_clusters = len(set(db.labels_)) - (1 if -1 in db.labels_ else 0) # -1 = noise
Hierarchical (Agglomerative) Clustering
Idea: start with every point as its own cluster and iteratively merge the two closest clusters, according to a linkage criterion, producing a tree (dendrogram) you can cut at any level to get a chosen number of clusters.
| Linkage | Distance between clusters A, B | Tendency |
|---|---|---|
| Single | min distance between any pair | Can produce long "chained" clusters |
| Complete | max distance between any pair | Compact, similarly-sized clusters |
| Average | mean pairwise distance | Balance between single and complete |
| Ward | minimizes increase in within-cluster variance | Tends to produce even-sized, spherical-ish clusters; most commonly used default |
When to use: you want the full hierarchy of nested clusters (not just one flat partition), don't know k in advance and want to inspect the dendrogram to decide, small-to-medium n (naive implementation is O(n³) time / O(n²) memory). Limitations: doesn't scale to large datasets; once a merge is made it can't be undone (greedy). Use cases: taxonomy/phylogenetic-style grouping, gene expression analysis, organizational/document clustering where nested structure matters.
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
Z = linkage(Xs, method="ward")
clusters = fcluster(Z, t=5, criterion="maxclust")
Gaussian Mixture Models (GMM)
Idea: model the data as a mixture of k multivariate Gaussians; fit via Expectation-Maximization (E-step: compute soft cluster-membership probabilities; M-step: update each Gaussian's mean/covariance/weight to maximize expected log-likelihood).
p(x) = Σₖ πₖ · N(x; μₖ, Σₖ), Σπₖ=1When to use: you want soft/probabilistic cluster assignments rather than hard labels, elliptical (not just spherical) clusters, clusters of different sizes/densities; also usable for density estimation and anomaly detection (low-likelihood points). Limitations: assumes Gaussian-shaped clusters; sensitive to initialization (also typically seeded with k-means); choosing k needs BIC/AIC; can converge to a degenerate solution if a component collapses onto a single point. Use cases: speaker identification, background subtraction in computer vision, soft customer segmentation ("70% price-sensitive, 30% premium-leaning").
from sklearn.mixture import GaussianMixture
gmm = GaussianMixture(n_components=4, covariance_type="full", random_state=42).fit(Xs)
soft_probs = gmm.predict_proba(Xs)
bic = gmm.bic(Xs) # compare across k to pick the best
Dimensionality Reduction
Principal Component Analysis (PCA)
Idea: find an orthogonal linear transformation to a new basis (principal components) that maximizes variance explained, ordered so the first few components capture most of the signal.
Solve the eigendecomposition of the covariance matrix: Σ = (1/n)XᵀX = VΛVᵀ (or equivalently via SVD of X) → PCs = top eigenvectors of Σ, ranked by eigenvalue (variance explained)When to use
Reducing dimensionality before modeling (speed, reducing overfitting, handling multicollinearity), visualization (project to 2-3D), noise reduction, compressing correlated features, whitening.
Limitations
Only captures linear structure; components are linear combinations of all original features so interpretability drops; sensitive to feature scale (always standardize first); variance ≠ relevance to the target (PCA is unsupervised — the direction of maximum variance may not align with what predicts y); sign/rotation of components is arbitrary across re-fits.
Example use cases
Preprocessing before clustering or KNN in high dimensions, image compression, exploratory data analysis, removing multicollinearity before linear regression, finance (yield-curve factor decomposition).
from sklearn.decomposition import PCA
pca = PCA(n_components=0.95) # keep enough components for 95% variance explained
X_reduced = pca.fit_transform(Xs)
print(pca.explained_variance_ratio_.cumsum())
t-SNE & UMAP
t-SNE converts high-dimensional pairwise distances into probabilities of "being neighbors" (Gaussian in high-D, Student-t in low-D — the heavier tail avoids the "crowding problem"), then minimizes the KL divergence between the high- and low-dimensional neighbor distributions via gradient descent.
UMAP is built on a similar neighbor-graph idea but with a stronger topological/manifold-learning foundation (fuzzy simplicial sets), and is generally faster, better preserves global structure, and — unlike classic t-SNE — supports transforming new/unseen points after fitting.
When to use
Visualizing high-dimensional data (embeddings, single-cell genomics, image features) in 2D/3D to spot clusters and structure by eye.
Limitations
Never use t-SNE/UMAP output as input features for a downstream supervised model or trust exact distances/cluster sizes between them at face value — both are non-linear, stochastic, and distort global distances/densities to preserve local neighborhoods; cluster sizes and inter-cluster distances in the plot are not meaningful; results are sensitive to hyperparameters (perplexity for t-SNE, n_neighbors/min_dist for UMAP) and to the random seed; slow on very large n (though UMAP scales much better than t-SNE).
Example use cases
Visualizing learned embeddings (word2vec, BERT, autoencoder latent space), single-cell RNA-seq visualization, sanity-checking cluster structure before running K-Means.
from sklearn.manifold import TSNE
emb = TSNE(n_components=2, perplexity=30, random_state=42).fit_transform(Xs)
# UMAP (pip install umap-learn)
import umap
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42)
emb_umap = reducer.fit_transform(Xs)
Anomaly & Outlier Detection
Isolation Forest
Idea: anomalies are "few and different," so they're easier to isolate with random splits. Build many random trees that split on random features/thresholds; anomalies end up isolated in fewer splits (shorter average path length) than normal points.
Anomaly score s(x) = 2^(−E[h(x)]/c(n)) — close to 1 → anomaly, close to 0.5 → normalWhen to use: unsupervised outlier/fraud detection with no labeled anomalies, high-dimensional data (doesn't suffer from distance concentration the way distance-based methods do), fast and scales well (linear time, sub-linear memory). Limitations: can miss local anomalies in datasets with varying density clusters; performance depends on contamination parameter (expected anomaly fraction) which is often unknown a priori. Use cases: credit card fraud detection, network intrusion detection, sensor/IoT fault detection, data-quality monitoring.
from sklearn.ensemble import IsolationForest
iso = IsolationForest(n_estimators=300, contamination=0.01, random_state=42)
anomaly_labels = iso.fit_predict(X) # -1 = anomaly, 1 = normal
scores = iso.decision_function(X) # higher = more normal
One-Class SVM & Local Outlier Factor (LOF)
One-Class SVM learns a boundary (using the kernel trick, typically RBF) that encloses the "normal" region of feature space containing most of the data, flagging points outside it. Good when the normal class has a complex but reasonably compact shape; sensitive to the ν and γ hyperparameters and doesn't scale to very large n.
LOF compares a point's local density to that of its neighbors — a point in a much sparser neighborhood than its neighbors gets flagged. Good for detecting local anomalies in data with varying density across regions (unlike Isolation Forest / global-density methods); computationally heavier (distance-based, like KNN).
from sklearn.neighbors import LocalOutlierFactor
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.02)
labels = lof.fit_predict(X) # -1 = outlier
Association Rule Mining
Apriori & FP-Growth
Idea: find frequent itemsets in transactional data, then derive "if A then B" rules.
Support(A) = P(A) = count(A)/n
Confidence(A→B) = P(B|A) = Support(A∪B)/Support(A)
Lift(A→B) = Confidence(A→B)/Support(B) ← >1 means A and B co-occur more than chance
Apriori prunes the itemset search space using the fact that a superset of an infrequent itemset can't be frequent; conceptually simple but can be slow on large item catalogs due to repeated database scans. FP-Growth compresses the transaction database into a tree structure (FP-tree) and mines frequent itemsets without candidate generation — much faster in practice.
Use cases
Market-basket analysis ("customers who bought X also bought Y"), recommendation rule generation, web clickstream analysis, cross-sell bundling.
from mlxtend.frequent_patterns import apriori, association_rules
freq_items = apriori(basket_onehot_df, min_support=0.02, use_colnames=True)
rules = association_rules(freq_items, metric="lift", min_threshold=1.2)
rules.sort_values("lift", ascending=False).head(10)
Deep Learning Overview
The core math behind each major architecture, when each shines, and a runnable snippet — without full textbook-depth derivations.
This part is a solid, interview-ready overview of the major architectures — the core math, when each shines, and a runnable code snippet — without going full textbook-depth on every derivation.
The Perceptron, MLP & Backpropagation
A single artificial neuron computes z = wᵀx + b, then applies a non-linear activation function φ(z). A Multi-Layer Perceptron (MLP) stacks layers of such neurons; without non-linear activations, stacking linear layers would just collapse into one linear function, so the non-linearity is what gives depth its expressive power (Universal Approximation Theorem: a sufficiently wide single hidden layer can approximate any continuous function, though depth is far more parameter-efficient in practice).
| Activation | Formula | Notes |
|---|---|---|
| Sigmoid | 1/(1+e⁻ᶻ) | Output layer for binary probabilities; saturates and kills gradients in hidden layers (vanishing gradient) |
| Tanh | (eᶻ−e⁻ᶻ)/(eᶻ+e⁻ᶻ) | Zero-centered, but still saturates |
| ReLU | max(0, z) | Default for hidden layers — cheap, avoids saturation for z>0; can "die" (stuck at 0 gradient) for z<0 permanently |
| Leaky ReLU / ELU / GELU | small slope for z<0 (Leaky/ELU); smooth probabilistic gate (GELU) | Fixes dying ReLU; GELU is standard in modern Transformers |
| Softmax | eᶻᵢ/Σⱼeᶻⱼ | Output layer for multiclass probabilities |
Loss functions
MSE (regression): L = (1/n)Σ(y−ŷ)²
Binary cross-entropy: L = −(1/n)Σ[y·log(ŷ) + (1−y)·log(1−ŷ)]
Categorical cross-entropy: L = −(1/n)ΣΣ yₖ·log(ŷₖ)
Backpropagation & gradient descent
Backprop is just the chain rule applied systematically: compute ∂L/∂(each weight) by propagating gradients backward from the loss through each layer. Weights update as w ← w − η·∂L/∂w (η = learning rate). In practice this uses mini-batch gradient descent (a compromise between noisy-but-cheap SGD on single examples and stable-but-slow full-batch gradient descent), almost always with an adaptive optimizer:
| Optimizer | Idea |
|---|---|
| SGD + Momentum | Accumulates a velocity vector from past gradients to smooth updates and escape shallow local minima/saddle points |
| RMSProp | Divides the learning rate by a running average of recent squared gradients (per-parameter adaptive step size) |
| Adam | Combines momentum (1st moment) + RMSProp-style scaling (2nd moment); the default choice for most deep learning today |
| AdamW | Adam with decoupled weight decay — standard for Transformers |
When to use MLPs
Tabular data with very large n and complex feature interactions (though gradient boosting usually still wins on tabular data — MLPs shine most when combined with embeddings for high-cardinality categoricals, or as a component of a larger architecture); as the final classification/regression "head" on top of CNN/Transformer features.
Limitations
Needs a lot of data relative to classical ML to avoid overfitting; many hyperparameters (architecture, learning rate, batch size, regularization); no built-in inductive bias for spatial/sequential structure (that's what CNNs/RNNs/Transformers add); training is non-convex — no global-optimum guarantee, sensitive to initialization.
import torch, torch.nn as nn
model = nn.Sequential(
nn.Linear(20, 64), nn.ReLU(), nn.Dropout(0.3),
nn.Linear(64, 32), nn.ReLU(),
nn.Linear(32, 1) # logit output for binary classification
)
loss_fn = nn.BCEWithLogitsLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4)
for epoch in range(50):
optimizer.zero_grad()
logits = model(X_train_t).squeeze()
loss = loss_fn(logits, y_train_t)
loss.backward()
optimizer.step()
Convolutional Neural Networks (CNN)
Idea: instead of fully-connected layers, slide small learnable filters (kernels) across the input to detect local patterns (edges, textures, then higher-level shapes as depth increases), exploiting two inductive biases: local connectivity and weight sharing (the same filter is applied everywhere, drastically reducing parameters vs. a dense layer and giving translation invariance).
Output size = floor[(W − F + 2P) / S] + 1 (W=input size, F=filter size, P=padding, S=stride)Core building blocks
- Convolution layer — learnable filters producing feature maps.
- Pooling (max/average) — downsamples spatial resolution, adds translation-invariance, reduces compute.
- Batch normalization — normalizes layer activations per mini-batch, stabilizes/speeds up training, mild regularization side-effect.
- Residual connections (ResNet) — skip connections (x + F(x)) that let gradients flow through very deep networks, solving the vanishing-gradient/degradation problem that previously capped usable depth.
When to use
Any grid-structured data — images, spectrograms, sometimes 1D signals/time series (via 1D convolutions) — where local spatial/temporal patterns matter and translation invariance is a valid assumption.
Limitations
Needs substantial labeled data (mitigated heavily by transfer learning/pretrained backbones); fixed receptive field size unless architecture is deep or uses dilated convolutions; less naturally suited to variable-length sequences than RNNs/Transformers; largely superseded by Vision Transformers (ViT) for the largest-scale image tasks, though CNNs remain highly competitive and far cheaper for many production settings.
Example use cases
Image classification, object detection (YOLO, Faster R-CNN), medical image analysis (tumor detection), OCR, quality-control defect detection in manufacturing.
import torch.nn as nn
cnn = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 10)
)
# Transfer learning: fine-tune a pretrained backbone instead of training from scratch
from torchvision.models import resnet50, ResNet50_Weights
backbone = resnet50(weights=ResNet50_Weights.DEFAULT)
for p in backbone.parameters(): p.requires_grad = False # freeze
backbone.fc = nn.Linear(backbone.fc.in_features, 10) # new head, trainable
RNN, LSTM & GRU
Idea: a Recurrent Neural Network processes a sequence step by step, maintaining a hidden state hₜ that summarizes everything seen so far: hₜ = φ(W_x·xₜ + W_h·h_{t-1} + b). Plain RNNs suffer from vanishing/exploding gradients over long sequences because the same weight matrix is multiplied repeatedly through backprop-through-time.
LSTM (Long Short-Term Memory) fixes this with a separate cell state and three gates (forget, input, output) that learn what to keep, add, and expose — an additive cell-state update lets gradients flow over long horizons without vanishing as fast.
fₜ = σ(W_f·[h_{t−1},xₜ]+b_f) (forget gate)
iₜ = σ(W_i·[h_{t−1},xₜ]+b_i) (input gate)
Cₜ = fₜ⊙C_{t−1} + iₜ⊙tanh(W_C·[h_{t−1},xₜ]+b_C) (cell state update — additive, not multiplicative)
oₜ = σ(W_o·[h_{t−1},xₜ]+b_o); hₜ = oₜ⊙tanh(Cₜ)
GRU (Gated Recurrent Unit) simplifies LSTM to two gates (reset, update) and no separate cell state — fewer parameters, often comparable accuracy, faster to train.
When to use
Sequential data where order and long-range dependencies matter and you don't have enough data/compute to justify a Transformer, or where causal/streaming (one-token-at-a-time, low-memory) inference is required; time series forecasting, sequence labeling.
Limitations
Inherently sequential — can't parallelize across time steps during training (unlike Transformer self-attention), making them slow on long sequences; still struggle with very long-range dependencies compared to attention; have been largely superseded by Transformers for NLP, though remain competitive/efficient for many time-series and streaming/edge-device applications.
Example use cases
Time series forecasting, speech recognition, sensor/IoT sequence modeling, older-generation machine translation and text generation.
import torch.nn as nn
lstm = nn.LSTM(input_size=10, hidden_size=64, num_layers=2, batch_first=True, dropout=0.2)
out, (h_n, c_n) = lstm(X_seq) # X_seq: (batch, seq_len, input_size)
last_hidden = h_n[-1] # use for classification/forecast head
Transformers & Self-Attention
Idea: replace recurrence entirely with self-attention, letting every position in a sequence directly attend to every other position in parallel, weighted by learned relevance — solving both the long-range-dependency problem and the sequential-computation bottleneck of RNNs.
Attention(Q,K,V) = softmax( QKᵀ / √d_k ) · V
Q = XW_Q (queries), K = XW_K (keys), V = XW_V (values); √d_k scales dot products to keep softmax gradients well-behaved
Multi-head attention: run h attention "heads" in parallel with separate learned projections, concatenate, then project — lets the model attend to different types of relationships simultaneously
A Transformer block = multi-head self-attention + a position-wise feed-forward MLP, each wrapped with a residual connection and layer normalization. Since attention has no inherent notion of order, positional encodings (sinusoidal or learned) are added to the input embeddings.
| Architecture | Structure | Used for |
|---|---|---|
| Encoder-only (BERT) | Bidirectional self-attention | Understanding tasks — classification, NER, embeddings/semantic search |
| Decoder-only (GPT family) | Causal/masked self-attention (each token only attends to previous tokens) | Text generation, chat, few-shot/in-context learning |
| Encoder-decoder (T5, original Transformer) | Encoder processes input, decoder generates output attending to encoder outputs (cross-attention) | Translation, summarization, seq2seq tasks |
When to use
Essentially the default for modern NLP and increasingly for vision (ViT), audio, and even tabular/structured data at scale; when you have (or can leverage via pretraining/fine-tuning) enough data, and need to model long-range dependencies.
Limitations
Self-attention is O(n²) in sequence length (compute and memory) — a major constraint for long documents (mitigated by sparse/linear attention variants, FlashAttention for memory efficiency); huge data and compute appetite to train from scratch, which is why fine-tuning pretrained models (transfer learning) dominates practice; less sample-efficient than RNNs/CNNs on small datasets without pretraining; can hallucinate/lack grounding in generative use.
Example use cases
Text classification/NER/summarization/translation via fine-tuned BERT/T5, chat and generation via GPT-style models, semantic search and retrieval-augmented generation via embedding models, code generation, ViT for image classification.
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)
def tokenize(batch): return tokenizer(batch["text"], truncation=True, padding="max_length", max_length=256)
tokenized_ds = raw_dataset.map(tokenize, batched=True)
trainer = Trainer(
model=model,
args=TrainingArguments(output_dir="out", per_device_train_batch_size=16,
num_train_epochs=3, learning_rate=2e-5, evaluation_strategy="epoch"),
train_dataset=tokenized_ds["train"], eval_dataset=tokenized_ds["validation"],
)
trainer.train() # fine-tuning, not training from scratch
Autoencoders
Idea: an encoder compresses x into a low-dimensional latent code z, a decoder reconstructs x̂ from z; trained to minimize reconstruction error, forcing the bottleneck to learn a compact, informative representation.
L = ‖x − decoder(encoder(x))‖²Variational Autoencoders (VAE) instead learn a probability distribution over the latent space (encoder outputs μ, σ instead of a point), regularized toward a standard normal prior via KL-divergence, enabling generation by sampling z ~ N(0,I) and decoding.
When to use
Dimensionality reduction/representation learning (non-linear alternative to PCA), anomaly detection (poorly-reconstructed inputs are likely anomalous/out-of-distribution), denoising, pretraining a representation for downstream tasks, generative modeling (VAE).
Limitations
Plain autoencoders don't guarantee a smooth/generative latent space (that's what VAEs add, at some cost to reconstruction sharpness); harder to train stably than supervised models; generative quality generally below GANs/diffusion models for sample sharpness.
Example use cases
Fraud/anomaly detection on transaction embeddings, image denoising, pretraining encoders for downstream classification, collaborative-filtering-style recommender embeddings.
import torch.nn as nn
encoder = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 32))
decoder = nn.Sequential(nn.Linear(32, 128), nn.ReLU(), nn.Linear(128, 784), nn.Sigmoid())
autoencoder = nn.Sequential(encoder, decoder)
loss_fn = nn.MSELoss() # train autoencoder(x) to reconstruct x
Generative Adversarial Networks (GAN)
Idea: two networks compete — a Generator G tries to produce fake samples indistinguishable from real data (starting from random noise z), a Discriminator D tries to tell real from fake. Trained as a minimax game:
min_G max_D E_x[log D(x)] + E_z[log(1 − D(G(z)))]When to use: high-fidelity image/data generation, data augmentation, style transfer, super-resolution, synthetic data generation for privacy-preserving ML. Limitations: notoriously unstable to train (mode collapse — generator produces limited variety; vanishing gradients if D becomes too strong too fast); no explicit likelihood, hard to evaluate quantitatively (FID/Inception Score are imperfect proxies); largely overtaken by diffusion models for state-of-the-art image generation quality as of the last few years, though GANs remain useful for fast single-pass generation and specific tasks like domain translation (CycleGAN). Use cases: synthetic image generation, image-to-image translation, data augmentation for imbalanced datasets, deepfake detection research (adversarially).
"When would you reach for deep learning vs. classical ML on tabular data?" — a strong senior answer: gradient boosting (XGBoost/LightGBM/CatBoost) is usually the better default on structured/tabular data with moderate n, because trees naturally handle mixed types, missing values, and non-smooth interactions with far less tuning and data than a neural net needs. Deep learning wins decisively on unstructured data (images, audio, text, video) where convolution/attention exploit spatial/sequential structure, and on very large-n structured problems where entity embeddings + a neural architecture (e.g., recommender systems, click-through-rate models at scale) can outperform trees.
Time Series, NLP Techniques & Reinforcement Learning
Forecasting methods old and new, the classical-to-contextual NLP toolchain, and the RL vocabulary interviewers expect.
Time Series Forecasting
ARIMA / SARIMA
ARIMA(p,d,q) combines: AutoRegression (AR, order p) — regress on p past values; Integration (I, order d) — difference the series d times to achieve stationarity; Moving Average (MA, order q) — regress on q past forecast errors.
(1 − Σφᵢ Lⁱ) (1−L)^d yₜ = (1 + Σθⱼ Lʲ) εₜ (L = lag operator)
SARIMA adds seasonal AR/I/MA terms (P,D,Q,s) for periodic patterns (e.g., s=12 for monthly data with yearly seasonality).
Key diagnostics
Stationarity (constant mean/variance/autocorrelation over time) is required — test with the Augmented Dickey-Fuller (ADF) test, achieve it via differencing or log-transforms. ACF/PACF plots guide order selection: PACF cutoff suggests AR order p, ACF cutoff suggests MA order q. auto_arima automates order search via AIC/BIC.
When to use
Univariate series with a moderate history, clear autocorrelation/seasonality structure, need for interpretable statistical forecasts with confidence intervals; econometric/financial time series, demand forecasting with limited external regressors.
Limitations
Assumes linear relationships; requires manual/careful stationarity handling; doesn't natively incorporate exogenous features (SARIMAX extends this) or multiple interacting series (use VAR/VARMAX instead); doesn't scale well to forecasting thousands of series individually without automation.
from statsmodels.tsa.statespace.sarimax import SARIMAX
model = SARIMAX(y_train, order=(1,1,1), seasonal_order=(1,1,1,12))
fit = model.fit(disp=False)
forecast = fit.get_forecast(steps=12)
mean_fc, ci = forecast.predicted_mean, forecast.conf_int()
Exponential Smoothing (ETS) & Prophet
Exponential smoothing (Holt-Winters / ETS) models level, trend, and seasonality as smoothed, weighted averages that decay exponentially into the past — simple, robust, and fast, a strong baseline especially for short series.
Prophet (Meta) decomposes a series into trend (piecewise linear/logistic with automatic changepoint detection) + seasonality (Fourier terms) + holiday effects, fit via a Bayesian additive model — designed to be robust to missing data and outliers with minimal tuning, and to give business-friendly, interpretable component plots.
When to use
ETS: quick, robust baseline for series with clear trend/seasonality and no complex exogenous drivers. Prophet: business forecasting at scale (many series, non-technical stakeholders need interpretable trend/seasonality decomposition), irregular/missing data, known holiday effects.
Limitations
Both are univariate-first (Prophet supports extra regressors but isn't built for rich multivariate interaction modeling); neither captures complex non-linear cross-series dynamics the way a gradient-boosted or deep model with lag/rolling features can; Prophet can over- or under-fit changepoints without tuning changepoint_prior_scale.
from prophet import Prophet
df = df.rename(columns={"date": "ds", "value": "y"})
m = Prophet(yearly_seasonality=True, weekly_seasonality=True)
m.add_country_holidays(country_name="US")
m.fit(df)
future = m.make_future_dataframe(periods=90)
forecast = m.predict(future) # columns: yhat, yhat_lower, yhat_upper, trend, weekly, yearly
Feature-Based ML for Forecasting (Gradient Boosting / Deep Learning)
Reframe forecasting as supervised regression: engineer lag features (yₜ₋₁, yₜ₋₇, …), rolling statistics (7-day mean/std), calendar features (day-of-week, month, holiday flags), and any exogenous regressors, then fit XGBoost/LightGBM (or an LSTM/Transformer for many related series at once, e.g., DeepAR, Temporal Fusion Transformer, N-BEATS). This approach dominates modern forecasting competitions (e.g., M5) because it naturally handles many series jointly, non-linear effects, and rich exogenous features that classical ARIMA-family models can't.
Critical rule
Cross-validate with walk-forward / TimeSeriesSplit only — never shuffle time series data into random folds, and never build lag/rolling features that peek across the train/validation boundary.
NLP-Specific Techniques
| Technique | Idea | Use when |
|---|---|---|
| Bag-of-Words | Represent text as raw/binary word counts, ignoring order | Simple baselines, small vocabularies |
| TF-IDF | tfidf(t,d)=tf(t,d)·log(N/df(t)) | Weighting words by how distinctive they are to a document — strong classical baseline for text classification/search, especially with Naive Bayes/linear SVM |
| Word2Vec / GloVe | Dense word embeddings learned from co-occurrence (skip-gram/CBOW for Word2Vec; global co-occurrence matrix factorization for GloVe) | Capturing semantic similarity ("king" − "man" + "woman" ≈ "queen") with lightweight, fast, static (non-contextual) embeddings |
| Contextual embeddings (BERT, etc.) | Same word gets a different vector depending on context, via Transformer self-attention | State-of-the-art for almost all modern NLP tasks — classification, NER, QA, semantic search |
| Named Entity Recognition (NER) | Sequence labeling (BIO tagging) to extract people/orgs/dates/etc. | Information extraction pipelines |
| Retrieval-Augmented Generation (RAG) | Embed & index a document corpus (vector DB), retrieve relevant chunks at query time, feed them into an LLM prompt | Grounding LLM answers in proprietary/current data without fine-tuning; reduces hallucination |
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
tfidf_baseline = make_pipeline(TfidfVectorizer(ngram_range=(1,2), min_df=3), LogisticRegression(max_iter=1000))
tfidf_baseline.fit(train_texts, train_labels) # fast, strong, hard-to-beat baseline before reaching for BERT
# Modern sentence embeddings for semantic search / RAG
from sentence_transformers import SentenceTransformer
encoder = SentenceTransformer("all-MiniLM-L6-v2")
doc_embeddings = encoder.encode(documents, normalize_embeddings=True)
Reinforcement Learning Basics
RL formalizes sequential decision-making as a Markov Decision Process (states S, actions A, transition probabilities P, reward R, discount γ). An agent learns a policy π(a|s) that maximizes expected cumulative discounted reward.
Return: Gₜ = Σ γᵏ r_{t+k+1} (γ ∈ [0,1) discounts future rewards)
Value function: V^π(s) = E_π[Gₜ | Sₜ=s]
Q-function: Q^π(s,a) = E_π[Gₜ | Sₜ=s, Aₜ=a]
Bellman equation: Q(s,a) = E[r + γ·max_{a'} Q(s',a')]
| Method | Idea | Notes |
|---|---|---|
| Q-Learning | Off-policy, learns Q(s,a) via the Bellman update using a table (or a neural net for Deep Q-Networks/DQN) | Works for discrete action spaces; tabular version needs small state spaces |
| Policy Gradient (REINFORCE) | Directly parametrize and optimize the policy π_θ(a|s) via gradient ascent on expected reward | Handles continuous action spaces naturally; high variance gradient estimates |
| Actor-Critic / PPO | Combine a policy (actor) with a learned value function (critic) that reduces gradient variance; PPO clips the policy update to keep it stable/trust-region-like | Current industry default for training LLMs with RLHF and for robotics/control |
Exploration vs. exploitation
An RL agent must balance trying new actions (exploration) against choosing the currently best-known action (exploitation) — classic strategies include ε-greedy, softmax/Boltzmann exploration, and upper-confidence-bound (UCB) methods (also the core idea behind multi-armed bandits used in A/B testing and ad allocation).
When to use / limitations
RL fits problems with sequential decisions and delayed rewards (game playing, robotics, resource allocation, ad bidding, RLHF fine-tuning of LLMs) but is sample-inefficient, hard to train stably, and usually overkill vs. supervised learning when you don't actually have a sequential-decision structure with delayed feedback — a very common interview trap is proposing RL for what is really a supervised prediction problem.
import gymnasium as gym
from stable_baselines3 import PPO
env = gym.make("CartPole-v1")
model = PPO("MlpPolicy", env, verbose=0).learn(total_timesteps=50000)
Model Selection & Hyperparameter Tuning
Search strategies, rigorous model comparison, calibration and interpretability — turning a trained model into a defensible one.
Hyperparameter Search Strategies
| Method | How it works | Tradeoffs |
|---|---|---|
| Grid Search | Exhaustively try every combination on a predefined grid | Guaranteed to check every point on the grid, but cost grows exponentially with the number of hyperparameters — impractical beyond 2-3 dimensions |
| Random Search | Sample random combinations from specified distributions for a fixed budget | Often finds as-good or better results than grid search for the same budget, because it explores each dimension more broadly (Bergstra & Bengio, 2012) |
| Bayesian Optimization | Build a surrogate probabilistic model (typically a Gaussian Process or Tree-structured Parzen Estimator) of the objective, and pick the next point balancing exploration/exploitation (e.g., via expected improvement) | Sample-efficient — needs far fewer trials than grid/random for expensive-to-train models; adds overhead and complexity; sequential by nature (though can be batched) |
| Hyperband / Successive Halving | Allocate a small budget to many configurations, progressively eliminate poor performers and allocate more budget to survivors | Very efficient for models where partial training (fewer epochs/trees) is informative about final performance |
| Population-Based Training / Genetic/Evolutionary search | Maintain a population of configurations, mutate/select based on performance | Good for very large search spaces and when training can be paused/resumed (e.g., neural nets) |
# Optuna: Bayesian (TPE) optimization with pruning
import optuna
from sklearn.model_selection import cross_val_score
def objective(trial):
params = {
"n_estimators": trial.suggest_int("n_estimators", 200, 1500),
"max_depth": trial.suggest_int("max_depth", 3, 10),
"learning_rate": trial.suggest_float("learning_rate", 1e-3, 0.3, log=True),
"subsample": trial.suggest_float("subsample", 0.5, 1.0),
}
model = xgb.XGBClassifier(**params, n_jobs=-1)
return cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc").mean()
study = optuna.create_study(direction="maximize", sampler=optuna.samplers.TPESampler())
study.optimize(objective, n_trials=100, timeout=3600)
print(study.best_params, study.best_value)
Comparing Models Rigorously
- Always compare models on the same CV folds (same random seed / same fold assignment) so comparisons are paired, not independent — enables a paired t-test or Wilcoxon signed-rank test on fold-level scores rather than eyeballing mean ± std.
- Use nested CV when the reported number needs to be an honest estimate of generalization performance and you tuned hyperparameters — an inner loop tunes, the outer loop evaluates, so the same data never both selects and scores a model.
- Report a metric aligned with business cost, plus a secondary metric to catch regressions the primary metric might miss (e.g., primary = AUC, secondary = calibration / Brier score).
- Occam's razor / parsimony — if two models perform within noise of each other, prefer the simpler, cheaper, more interpretable, or more maintainable one; this is very often the right answer to "which model would you ship" in interviews.
Model Calibration
A classifier is calibrated if predicted probabilities match empirical frequencies (among all predictions of 0.7, ~70% should actually be positive). Tree ensembles and SVMs are often poorly calibrated out of the box (e.g., pushed toward extremes); fix with:
- Platt scaling — fit a logistic regression on top of the raw scores.
- Isotonic regression — fit a non-parametric monotonic mapping; more flexible, needs more data to avoid overfitting.
from sklearn.calibration import CalibratedClassifierCV
calibrated = CalibratedClassifierCV(base_estimator=rf, method="isotonic", cv=5).fit(X_train, y_train)
"Why might you prefer a well-calibrated but slightly-lower-AUC model?" — because downstream decisions (e.g., pricing risk, expected-value ranking, thresholds set by a business team who isn't retraining the threshold per model) depend on probabilities being meaningful, not just rank-ordered.
Model Interpretability
| Method | Scope | Idea |
|---|---|---|
| Coefficients / odds ratios | Global | Directly interpretable for linear/logistic models |
| Permutation importance | Global | Shuffle one feature, measure performance drop — model-agnostic, accounts for the fact that a feature is used in context of others |
| SHAP (SHapley Additive exPlanations) | Global & local | Game-theoretic attribution of each feature's contribution to a specific prediction, with consistent, additive properties; the current standard for explaining tree ensembles and neural nets |
| LIME | Local | Fits a simple interpretable model locally around one prediction to explain it |
| Partial Dependence Plots (PDP) / ICE | Global (PDP) / individual (ICE) | Shows the marginal effect of a feature on predictions, averaged (PDP) or per-instance (ICE) |
import shap
explainer = shap.TreeExplainer(xgb_model)
shap_values = explainer.shap_values(X_test)
shap.summary_plot(shap_values, X_test) # global feature importance + direction
shap.force_plot(explainer.expected_value, shap_values[0], X_test.iloc[0]) # one prediction
Python Library Reference
Which library to reach for is as much a part of ML fluency as knowing the algorithms — a map from scenario to tool.
Which library to reach for is as much a part of ML fluency as knowing the algorithms. This section maps libraries to the scenarios where they're the right tool.
Core Data Handling
| Library | Use for | Notes |
|---|---|---|
| NumPy | Vectorized array math, the foundation almost everything else is built on | Know broadcasting rules and vectorization — avoiding Python loops over arrays is often a 10-100x speedup |
| pandas | Tabular data manipulation — loading, cleaning, joining, grouping, reshaping | For very large data (>RAM), consider Polars (much faster, multi-threaded, lazy execution) or Dask/PySpark for distributed processing |
| Polars | High-performance dataframes, larger-than-pandas-comfortable datasets on a single machine | Lazy query optimization, Rust-based, increasingly the default choice for new projects |
| PySpark | Distributed data processing / feature engineering across a cluster | Necessary once data no longer fits on one machine; steeper learning curve, JVM overhead for small jobs |
| SciPy | Statistical tests, optimization, sparse matrices, signal processing, distance metrics | scipy.stats for hypothesis testing, scipy.optimize for custom loss minimization |
Classical ML
| Library | Use for | Notes |
|---|---|---|
| scikit-learn | The default toolkit for classical ML — linear models, SVMs, trees, clustering, PCA, preprocessing, pipelines, model selection, metrics | Consistent fit/predict/transform API; Pipeline and ColumnTransformer are essential for leakage-free, production-safe preprocessing |
| statsmodels | Statistical inference — p-values, confidence intervals, GLMs, time series (ARIMA/VAR), hypothesis tests | Reach for this over sklearn when you need coefficients' statistical significance, not just predictions |
| XGBoost / LightGBM / CatBoost | Gradient boosting — the strongest general tabular-data models | See Part 5.4 for when to pick which |
| imbalanced-learn (imblearn) | SMOTE/ADASYN and other resampling techniques, imbalance-aware pipelines | Use its Pipeline, not sklearn's, when resampling is a step (so resampling happens only on training folds) |
| mlxtend | Association rule mining (Apriori/FP-Growth), stacking utilities, plotting decision regions | Handy extras that complement sklearn |
| UMAP-learn | UMAP dimensionality reduction/visualization | See Part 6.2 |
| Optuna / Hyperopt / scikit-optimize | Hyperparameter optimization (Bayesian/TPE) | Optuna is currently the most widely adopted; supports pruning, distributed search, great visualization |
Deep Learning
| Library | Use for | Notes |
|---|---|---|
| PyTorch | Research-friendly, dynamic-graph deep learning; the dominant framework in research and increasingly in production | Pythonic, eager execution (easy debugging); torch.compile and TorchScript for production speed; ecosystem: torchvision, torchaudio, Lightning (training loop boilerplate) |
| TensorFlow / Keras | Production deployment pipelines (TF Serving, TF Lite for mobile/edge, TensorFlow.js), enterprise environments already standardized on it | Keras (now the high-level API for TF, also has a JAX/PyTorch-backend-agnostic version) is the fastest way to prototype standard architectures |
| JAX | High-performance numerical computing with composable function transforms (autodiff, vmap, jit, pmap) | Popular for research and large-scale training (used internally at Google/DeepMind); steeper learning curve, functional style |
| Hugging Face Transformers | Pretrained Transformer models for NLP/vision/audio, fine-tuning, tokenizers | The standard interface to thousands of pretrained models; pairs with datasets and accelerate for scaled training |
| Hugging Face PEFT | Parameter-efficient fine-tuning (LoRA, QLoRA, prefix tuning) | Fine-tune large models on modest hardware by updating a small fraction of parameters |
| sentence-transformers | Sentence/document embeddings for semantic search, clustering, RAG | Built on top of Hugging Face transformers, optimized for embedding quality via contrastive training |
| ONNX / ONNX Runtime | Framework-agnostic model export/inference optimization | Convert a trained PyTorch/TF model to a portable, optimized format for production serving across languages/hardware |
Visualization & Experimentation
| Library | Use for | Notes |
|---|---|---|
| Matplotlib | Low-level, fully customizable static plots | The foundation most other Python plotting libraries build on |
| Seaborn | Statistical visualization with sensible defaults (distributions, regressions, heatmaps) | Faster than raw matplotlib for exploratory data analysis |
| Plotly | Interactive charts and dashboards (zoom, hover, filter) | Good for stakeholder-facing reports and Dash apps |
| Yellowbrick | ML-specific diagnostic visualizations (residual plots, ROC curves, elbow plots) integrated with sklearn | Quick diagnostic plots with one line of code |
| MLflow | Experiment tracking, model registry, packaging/deployment | Logs params/metrics/artifacts per run; open-source, cloud-agnostic, integrates with SageMaker/Azure ML/Vertex AI |
| Weights & Biases (wandb) | Experiment tracking with rich dashboards, hyperparameter sweeps, model/data versioning | Popular in deep learning research and industry teams; hosted SaaS with a free tier |
| DVC (Data Version Control) | Versioning datasets and model artifacts alongside Git, reproducible pipelines | Complements MLflow/W&B — DVC for data/pipeline versioning, the others for experiment tracking |
Domain-Specific Toolkits
| Library | Domain | Notes |
|---|---|---|
| NLTK | NLP | Classic teaching/prototyping toolkit — tokenization, stemming, POS tagging, classic corpora |
| spaCy | NLP | Production-grade, fast NLP pipelines — NER, dependency parsing, easy integration with Transformers via spacy-transformers |
| Gensim | NLP | Topic modeling (LDA), Word2Vec/Doc2Vec training, similarity queries at scale |
| OpenCV | Computer Vision | Classical image processing (filtering, edge detection, feature matching) and video I/O, often used alongside deep models for preprocessing/augmentation |
| Albumentations | Computer Vision | Fast, extensive image augmentation pipelines for training CNNs/ViTs |
| LangChain / LlamaIndex | LLM applications | Orchestration frameworks for RAG, agents, and chaining LLM calls with tools/retrieval |
| FAISS | Vector search | Facebook's library for efficient approximate nearest-neighbor search over dense embeddings — the backbone of many RAG/semantic-search systems |
start every tabular problem with scikit-learn (linear baseline) → XGBoost/LightGBM/CatBoost (strong model) → only reach for PyTorch/TensorFlow if you have unstructured data (image/text/audio) or a very large, complex structured problem where embeddings and custom architectures pay off. Most "we need deep learning" requests on tabular business data are better served by a well-tuned gradient booster.
Cloud Platforms for ML
What AWS, Azure and Google Cloud each actually offer across the ML lifecycle, and the practical considerations for choosing between them.
Understanding platform-specific implementation is a common gap for otherwise-strong data scientists in senior interviews, because most day-to-day algorithm work happens in a notebook, not a cloud console. This part covers what each of the "big three" actually offers for the ML lifecycle, and the practical considerations for choosing/using each. (Current as of August 2026 — these platforms iterate quickly, so verify exact product names/pricing before a real project.)
Platform Comparison at a Glance
| Capability | AWS | Azure | Google Cloud |
|---|---|---|---|
| Unified ML/AI workbench | SageMaker Unified Studio (2024+; converges analytics, ML & GenAI on an Iceberg-compatible lakehouse) / classic SageMaker AI | Azure Machine Learning Studio (full ML lifecycle) + Azure AI Foundry (GenAI/LLM-focused studio, model catalog, agents) | Vertex AI (single unified platform for classical ML and GenAI since 2021) |
| Notebooks | SageMaker Studio notebooks / JupyterLab spaces | Azure ML Notebooks, compute instances | Vertex AI Workbench (managed JupyterLab, integrated with BigQuery/GCS) |
| AutoML | SageMaker Autopilot / Canvas (no-code) | Azure AutoML (tabular/vision/NLP) | Vertex AI AutoML (tabular, image, text, video) |
| Managed training | SageMaker Training Jobs, distributed training libraries (SMDDP) | Azure ML compute clusters/serverless compute, distributed training support (PyTorch/TF/MPI/Spark) | Vertex AI custom training, serverless or dedicated GPU/TPU clusters (TPUs are a GCP differentiator) |
| Hyperparameter tuning | SageMaker Automatic Model Tuning (Bayesian) | Azure ML HyperDrive | Vertex AI Hyperparameter Tuning (Bayesian) |
| Feature store | SageMaker Feature Store | Managed Feature Store (in Azure ML) | Vertex AI Feature Store |
| Pipelines / orchestration | SageMaker Pipelines; also integrates with MWAA (managed Airflow) | Azure ML Pipelines (Git/MLflow-integrated) | Vertex AI Pipelines (Kubeflow-based) |
| Model registry | SageMaker Model Registry | Azure ML Model Registry / Model Catalog | Vertex AI Model Registry |
| Deployment / serving | SageMaker real-time / serverless / async / batch-transform endpoints | Azure ML managed online & batch endpoints | Vertex AI Endpoints (online prediction), batch prediction |
| Labeling | SageMaker Ground Truth | Azure ML Data Labeling | Vertex AI Data Labeling |
| Monitoring / drift | SageMaker Model Monitor, Clarify (bias/explainability) | Azure ML Data Drift Monitor, Responsible AI dashboard | Vertex AI Model Monitoring |
| Foundation-model / GenAI hub | Amazon Bedrock (foundation models: Anthropic, Meta, Amazon Nova, etc.), integrated into SageMaker Unified Studio | Azure AI Foundry Model Catalog (Azure OpenAI, Mistral, Meta, Cohere, Hugging Face, hundreds of models) | Vertex AI Model Garden (200+ models: Gemini, Imagen, Claude, Mistral, open-source) |
| Agent building | Bedrock Agents | Azure AI Foundry Agent Service | Vertex AI Agent Builder |
| Distinctive strength | Breadth of the AWS data ecosystem (S3, Redshift, Glue, EMR), enterprise maturity, lakehouse convergence of analytics + ML + GenAI | Deep enterprise/Microsoft 365 & identity (Entra ID) integration, strong governance/Responsible AI tooling, easiest adoption path for Microsoft-standardized enterprises | Best-in-class for large-scale training (TPUs), tightest integration with BigQuery for data warehousing, strong open-source/Kubeflow lineage |
AWS — SageMaker
SageMaker's next-generation Unified Studio (announced re:Invent 2024) converges analytics, ML, and generative AI into a single environment on an open, Apache Iceberg-compatible lakehouse spanning S3 data lakes and Redshift warehouses, with zero-ETL integrations from operational databases and federated queries into DynamoDB/BigQuery/Snowflake. It bundles SQL analytics (Athena/Redshift), Spark/Trino data processing, SageMaker AI for ML, and Bedrock-powered generative AI behind one interface, plus governance via SageMaker Catalog (AI-generated metadata, semantic search) and Amazon Q Developer for natural-language data discovery.
Implementation considerations
- Choose classic SageMaker AI vs. Unified Studio based on scope: pure ML lifecycle work (prepare → build → train → deploy) with Feature Store, Canvas (no-code), RStudio, and real-time collaborative Spaces still runs well on classic SageMaker AI; choose Unified Studio when you need to unify data engineering, analytics, ML, and GenAI workflows with enterprise governance across teams.
- Training — use SageMaker Training Jobs with managed spot instances for cost savings (up to ~70% off, with checkpointing to resume interrupted jobs), and the SageMaker Distributed Data Parallel (SMDDP) library for multi-GPU/multi-node training of large models.
- Deployment options map to latency/cost tradeoffs: real-time endpoints (low-latency, always-on, autoscaling), serverless inference (spiky/intermittent traffic, pay only per invocation, has cold-start latency), asynchronous inference (large payloads, long processing time), and batch transform (offline scoring of a full dataset).
- MLOps — SageMaker Pipelines for CI/CD-style ML workflows, integrated with the Model Registry for approval-gated promotion to production, and SageMaker Clarify for bias detection and SHAP-based explainability baked into the pipeline.
- Cost management — right-size instance types (e.g.,
ml.g5for GPU inference vs. training-only instances), use Savings Plans for predictable workloads, and SageMaker Model Monitor to catch drift before it silently degrades production performance.
Azure — Azure Machine Learning & Azure AI Foundry
Azure Machine Learning is the full-lifecycle ML platform: workspaces organize projects/compute/environments; compute clusters (CPU/GPU, serverless, or Kubernetes via Azure Arc) run training with native PyTorch/TensorFlow/MPI/Spark distributed support; the no-code Designer handles drag-and-drop pipelines; AutoML automates feature engineering, algorithm selection, and hyperparameter tuning; and managed online/batch endpoints handle deployment with built-in traffic splitting for canary/blue-green rollouts. Azure AI Foundry is the complementary, more GenAI/LLM-focused studio — a model catalog spanning Azure OpenAI, Mistral, Meta, Cohere, and Hugging Face models, plus Prompt Flow for building and iterating generative AI applications and an Agent Service for agent orchestration.
Implementation considerations
- Choosing between the two studios — use Azure Machine Learning Studio for classical ML training/MLOps (custom models, AutoML, full pipeline lifecycle); use Azure AI Foundry when the work is centered on foundation models, prompt engineering, RAG, or agents. Microsoft's own guidance is to pick based on whether the workload is "train a model" (Azure ML) vs. "build with an LLM" (AI Foundry) — the two increasingly interoperate rather than compete.
- Enterprise identity — Azure ML integrates tightly with Microsoft Entra ID (formerly Azure AD) for RBAC, and with Azure Key Vault for secrets and Azure Virtual Networks/private endpoints for network isolation — a major draw for enterprises already standardized on Microsoft identity infrastructure.
- MLOps — native Git and MLflow integration means experiment tracking and model versioning work the same way locally and in the cloud; CI/CD wires up cleanly with GitHub Actions or Azure DevOps pipelines; Apache Airflow orchestration is supported via a dedicated provider package.
- Responsible AI tooling — the built-in Responsible AI dashboard (fairness metrics, error analysis, counterfactual/what-if analysis, causal analysis) is more turnkey out-of-the-box than the AWS/GCP equivalents, relevant for regulated industries.
- Deployment — managed online endpoints support safe rollout via traffic-split percentages between model versions; batch endpoints handle large-scale asynchronous scoring on compute clusters.
Google Cloud — Vertex AI
Vertex AI has been Google's single unified ML/AI platform since 2021, spanning classical ML and generative AI in one product rather than two separate studios. Core components: Vertex AI Workbench (managed JupyterLab tightly integrated with BigQuery and Cloud Storage), AutoML (no-code training across tabular/image/text/video), custom training (full framework control, serverless or dedicated GPU/TPU clusters), Feature Store (share/reuse features across projects), Pipelines (Kubeflow-based managed orchestration), Model Registry (versioning/governance), and Endpoints (fully managed model-as-a-service prediction with monitoring). For generative AI: Vertex AI Studio for prototyping with natural language/code/image/video inputs, Model Garden (200+ models including Gemini, Imagen, and third-party/open-source models like Claude and Mistral), and Agent Builder for no-code agent development with enterprise security/compliance (including HIPAA).
Implementation considerations
- TPUs are GCP's key differentiator — for very large-scale training (especially deep learning/Transformers), Tensor Processing Units often deliver better price-performance than GPUs; this matters when comparing raw large-scale training cost across clouds.
- BigQuery ML lets you train and even serve certain models (linear/logistic regression, k-means, boosted trees, ARIMA, deep neural nets) directly via SQL inside BigQuery — a distinctive option when your data already lives in BigQuery and the modeling team includes analysts more comfortable in SQL than Python.
- Pipelines are Kubeflow-native — if your organization already invests in Kubeflow/Kubernetes-based ML infrastructure, Vertex AI Pipelines will feel the most portable of the three clouds' orchestration offerings.
- Feature Store & Model Registry integrate closely with BigQuery for both online (low-latency serving) and offline (training-time) feature retrieval from the same underlying source of truth, reducing train/serve skew.
- Deployment — Vertex AI Endpoints support online prediction (real-time, autoscaling) and batch prediction (offline scoring); Model Monitoring watches for training/serving skew and prediction drift automatically once configured.
Choosing a Platform & General Cross-Cloud Considerations
- Follow the data gravity — the platform hosting your organization's primary data warehouse/lake (Redshift/S3, Synapse/ADLS, BigQuery) usually wins by default because of reduced data-transfer cost/latency and tighter native integration.
- Follow existing enterprise agreements — most large orgs are already committed to one cloud for cost/compliance reasons; "which cloud is technically best" rarely overrides that in practice, and interviewers value candidates who recognize this.
- Avoid hard lock-in where practical — using framework-agnostic formats (ONNX), open training code (plain PyTorch/TensorFlow rather than heavily platform-specific APIs), and cloud-agnostic experiment tracking (MLflow, W&B) keeps a path open to multi-cloud or migration.
- All three platforms converge on the same MLOps shape — managed notebooks → managed training jobs → a model registry with approval gates → managed real-time/batch endpoints → drift/bias monitoring — so the underlying ML engineering skills transfer directly between clouds even though the console/API surface differs.
- Cost model differences — all three offer spot/preemptible compute for training (significant savings with checkpointing), and serverless/pay-per-invocation inference for spiky traffic; compare GPU/TPU instance pricing and data egress costs for your specific workload rather than assuming one cloud is categorically cheaper.
"How would you take a model from notebook to production?" — a strong cloud-agnostic answer: version the training code and data (Git + DVC/lineage), track experiments (MLflow/W&B), package the model with its environment (container/ONNX), register it with metadata and an approval gate (model registry), deploy behind a managed endpoint with canary/blue-green rollout, and wire up drift/performance monitoring with an alerting and retraining trigger — then name the specific service on whichever cloud the interviewer's company uses.
Algorithm Selection Cheat-Sheet
A fast situation-to-algorithm lookup table for when you need to justify a choice out loud, quickly.
| If the situation is… | Consider |
|---|---|
| Need a fast, interpretable baseline for tabular regression | Linear/Ridge/Lasso Regression |
| Need a fast, interpretable baseline for tabular classification | Logistic Regression |
| Tabular data, want the strongest predictive accuracy, willing to tune | XGBoost / LightGBM / CatBoost |
| Tabular data, want minimal tuning + robust out-of-the-box performance | Random Forest, or CatBoost with defaults |
| Many high-cardinality categorical features | CatBoost, or target-encoding + any GBM |
| Need a fully auditable "if-then" model for regulators | Single Decision Tree, or Logistic Regression with clear coefficients |
| Text classification baseline | TF-IDF + Logistic Regression / Naive Bayes / Linear SVM |
| State-of-the-art text understanding/generation | Fine-tuned Transformer (BERT-family for understanding, GPT-family for generation) |
| Image classification | Pretrained CNN (ResNet/EfficientNet) fine-tuned, or Vision Transformer for very large data |
| Unlabeled data, want groups | K-Means (spherical, know k), DBSCAN (irregular shapes/noise), GMM (soft/elliptical), Hierarchical (want the dendrogram) |
| Reduce dimensionality for modeling | PCA (linear, fast); autoencoder (non-linear, needs more data) |
| Reduce dimensionality for visualization only | t-SNE / UMAP |
| Detect rare anomalies/fraud, unlabeled | Isolation Forest (global, scalable), LOF (local density), Autoencoder reconstruction error |
| Severe class imbalance | Class weights first, then threshold tuning, then SMOTE if still needed; consider PR-AUC over ROC-AUC |
| Time series with clear seasonality, need interpretable components | Prophet or SARIMA |
| Time series forecasting at scale, many related series | Feature-based gradient boosting, or DeepAR/Temporal Fusion Transformer |
| Sequential decision-making with delayed reward | Reinforcement learning (Q-learning/DQN for discrete actions, PPO for continuous/complex) |
| Market-basket / co-occurrence patterns | Apriori / FP-Growth association rules |
Interview Questions
High-frequency questions, grouped loosely by depth. Write your own answer before revealing mine.
coreExplain the bias-variance tradeoff and how you'd diagnose which one is the problem.
See Part 1.2 & 1.4 — decompose error into bias² + variance + irreducible noise; diagnose via learning curves (train vs. validation error gap and level).
coreHow does Random Forest differ from Gradient Boosting?
RF trains trees independently on bootstrap samples + random feature subsets, then averages (variance reduction via decorrelation); GBM trains trees sequentially, each fitting the residual/gradient of the current ensemble (bias reduction). RF parallelizes across trees; GBM does not. GBM usually needs more careful tuning but often wins on accuracy.
practicalHow would you handle a dataset with 95% missing values in one column?
First ask whether the missingness itself is informative (MNAR) — if so, a missing-indicator flag may be more valuable than any imputation. Consider dropping the column if it carries little signal, or keep just the "is missing" flag. Native tree-boosting missing-value handling avoids needing to decide at all.
corePrecision vs recall — how do you decide which to prioritize?
Tie it to the cost of each error type in the specific business context: false positives expensive → optimize precision (e.g., spam filter blocking real mail); false negatives expensive → optimize recall (e.g., missed cancer diagnosis, missed fraud). Use Fβ or a cost-weighted metric, and pick the threshold from the PR curve rather than defaulting to 0.5.
practicalYour model has 99% accuracy — is it good?
Not necessarily — check the base rate; on a 99:1 imbalanced problem, predicting the majority class alone gets 99% accuracy. Look at precision/recall/F1/PR-AUC and compare against that naive baseline.
practicalHow do you detect and prevent overfitting?
Detect via the train/validation error gap (learning curves) and CV score variance across folds. Prevent via regularization, simpler models, more data, early stopping, dropout, ensembling, and proper cross-validation during model selection.
mathExplain the kernel trick.
Lets algorithms like SVM operate in an implicit high-dimensional feature space without ever explicitly computing the transformed features, by replacing dot products with a kernel function K(x,x') = φ(x)ᵀφ(x') that can be computed cheaply in the original space.
mathWhat is the curse of dimensionality and how does it affect KNN/K-Means?
As dimensionality grows, the volume of space grows exponentially and data becomes sparse; distances between points converge (the ratio of nearest to farthest distance approaches 1), so distance-based methods (KNN, K-Means, LOF) lose discriminative power. Mitigate with dimensionality reduction or feature selection first.
scenarioWalk through how you'd design an end-to-end ML system for [X].
Structure the answer: (1) clarify the business objective and how it maps to an ML problem/metric, (2) data sources and labeling strategy, (3) feature engineering and leakage checks, (4) baseline model → iterate to a stronger model, (5) offline evaluation matched to business cost, (6) deployment architecture (batch vs real-time), (7) monitoring for drift/performance decay, (8) retraining cadence and rollback plan.
practicalHow do you explain a "black-box" model to a non-technical stakeholder?
Global explanations via SHAP summary plots or permutation importance for "what drives predictions overall"; local explanations via SHAP force plots or LIME for "why did this specific customer get this score"; partial dependence plots for "how does this one factor affect the outcome, holding others constant."
coreWhat's the difference between parametric and non-parametric models?
Parametric models (linear/logistic regression, LDA) assume a fixed functional form with a fixed number of parameters regardless of data size — fast, interpretable, more biased if the assumption is wrong. Non-parametric models (KNN, decision trees, kernel SVM) let model complexity grow with the data — more flexible, need more data, higher variance risk.
Glossary
Every term used across this guide, in one place.
- Activation function
- Non-linear function applied to a neuron's weighted input (ReLU, sigmoid, tanh, softmax).
- Batch normalization
- Normalizes layer activations per mini-batch during training to stabilize and speed up deep network training.
- Bootstrap
- Sampling with replacement from a dataset to create resampled training sets, e.g., for bagging or confidence-interval estimation.
- Confusion matrix
- Table of TP/FP/FN/TN counts for a classifier's predictions vs. actual labels.
- Cross-entropy / log loss
- Loss function measuring the difference between predicted probability distribution and the true label distribution; the negative log-likelihood under a categorical/Bernoulli model.
- Embedding
- A learned dense vector representation of a discrete entity (word, item, user) that captures semantic similarity in geometric distance.
- Epoch
- One full pass through the training dataset during iterative training.
- Feature leakage
- A feature that inadvertently encodes information about the target that wouldn't be available at prediction time.
- Gradient descent
- Iterative optimization that updates parameters in the direction that most reduces the loss function.
- Hyperparameter
- A configuration value set before training (not learned from data), e.g., learning rate, tree depth, k in KNN.
- Inductive bias
- The built-in assumptions a model architecture makes about the data (e.g., CNNs assume local spatial structure matters).
- Latent space
- A compressed, learned representation space (e.g., an autoencoder's bottleneck, a VAE's z) that captures the essential structure of the data.
- Learning rate
- Step size for gradient-based parameter updates; too high diverges, too low is slow to converge.
- MLOps
- Practices/tooling for reliably deploying, versioning, and monitoring ML models in production (the ML analog of DevOps).
- Normalization/Standardization
- Rescaling features to a common range or to zero mean/unit variance.
- One-hot encoding
- Representing a categorical variable as a binary vector with one "1" indicating the active category.
- Overfitting/Underfitting
- Fitting noise in training data (overfit, high variance) vs. failing to capture the true pattern (underfit, high bias).
- Pretraining/Fine-tuning
- Training a model on a large general dataset/task first (pretraining), then adapting it to a specific task with additional, usually smaller, training (fine-tuning).
- Regularization
- Techniques that constrain model complexity to reduce overfitting (L1/L2 penalties, dropout, early stopping).
- Softmax
- Function converting a vector of raw scores into a probability distribution over classes.
- Stationarity
- A time series property where statistical properties (mean, variance, autocorrelation) don't change over time — required by many classical time-series models.
- Vanishing/exploding gradient
- Gradients shrinking toward zero or growing unboundedly as they propagate through many layers/time steps, hampering training of deep/recurrent networks.
Further Reading & Sources
Where to go deeper, plus the sources consulted for the cloud-platform comparisons in Part 11.
- Books: "The Elements of Statistical Learning" (Hastie, Tibshirani, Friedman) for the statistical theory; "Hands-On Machine Learning with Scikit-Learn, Keras & TensorFlow" (Géron) for practical implementation; "Deep Learning" (Goodfellow, Bengio, Courville) for DL foundations; "Designing Machine Learning Systems" (Chip Huyen) for production/MLOps thinking.
- Practice: re-implement 2-3 algorithms from this guide from scratch in NumPy (linear regression via gradient descent, K-Means, a decision tree) — nothing cements the math like coding the update rule yourself.
- Interview practice: for each algorithm section in this guide, practice a 2-minute verbal explanation covering: what it does, the cost function, when to use it, one limitation, and one real use case — this is almost exactly the shape senior DS interview answers should take.