Skip to the content.

Machine Learning Interview Questions and Answers: From Basics to Deep Learning and LLMs (2027)

machine-learning-interview-questions is a free, practical list of machine learning interview questions with answers, for ML engineer, data scientist, applied scientist and AI engineer interviews. It goes from the basics (bias-variance, overfitting, regularization, evaluation metrics) through classical algorithms (linear and logistic regression, trees, ensembles, SVMs, clustering) and the math behind them, to deep learning (backpropagation, optimizers, normalization, CNNs, RNNs, transformers and attention), large language models, and ML system design. The “implement it from scratch” questions (metrics, AUC, logistic regression, k-means, decision-tree splits, softmax, attention) are in mlq/ with tests that need only Python’s standard library.

Last reviewed: December 2026. Fundamentals change slowly; the LLM section reflects common practice as of late 2026 and links the original papers so you can check details.

git clone https://github.com/Ralpberry-Labs/machine-learning-interview-questions
cd machine-learning-interview-questions
python3 -m unittest discover -s tests -t .     # Python 3.10+, no dependencies

Table of Contents

How to Use This List

What ML Interviews Look Like

Round Content Sections
ML fundamentals / breadth Rapid conceptual questions: bias-variance, regularization, metrics, algorithms 1 to 7
Math and statistics Probability, linear algebra, gradients, hypothesis testing 8
Deep learning depth Backprop, optimizers, architectures, transformers 9 to 12
ML coding Implement an algorithm or metric from scratch; data manipulation with pandas 14
General coding LeetCode-style data structures and algorithms (most ML engineer loops) leetcode-patterns
ML system design Design a recommender, search ranking, fraud detection, or an LLM-powered feature end to end 13
Project deep dive Explain a past project: data, model choices, metrics, what failed Prepare 2 projects in depth

A 6-Week Preparation Plan

Week Focus Done when you can…
1 Fundamentals, data, metrics (sections 1 to 3) Explain bias-variance with a concrete model, choose metrics for an imbalanced problem, and design a leak-free validation scheme
2 Linear models, trees, ensembles, other algorithms (sections 4 to 6) Derive the logistic regression gradient and explain why gradient boosting often wins on tabular data
3 Unsupervised learning, math and statistics (sections 7 and 8) Explain PCA via eigenvectors/SVD, MLE vs MAP, and run through an A/B test analysis
4 Neural networks and training (sections 9 and 10) Backpropagate through a 2-layer network by hand and debug a model that does not train
5 Architectures and LLMs (sections 11 and 12) Draw a transformer block and explain attention, positional encoding, fine-tuning and RAG
6 ML system design + coding (sections 13 and 14) + mock interviews Run a 45-minute design interview for a recommender and implement k-means and AUC from scratch

1. ML Fundamentals

Q1. Supervised vs unsupervised vs self-supervised vs reinforcement learning? [J]

Semi-supervised learning combines a small labeled set with a large unlabeled one.

Q2. What is the bias-variance trade-off? [J]

Expected test error splits into bias² (error from wrong assumptions, so the model is too simple and underfits), variance (error from sensitivity to the particular training set, so the model is too flexible and overfits), and irreducible noise. More complex models lower bias and raise variance. You manage it with model complexity, regularization, more data, and ensembling (bagging reduces variance, boosting reduces bias). Very large neural networks can show “double descent”, where test error falls again past the interpolation point, so the classic U-shaped curve is not the whole story.

Q3. How do you detect and fix overfitting and underfitting? [J]

Compare training and validation performance. Overfitting: low training error, much higher validation error. Fixes: more data, data augmentation, regularization (L1/L2, dropout, weight decay), simpler models, early stopping, ensembling, fewer or better features. Underfitting: both errors high. Fixes: a more expressive model, better features, less regularization, training longer. Learning curves (error vs training set size) show which problem you have and whether more data will help.

Q4. What is regularization? L1 vs L2? [J]

Regularization adds a penalty on model complexity to the loss. L2 (ridge, weight decay) adds λ·Σw², shrinking all weights smoothly toward zero; it handles correlated features well. L1 (lasso) adds λ·Σ w , which pushes some weights exactly to zero, so it also selects features. Elastic net combines both. Geometrically, the L1 constraint region has corners on the axes, which is where solutions tend to land. From a Bayesian view, L2 is a Gaussian prior on weights and L1 a Laplace prior (MAP estimation).

Q5. Parametric vs non-parametric models? [M]

Parametric models have a fixed number of parameters regardless of data size (linear regression, logistic regression, a fixed neural network); they are fast and need less data but make strong assumptions. Non-parametric models grow with the data (k-NN, decision trees without depth limits, kernel methods, Gaussian processes); they are flexible but can be slow at prediction time and need more data.

Q6. Generative vs discriminative models? [M]

Discriminative models learn P(y x) or a decision boundary directly (logistic regression, SVMs, most neural classifiers). Generative models learn P(x y) and P(y), or P(x) itself, so they can generate data (naive Bayes, Gaussian mixture models, VAEs, GANs, diffusion models, autoregressive language models). Discriminative models usually classify better with enough data; generative models can handle missing data and sometimes need fewer labels.

Q7. What is the curse of dimensionality? [M]

As the number of features grows, the volume of the space grows exponentially, so data becomes sparse, distances between points become similar (nearest neighbors stop being meaningful), and you need much more data to cover the space. It hurts k-NN and clustering most. Remedies: feature selection, dimensionality reduction (PCA, embeddings), regularization, and models that exploit structure (convolutions for images).

Q8. What is the “no free lunch” theorem in practice? [M]

No single algorithm is best for every problem; averaged over all possible problems, all learners perform equally. In practice it means you should match model assumptions to the data (gradient-boosted trees for tabular data, CNNs or vision transformers for images, transformers for text) and validate empirically instead of assuming one method always wins.

2. Data Preparation and Feature Engineering

Q9. How do you handle missing data? [J]

First ask why it is missing: completely at random, at random given other features, or not at random (the missingness itself carries information). Options: drop rows or columns (only if little is lost), impute with mean/median/mode, model-based imputation (k-NN, iterative imputation), add a “was missing” indicator feature, or use models that handle missing values natively (many gradient-boosting libraries do). Fit imputers on the training fold only.

Q10. How do you encode categorical variables? [J]

Q11. When do you need feature scaling? [J]

