Machine learning interview questions
69 questions that come up in ML interviews, each with a model answer and what interviewers listen for.
Practise out loud. Gradient Lab has a timed mock-interview mode and brings back the questions you miss.
Start a mock interviewFoundations
What is the difference between supervised, unsupervised and reinforcement learning? Junior
Supervised learning trains on examples that come with the right answer (labels), like emails marked spam or not. Unsupervised learning has no labels and looks for structure, such as groups of similar customers. Reinforcement learning has an agent that takes actions in an environment and learns from rewards over time, like a game-playing program.
Interviewers listen for: Labels vs no labels vs rewards; One concrete example of each; Semi-supervised and self-supervised sit in between.
Learn it: Types of learning, Agents and rewards
What is overfitting, and how do you detect and prevent it? Junior
Overfitting is when a model memorises the training data, including its noise, and does worse on new data. You detect it when training performance is much better than validation performance. You prevent it with more data, a simpler model, regularization, early stopping, dropout, or by averaging many models.
Interviewers listen for: Gap between train and validation scores; At least three remedies; Underfitting is the opposite problem.
Learn it: Underfitting and overfitting, L1 and L2 regularization, Dropout
Explain the bias–variance trade-off. Mid
Bias is error from a model being too simple to capture the pattern; variance is error from being too sensitive to the particular training sample. Making a model more flexible usually lowers bias but raises variance. The goal is the sweet spot with the lowest total error on unseen data, and techniques like regularization, ensembling and more data shift that balance.
Interviewers listen for: High bias = underfitting, high variance = overfitting; Total error = bias² + variance + noise; Bagging cuts variance, boosting cuts bias.
Learn it: Bias and variance, Bagging, Boosting
Why do we split data into training, validation and test sets? Junior
The training set fits the model’s parameters, the validation set is used to choose settings like hyperparameters and compare models, and the test set is kept untouched until the end to estimate how the final model will do on new data. If you tune on the test set, its score stops being an honest estimate.
Interviewers listen for: Each set has one job; Test set used once, at the end; Use cross-validation when data is small.
Learn it: Training and test sets, Cross-validation
What is the difference between a parameter and a hyperparameter? Junior
Parameters are learned from data during training, such as the weights of a linear model or a neural network. Hyperparameters are set before training and control how learning happens, such as the learning rate, tree depth or k in k-nearest neighbors. Hyperparameters are tuned using a validation set or cross-validation.
Interviewers listen for: Learned vs chosen; Examples of each; How hyperparameters are tuned.
Learn it: Hyperparameter tuning
How does gradient descent work? Junior
Gradient descent starts with some parameters, measures the loss, and computes the gradient, which points in the direction the loss increases fastest. It then takes a small step in the opposite direction, scaled by the learning rate, and repeats until the loss stops improving.
Interviewers listen for: Gradient = direction of steepest increase; Learning rate controls the step size; Batch, stochastic and mini-batch variants.
Learn it: Gradient descent, Derivatives and slopes, The learning rate
What happens if the learning rate is too high or too low? Mid
Too high, and the steps overshoot the minimum so the loss bounces around or explodes. Too low, and training is very slow and may stall in a poor region. In practice people use a learning-rate finder, warm-up, and schedules that lower the rate over time.
Interviewers listen for: Divergence vs slow convergence; Look at the loss curve; Schedules and warm-up.
Learn it: The learning rate, Optimizers: SGD, momentum and Adam
How do you choose which algorithm to use for a new problem? Mid
Start from the problem: is it classification, regression, ranking or clustering, how much labelled data is there, and do you need an explanation? Build a simple baseline first, such as logistic regression or a gradient-boosted tree on tabular data, then try more complex models only if they beat it on validation data enough to justify the cost.
Interviewers listen for: Problem type and data size first; Always start with a baseline; Trade accuracy against speed, cost and interpretability.
Learn it: What is machine learning?, Gradient boosting
Data and features
What is data leakage? Give an example. Mid
Leakage is when information that wouldn’t be available at prediction time sneaks into training, so validation scores look great but the model fails in production. Examples: scaling with statistics from the whole dataset before splitting, using a “cancelled_at” column to predict cancellation, or random splits on time-series data so the model sees the future.
Interviewers listen for: Too-good-to-be-true scores are the warning sign; Fit preprocessing on the training split only; Split by time or by user when needed.
Learn it: Data leakage, Training and test sets
How do you handle a heavily imbalanced dataset, such as 1% fraud? Mid
First, use the right metrics: accuracy is misleading, so look at precision, recall, F1 or the precision–recall curve. Then options include class weights in the loss, resampling (undersampling the majority or oversampling the minority, for example with SMOTE), choosing the decision threshold deliberately, and anomaly-detection approaches if positives are extremely rare.
Interviewers listen for: Why accuracy fails; Class weights and resampling; Tune the threshold to the business cost.
Learn it: Precision, recall and F1, Anomaly detection, The confusion matrix
How do you deal with missing values? Junior
First understand why values are missing, because missingness can itself be informative. Options: drop rows or columns if very few or very many values are missing, impute with the mean, median or most frequent value, use model-based imputation, or add an “is missing” flag. Some models, such as gradient-boosted trees, handle missing values natively.
Interviewers listen for: Ask why the data is missing; Simple and model-based imputation; Fit the imputer on training data only.
Learn it: Data, features and labels, Data pipelines
Why and when do you need feature scaling? Junior
Models that use distances or gradients, like k-nearest neighbors, SVMs, k-means, logistic regression and neural networks, are thrown off when one feature has a much larger range than another. Standardization (mean 0, standard deviation 1) or min–max scaling puts features on a comparable scale. Tree-based models don’t need it, because they split on one feature at a time.
Interviewers listen for: Distance and gradient based models need it; Standardization vs min–max; Trees don’t care.
Learn it: Feature scaling, k-nearest neighbors
How do you encode categorical variables? Junior
One-hot encoding creates a 0/1 column per category and works well with few categories. Ordinal encoding maps ordered categories to numbers. For many categories, options include target encoding (with care to avoid leakage), hashing, or learned embeddings in neural networks.
Interviewers listen for: One-hot for low cardinality; Ordinal only when there is an order; High-cardinality options and their leakage risk.
Learn it: Data, features and labels, Word embeddings
How would you select the most useful features? Mid
Combine domain knowledge with data-driven checks: filter methods such as correlation or mutual information, wrapper methods such as recursive feature elimination, and embedded methods such as L1 regularization or tree feature importances. Validate any selection with cross-validation, and be careful that permutation importance is more reliable than impurity-based importance for correlated features.
Interviewers listen for: Filter, wrapper, embedded; L1 drives weights to zero; Validate the selection, don’t just trust the ranking.
Learn it: L1 and L2 regularization, Random forests
What is the curse of dimensionality? Mid
As the number of features grows, the space becomes so large that data points become sparse and distances between them become less meaningful. Distance-based methods like k-NN suffer, and you need far more data to cover the space. Remedies include feature selection, dimensionality reduction like PCA, and regularization.
Interviewers listen for: Sparsity and distance concentration; Effect on k-NN and clustering; PCA and feature selection.
Learn it: Principal component analysis, k-nearest neighbors
Evaluation
Explain precision and recall. When would you prioritise each? Junior
Precision is, of everything the model flagged as positive, how much was actually positive. Recall is, of all the real positives, how many the model caught. Prioritise recall when missing a case is costly, like cancer screening; prioritise precision when false alarms are costly, like blocking a legitimate payment.
Interviewers listen for: Formulas: TP/(TP+FP) and TP/(TP+FN); Tie each to a real cost; F1 is their harmonic mean.
Learn it: Precision, recall and F1, The confusion matrix
What does ROC AUC measure, and when is the precision–recall curve better? Mid
The ROC curve plots true positive rate against false positive rate across all thresholds, and AUC is the probability that a random positive gets a higher score than a random negative. With heavy class imbalance, ROC AUC can look great even when precision is poor, so the precision–recall curve and average precision are more informative.
Interviewers listen for: Threshold-independent ranking quality; AUC 0.5 = random, 1.0 = perfect; PR curve for rare positives.
Learn it: ROC curves and AUC, Precision, recall and F1
What is k-fold cross-validation and why use it? Junior
The data is split into k parts; the model trains on k−1 parts and is tested on the remaining one, rotating until every part has been the test fold. Averaging the k scores gives a more stable estimate than a single split, which matters when data is limited. Use stratified folds for classification and time-based splits for time series.
Interviewers listen for: Rotation of the test fold; Mean and spread of scores; Stratified and time-series variants.
Learn it: Cross-validation
What metrics would you use for a regression model? Junior
Mean absolute error (MAE) is the average size of the miss and is easy to explain. Root mean squared error (RMSE) punishes large errors more. R² says how much of the variance the model explains compared with predicting the mean. Pick the one that matches the cost of errors, and report it in the target’s units.
Interviewers listen for: MAE vs RMSE and outliers; R² meaning; Match the metric to the business cost.
Learn it: Loss functions, Linear regression
Why can accuracy be a misleading metric? Junior
With imbalanced classes, a model that always predicts the majority class can score very high accuracy while being useless. For 1% fraud, predicting “not fraud” every time gives 99% accuracy and catches nothing. Look at the confusion matrix, precision, recall or balanced accuracy instead.
Interviewers listen for: The always-majority baseline; Confusion matrix first; Better alternatives.
Learn it: The confusion matrix, Precision, recall and F1
How do you choose a classification threshold? Mid
The default of 0.5 is rarely right. Choose the threshold on validation data based on the cost of each kind of mistake: for example, the threshold that keeps recall above 95%, or the one that maximises expected profit. Re-check it when the class balance in production shifts.
Interviewers listen for: 0.5 is arbitrary; Use costs or a recall/precision target; Validate, then monitor.
Learn it: Precision, recall and F1, ROC curves and AUC
Your new model has better offline metrics. How do you know it’s better in production? Mid
Run an online A/B test: randomly split users between the old and new model, decide the success metric and sample size up front, and compare with a significance test or confidence interval. Offline metrics often don’t translate directly into business outcomes, and you should also watch guardrail metrics like latency and complaints.
Interviewers listen for: Randomisation and a pre-registered metric; Sample size and significance; Guardrail metrics.
Learn it: Episode 5: Real customers decide, Experiment tracking
How would you evaluate a chatbot or other LLM application? Senior
Combine several methods. Build a test set of real and tricky prompts, and score answers with human raters using clear rubrics or side-by-side preferences, checking rater agreement. Use LLM-as-judge for scale, but calibrate it against human labels. Red-team for safety, then run A/B tests with real users and keep a feedback loop.
Interviewers listen for: Human eval with rubrics or pairwise; Rater agreement such as Cohen’s kappa; LLM-as-judge calibrated against humans; Red-teaming and online tests.
Learn it: Episode 1: Launch week, Episode 3: Which version is better?, Episode 7: Too many answers to read, Episode 6: Paid to break it
Two annotators agree 85% of the time. Is that good? Senior
Not necessarily. If most items belong to one class, two raters guessing would agree often by chance. Cohen’s kappa corrects for chance agreement; a kappa around 0.6–0.8 is usually considered substantial. Low kappa means unclear guidelines or a genuinely ambiguous task, so fix the rubric before trusting the labels.
Interviewers listen for: Chance agreement; Cohen’s kappa; Fix guidelines when agreement is low.
Learn it: Episode 4: Two raters, two verdicts, Episode 2: Give it a score
Classic models
What are the assumptions of linear regression? Mid
A linear relationship between features and target, independent errors, constant error variance (homoscedasticity), normally distributed errors for valid confidence intervals, and features that aren’t strongly collinear. Prediction can still work when some assumptions bend, but inference about coefficients becomes unreliable.
Interviewers listen for: Linearity, independence, constant variance, normal errors; Multicollinearity; Prediction vs inference.
Learn it: Linear regression
How does logistic regression work, and why is it called regression? Junior
It computes a weighted sum of the features, like linear regression, then passes it through the sigmoid function to turn it into a probability between 0 and 1. It’s called regression because it regresses the log-odds of the class linearly on the features. It is trained by minimising log loss (cross-entropy).
Interviewers listen for: Linear score → sigmoid → probability; Log-odds are linear; Trained with log loss.
Learn it: Logistic regression, Sigmoid and softmax, Cross-entropy loss
What is the difference between L1 and L2 regularization? Mid
Both add a penalty on weight size to the loss. L1 (lasso) penalises the absolute values and tends to push some weights exactly to zero, which performs feature selection. L2 (ridge) penalises squared values and shrinks weights smoothly without zeroing them, which helps with correlated features. Elastic net mixes both.
Interviewers listen for: Penalty on weights; L1 gives sparsity; L2 shrinks smoothly; elastic net combines.
Learn it: L1 and L2 regularization
How does k-nearest neighbors work, and what are its weaknesses? Junior
To predict, it finds the k training points closest to the new point and takes a majority vote (or average for regression). There’s no real training step. Weaknesses: slow predictions on big datasets, sensitivity to feature scaling and irrelevant features, and poor performance in high dimensions.
Interviewers listen for: Lazy learner; Choice of k and distance; Scaling and the curse of dimensionality.
Learn it: k-nearest neighbors, Feature scaling
Why is Naive Bayes called naive, and why does it still work? Junior
It assumes every feature is independent of the others given the class, which is rarely true, for example words in an email are related. It still works well for tasks like spam filtering because it only needs to rank the classes correctly, not get exact probabilities, and it is fast and needs little data.
Interviewers listen for: Conditional independence assumption; Bayes’ rule; Good for text, fast, little data.
Learn it: Naive Bayes, Probability basics
Explain support vector machines and the kernel trick. Mid
An SVM finds the boundary with the widest margin between classes; only the closest points, the support vectors, define it. The kernel trick lets it compute similarities as if the data were mapped into a higher-dimensional space without doing the mapping, so it can learn curved boundaries, for example with an RBF kernel.
Interviewers listen for: Maximum margin; Support vectors; Kernels for non-linear boundaries; C controls softness.
Learn it: Support vector machines, Decision boundaries
What is the difference between sigmoid and softmax? Junior
Sigmoid squashes one score into a probability between 0 and 1, used for binary or multi-label problems. Softmax turns a vector of scores into probabilities that sum to 1 across all classes, used when exactly one class is correct.
Interviewers listen for: One output vs many; Sums to 1; Multi-label uses sigmoids.
Learn it: Sigmoid and softmax
What is the difference between generative and discriminative models? Senior
Discriminative models learn the boundary between classes directly, P(label | features); logistic regression and most neural classifiers are examples. Generative models learn how the data itself is produced, P(features | label) or P(features), so they can generate new samples; Naive Bayes, VAEs, GANs and diffusion models are examples.
Interviewers listen for: P(y|x) vs P(x|y) or P(x); Examples of each; Generative models can sample new data.
Learn it: Naive Bayes, Variational autoencoders, Diffusion models
Trees and ensembles
How does a decision tree decide where to split? Junior
At each node it tries candidate splits on each feature and picks the one that makes the child groups purest, measured by Gini impurity or entropy (information gain) for classification, or variance reduction for regression. It repeats until a stopping rule, such as maximum depth or minimum samples per leaf.
Interviewers listen for: Greedy search over splits; Gini or entropy; Stopping rules control overfitting.
Learn it: Decision trees, Entropy and Gini
Random forest vs gradient boosting: what’s the difference? Mid
A random forest trains many deep trees independently on bootstrapped samples with random feature subsets and averages them, which mainly reduces variance. Gradient boosting trains shallow trees one after another, each fitting the errors of the ones before, which mainly reduces bias. Boosting is often more accurate but needs more tuning and is more prone to overfitting.
Interviewers listen for: Parallel averaging vs sequential correction; Variance vs bias; Tuning: learning rate, number of trees, depth.
Learn it: Random forests, Gradient boosting, Bagging
What is bagging and why does it help? Junior
Bagging (bootstrap aggregating) trains several models on different random samples drawn with replacement, then averages their predictions. Each model makes different mistakes, so averaging cancels a lot of the noise and reduces variance, which especially helps unstable models like deep trees.
Interviewers listen for: Bootstrap samples; Averaging reduces variance; Out-of-bag evaluation.
Learn it: Bagging
Why do gradient-boosted trees often beat neural networks on tabular data? Mid
Tabular data has mixed feature types, irregular patterns and often modest size. Trees handle different scales, missing values and sharp thresholds naturally, while neural networks need careful preprocessing and lots of data to match them. Libraries like XGBoost, LightGBM and CatBoost are also very well optimised.
Interviewers listen for: Heterogeneous features and thresholds; Little preprocessing needed; Data size and tuning effort.
Learn it: Gradient boosting, Boosting
How would you explain a tree ensemble’s prediction to a business stakeholder? Senior
Use global explanations like permutation importance to show which features matter overall, and local explanations like SHAP values to show why this particular customer got this score, as “income pushed the score up, missed payments pushed it down”. Check explanations for features that act as proxies for sensitive attributes.
Interviewers listen for: Global vs local explanations; SHAP and permutation importance; Fairness and proxy features.
Learn it: Random forests, Fairness and responsible ML
Unsupervised
How does k-means work, and how do you choose k? Junior
Pick k starting centers, assign each point to its nearest center, move each center to the mean of its points, and repeat until assignments stop changing. Choose k with the elbow method on inertia, the silhouette score, or what makes sense for the business. Scale features first, and run several random starts.
Interviewers listen for: Assign then update loop; Elbow and silhouette; Assumes round, similar-sized clusters.
Learn it: k-means clustering, Feature scaling
When would you use DBSCAN instead of k-means? Mid
When clusters have irregular shapes, when you don’t know how many clusters there are, or when the data has outliers. DBSCAN groups points that are densely packed and labels isolated points as noise. It struggles when clusters have very different densities, and you have to choose eps and min_samples.
Interviewers listen for: Density-based, any shape; No k needed; finds noise; Parameter sensitivity.
Learn it: DBSCAN, k-means clustering
Explain PCA in simple terms. Mid
PCA finds new axes, called principal components, that capture as much of the data’s spread as possible: the first points along the direction of greatest variance, the second along the next greatest at a right angle, and so on. Keeping the first few compresses the data with little information lost. Scale features first, since PCA is driven by variance.
Interviewers listen for: Directions of maximum variance; Orthogonal components; explained variance; Linear only; scaling matters.
Learn it: Principal component analysis, Mean, variance and the normal curve
What are the pitfalls of reading t-SNE or UMAP plots? Senior
They preserve local neighbourhoods, not global distances, so cluster sizes and the gaps between clusters can be misleading. Results change with hyperparameters like perplexity and random seed. Use them for exploration and visual intuition, not as evidence of how many clusters exist.
Interviewers listen for: Local vs global structure; Sensitive to settings and seed; Exploration only.
Learn it: t-SNE and UMAP, Principal component analysis
How would you detect anomalies when you have no fraud labels? Mid
Model what normal looks like and flag what doesn’t fit: Isolation Forest isolates unusual points in fewer random splits, and alternatives include Local Outlier Factor, autoencoder reconstruction error, or simple statistical rules. Review a sample of flags with experts, then use their feedback to build labels for a supervised model.
Interviewers listen for: Model normal behaviour; Isolation Forest, LOF, autoencoders; Human review creates labels.
Learn it: Anomaly detection, Autoencoders
Deep learning
Explain backpropagation. Mid
After a forward pass computes the loss, backpropagation uses the chain rule to work out how much each weight contributed to that loss, layer by layer from the output back to the input. Those gradients are then used by an optimizer such as SGD or Adam to update the weights.
Interviewers listen for: Forward pass then backward pass; Chain rule; Gradients feed the optimizer.
Learn it: Backpropagation, The forward pass, Derivatives and slopes
What are vanishing and exploding gradients, and how are they fixed? Mid
In deep networks, gradients are multiplied through many layers and can shrink towards zero, so early layers stop learning, or grow huge, so training becomes unstable. Fixes include ReLU-family activations, careful initialization like He or Xavier, batch or layer normalization, residual connections, gradient clipping, and LSTMs or GRUs for sequences.
Interviewers listen for: Repeated multiplication through layers; Activations, initialization, normalization; Residual connections and clipping.
Learn it: Activation functions, Weight initialization, Batch normalization, LSTM and GRU
Why do neural networks need activation functions, and why is ReLU popular? Junior
Without non-linear activations, stacking layers is still just one linear function, so the network couldn’t learn curved patterns. ReLU, which outputs max(0, x), is cheap to compute and doesn’t saturate for positive inputs, which keeps gradients flowing. Its weakness is “dead” neurons, which variants like Leaky ReLU or GELU address.
Interviewers listen for: Non-linearity is essential; ReLU avoids saturation; Dead ReLUs and alternatives.
Learn it: Activation functions, The perceptron
How does dropout work? Junior
During training, dropout randomly switches off a fraction of neurons on each step, so the network can’t rely on any single neuron and learns more robust features. It acts like training many thinned networks and averaging them. At inference, all neurons are used and activations are scaled to match.
Interviewers listen for: Random masking during training only; Prevents co-adaptation; Scaling at inference.
Learn it: Dropout, Underfitting and overfitting
What does batch normalization do? Mid
It normalises each layer’s inputs over the mini-batch to have roughly zero mean and unit variance, then applies a learned scale and shift. This stabilises and speeds up training and allows higher learning rates. At inference it uses running averages collected during training. Transformers usually use layer normalization instead.
Interviewers listen for: Normalise per mini-batch, then scale and shift; Faster, more stable training; Train vs inference behaviour; layer norm.
Learn it: Batch normalization
Compare SGD, momentum and Adam. Mid
Plain SGD steps along the current gradient. Momentum keeps a running average of past gradients, smoothing the path and speeding up along consistent directions. Adam combines momentum with per-parameter learning rates scaled by recent gradient sizes, so it usually works well out of the box, though well-tuned SGD with momentum can generalise better on some vision tasks.
Interviewers listen for: Momentum smooths updates; Adam adapts per parameter; Trade-offs in generalisation.
Learn it: Optimizers: SGD, momentum and Adam
Why are CNNs good for images? Junior
Convolutions slide small filters across the image, so the same pattern detector is reused everywhere, which needs far fewer parameters than a fully connected layer and makes the network robust to where an object appears. Stacking layers builds features from edges to textures to object parts, and pooling adds tolerance to small shifts.
Interviewers listen for: Weight sharing and local connections; Hierarchy of features; Pooling and translation invariance.
Learn it: Convolution, Filters and feature maps, Pooling and stride
What is transfer learning and when would you use it? Mid
Start from a model pretrained on a large dataset, like ImageNet or a large text corpus, and adapt it to your task, either by training only a new head on top of frozen features or by fine-tuning some or all layers with a small learning rate. Use it whenever your labelled data is limited, which is most real projects.
Interviewers listen for: Reuse pretrained features; Feature extraction vs fine-tuning; Small learning rate; watch for overfitting.
Learn it: Transfer learning, Fine-tuning and LoRA
NLP, transformers and LLMs
Explain the attention mechanism. Mid
Each token creates a query, a key and a value. The query is compared with every key to get attention scores, which are softmaxed into weights, and the output is the weighted sum of the values. This lets each token pull in information from whichever other tokens are most relevant, regardless of distance.
Interviewers listen for: Queries, keys, values; Scaled dot product and softmax; Handles long-range dependencies.
Learn it: Attention, Queries, keys and values
Why did transformers replace RNNs for most language tasks? Mid
RNNs process tokens one at a time, which is slow to train and struggles with long-range dependencies. Transformers use self-attention to look at all tokens at once, so training parallelises across the sequence on GPUs and distant words can interact directly. The cost is attention that grows quadratically with sequence length.
Interviewers listen for: Parallelism; Direct long-range connections; Quadratic attention cost.
Learn it: The transformer block, Recurrent networks, Queries, keys and values
Why do transformers need positional encodings? Mid
Self-attention treats its input as a set, so without extra information “dog bites man” and “man bites dog” would look the same. Positional encodings add information about each token’s position, using fixed sine waves, learned position embeddings, or relative methods like rotary embeddings (RoPE).
Interviewers listen for: Attention is order-blind; Sinusoidal, learned and rotary; Effect on long contexts.
Learn it: Positional encoding
What are embeddings? Junior
Embeddings are dense vectors that represent items such as words, sentences, products or users so that similar items end up close together. They are learned from data, and they power semantic search, recommendations and clustering, and form the first layer of language models.
Interviewers listen for: Dense vectors; Similar meaning = nearby; Uses: search, recommendations, RAG.
Learn it: Word embeddings, Embeddings and vector search
What is tokenization and why use subword tokens? Junior
Tokenization splits text into the units a model reads. Whole-word vocabularies can’t handle new or rare words, and characters make sequences very long. Subword methods like BPE or WordPiece split rare words into common pieces, keeping the vocabulary manageable while still representing any text.
Interviewers listen for: Words vs characters vs subwords; BPE and WordPiece; Effects on cost and multilingual text.
Learn it: Tokenization
What is RAG, and when would you use it instead of fine-tuning? Mid
Retrieval-augmented generation finds relevant documents with search, usually vector search over embeddings, and puts them into the prompt so the LLM answers from them, ideally with citations. Use RAG when knowledge changes often or must be traceable to sources; use fine-tuning to change the model’s behaviour, style or format. They are often combined.
Interviewers listen for: Retrieve, then generate; Fresh, citable knowledge; Fine-tuning changes behaviour, not facts.
Learn it: Retrieval-augmented generation, Embeddings and vector search, Fine-tuning and LoRA
How would you reduce hallucinations in an LLM application? Senior
Ground answers in retrieved sources and ask for citations, tell the model to say when it doesn’t know, keep temperature low for factual tasks, and validate outputs with rules or a second checking step. Measure the hallucination rate on a labelled test set and with human review, and monitor it in production.
Interviewers listen for: Grounding with RAG and citations; Allow “I don’t know”; Measure with evals, not anecdotes.
Learn it: Retrieval-augmented generation, Episode 7: Too many answers to read, Episode 8: The evaluation ladder
Explain RLHF at a high level. Senior
Start with a pretrained model that has been instruction-tuned. Collect human comparisons of pairs of responses, train a reward model to predict which response people prefer, then optimise the language model to produce responses the reward model scores highly, while a penalty keeps it close to the original model. Direct preference optimisation (DPO) is a simpler alternative that skips the separate reward model.
Interviewers listen for: Pairwise human preferences; Reward model then policy optimisation; KL penalty; DPO as an alternative.
Learn it: RLHF and preference tuning, Episode 3: Which version is better?, Policy gradients
What does temperature do when sampling from a language model? Junior
Temperature rescales the model’s scores before softmax. Low temperature makes the most likely tokens even more likely, giving focused, repeatable output; high temperature flattens the distribution, giving more varied and creative but less reliable output. Top-k and top-p sampling further limit which tokens can be picked.
Interviewers listen for: Sharpens or flattens the distribution; Low for facts, higher for creativity; Top-k and top-p.
Learn it: Sigmoid and softmax, Pretraining
Production and MLOps
What is data drift vs concept drift, and how do you monitor them? Mid
Data drift is when the input distribution changes, like a new customer segment. Concept drift is when the relationship between inputs and the target changes, like fraudsters changing tactics. Monitor input feature distributions with statistics such as PSI or KS tests, track prediction distributions, and measure real performance when labels arrive. Set alerts and a retraining plan.
Interviewers listen for: Inputs change vs the relationship changes; Statistical tests and prediction monitoring; Delayed labels; retraining triggers.
Learn it: Monitoring and drift, Deploying models
How would you deploy a model safely? Mid
Package the model with its preprocessing so training and serving match, serve it behind an API or batch job, and validate inputs. Roll out gradually with shadow mode, a canary release or an A/B test, keep the previous version ready for rollback, and monitor latency, errors, input drift and business metrics.
Interviewers listen for: Same preprocessing in training and serving; Shadow, canary and rollback; Monitoring from day one.
Learn it: Deploying models, Monitoring and drift, Episode 5: Real customers decide
How do you make ML experiments reproducible? Mid
Version the code, data and environment; fix random seeds; and log every run’s parameters, metrics and artefacts with an experiment tracker such as MLflow or Weights & Biases. Use pipelines so the same steps run the same way every time, and store the exact model files that went to production.
Interviewers listen for: Version code, data and environment; Seeds and experiment tracking; Pipelines and a model registry.
Learn it: Experiment tracking, Data pipelines
What is training–serving skew and how do you prevent it? Senior
It’s when features are computed differently in training and in production, for example a different time window or a bug in the online code, so the model sees different inputs than it learned from. Prevent it by sharing one feature pipeline or a feature store, logging production features and comparing them with training data, and testing the end-to-end path.
Interviewers listen for: Different feature code paths; Feature stores and shared pipelines; Log and compare production inputs.
Learn it: Data pipelines, Monitoring and drift
How would you check a model for unfair bias? Senior
Define the groups and harms that matter, then compare metrics such as approval rate, false positive rate and false negative rate across groups, including intersections. Look for proxy features that stand in for protected attributes. Mitigate with better data, constraints during training or adjusted thresholds, document the trade-offs, and keep monitoring after launch.
Interviewers listen for: Per-group metrics, not just overall accuracy; Proxy variables; Mitigation and documentation.
Learn it: Fairness and responsible ML, The confusion matrix
Your model is accurate but too slow in production. What can you do? Senior
Measure where time goes first. Options: a smaller model or knowledge distillation, quantization and pruning, batching requests, caching frequent predictions, precomputing features or embeddings, faster serving runtimes like ONNX, and better hardware. Re-check accuracy after each change.
Interviewers listen for: Profile before optimising; Distillation, quantization, caching; Trade accuracy for speed knowingly.
Learn it: Deploying models, CNN architectures
ML system design
Design a spam detection system for an email provider. Senior
Clarify goals: catch spam while keeping false positives on real mail very low. Labels come from user “report spam” and “not spam” actions plus reviewers. Features: text (embeddings or n-grams), sender reputation, links, and sending patterns. Use a fast model with rules for known patterns, choose the threshold for a target false positive rate, monitor drift as spammers adapt, and retrain often.
Interviewers listen for: Clarify the cost of each mistake; Labels from user feedback; Adversarial drift and frequent retraining.
Learn it: Naive Bayes, Precision, recall and F1, Monitoring and drift
Design a product recommendation system. Senior
Use two stages: candidate generation (collaborative filtering or embedding similarity over millions of items, retrieved with vector search) then a ranking model (often gradient-boosted trees or a neural network) that scores a few hundred candidates using user, item and context features. Handle cold start with content features and popularity. Evaluate offline with ranking metrics, then online with A/B tests on engagement and revenue.
Interviewers listen for: Retrieval then ranking; Cold start; Offline ranking metrics and online A/B tests.
Learn it: Word embeddings, Embeddings and vector search, Episode 5: Real customers decide
Design a real-time card fraud detection system. Senior
Requirements: decisions in tens of milliseconds and very rare positives. Compute features like amount versus the user’s usual, location, merchant and velocity (transactions in the last hour) from streaming data. Combine rules with a gradient-boosted model, set thresholds by expected loss, send borderline cases to human review, and feed confirmed outcomes back as labels. Watch for drift and delayed labels.
Interviewers listen for: Latency and imbalance constraints; Real-time aggregate features; Human review loop and delayed labels.
Learn it: Anomaly detection, Gradient boosting, Monitoring and drift
Design a customer-support chatbot that answers from company documents. Senior
Use RAG: split documents into chunks, embed them into a vector index, retrieve the most relevant chunks for each question, and prompt an LLM to answer only from them with citations. Add guardrails (refuse off-topic or risky requests, hand off to a human), log conversations, and evaluate with a test set, human ratings and LLM-as-judge, then improve retrieval and prompts in a loop.
Interviewers listen for: Chunking, embeddings and retrieval; Citations and human handoff; Evaluation loop with humans and LLM judges.
Learn it: Retrieval-augmented generation, Embeddings and vector search, Episode 8: The evaluation ladder, Episode 6: Paid to break it