← All posts
Careers

Machine learning interview questions, with the answers interviewers want to hear

Forty machine learning interview questions with short answers, what a good answer must contain, and the follow-up each one invites. Fundamentals to LLMs to AI security.

Here are forty machine learning interview questions, grouped the way interviews actually run: fundamentals, classical algorithms, deep learning, NLP and LLMs, practical systems, and a few on security and safety. Each answer is short, says what a good answer has to contain, and names the follow-up you should expect. The follow-up is the point. Interviewers rarely care whether you can recite a definition. They care whether you can take the next step when they push.

How to prepare for machine learning interview questions

Read the questions once, then close the page and answer each one out loud in your own words. If you can't, that's the gap. Don't memorise the text here; an interviewer hears a memorised answer in the first sentence and pushes until it falls over.

Three habits that help more than any question bank:

  • For every concept, know one place it goes wrong in practice. "Overfitting" is a definition. "Validation looked fine because the split shared users with training" is understanding.
  • For every metric, know what it hides. Accuracy hides class imbalance. ROC-AUC hides the threshold you'll actually deploy at.
  • For every model, know one sentence on why you'd pick it over the alternative. Nobody asks "explain gradient boosting" in isolation. They ask "why not logistic regression here".

If you're earlier than this, the machine learning roadmap covers the order to learn things in.

Fundamentals

1. What is the bias-variance tradeoff?

Bias is error from a model too simple to capture the pattern; variance is error from a model so flexible it captures the noise in the sample. Raising capacity usually lowers bias and raises variance, and the job is to find where the sum is lowest on unseen data. Give one example of each: a straight line fitted to a curve is high bias, a deep tree fitted to a hundred rows is high variance.

Follow-up: "How would you tell which one you have?" Training and validation curves. High training error means bias; a large gap between the two means variance.

2. What is overfitting, and how do you detect it?

Overfitting is when a model learns the specifics of the training set, noise included, instead of the pattern that generalises. You detect it by comparing training and held-out performance: training loss keeps dropping while validation loss flattens or rises. The gap, not the absolute number, is the signal.

Follow-up: "Validation is low but production is bad. Why?" That's leakage or distribution shift, not overfitting, and they want you to say so.

3. What is regularisation, and how do L1 and L2 differ?

Regularisation adds a penalty on complexity to the loss so the optimiser prefers simpler solutions. L2 (ridge) penalises squared weights and shrinks everything smoothly towards zero. L1 (lasso) penalises absolute weights and pushes some to exactly zero, so it selects features as a side effect, because the penalty has a corner at zero and the optimum often lands on an axis.

Follow-up: "When would you prefer L1?" Many features, most probably irrelevant, or when you need a sparse model for speed or interpretability.

4. Why cross-validation instead of a single train-test split?

One split gives one estimate of generalisation error, and that estimate has its own variance, badly so on small data. K-fold trains k models on k different splits and averages, which is more stable and uses all the data for both roles. Cross-validation is for model selection and tuning; you still keep a final untouched test set.

Follow-up: "How do you cross-validate time series?" Not with random folds. Forward-chaining splits, so you never train on the future and test on the past.

5. When does accuracy lie?

Whenever the classes are imbalanced. A fraud model that predicts "not fraud" for every transaction scores very high accuracy and is useless. Report precision, recall, F1 or the precision-recall curve, and pick a threshold from the cost of each error, because a missed fraud and a wrongly blocked customer are not equally expensive.

Follow-up: "ROC-AUC or PR-AUC for a rare positive class?" PR-AUC. ROC can look fine when the negative class is huge and the false positive rate stays small in relative terms.

6. Explain precision and recall without the formulas.

Precision: of everything the model flagged, how much was right. Recall: of everything actually there, how much did it find. A spam filter with high precision rarely buries a real email; one with high recall rarely lets spam through. You trade one for the other by moving the threshold.

Follow-up: "Which matters more for cancer screening?" Recall, usually, because a miss costs more than a second test. Then they'll ask you to argue the opposite.

7. Parametric versus non-parametric models?

A parametric model has a fixed number of parameters regardless of data size: linear or logistic regression, a neural network of fixed architecture. A non-parametric model's complexity grows with the data: k-nearest neighbours, unbounded decision trees. Parametric models need less data but assume a form; non-parametric ones are flexible but overfit more easily.