Needed for algorithms that use distances or gradients: k-NN, k-means, SVMs, PCA, linear and logistic regression with regularization, and neural networks (scaling speeds up and stabilizes training). Tree-based models do not need it, because splits depend only on ordering. Standardization (zero mean, unit variance) is the usual default; min-max scales to a range; robust scaling (median and IQR) resists outliers. Fit the scaler on training data only.

Q12. What is data leakage, and how do you prevent it? [M]

Leakage is when information that would not be available at prediction time gets into training, giving great validation scores and poor production results. Examples: fitting a scaler or imputer on the full dataset before splitting; features computed from the future (a “total purchases” field that includes purchases after the prediction date); target encoding without out-of-fold computation; duplicate or near-duplicate records across train and test; random splits of time series. Prevent it with pipelines that fit transforms inside each fold, time-based splits, group splits (by user or patient), and a sanity check: “Would I know this value at the moment I make the prediction?”

Q13. How do you handle imbalanced classes? [M]

If you resample, predicted probabilities are no longer calibrated to the real base rate; recalibrate if you need probabilities.

Q14. How do you select features? [M]

Filter methods (correlation, mutual information, chi-squared) are fast and model-agnostic. Wrapper methods (recursive feature elimination, forward selection) evaluate subsets with the model and are expensive. Embedded methods select during training (L1 regularization, tree feature importance). Use permutation importance on a validation set rather than impurity-based importance, which is biased toward high-cardinality features. Domain knowledge often beats all three.

3. Evaluation Metrics and Validation

Q15. Explain the confusion matrix, precision, recall and F1. [J]

  Predicted positive Predicted negative
Actual positive True positive (TP) False negative (FN)
Actual negative False positive (FP) True negative (TN)

Pick by cost: a spam filter values precision (do not lose real email); a cancer screen values recall (do not miss cases). Implemented in mlq/metrics.py.

Q16. What is ROC-AUC, and when should you use PR-AUC instead? [M]

The ROC curve plots true positive rate vs false positive rate across all thresholds. ROC-AUC equals the probability that a randomly chosen positive gets a higher score than a randomly chosen negative, so 0.5 is random and 1.0 is perfect ranking. Because the FPR denominator is all negatives, ROC-AUC can look great on heavily imbalanced data even when precision is poor. The precision-recall curve and PR-AUC (average precision) focus on the positive class and are more informative when positives are rare (fraud, rare disease). roc_auc computes AUC from ranks in O(n log n), and the test checks it against the pairwise definition.

Q17. Which regression metrics should you know? [J]

MSE/RMSE penalize large errors heavily and are in squared/original units. MAE is more robust to outliers. R² is the fraction of variance explained relative to predicting the mean (it can be negative on test data). MAPE is scale-free but explodes near zero targets. Choose the metric that matches the business cost; the loss you train with can differ from the metric you report.

Q18. What is log loss, and why do probabilities need calibration? [M]

Log loss (binary cross-entropy) is −[y·log p + (1−y)·log(1−p)], averaged. It rewards confident correct predictions and heavily punishes confident wrong ones. A model is calibrated if, among predictions of 0.8, about 80% are positive. Boosted trees, SVMs and modern neural networks are often miscalibrated. Check with a reliability diagram or expected calibration error; fix with Platt scaling (logistic fit), isotonic regression, or temperature scaling for neural networks. Calibration matters whenever scores are used as probabilities (pricing, risk, combining models).

Q19. Explain cross-validation and its variants. [J]

k-fold: split data into k folds, train on k−1, validate on the remaining one, rotate, and average. Stratified k-fold keeps class ratios per fold. Group k-fold keeps all rows from one group (user, patient) in the same fold to avoid leakage. Time-series split (forward chaining) always trains on the past and validates on the future. Nested cross-validation separates hyperparameter tuning (inner loop) from performance estimation (outer loop) so the estimate is not optimistically biased.

Q20. Why do we need train, validation and test sets? [J]

The training set fits parameters. The validation set tunes hyperparameters and chooses models. The test set is touched once at the end to estimate real-world performance. Reusing the test set for decisions makes it another validation set and its score optimistic. In production, the final check is an online experiment.

Q21. How do you choose a decision threshold? [M]

The default 0.5 is rarely optimal. Pick the threshold on validation data to optimize what matters: maximize F1, meet a minimum precision or recall, or minimize expected cost = FP·cost_FP + FN·cost_FN. Revisit it when the base rate changes in production.

Q22. How do you evaluate a model online? [M]

Offline metrics are proxies. Online, run an A/B test: randomly assign users to the old and new model, measure business metrics (conversion, retention, revenue, latency) and guardrail metrics, and decide with a pre-registered hypothesis, sample size and test duration. Watch for novelty effects, network effects between users, and peeking at results early. Interleaving experiments are a more sensitive option for ranking systems. Shadow deployments (run the new model without acting on it) catch errors before an A/B test.

4. Linear Models

Q23. What are the assumptions of linear regression? [J]

Linearity between features and target, independent errors, homoscedasticity (constant error variance), no strong multicollinearity, and (for inference such as confidence intervals) normally distributed errors. Prediction can still work when some assumptions are violated; coefficient interpretation and p-values cannot. Check with residual plots.

Q24. Closed-form solution vs gradient descent for linear regression? [M]

The normal equation w = (XᵀX)⁻¹Xᵀy gives the exact least-squares solution, but computing the inverse costs about O(d³) and is numerically unstable when features are collinear (in practice you use QR or SVD). Gradient descent scales to many features and huge datasets and works with streaming (SGD) and regularizers without closed forms. Ridge regression has a closed form with (XᵀX + λI), which is always invertible for λ > 0. LinearRegression shows batch gradient descent with optional L2.

Q25. Why is logistic regression a classification model, and what loss does it use? [J]

It models P(y=1 x) = σ(wᵀx + b), where σ is the sigmoid, so outputs are probabilities, and the decision boundary wᵀx + b = 0 is linear. It is trained by maximizing likelihood, which is the same as minimizing log loss (binary cross-entropy). MSE is not used because combined with the sigmoid it gives a non-convex objective with weak gradients for confident mistakes; log loss is convex in w. The gradient is the neat Σ(σ(z) − y)·x, the same form as linear regression. See mlq/linear.py.

Q26. How do you interpret logistic regression coefficients? [M]

