Machine learning interview questions
Build intuition with worked examples, then connect each concept to a design decision. 129 guides on models, evaluation, and trustworthy production ML.
Build a reliable foundation.
Start with a question you struggle to explain.
How do you know a recommendation is good?
Worked examples for retrieval, ranking, and product evaluation.
Data leakage: when a model knows too much
Point-in-time features, preprocessing boundaries, and delayed labels.
Class imbalance and decision thresholds
Precision, recall, calibration, sampling, and action thresholds.
Overfitting, regularization, and early stopping
Learning curves, L1 and L2, validation discipline, and model selection.
Logistic regression, from score to decision
Understand the sigmoid, log loss, coefficients, and the difference between probability and action.
Gradient descent and training diagnostics
Calculate an update, compare step sizes, and diagnose a training run before changing the model.
The bias–variance trade-off
State the assumptions, work through the decomposition, and connect it to model choices.
Decision trees, random forests, and boosting
Follow a split and a boosting update, then compare the practical costs of tree ensembles.
Embeddings and similarity search
Connect learned geometry to similarity functions, index recall, and model versioning.
Choose the right validation strategy
Match splits to deployment and separate model selection from final assessment.
When can you trust a probability?
Distinguish ranking from calibration and fit a probability mapping without leakage.
Model drift and production monitoring
Separate population changes from pipeline failures, then choose an evidence-based response.
K-means: what makes a useful cluster?
Work through an assignment step, then question the distance function and the purpose of the groups.
PCA and dimensionality reduction
Separate variance preservation from predictive usefulness, and reason about scaling and reconstruction.
Feature engineering and missing data
Design transformations around prediction time, missingness, and consistent serving behavior.
Feature selection and importance
Distinguish a useful predictor from a causal explanation and measure whether a feature earns its cost.
Regression metrics and asymmetric errors
Calculate MAE and RMSE, then choose a loss that reflects the decision being made.
A/B tests: from randomization to a decision
Choose the experimental unit, interpret uncertainty, and avoid declaring a winner from noise.
Negative sampling for retrieval models
Understand what an unobserved interaction means and how sampled training differs from catalog-wide evaluation.
Attention and transformers: the serving trade-offs
Trace one attention operation and connect context length to memory, caching, and system design.
Confidence intervals for model comparisons
Work through paired accuracy differences, bootstrap sampling units and practical significance.
Diagnose selection bias in recommendation data
Worked population-mix and propensity-weighting examples, with support and uncertainty limits.
Choose thresholds using precision–recall curves
Worked threshold choices, average precision, tied scores and changing positive-class prevalence.
Distinguish prediction from causal effects
Worked coupon economics, randomized assignment, confounding and policy evaluation.
Control false discoveries across many model experiments
Worked Bonferroni, Holm and BH examples, dependence assumptions and test-set reuse.
Survival Analysis: Censoring, Kaplan–Meier and Competing Risks
Work through survival probabilities, right censoring, Kaplan–Meier estimates and competing risks. Learn why terminal cancellation is not ordinary missing follow-up.
Choose a bootstrap strategy for dependent observations
Cluster dependence, paired differences, ratio metrics and uncertainty limits.
Gradient Accumulation: Effective Batch Size and DDP Scaling
Calculate effective batch size and correctly normalize unequal token batches in distributed gradient accumulation. Cover clipping, AMP and synchronization.
Explain contrastive representation learning
Worked contrastive loss, false negatives, batch interactions and retrieval evaluation.
Explain quantization accuracy and memory trade-offs
Scale and zero point, outliers, metadata, calibration and hardware limits.
Ranking Losses Explained: Pointwise, Pairwise and Listwise
Compare pointwise, pairwise and listwise ranking losses with worked gradients, NDCG examples, query weighting and biased click-label limitations.
Diagnose high-variance importance-weighted estimates
Rare-event variance, misleading effective sample size, self-normalization and clipping bias.
Reason about base rates and diagnostic evidence
Natural frequencies, likelihood ratios, prevalence shift and operational decisions.
Connect regularization with probabilistic priors
Gaussian and Laplace priors, feature scaling, sparse solutions and posterior uncertainty.
Distinguish missingness mechanisms and remedies
MCAR, MAR, MNAR, weighted means, nonidentifiability and sensitivity analysis.
Explain reversals under aggregation
Simpson’s paradox, common population weights, decomposition and evaluation design.
Construct and evaluate conformal prediction sets
Calibration ranks, adaptive intervals, prediction sets and distribution-shift limits.
Compare momentum and adaptive optimization
Momentum dynamics, Adam moments, numerical conventions and faithful restarts.
Combine rankings from incompatible retrievers
Worked rank fusion, truncation and duplicate-branch counterexamples.
Compare batch and layer normalization
Tiny-matrix calculations, saved statistics, small batches and padding.
Choose targets and losses for model distillation
Temperature, teacher mistakes, worked gradients and honest compression evaluation.
Explain positional information in attention
A numerical RoPE example, precise causal-mask caveats and long-context validation.
Explain gradient clipping and its side effects
Global versus coordinate clipping, accumulation order, loss scaling and update-size counterexamples.
Use Jensen's inequality in ML reasoning
Probability ensembles, perplexity aggregation and a support-aware likelihood bound.
Correct probabilities under changing class priors
Prior correction, confusion-based prevalence estimation and a failure counterexample.
Effective Sample Size: Correlated Data and Unequal Weights
Calculate effective sample size for clustered observations and unequal weights. Compare sampling designs and learn where common ESS formulas stop applying.
Explain probability accuracy with the Brier score
Worked Brier decomposition, binning pitfalls and honest reference forecasts.
Choose a low-rank approximation using singular values
Worked SVD residuals, factor storage and an activation-distribution counterexample.
Explain fast adaptation with meta-learning
Support/query splits, exact and first-order gradients, and leakage-resistant evaluation.
Predict conditional quantiles with pinball loss
Worked pinball losses, nonunique quantiles, cost ratios and crossing predictions.
Choose the direction of KL divergence
Asymmetry, support, likelihood gradients and a restricted-family mode example.
Mutual Information Explained: Examples, Conditioning and Leakage
Understand mutual information in bits and nats, nonlinear dependence, conditional information and feature leakage through worked discrete examples.
Derive expectation maximization for a mixture
A numerical EM iteration, lower-bound proof, singularities and validation.
Use curvature to reason about optimization
Quadratic dynamics, eigenvalues, saddle points, conditioning and HVP diagnostics.
Model counts with Poisson regression
Count likelihood, weighted rates, coefficient interpretation and conditional dispersion.
Estimate expectations with Monte Carlo
Paired estimators, control variates, stopping rules and reproducible simulation.
Approximate uncertainty with the delta method
Propagate uncertainty through ratio metrics, retain covariance, and recognize when a linear approximation fails.
Compare nested models with likelihood ratios
Compute a nested-model test, check its regularity assumptions, and derive a case where boundary constraints change the answer.
Reason about stationary Markov distributions
Solve an invariant distribution, distinguish it from a limiting law, and diagnose periodicity and slow mixing.
Select diverse items with diminishing returns
Derive a greedy coverage guarantee, then test its limits with prerequisites, unequal costs and stale marginal gains.
Understand focal loss and difficult examples
Derive focal-loss gradients, compare easy and difficult examples, and separate classification decisions from probability calibration.
Compare distributions with optimal transport
Solve a weighted transport example, preserve meaningful geometry, and distinguish empirical distance from evidence of drift.
Preserve geometry with random projections
Derive a finite-set distortion budget, test nearest-neighbor margins, and compare theoretical guarantees with empirical compression.
Learn when outcomes are only partially observed
Distinguish censoring from truncation, derive a likelihood for capped measurements, and expose assumptions about an unseen tail.
Predict with a Gaussian process and explain its uncertainty
Calculate a kernel posterior, distinguish latent and observation uncertainty, and budget stable Gaussian-process inference.
Estimate an outcome with two imperfect nuisance models
Worked AIPW scores, robustness proof, cross-fitting and overlap failures.
Keep a uniform sample from an unknown-length stream
Sample stream positions without replacement.
Sample a fixed categorical distribution in constant time
Assume nonnegative finite weights with positive total, independent random draws and a distribution that stays fixed between rebuilds.
Update a conversion probability with a beta prior
Assume conditionally independent Bernoulli outcomes with a stable common probability p.
Distinguish sequence likelihood from the best hidden path
Assume two hidden states, a first-order Markov transition model and observations conditionally independent given the state sequence.
Explain support-vector margins and feature scaling
Use binary labels −1 and +1 and the canonical hard-margin constraints y(w·x+b) at least 1.
Interpret ROC AUC through positive-negative pairs
Assume binary labels, larger scores indicating positives and half credit for ties.
Compare datasets with a kernel two-sample statistic
Assume independent samples within and between groups for the basic test.
Test paired model improvements with valid permutations
Specify the null that makes within-pair label swaps valid.
Monitor experiments without treating every peek as a fixed test
Separate fixed-horizon inference from time-uniform inference.
Connect entropy to lossless coding and log loss
Use base-two logarithms and a discrete distribution with positive probabilities for observed symbols.
Compute softmax stably and derive its gradient
Assume finite logits and a normalized target distribution.
Trade activation memory for recomputation during training
This is recomputing forward activations during backward, distinct from saving training checkpoints to durable storage or accumulating gradients across batches.
Measure monotonic association with ranks
Two model scores have different scales.
Explain ranking agreement through concordant pairs
Compare two rankings using Kendall correlation and explain what changes when there are ties.
Update uncertainty over several category probabilities
Use a Dirichlet prior to estimate category proportions from a small multinomial sample.
Use Student's t when estimating a mean
Explain a t interval for a small sample and the assumptions that make it exact.
Explain why naive Bayes can overcount evidence
Derive a two-feature naive Bayes decision and show how duplicated features distort confidence.
Interpret agreement beyond a raw percentage
Calculate Cohen's kappa for two annotators and explain why it is not a universal label-quality score.
Solve one-to-one matching without greedy mistakes
Assign workers to tasks at minimum total cost and show why choosing the cheapest available pair can fail.
Use low-discrepancy samples for integration
Explain when a Sobol sequence can improve numerical integration and how its error assessment differs from independent Monte Carlo.
Separate latent components with independent component analysis
Explain when ICA can recover mixed signals and which ambiguities remain even in an ideal setting.
Interpret nonnegative matrix factorization
Factor a nonnegative count matrix into additive components and explain why the factors are not uniquely determined.
Stabilize a noisy covariance estimate
Explain covariance shrinkage when feature count is large relative to sample size.
Connect two feature views with canonical correlation
Explain how CCA finds related directions in two views and why high training correlation can be misleading.
Fit a monotone curve by pooling violations
Fit nondecreasing predictions to a small ordered sequence and explain isotonic regression's limits.
Understand CTC paths, blanks and repeated labels
Explain how CTC maps frame-level paths to a shorter label sequence and why greedy decoding need not maximize sequence probability.
Calculate a convolutional network's receptive field
Calculate receptive field and effective stride through a stack of convolutions, stating padding assumptions.
Reason about transposed convolution output shape
Explain transposed convolution shape arithmetic and why it is not generally the inverse of a convolution.
Derive inverted dropout and its variance
Explain the scaling used by inverted dropout and what it preserves during training.
Distinguish weight decay from an L2 gradient in Adam
Explain why adding an L2 penalty to an adaptive optimizer is not generally equivalent to decoupled weight decay.
Calculate label-smoothed targets and their trade-offs
Explain multiclass label smoothing and distinguish two conventions for distributing the smoothing mass.
Work through mixup training
Explain input and target interpolation in mixup and when the interpolated examples may be inappropriate.
Learn a mean and input-dependent variance
Derive a Gaussian negative log-likelihood loss when prediction noise changes with the input.
Connect Fisher information to estimation precision
Calculate Fisher information for a normal mean with known variance and explain the Cramer–Rao bound's scope.
Use KKT conditions to identify an active constraint
Solve a simple constrained optimization problem and explain complementarity.
Explain optimism in a bandit selection rule
Work through a simple upper-confidence selection rule and contrast it with always choosing the highest observed mean.
Estimate variance from leave-one-out fits
Compute a jackknife variance estimate for a sample mean and explain why the leave-one-out estimates are not independent samples.
Derive waiting time for independent successes
How many independent attempts should a worker expect before its first success, and when is that model misleading?.
Explain exponential waiting times
Why does an exponential waiting model say past waiting does not change the remaining wait?.
Update a Poisson rate with a Gamma prior
Estimate an event rate from counts and exposure while keeping uncertainty explicit.
Model counts whose variance exceeds the mean
A count series has mean 4 and variance 12.
Derive the maximum of uniform samples
For independent Uniform(0,1) samples, derive the distribution and mean of their maximum.
Estimate time to observe every category
How many independent draws are needed on average to see every equally likely category?.
Estimate identifier collision probability
Estimate the risk of at least one collision when assigning random identifiers from a finite space.
Separate within-group and between-group variance
Explain how two stable populations can produce a variable combined metric.
Reduce Monte Carlo variance with a control variate
Estimate E[X] using a correlated variable Y whose expectation is known.
Use antithetic pairs without assuming they always help
Explain when paired samples U and 1−U reduce simulation variance.
Design a valid rejection sampler
Sample from an unnormalized density using a proposal and a dominating envelope.
Construct samples with an inverse CDF
Generate samples from an exponential distribution and explain how inverse-CDF sampling extends to discrete distributions.
Bound deviations using only finite variance
How much can you say about a random variable when you know only its mean and variance?.
Use a bounded-sample concentration bound
Choose a sample size for a bounded metric without assuming a normal distribution.
Derive a scalar Kalman measurement update
Combine a noisy prediction and measurement with explicit uncertainty.
Explain particle-filter weight collapse
Track a nonlinear hidden state with weighted particles and decide when resampling is needed.
Derive stability of an AR(1) process
Explain when Xt=φXt−1+εt has a stationary variance.
Align time series with dynamic time warping
Compare two sequences that express similar shapes at different speeds.
Explain aliasing in sampled signals
Why can a sampled signal confuse a high frequency with a lower one?.
Explain FFT leakage and window trade-offs
A pure tone appears in several FFT bins.
Compare linear and quadratic discriminant analysis
Explain why sharing class covariance creates a linear decision boundary.
Trace one AdaBoost reweighting step
Show how a binary weak learner changes example weights in AdaBoost.
Quantify how correlation limits bagging
Why does averaging more models eventually stop reducing variance much?.
Derive the Huber loss and robust gradient
Design a regression loss that is quadratic near zero error and less sensitive to large residuals.
Derive soft thresholding for an L1 penalty
Solve a quadratic-plus-L1 subproblem and explain why coefficients can become exactly zero.
Compare two rankers with a controlled interleaving test
Two search rankers reorder similar candidates. Design a small online interleaving experiment and explain what its click preference can and cannot establish.
Take the ideas into a system.
Recommendations
Choose metrics for retrieval, ranking, and real user outcomes.
Fraud detection
Handle rare labels, delayed outcomes, and a limited review queue.
Search ranking
Evaluate relevance and diagnose failures on unfamiliar queries.