Follow-up: "Is a neural network parametric?" Yes, which surprises people. The parameter count is fixed once you pick the architecture.

8. What is the curse of dimensionality?

As features grow, the volume of the space grows exponentially, so a fixed amount of data becomes sparse and distances stop meaning much. Distance-based methods like nearest neighbours degrade first. The fix is dimensionality reduction, feature selection, or a model that's less distance-sensitive.

Follow-up: "Why does PCA help?" It keeps the directions with the most variance and drops the rest, so you're back in a space where distances carry information.

Classical algorithms

9. How does linear regression work, and what does it assume?

It fits a weighted sum of inputs to minimise squared error, by closed form or gradient descent. The assumptions to name: a linear relationship, independent errors with roughly constant variance, and no severe multicollinearity. Say what breaks when one fails: non-constant error variance makes your confidence intervals wrong even when the point estimates are fine.

Follow-up: "What does multicollinearity do to the coefficients?" Makes them unstable, large and opposite-signed, while predictions can still look fine.

10. Why not use linear regression for classification?

The output is unbounded and squared error punishes confident correct predictions. Logistic regression passes the linear combination through a sigmoid so the output is a probability, and trains with log loss, which is the right loss for probabilities. It's still a linear model: the decision boundary is a straight line in feature space.

Follow-up: "More than two classes?" Softmax, or one-versus-rest.

11. How does a decision tree decide where to split?

At each node it tries every feature and threshold and picks the split that reduces impurity most: Gini or entropy for classification, variance for regression. It recurses until a stopping rule such as max depth or minimum samples per leaf. This is greedy, so the tree isn't globally optimal, and an unconstrained tree fits the training set perfectly.

Follow-up: "Why are trees unstable?" A small data change can move the top split, and everything below changes with it. That instability is exactly why ensembles of trees work.

12. Random forest versus gradient boosting?

Random forest trains many deep trees independently on bootstrapped samples with random feature subsets, then averages, which cuts variance. Gradient boosting trains shallow trees in sequence, each fitted to the residuals of the ensemble so far, which cuts bias. Forests are hard to overfit and easy to parallelise; boosting is usually more accurate but sensitive to learning rate, depth and rounds.

Follow-up: "Which first on tabular data?" Boosting (XGBoost, LightGBM, CatBoost) for accuracy; random forest when you want something that works with almost no tuning.

13. Explain an SVM in a sentence.

An SVM finds the hyperplane that separates classes with the largest margin, where the margin is the distance to the nearest points, the support vectors. The kernel trick lets it find that hyperplane in a higher-dimensional space without computing the coordinates there, which is how it draws non-linear boundaries.

Follow-up: "What does C do?" It trades margin width against misclassified training points: large C punishes errors hard and risks overfitting.

14. How does k-means work, and when does it fail?

Pick k centroids, assign each point to the nearest, move each centroid to the mean of its points, repeat until nothing changes. It minimises within-cluster squared distance, so it wants round, similar-sized clusters and fails on anything else. It also fails on poor initial centroids (k-means++ helps) and on the wrong k.

Follow-up: "How do you choose k?" Elbow on inertia, silhouette score, or, more honestly, whatever the downstream use needs. Then: "Non-spherical clusters?" DBSCAN or a Gaussian mixture.

15. Bagging versus boosting?

Bagging trains models in parallel on resampled data and averages, which mainly cuts variance. Boosting trains in sequence, each model correcting the last, which mainly cuts bias. Bagging tolerates noisy labels; boosting can chase them.

Follow-up: "Can you boost a linear model?" You can, but the sum of linear models is still linear, so there's little point.

16. What is k-nearest neighbours, and why is it rare in production?

KNN stores the training set and classifies a new point by majority vote among its k closest neighbours. No training phase, but every prediction searches the whole dataset, memory grows with data, and it suffers from the curse of dimensionality. Fine as a baseline, or with an approximate nearest-neighbour index.

Follow-up: "What if you don't scale the features?" The feature with the largest range dominates the distance and the rest barely count.

Deep learning

The neural network explanation on this site walks through this section at length from a developer's point of view.

17. Explain backpropagation in words.

A network is a chain of functions, and the loss depends on every weight along the chain. Backprop applies the chain rule from the loss backwards, layer by layer, working out how much each weight contributed to the error, reusing values cached from the forward pass. The output is a gradient per weight; the optimiser then uses it. Backprop computes gradients, it is not itself the learning algorithm.