A coefficient w_j is the change in log-odds for a one-unit increase in x_j, holding others fixed; e^(w_j) is the odds ratio. Interpretation requires comparable feature scales and is unreliable with strong multicollinearity.

Q27. What is multicollinearity, and why does it matter? [M]

Highly correlated features make coefficient estimates unstable (large variance, sign flips) even when predictions remain fine. Detect with correlation matrices or the variance inflation factor (VIF). Fix with L2 regularization, removing or combining features, or PCA. It matters most when you need to interpret coefficients.

Q28. How do you extend linear models to multiple classes? [J]

One-vs-rest: one binary classifier per class, pick the highest score. Softmax (multinomial) regression: one weight vector per class, outputs a probability distribution with the softmax function, trained with categorical cross-entropy. Softmax regression is exactly the last layer of most neural classifiers.

5. Trees and Ensembles

Q29. How does a decision tree decide where to split? [J]

Greedily, at each node it tries every feature and threshold and picks the split that most reduces impurity: Gini impurity (1 − Σp²) or entropy (−Σp log p) for classification, variance (MSE) for regression. The reduction with entropy is called information gain. It stops at a maximum depth, a minimum number of samples, or when no split helps. mlq/trees.py implements Gini, entropy, information gain and the best-split search.

Q30. Why do decision trees overfit, and how do you stop it? [J]

An unrestricted tree can keep splitting until each leaf holds one sample, memorizing noise (high variance). Control it with maximum depth, minimum samples per leaf or split, maximum number of leaves, cost-complexity pruning, or, most effectively, by ensembling many trees.

Q31. Bagging vs boosting? [M]

  Bagging (e.g. random forest) Boosting (e.g. gradient boosting)
How models are built In parallel, independently on bootstrap samples Sequentially, each fixing the previous ensemble’s errors
Mainly reduces Variance Bias (and variance with shrinkage)
Base learners Deep, low-bias trees Shallow trees (weak learners)
Overfitting risk Low; more trees do not hurt Higher; tune learning rate, depth, early stopping
Parallel training Easy Within each tree only

Stacking trains a meta-model on the out-of-fold predictions of several different models.

Q32. How does a random forest work? [J]

It trains many decision trees, each on a bootstrap sample of the rows, and at each split considers only a random subset of features (often √d for classification). The feature subsampling decorrelates the trees, so averaging them reduces variance much more than bagging alone. Predictions are a majority vote or average. Out-of-bag samples (rows not in a tree’s bootstrap, about 37%) give a free validation estimate.

Q33. How does gradient boosting work? [M]

It builds an additive model F(x) = Σ η·h_m(x). At each step it computes the negative gradient of the loss with respect to the current predictions (for squared error, simply the residuals), fits a small tree h_m to those “pseudo-residuals”, and adds it scaled by a learning rate η. It is gradient descent in function space. Popular libraries are XGBoost (second-order gradients, regularized objective), LightGBM (histogram-based, leaf-wise growth, fast) and CatBoost (ordered boosting and strong handling of categorical features). Key hyperparameters: learning rate, number of trees (with early stopping), tree depth or number of leaves, row and column subsampling, and regularization terms.

Q34. Why do gradient-boosted trees still dominate tabular data? [M]

They handle mixed feature types, missing values and different scales without preprocessing, capture non-linear interactions, are robust to irrelevant features, and train fast on CPUs. Neural networks are competitive in some tabular settings, especially with very large data or when combined with text and images, but boosted trees remain the strong default baseline that interviewers expect you to try first.

Q35. How do you explain a tree ensemble’s predictions? [M]

Global: permutation importance, partial dependence plots. Local (per prediction): SHAP values, which split a prediction into additive feature contributions based on Shapley values from game theory (TreeSHAP computes them exactly and efficiently for trees), or LIME, which fits a simple local surrogate. Impurity-based feature importance is fast but biased toward high-cardinality and continuous features.

6. Other Classical Algorithms

Q36. How do support vector machines work? [M]

An SVM finds the separating hyperplane with the maximum margin between classes; only the points on or inside the margin (the support vectors) define it. Soft margin (parameter C) allows some violations: a large C fits training data tightly, a small C gives a wider margin and more regularization. The kernel trick computes inner products in a high-dimensional feature space without constructing it (RBF, polynomial kernels), enabling non-linear boundaries. Training scales poorly beyond hundreds of thousands of samples, and outputs are not probabilities without calibration.

Q37. How does k-nearest neighbors work, and what are its weaknesses? [J]

To predict, find the k closest training points and take a majority vote (classification) or average (regression). No training phase, but prediction is O(n·d) per query without an index, it needs feature scaling, and it degrades in high dimensions. Small k means high variance; large k means high bias. Approximate nearest-neighbor indexes (HNSW, IVF) make it practical at scale, which is also how vector search works. See knn_predict in mlq/clustering.py.

Q38. Why is naive Bayes “naive”, and why does it still work? [J]

It applies Bayes’ theorem assuming all features are conditionally independent given the class, so P(x y) is a product of per-feature probabilities. The assumption is almost never true, but classification only needs the ranking of classes to be right, not exact probabilities, and the model has very low variance. It is fast and a strong baseline for text classification. Use Laplace (additive) smoothing so an unseen word does not zero out a class.

Q39. What is a Gaussian process? [S]

A distribution over functions: any finite set of function values is jointly Gaussian, with covariance defined by a kernel. It gives predictions with calibrated uncertainty and works well on small datasets, which is why it powers Bayesian optimization for hyperparameter tuning. Exact inference costs O(n³), so it does not scale to large n without approximations.

7. Unsupervised Learning

Q40. How does k-means work, and what are its limitations? [J]

Lloyd’s algorithm: initialize k centroids, assign each point to the nearest centroid, move each centroid to the mean of its points, repeat until assignments stop changing. It minimizes within-cluster sum of squared distances (inertia) and converges to a local optimum, so initialization matters: k-means++ picks initial centroids far apart with probability proportional to squared distance. Limitations: you must choose k (elbow method, silhouette score), it assumes roughly spherical, similarly sized clusters, it is sensitive to scaling and outliers, and it only works with Euclidean-like distances. mlq/clustering.py implements k-means with k-means++.

Q41. Compare clustering algorithms. [M]

Algorithm Cluster shapes Need k? Handles noise Notes
k-means Spherical Yes No Fast, scalable
Gaussian mixture model Elliptical, soft assignments Yes Partly Fit with EM; gives probabilities
DBSCAN / HDBSCAN Arbitrary No Yes, labels outliers Density-based; DBSCAN struggles with varying density, HDBSCAN handles it
Hierarchical (agglomerative) Depends on linkage No (cut the dendrogram) No O(n²) memory; gives a hierarchy
Spectral clustering Non-convex Yes No Uses graph Laplacian eigenvectors

Q42. How does PCA work? [M]

PCA finds orthogonal directions (principal components) that capture the most variance. Center the data (and usually standardize), then take the eigenvectors of the covariance matrix sorted by eigenvalue, or equivalently the right singular vectors from an SVD of the data matrix. Projecting onto the top k components gives the best rank-k linear approximation in squared error. The explained variance ratio guides the choice of k. PCA is linear and sensitive to scaling; components are hard to interpret.

Q43. PCA vs t-SNE vs UMAP? [M]

PCA is linear, fast, deterministic, preserves global structure, and can transform new data. t-SNE and UMAP are non-linear methods for visualization that preserve local neighborhoods; t-SNE distorts global distances and cluster sizes and does not naturally embed new points; UMAP is faster and keeps somewhat more global structure. Do not read distances between clusters in a t-SNE plot as meaningful.

Q44. How do you detect anomalies? [M]

Statistical rules (z-scores, IQR), density or distance methods (local outlier factor, k-NN distance), Isolation Forest (anomalies are isolated by fewer random splits), one-class SVM, and reconstruction error from autoencoders. With some labels, treat it as highly imbalanced classification. Evaluate with precision at the top of the ranking, since investigators only see the highest scores.

8. Math and Statistics for ML

Q45. Explain MLE and MAP. [M]

Maximum likelihood estimation picks parameters that maximize P(data θ). Maximum a posteriori maximizes P(θ data) ∝ P(data θ)·P(θ), adding a prior. MSE loss is MLE under Gaussian noise; cross-entropy is MLE for categorical outputs; L2 regularization is MAP with a Gaussian prior; L1 is MAP with a Laplace prior. Full Bayesian inference keeps the whole posterior instead of one point.

Q46. What is Bayes’ theorem? Walk through the classic test example. [J]

P(A B) = P(B A)·P(A) / P(B). Example: a disease affects 1% of people; a test catches 99% of cases and has a 5% false positive rate. P(disease positive) = 0.99·0.01 / (0.99·0.01 + 0.05·0.99) ≈ 0.0099 / 0.0594 ≈ 16.7%. Most positives are false because the base rate is low. This intuition matters for imbalanced classification and alerting systems.

Q47. Which probability distributions should you know? [J]

Bernoulli and binomial (binary outcomes), categorical and multinomial, Poisson (counts per interval), uniform, normal (sums of many effects, via the central limit theorem), exponential (waiting times), beta (probabilities; conjugate prior for Bernoulli), and Dirichlet (probability vectors). Know means, variances and when each arises.

Q48. What is the central limit theorem, and why does it matter? [J]

The mean of many independent samples with finite variance is approximately normally distributed, whatever the original distribution, with standard error σ/√n. It justifies confidence intervals and z/t-tests for averages, including A/B test metrics.

Q49. Explain p-values, statistical power and common A/B testing pitfalls. [M]

A p-value is the probability of a result at least as extreme as observed if the null hypothesis were true. It is not the probability that the null is true. Power is the probability of detecting a real effect of a given size; choose the sample size up front from the minimum detectable effect, significance level and power (often 80%). Pitfalls: peeking and stopping early (inflates false positives; use sequential testing if you must), testing many metrics without correction, sample ratio mismatch (assignment bugs), novelty effects, and units of randomization that interact (network effects).

Q50. What linear algebra do you need for ML? [M]

Vectors and matrices, matrix multiplication shapes, dot products as similarity, norms, rank, eigenvalues and eigenvectors (PCA, stability), singular value decomposition (PCA, low-rank approximation, LoRA’s motivation), positive semi-definite matrices (covariances, kernels), and matrix calculus basics (gradients of wᵀx, xᵀAx, and the chain rule through matrix products).

Q51. What is gradient descent, and how do batch, mini-batch and stochastic versions differ? [J]

Gradient descent updates parameters in the direction of the negative gradient: θ ← θ − η∇L(θ). Batch uses the whole dataset per step (accurate, slow). Stochastic uses one example (noisy, cheap). Mini-batch (32 to thousands of examples) balances the two, uses GPU parallelism well, and is the standard. Some gradient noise helps escape sharp minima and saddle points. The learning rate is the most important hyperparameter.

Q52. Is the loss of a neural network convex? Does it matter? [M]

No. Neural network losses are highly non-convex with many local minima and saddle points. In high dimensions, most critical points are saddle points rather than bad local minima, and many minima found by SGD generalize similarly well. Momentum, adaptive optimizers, normalization, residual connections and good initialization make optimization work in practice.

Q53. What are entropy, cross-entropy and KL divergence? [M]

Entropy H(p) = −Σp log p measures uncertainty. Cross-entropy H(p, q) = −Σp log q is the expected cost of encoding samples from p using a code built for q; it is the classification loss with p the true labels and q the model’s predictions. KL divergence KL(p‖q) = H(p, q) − H(p) ≥ 0 measures how much q differs from p; it is not symmetric. KL appears in VAEs, knowledge distillation, and as a penalty keeping a fine-tuned language model close to its reference model during RLHF.

9. Neural Network Basics

Q54. What does a neuron compute, and why do we need non-linear activations? [J]

A neuron computes a weighted sum plus bias, z = wᵀx + b, then applies an activation a = f(z). Without non-linear activations, any stack of layers collapses into a single linear transformation, so depth would add nothing. With them, networks can approximate a very wide class of functions (the universal approximation theorem says one wide hidden layer suffices in principle; depth makes it efficient in practice).

Q55. Compare activation functions. [J]

Activation Formula Pros Cons
Sigmoid 1 / (1 + e^−x) Output in (0, 1) for probabilities Saturates (vanishing gradients); not zero-centered
Tanh (e^x − e^−x) / (e^x + e^−x) Zero-centered Still saturates
ReLU max(0, x) Cheap; no saturation for x > 0 “Dying ReLU” units stuck at zero
Leaky ReLU / PReLU max(αx, x) Avoids dead units Extra hyperparameter
GELU x·Φ(x) Smooth; standard in many transformers Slightly more compute
SiLU / Swish x·σ(x) Smooth; used in many modern models Slightly more compute
SwiGLU Gated linear unit with Swish Common in recent LLM feed-forward layers More parameters per layer
Softmax e^(z_i) / Σe^(z_j) Turns logits into a distribution Output layer only; needs a stable implementation