Follow-up: "Why do gradients vanish?" Each layer multiplies the gradient by its local derivative, and if those sit below one (sigmoid's maximum slope is a quarter), the product shrinks to nothing by the early layers.

18. Why do we need non-linear activations?

Without them, stacked layers compose linear maps, and that composition is a single linear map, so the network learns no more than one layer could. ReLU is the default: cheap, doesn't saturate for positive inputs, keeps gradients flowing. Its downside is that units can "die" and output zero forever, which is why leaky ReLU and GELU exist.

Follow-up: "Why sigmoid in the output but not the hidden layers?" Output needs a probability; hidden layers need gradients that don't vanish.

19. What does batch normalisation do?

It normalises each layer's inputs across the mini-batch to zero mean and unit variance, then rescales with two learned parameters so the network can undo it if useful. In practice it permits higher learning rates, reduces sensitivity to initialisation, and regularises slightly because each example's normalisation depends on its batch-mates. Admit that the original "internal covariate shift" explanation is disputed and the empirical benefit is what matters.

Follow-up: "What changes at inference?" No batch, so you use running averages of mean and variance from training.

20. How does dropout work?

During training each unit is zeroed with probability p, so the network can't rely on any one unit and spreads the representation. At inference all units are active and outputs are scaled to compensate. One reading is that it trains an implicit ensemble of thinned networks.

Follow-up: "Where would you not use it?" The output layer, the input of a small network, and most convolutional layers that already have batch norm.

21. SGD, momentum, Adam: what's the difference?

SGD steps along the gradient of a mini-batch. Momentum keeps a running average of past gradients, smoothing noise and accelerating along consistent directions. Adam keeps per-parameter running averages of the gradient and its square, so each weight gets its own adaptive step. Adam is the safe default; SGD with momentum sometimes generalises better on vision models if you can tune it.

Follow-up: "What does the learning rate schedule do?" Shrinks the step over time so you settle into a minimum instead of bouncing around it.

22. What is a convolution, and why does weight sharing matter?

A convolutional layer slides a small filter across the input with the same weights at every position, so it detects a pattern wherever it appears. Parameter count depends on filter size, not image size, which makes the layer cheap and translation-equivariant.

Follow-up: "Why transformers for images now?" With enough data, attention learns the useful locality itself and also captures long-range structure that convolutions reach only by stacking many layers.

23. What is transfer learning, and when does it fail?

You take a model pretrained on a large general dataset and reuse its features or fine-tune it on your task; early layers learn general features that transfer. It fails when the target domain is far from the source, when you fine-tune too hard on too little data and wreck the pretrained features, or when the pretraining data contained your test set.

Follow-up: "Would you freeze the backbone?" For tiny datasets yes, then unfreeze the top layers at a low learning rate as data grows.

24. What did residual connections fix?

Deep networks pass the gradient through every layer on the way back, and it can shrink to nothing. A residual connection adds a layer's input to its output, so the layer learns only the difference and the gradient has a direct path around the multiplication. That's how depth went from tens of layers to hundreds.

Follow-up: "What else helps?" ReLU, careful initialisation, batch or layer norm, and gated units like LSTM in recurrent networks.

NLP and LLMs

The transformer post and the RAG post go deeper than I can here. Read both before any interview that mentions LLMs in the job description.

25. What is an embedding?

A dense vector representation of a discrete thing (token, sentence, product) learned so that similar things end up close in vector space, replacing a sparse one-hot encoding with something the model can do arithmetic on. Embeddings are learned, not designed, and "closeness" depends entirely on the training objective.

Follow-up: "How do you measure similarity?" Cosine, usually, because it ignores magnitude. Then: "Why might two similar sentences sit far apart?" Different objective, different domain, or one of them is just long.

26. Explain attention in plain words.

For each token, attention asks which other tokens to look at and how much. It builds a query from the current token, keys and values from all tokens, scores the query against every key, softmaxes the scores into weights, and takes a weighted sum of the values. Every token gets a context-aware representation in one parallel step. Multi-head attention runs this several times with different projections so heads can track different relationships.

Follow-up: "What's the cost?" Quadratic in sequence length, since every token scores against every other. That's why context windows were small and why efficient attention is a research field.

27. Why did transformers replace RNNs?

RNNs process tokens one at a time, so training can't be parallelised across the sequence, and early information must survive many steps to reach late positions. Transformers see the whole sequence at once, train in parallel, and connect any two positions in one step. The price is quadratic cost and the need for positional encodings, since attention alone has no sense of order.

Follow-up: "What do positional encodings do?" Inject position into each token so the model can tell "dog bites man" from "man bites dog".

28. Fine-tuning versus RAG versus prompting?

Prompting changes behaviour at zero training cost and is where you start. RAG retrieves relevant documents at query time and puts them in the prompt: right when the model needs facts it wasn't trained on, facts that change, or answers with sources. Fine-tuning changes weights and is right for style, format and task behaviour, not for injecting knowledge, which it does badly and expensively. They compose.

Follow-up: "Why not fine-tune on company documents?" The model learns the documents' style far more reliably than their content, goes stale the day they change, and you lose the ability to say where an answer came from.

29. What is hallucination, mechanically?

The model generates the most likely next token given the context, and nothing in that objective rewards truth over plausibility. When the context lacks the answer, the most plausible continuation is often a confident fabrication. Resist calling it a bug: it's the sampling objective doing its job on a question it has no grounding for.

Follow-up: "How do you reduce it?" Ground with retrieval, require citations and verify they exist, lower temperature for factual tasks, and make "I don't know" an answer the prompt actually rewards.

30. What is tokenisation, and why does it matter?

Models see tokens, not words: sub-word pieces chosen by an algorithm like byte-pair encoding so common strings get one token and rare ones get split. Context limits and cost are in tokens, and odd behaviour with numbers, code and non-English text is often tokenisation, not the model.

Follow-up: "Why can't LLMs count letters in a word?" They never see the letters, only one or two tokens for the whole word.

31. Pretraining, instruction tuning, RLHF: what does each add?

Pretraining is next-token prediction on a huge corpus, producing a model that completes text but doesn't follow instructions. Instruction tuning fine-tunes on instruction and response pairs so it answers rather than continues. RLHF, or cheaper relatives like DPO, trains on human preferences between responses, shaping tone, helpfulness and refusals. Nearly all the capability lives in pretraining; the later stages shape how it's expressed.

Follow-up: "What's the risk of preference tuning?" Sycophancy. The model learns that agreeable answers get rated higher.

32. How would you evaluate an LLM application?

Not with one accuracy number. Build a test set of real inputs with reference answers; score with exact checks where possible, rubric grading where not, and a model-as-judge spot-checked against humans. Track metrics per input category, because averages hide the one you're failing, and include adversarial inputs.

Follow-up: "Can an LLM grade an LLM?" Partly. Calibrate it against a human-labelled sample, and never let it grade its own outputs on the thing you're optimising.

Practical and systems

33. What is data leakage?

Information that wouldn't exist at prediction time gets into training, so the model scores well offline and fails live. The usual forms: a feature computed after the label was known, near-duplicate rows split across train and test, scaling fitted on the full dataset before the split, and time series split randomly. The fix is to fit every preprocessing step inside the cross-validation fold.

Follow-up: "A feature has suspiciously high importance. First check?" When it's populated. If a process that runs after the outcome fills it in, it's leaking the label.

34. What is model drift, and how do you detect it?

Drift is the gap between the training data and what the model sees now. Data drift is a change in input distribution; concept drift is a change in the relationship between inputs and target. Detect the first by monitoring feature distributions against the training baseline, the second by scoring labelled production samples, which means building a pipeline to collect labels after the fact.

Follow-up: "Labels arrive weeks late?" Use proxies meanwhile: prediction distribution shifts, confidence drops, and business metrics that track model quality.

35. How do you A/B test a model?

Randomly assign users (not requests, if users should see consistent behaviour) to current and candidate, run long enough to cover weekly cycles, and compare the business metric you care about with a proper significance test. Name the pitfalls: peeking and stopping early, dilution when most users never touch the feature, and interference when both arms share a resource.

Follow-up: "Offline metric improved, A/B test flat. Why?" The offline metric wasn't measuring what users value, or the gain is in a segment too small to move the aggregate.

36. How do you deploy a model, and what goes wrong?

Package the model with its exact preprocessing code and pinned dependencies, serve it behind an API or batch job, version the artefact so you can roll back, and monitor latency, errors and input and prediction distributions from day one. What goes wrong is rarely the model: training-serving skew, a dependency upgrade that changes numerics, and features that arrive null at serving time.

Follow-up: "Shadow or canary?" Shadow first if you can afford to run both: the new model sees real traffic without touching users, so you compare outputs before anyone is exposed.

37. How would you handle a severely imbalanced dataset?

First decide whether it's a problem: a well-calibrated model with the right threshold often needs nothing. Then, in order: change the metric and threshold, weight the loss by class, collect more minority examples, and only then resample. Synthetic oversampling invents points that may not exist; undersampling throws data away. Always evaluate on the real distribution, never the resampled one.

Follow-up: "Does SMOTE help with gradient boosting?" Usually less than class weights do, and it's easy to leak synthetic points into validation.

AI security and safety

These come up more every year, and most candidates haven't prepared. Three questions is enough to stand out.

38. What is prompt injection, and why isn't it just input validation?

Prompt injection is when text the model reads as data, such as a web page, an email or a retrieved document, contains instructions it follows as if they came from the developer or user. The term and framing are Simon Willison's: the model has no reliable boundary between instructions and data, because both are tokens in the same context. Validation doesn't fix it because any sentence can carry an instruction. The defence is architectural: limit what the model can do with the result, not what it can read. The prompt injection explainer covers the mechanism.

Follow-up: "What's the lethal trifecta?" Willison's term again: private data access, exposure to untrusted content, and a way to send data out. Remove any one and exfiltration via injection stops.

39. What is data poisoning?

An attacker influences the training data so the model behaves as the attacker wants: a backdoor that fires on a trigger input, degraded performance on a target class, a skewed recommendation. The boundary crossed is between "data we collected" and "data we verified"; web-scraped and user-contributed datasets are the exposure. Detection after the fact is hard, so the defences are provenance for training data, outlier checks on contributions, and a clean held-out evaluation set the pipeline never touches. Provenance has a cost: it slows collection and someone has to own it.

Follow-up: "Does this apply to RAG?" Directly. Poisoning the document store is far cheaper than poisoning a training run, and the effect is immediate.

40. How do you handle PII in training data?

Assume anything personal in the training set can be regurgitated, because memorisation of rare strings is real and repetition makes it likelier. So: scrub identifiers before training, record what data was used and under what consent, and test the trained model by prompting it for data it should not know. De-identification is lossy; "we removed the names" is not "there is no personal data".

Follow-up: "What about PII users paste at inference time?" That's a retention question: decide what you store, for how long, and whether prompts feed future training, and tell users. The post on what you paste into an LLM is the user's side of the same problem.

Frequently asked questions

How many of these will actually come up?

In a screening round, five to eight, tilted towards whatever the team does. A deep learning team spends longer on backprop and optimisers; an applied team on leakage, drift and deployment. The security questions are rarer but are becoming a deliberate filter for roles that touch LLM products.

Should I memorise formulas?

Know how to write the ones that define a concept: log loss, the attention equation, the L1 and L2 penalties. Nobody expects the Adam update from memory. Explaining what each term in a formula does is worth more than the formula.

What if I don't know an answer?

Say what you know, say where it stops, and reason out loud from there. "I haven't used DBSCAN, but if k-means assumes round clusters I'd want something density-based" is a good answer to a question you don't know. Bluffing is the one thing that reliably ends an interview badly.

Do I need the security questions for a non-security ML role?

If the role ships anything built on an LLM, yes, because prompt injection and PII handling are product questions now. For a quick view of what an interviewer might probe, run an LLM app you've built through the AI Audit and note which items you can't answer.

Pick the ten questions above you answered worst, write your own answer to each in a notebook, and have someone ask you the follow-ups out loud. That's the preparation that actually moves the result.

CareersAI explained
What carries over from web development, and what is newCareers

How to become an AI engineer, from a full-stack developer who is doing it

What the AI engineer job actually is, what carries over from web development, what is new, a learning order, three portfolio projects, and the security basics I wish I had known.

Real data you collected, a baseline you beat, something deployedCareers

AI/ML final year project ideas from someone who builds apps for a living

Twenty-one AI/ML final year project ideas filtered the way a hiring manager reads them: real data you collected, a baseline you beat, and something deployed.

Seven stages from Python to deployed modelsCareers

Machine learning roadmap for beginners (2027)

A seven-stage machine learning roadmap from Python to deployed models, with a free resource type per stage, a done test for each, and three portfolio projects.