Q56. Explain backpropagation. [M]

Backpropagation computes the gradient of the loss with respect to every parameter by applying the chain rule backward through the computation graph, reusing intermediate results so the cost is about the same as one forward pass. For a layer z = Wx + b, a = f(z): given ∂L/∂a from above, ∂L/∂z = ∂L/∂a ⊙ f′(z), then ∂L/∂W = (∂L/∂z)·xᵀ, ∂L/∂b = ∂L/∂z, and ∂L/∂x = Wᵀ·(∂L/∂z) is passed to the previous layer. A key identity: for softmax followed by cross-entropy, the gradient with respect to the logits is simply softmax(z) − one_hot(y). mlq/neural.py implements it and the test checks it with finite differences.

Q57. What are vanishing and exploding gradients? [M]

Backpropagation multiplies many Jacobians. If their scale is below 1, gradients shrink exponentially with depth (early layers stop learning); above 1, they explode (training diverges, NaNs). Causes: saturating activations, poor initialization, very deep or recurrent networks. Fixes: ReLU-family activations, careful initialization (Xavier/Glorot for tanh-like, He/Kaiming for ReLU), normalization layers, residual connections, gating (LSTMs, GRUs), and gradient clipping for explosions.

Q58. Why does weight initialization matter? [M]

If all weights start equal, all neurons in a layer compute the same thing and receive the same gradient (symmetry is never broken). If weights are too large or small, activations and gradients explode or vanish through the layers. Xavier/Glorot initialization keeps variance stable for tanh/sigmoid; He/Kaiming initialization (variance 2/fan_in) does it for ReLU. Transformers often add scaled initialization for residual branches.

Q59. Which loss function goes with which task? [J]

Task Output layer Loss
Regression Linear MSE (or MAE, Huber for robustness)
Binary classification Sigmoid (one logit) Binary cross-entropy
Multi-class (one label) Softmax Categorical cross-entropy
Multi-label Sigmoid per label Binary cross-entropy per label
Ranking Scores Pairwise (hinge, BPR) or listwise losses
Embedding / similarity Normalized vectors Contrastive / triplet / InfoNCE

Libraries combine the final activation and the loss in one numerically stable function (for example PyTorch’s CrossEntropyLoss takes raw logits). Do not apply softmax yourself first.

10. Training Deep Networks

Q60. Compare SGD with momentum, RMSProp, Adam and AdamW. [M]

Newer optimizers (for example ones based on orthogonalized updates for matrix parameters) are actively researched; if you mention one, be ready to explain it.

Q61. What are learning rate schedules and warmup? [M]

Schedules change the learning rate during training: step decay, exponential decay, cosine decay, one-cycle, and linear decay. Warmup starts with a small learning rate and increases it over the first steps, which stabilizes early training when Adam’s second-moment estimates are poor and gradients are large; it is standard for transformers. A learning-rate range test (increase the rate until the loss diverges) helps find a good maximum.

Q62. How does batch normalization work, and how is layer normalization different? [M]

Batch norm normalizes each feature to zero mean and unit variance across the batch, then applies learnable scale (γ) and shift (β). It stabilizes and speeds up training and allows higher learning rates. At inference it uses running averages collected during training, so train and eval mode differ, and it behaves poorly with tiny batches. Layer norm normalizes across the features of each example, so it does not depend on batch size or other examples, which suits transformers and sequence models. RMSNorm drops the mean-centering and is common in recent LLMs. A minimal batch norm is in mlq/neural.py.

Q63. How does dropout work? [J]

During training, each unit is zeroed with probability p, so the network cannot rely on any single unit; it acts like training an ensemble of thinned networks. With inverted dropout (the standard), kept activations are scaled by 1/(1−p) during training so nothing changes at inference, when dropout is turned off. Forgetting model.eval() at inference is a classic bug. See dropout in mlq/neural.py.

Q64. Your model’s loss is not going down. How do you debug it? [M]

  1. Overfit a single small batch first. If you cannot reach near-zero loss, there is a bug.
  2. Check the data: labels aligned with inputs, preprocessing identical in train and eval, augmentations sane, no NaNs.
  3. Check the loss setup: logits vs probabilities (double softmax), wrong loss for the task, wrong label format.
  4. Try a range of learning rates; too high diverges, too low stalls.
  5. Watch gradient norms and activations per layer for vanishing, exploding or dead units; add gradient clipping.
  6. Verify train()/eval() modes, that the optimizer gets the right parameters, and that gradients are zeroed each step.
  7. Compare with a simple baseline to know what “good” looks like.

Q65. What is transfer learning, and how do you fine-tune? [M]

Start from a model pretrained on a large dataset and adapt it to your task. Options: use it as a frozen feature extractor and train a new head; fine-tune all or the top layers with a small learning rate; or use parameter-efficient fine-tuning (adapters, LoRA). With little data and a similar domain, freeze more; with more data or a different domain, fine-tune more. Use discriminative (lower) learning rates for earlier layers, and watch for catastrophic forgetting.

Q66. Which techniques make large models train faster or fit in memory? [S]

Mixed precision (bf16/fp16 with fp32 master weights), gradient accumulation (larger effective batch), gradient (activation) checkpointing (recompute activations to save memory), data parallelism, sharded data parallelism (ZeRO, FSDP) that splits optimizer states, gradients and weights across GPUs, tensor and pipeline parallelism for very large models, efficient attention kernels (FlashAttention), and quantization (8-bit optimizers, 4-bit weights for QLoRA-style fine-tuning).

11. CNNs, RNNs and Transformers

Q67. Why do CNNs work well for images? [J]

Convolutions apply the same small filter across the image, building in two useful assumptions: locality (nearby pixels are related) and translation equivariance (a pattern is detected wherever it appears). Weight sharing means far fewer parameters than fully connected layers. Stacking layers grows the receptive field, so early layers detect edges and later layers detect parts and objects. Pooling or strided convolutions downsample. Output size = (input − kernel + 2·padding) / stride + 1.

Q68. What problem did residual connections (ResNets) solve? [M]

Very deep plain networks trained worse than shallower ones, even on training data, because optimization was hard. Residual blocks compute y = x + F(x): the layer learns a correction to the identity, and gradients flow directly through the skip connection. This made networks with hundreds of layers trainable and is now part of nearly every deep architecture, including transformers.

Q69. How do RNNs, LSTMs and GRUs work, and why were they replaced? [M]

An RNN processes a sequence step by step with a hidden state h_t = f(W·x_t + U·h_(t−1)). Plain RNNs suffer from vanishing gradients over long sequences. LSTMs add a cell state with input, forget and output gates that control information flow; GRUs are a simpler gated variant. Transformers largely replaced them because RNNs process tokens sequentially (no parallelism across time during training) and still struggle with very long dependencies. State-space models and modern linear-recurrence architectures revisit recurrence with parallel training.

Q70. Explain self-attention. [M]

Each token’s embedding is projected into a query Q, a key K and a value V. Attention computes softmax(QKᵀ / √d_k)·V: each token’s output is a weighted average of all value vectors, weighted by how well its query matches each key. Dividing by √d_k keeps dot products from growing with dimension and saturating the softmax. A causal mask stops tokens attending to future positions in decoders. Multi-head attention runs several attention heads in parallel on lower-dimensional projections so different heads can capture different relationships. scaled_dot_product_attention implements one head with an optional causal mask.

Q71. Describe a transformer block. [M]

Input token embeddings plus positional information go through N identical blocks. Each block has a multi-head self-attention sublayer and a position-wise feed-forward network (two linear layers with an activation, often 4x wider; SwiGLU in many recent LLMs), each wrapped with a residual connection and layer normalization (pre-norm, applied before the sublayer, is standard now because it trains more stably). Encoder-only models (BERT) use bidirectional attention; decoder-only models (GPT-style LLMs) use causal attention; encoder-decoder models (the original transformer, T5) add cross-attention from decoder to encoder.

Q72. Why do transformers need positional encodings? What are the options? [M]

Self-attention is permutation-invariant: without position information, “dog bites man” and “man bites dog” look the same. Options: fixed sinusoidal encodings (original transformer), learned absolute position embeddings (BERT, GPT-2), relative position biases, and rotary position embeddings (RoPE), which rotate query and key vectors by position-dependent angles so their dot product depends on relative distance; RoPE is used in most current open LLMs and can be extended to longer contexts with scaling tricks.

Q73. What is the computational cost of attention, and how is it reduced? [S]

Standard attention costs O(n²·d) time and O(n²) memory for sequence length n. Reductions: FlashAttention (exact attention computed in tiles to minimize GPU memory traffic; faster, linear memory), sparse or sliding-window attention, linear-attention approximations, and grouped-query or multi-query attention (sharing keys and values across heads to shrink the KV cache at inference).

Q74. What are vision transformers? [M]

A ViT splits an image into fixed-size patches (for example 16×16), linearly embeds each patch as a token, adds position embeddings, and runs a standard transformer encoder. With little data, ViTs underperform CNNs because they lack built-in locality; with large-scale pretraining they match or beat them. Hybrid and hierarchical designs (Swin, ConvNeXt as the CNN response) blur the line.

12. Large Language Models

Q75. How are LLMs trained? [M]

  1. Pretraining: a decoder-only transformer learns next-token prediction (cross-entropy) on a very large text corpus. This is where most knowledge and capability comes from.
  2. Supervised fine-tuning (SFT) / instruction tuning: train on curated prompt-response examples so the model follows instructions.
  3. Preference tuning: align outputs with human or AI preferences, for example RLHF (train a reward model on comparisons, then optimize the policy with RL, classically PPO, with a KL penalty to the SFT model) or DPO, which optimizes directly on preference pairs without a separate reward model or RL loop.
  4. Increasingly, reinforcement learning with verifiable rewards (math answers, unit tests) is used to improve reasoning.

Q76. What is tokenization, and why does it matter? [J]

Models operate on tokens, not characters. Subword tokenizers such as byte-pair encoding (BPE), WordPiece and SentencePiece split rare words into pieces and keep common words whole, balancing vocabulary size and sequence length. Tokenization affects cost (pricing and context limits are per token), multilingual fairness (some languages need more tokens per word), arithmetic and spelling quirks, and how prompts are counted.

Q77. What do temperature, top-k and top-p do? [J]

At each step the model outputs logits over the vocabulary. Temperature divides logits before softmax: below 1 sharpens the distribution (more deterministic), above 1 flattens it (more diverse). Top-k samples only from the k most likely tokens. Top-p (nucleus) samples from the smallest set whose cumulative probability exceeds p. Greedy decoding picks the argmax; beam search keeps several candidate sequences and suits tasks like translation more than open-ended chat.

Q78. What is the KV cache? [M]

During autoregressive generation, keys and values of previous tokens do not change, so they are cached instead of recomputed at each step. This makes each new token cost O(n) attention instead of reprocessing the whole sequence, but the cache grows linearly with sequence length and batch size and often dominates GPU memory at inference. Grouped-query attention, quantized caches and paged memory management (as in vLLM’s PagedAttention) reduce the cost.

Q79. Explain LoRA and parameter-efficient fine-tuning. [M]

Full fine-tuning updates every weight and needs optimizer state for all of them. LoRA freezes the pretrained weights W and learns a low-rank update ΔW = B·A with rank r much smaller than the layer dimensions, often on the attention and MLP projections. It trains a tiny fraction of the parameters, adapters can be swapped per task, and the update can be merged into W for no inference overhead. QLoRA fine-tunes LoRA adapters on top of a 4-bit quantized frozen base model to cut memory further.

Q80. What is retrieval-augmented generation (RAG), and when do you use it instead of fine-tuning? [M]

RAG retrieves relevant documents (with embeddings and a vector index, keyword search like BM25, or both, often followed by a re-ranker) and puts them into the prompt so the model answers from them. Use RAG for knowledge that changes or must be cited and access-controlled; use fine-tuning for behavior: format, style, domain-specific skills, or a smaller, cheaper model for a narrow task. They combine well. Evaluate retrieval (recall@k, MRR) separately from generation (faithfulness, answer correctness). See generative-ai-for-beginners-rag.

Q81. How do you evaluate LLM applications? [M]

Build a task-specific evaluation set from real examples, with clear pass criteria. Combine exact or programmatic checks (JSON validity, unit tests, string match), reference-based metrics where they fit, LLM-as-judge with a written rubric (validated against human labels, watching for position and verbosity bias), human review for high-stakes outputs, and online metrics (task success, user feedback, escalation rate). Track hallucination, safety and latency/cost alongside quality, and re-run evals on every prompt or model change. See llm-evals-for-beginners.

Q82. What are scaling laws? [S]

Empirical power-law relationships between loss and model size, data size and compute. A key result from the Chinchilla paper was that, for a fixed compute budget, many earlier large models were undertrained, and parameters and training tokens should be scaled roughly in proportion (about 20 tokens per parameter in that study). Since then, many models are deliberately trained on far more tokens than “compute-optimal” because smaller models are cheaper to serve. More recently, spending more compute at inference time (longer reasoning, sampling and verifying) has become another scaling axis.

Q83. What causes hallucinations, and how do you reduce them? [M]

Language models are trained to produce plausible continuations, not verified facts; gaps in training data, ambiguous prompts and decoding randomness all contribute. Reduce them with retrieval and instructions to answer only from provided sources (and to say “I don’t know”), citations that you verify, lower temperature for factual tasks, constrained outputs (schemas, tool calls), self-consistency or verifier checks, and evaluation sets that specifically probe for fabricated facts.

13. ML System Design and MLOps

A useful structure for ML system design interviews:

  1. Clarify the problem: the business goal, users, scale, latency budget, and how success is measured (business metric and offline proxy).
  2. Frame it as ML: inputs, outputs, prediction target, labels and where they come from, and whether ML is needed at all (start with heuristics).
  3. Data: sources, labeling, sampling, class balance, privacy, feedback loops.
  4. Features: user, item and context features; real-time vs batch features; a feature store to keep training and serving consistent.
  5. Model: a simple baseline first, then candidates and trade-offs (quality, latency, interpretability).
  6. Evaluation: offline metrics and validation scheme, then online A/B tests and guardrails.
  7. Serving: batch vs online inference, latency, caching, scaling, fallback when the model is down.
  8. Monitoring and iteration: data and prediction drift, performance by segment, retraining cadence, alerting.

Q84. Design a recommendation system (e.g. “videos you may like”). [S]

Q85. Design a fraud detection system. [S]

Highly imbalanced labels that arrive late (chargebacks take weeks), adversaries that adapt, and strict latency for real-time decisions. Key points: real-time features (velocity counts per card, device, IP over sliding windows), graph features (shared devices and accounts), a gradient-boosted model plus rules for known patterns, thresholds set from the cost of fraud vs blocking good customers, a review queue for medium scores, delayed-label handling in training, monitoring for drift and new attack patterns, and frequent retraining.

Q86. What is training-serving skew, and how do you prevent it? [M]

The model sees different data in production than in training: features computed by different code paths, different preprocessing, missing real-time features, or time leakage in training. Prevent it with a single feature pipeline or feature store for both, logging the exact features used at serving time and training on those logs, and validation that compares feature distributions between training and serving.

Q87. What is data drift vs concept drift? How do you monitor models? [M]

Data (covariate) drift: the input distribution changes (new user demographics, a new device). Concept drift: the relationship between inputs and the target changes (fraud patterns evolve, behavior changes after a policy change). Label drift: the class balance changes. Monitor input feature distributions (population stability index, KS tests), prediction distributions, live performance when labels arrive, and performance per segment. Retrain on a schedule or when monitored metrics cross thresholds, and keep a rollback path.

Q88. Batch vs online inference? [J]

Batch: predictions computed periodically for all entities and stored (daily churn scores, nightly recommendations). Simple and cheap, but stale and wasteful for entities never used. Online: predictions computed on request with fresh features, needed for search ranking, fraud checks and chat; requires low-latency serving, autoscaling and fallbacks. Many systems mix them: precompute embeddings in batch and rank online.

Q89. How do you make a model smaller or faster for production? [M]

Quantization (int8 or lower precision for weights and activations), pruning (remove weights or whole structures), knowledge distillation (train a small student on a large teacher’s outputs), efficient architectures, compiling and optimizing graphs (ONNX Runtime, TensorRT, torch.compile), batching requests, caching frequent predictions, and for LLMs, serving engines with continuous batching, KV-cache management and speculative decoding.

Q90. What should an ML platform provide (MLOps)? [M]

Versioned data and models, reproducible training pipelines, experiment tracking (MLflow, Weights & Biases), a feature store, a model registry with approval steps, CI for data and model validation, automated deployment with canary or shadow releases, monitoring for drift and performance, and lineage linking each prediction back to the model version and data that produced it.

14. Coding Round: Implement It From Scratch

Every implementation below is in mlq/ and tested in tests/test_mlq.py with only the standard library, so you can focus on the algorithm rather than tooling. In interviews you will usually be allowed NumPy; translating these loops into vectorized NumPy is good extra practice.

Exercise File What interviewers check
Precision, recall, F1, confusion counts metrics.py Definitions, division-by-zero edge cases
ROC-AUC in O(n log n) with ties metrics.py Rank-based AUC (Mann-Whitney), tie handling
Log loss with clipping, MSE, R² metrics.py Numerical stability
Linear regression with gradient descent and L2 linear.py Gradient derivation, not regularizing the bias
Logistic regression linear.py Stable sigmoid, gradient σ(z) − y
k-means with k-means++ clustering.py Assignment/update loop, initialization, empty clusters
k-nearest neighbors clustering.py Distances, voting, ties
Gini, entropy, information gain, best split trees.py Weighted impurity, candidate thresholds
Stable softmax and cross-entropy neural.py Max subtraction, log-sum-exp
Softmax + cross-entropy gradient neural.py p − one_hot(y), checked by finite differences
Scaled dot-product attention with causal mask neural.py Shapes, √d_k scaling, masking
Inverted dropout, batch norm neural.py Train vs inference behavior

Q91. Why subtract the maximum in softmax? [J]

e^z overflows for large z (e^1000 is infinite in float64). Softmax is unchanged by adding a constant to all logits, so subtracting max(z) makes the largest exponent e^0 = 1 and prevents overflow without changing the result. For cross-entropy, compute the log-sum-exp directly instead of taking the log of a softmax probability that may have underflowed to zero.

Q92. How do you compute AUC without plotting a curve? [M]

Sort by score, assign ranks (averaging ranks for tied scores), sum the ranks of positives, and compute AUC = (R_pos − n_pos(n_pos + 1)/2) / (n_pos · n_neg). This counts the fraction of positive-negative pairs ranked correctly, with ties counted as half, in O(n log n) instead of O(n_pos · n_neg).

Q93. What pandas and SQL tasks should you expect? [J]

Filtering, groupby aggregations, joins/merges, pivoting, handling missing values, window operations (rolling, shift, ranking within groups), deduplication, and date handling. Data scientist loops often include SQL questions like “top N per group” or “7-day rolling active users”. See sql-interview-questions.

Best Resources to Prepare

Resource Type Cost Best for
An Introduction to Statistical Learning (with Python edition) by James, Witten, Hastie, Tibshirani and Taylor Book Free PDF from the authors Best first book for classical ML and the statistics behind it
The Elements of Statistical Learning by Hastie, Tibshirani and Friedman Book Free PDF from the authors Mathematical depth on classical methods
Dive into Deep Learning Interactive book Free Best free deep learning book with code
Deep Learning by Goodfellow, Bengio and Courville Book Free HTML online Foundations of neural network theory
Understanding Deep Learning by Simon J. D. Prince Book Free PDF from the author Modern, clear, well-illustrated deep learning including transformers and diffusion
Probabilistic Machine Learning by Kevin Murphy Books Free drafts from the author Probabilistic view, reference depth
Pattern Recognition and Machine Learning by Christopher Bishop Book Free PDF from Microsoft Research Bayesian and classical ML
Mathematics for Machine Learning by Deisenroth, Faisal and Ong Book Free PDF from the authors Linear algebra, calculus and probability for ML
Machine Learning Interviews Book by Chip Huyen Book Free online Interview process and hundreds of practice questions
Designing Machine Learning Systems by Chip Huyen (O’Reilly) Book Paid ML system design and production ML
Google Machine Learning Crash Course Course Free Fast refresher on fundamentals
Machine Learning Specialization (DeepLearning.AI and Stanford) Course Free to audit in many regions, certificate paid Beginner-friendly fundamentals
Practical Deep Learning for Coders Course Free Top-down, hands-on deep learning
Neural Networks: Zero to Hero Video course Free Backprop and GPT built from scratch in code
3Blue1Brown neural network series Videos Free Visual intuition for backprop and transformers
StatQuest Videos Free Clear explanations of statistics and classical ML
Stanford CS229 and CS231n Course materials Free notes Rigorous lecture notes
scikit-learn User Guide Docs Free Practical details of classical algorithms, metrics and validation
PyTorch Tutorials Docs Free Hands-on deep learning code

If you pick only three: ISL for classical ML, Dive into Deep Learning (or Understanding Deep Learning) for deep learning, and the Machine Learning Interviews Book for the interview process.

Key Papers

Interviewers for research-leaning and LLM roles often expect you to know what these papers changed.

Paper Year Why it matters
Dropout: A Simple Way to Prevent Neural Networks from Overfitting 2014 Standard regularizer
Adam: A Method for Stochastic Optimization 2014 Default optimizer family
Batch Normalization 2015 Faster, more stable training
Deep Residual Learning for Image Recognition (ResNet) 2015 Residual connections
XGBoost: A Scalable Tree Boosting System 2016 Gradient boosting at scale
Attention Is All You Need 2017 The transformer
Decoupled Weight Decay Regularization (AdamW) 2017 Correct weight decay with Adam
BERT 2018 Bidirectional pretraining, fine-tuning paradigm
Language Models are Few-Shot Learners (GPT-3) 2020 In-context learning at scale
An Image is Worth 16x16 Words (ViT) 2020 Transformers for vision
LoRA: Low-Rank Adaptation of Large Language Models 2021 Parameter-efficient fine-tuning
Training Compute-Optimal Large Language Models (Chinchilla) 2022 Scaling data with model size
Training Language Models to Follow Instructions with Human Feedback (InstructGPT) 2022 RLHF recipe
FlashAttention 2022 IO-aware exact attention
Direct Preference Optimization (DPO) 2023 Preference tuning without RL

FAQ

What machine learning questions are asked most often? Bias-variance, overfitting and regularization, precision/recall/AUC and choosing metrics for imbalanced data, cross-validation and leakage, logistic regression, decision trees vs random forests vs gradient boosting, k-means, PCA, backpropagation, optimizers, batch norm and dropout, attention and transformers, and one ML system design problem.

How much math do I need for ML interviews? Enough to derive gradients for linear and logistic regression, explain backprop with the chain rule, reason about probability (Bayes’ theorem, common distributions, MLE), and explain PCA with eigenvectors or SVD. Research roles go deeper (proofs, optimization theory); applied roles focus on intuition and trade-offs.

What is the difference between ML engineer and data scientist interviews? ML engineer loops emphasize coding (LeetCode-style and ML coding), ML system design, and production concerns (serving, monitoring, scale). Data scientist loops emphasize statistics, experimentation and A/B testing, SQL and pandas, product sense and communicating results. Both include ML fundamentals.

Do I need to know LLMs for an ML interview in 2027? For most ML and AI engineer roles, yes: at least transformers and attention, pretraining vs fine-tuning vs RAG, LoRA, decoding parameters and how to evaluate LLM features. Traditional ML (tabular models, metrics, experimentation) is still asked everywhere, because most production ML is still recommendation, ranking, forecasting and classification.

Should I implement algorithms in NumPy or PyTorch in interviews? Ask. “Implement from scratch” usually means NumPy or plain Python. For deep learning coding, PyTorch is the most common framework. Practice writing k-means, logistic regression, softmax and attention without looking anything up.

How do I prepare for the ML system design round? Learn a repeatable structure (section 13), practice 6 to 8 classic prompts out loud (recommendations, search ranking, ads click prediction, fraud, spam/content moderation, ETA prediction, an LLM-powered assistant), and always cover data, labels, metrics, baselines, serving and monitoring, not just the model.

Where to Go Next

Contributing

Pull requests are welcome: new questions, clearer answers, corrections, more from-scratch implementations, and paper links. Please write in your own words, keep answers short and accurate, mark the level ([J], [M], [S]), add a test in tests/ for any new code (standard library only), and run python3 -m unittest discover -s tests -t . before opening a PR.

License

The code and content in this repository are released under the MIT License.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.