Blog · Machine learning

Machine learning interview questions: how to prepare, with worked answers

Machine learning interview questions with worked answers: splits, leakage, precision and recall, baselines, gradient descent and regularisation, in Python.

Machine learning interview questions test whether you can explain a decision, work through a small example and recognise when a reported score is misleading. Most come back to a few topics: data splits, leakage, baselines, metrics, how a model is trained and one model you can explain from inputs to predictions.

Below are seven practice questions on those topics, each with a worked answer and a follow-up to practise aloud, and a short Python script that checks the arithmetic. They are original practice prompts, not questions used by any particular employer.

What to revise first

Topic What to explain without notes A practical check
Problem framing Target, unit of observation and prediction time Define what one row represents
Data splits What stays out of fitting and model selection Draw a split that matches the use case
Leakage How future or held-out information reaches training Name one tempting but unavailable input
Baselines What the model must improve upon Calculate a mean or majority prediction
Metrics Which errors matter for the decision Work through a confusion matrix
Regression How features become a number and how fitting changes coefficients Predict from a simple fitted line
Training How gradient descent and regularisation change the weights Take one gradient step by hand

Use the beginner learning order if any of these topics are unfamiliar. For the concepts, tools and practice datasets interviews draw on, see these machine learning interview questions.

Question 1: how would you split repeat-customer data?

Prompt: a dataset has several visits from each customer. You want to estimate performance for customers the model has never seen. Is a random row split sufficient?

Worked answer: it can put visits from the same customer in both training and test data. The model may benefit from repeated customer-specific patterns, making the score a poor match for the stated goal. Split by customer so a test customer has no training visits. Fit preprocessing using training data only.

If the real goal is predicting a future visit for an existing customer, you may instead need a time-based design. The right split follows the deployment question, not a rule that one split is always best. Cross-validation with groups and time shows both designs in code.

Follow-up: what if several customers share a household? Explain whether household information creates another grouping to consider and what population you want the test to represent.

Question 2: where is the leakage?

Prompt: a model predicts whether a support request will be escalated. An input column records the final escalation status. Why is that a problem?

Worked answer: the field directly contains the outcome and is not known when the prediction must be made. Exclude it and inspect other columns derived from later workflow steps. Renaming it does not change the information it carries.

Also check learned preprocessing: using the held-out set to choose feature transformations or tune thresholds allows evaluation information to influence decisions. Keep model selection separate from the final test.

Follow-up: a text field includes the phrase "escalated to specialist" in a note written after resolution. Explain why removing the explicit status column would not remove this second leak. See data leakage in machine learning for a fuller checklist.

Question 3: calculate precision and recall

Prompt: among 100 messages, 20 are urgent. A model flags 15, of which 12 are truly urgent. Calculate precision, recall and the number of missed urgent messages.

Worked answer: precision is 12 / 15 = 80%; recall is 12 / 20 = 60%; missed urgent messages number 20 - 12 = 8. There are three unnecessary flags. A system that never flags anything has 80% accuracy, so accuracy alone does not describe whether the queue is useful.

Follow-up: if urgent misses cost more than unnecessary reviews, would you immediately lower the threshold? A complete answer asks about the resulting review volume and measures the new trade-off on validation data. The preference for recall does not remove capacity constraints. ROC AUC vs PR AUC shows how each summary changes as positives become rare.

For a fully worked report table, read machine learning for non technical people.

Question 4: explain a regression baseline

Prompt: training targets are 12, 14, 16, 18 and 20. What does a mean baseline predict? What is its MAE on held-out targets 22 and 24?

Worked answer: the training mean is 16. The held-out absolute errors are 6 and 8, giving MAE 7. Computing the baseline from the test targets would use information that was meant to remain held out.

Now suppose a fitted model is prediction = 10 + 2x. It predicts 22 at x = 6 and 24 at x = 7. Its MAE on those two cases is zero. That is a result on a tiny constructed example, not a general claim about its accuracy. Run the linear regression tutorial to check the arithmetic in code.

Follow-up: why does a coefficient not prove causation? Give an example of an omitted factor that affects both an input and an outcome.

Question 5: explain overfitting without a slogan

Prompt: training error keeps falling as you increase model complexity, but validation error begins rising. What would you check?

Worked answer: compare the change across appropriate validation splits, inspect leakage and ask whether the data support the extra flexibility. Try a simpler model or regularisation, and compare against the same baseline. Do not repeatedly inspect the final test set while choosing among variants.

The explanation should connect the measured behaviour to a concrete next experiment. "The model memorised" is incomplete unless you can show what changed and how you will evaluate an alternative. Review overfitting vs underfitting for examples.

Question 6: take one gradient descent step

Prompt: a model's loss is (w - 3)² and w starts at 0. With a learning rate of 0.1, what is w after one gradient descent step? What happens with a learning rate of 1.1?

Worked answer: the gradient is 2(w - 3), which is -6 at w = 0. One step moves against the gradient: w = 0 - 0.1 × (-6) = 0.6, and the loss falls from 9 to 5.76. With a learning rate of 1.1, the step is w = 0 - 1.1 × (-6) = 6.6, which jumps past the minimum at 3, and the loss rises to 12.96. Each further step overshoots by more, so training diverges.

Follow-up: the training loss goes down for a few steps, then becomes nan. What would you check first, and why? Gradient descent learning rates runs converging and diverging rates side by side and derives where the boundary lies.

Question 7: L1 or L2 regularisation?

Prompt: what is the difference between L1 (lasso) and L2 (ridge) regularisation, and when would you choose each?

Worked answer: both add a penalty on the size of the coefficients to the training loss. L2 adds the sum of squared coefficients: it shrinks every coefficient toward zero but rarely makes one exactly zero. L1 adds the sum of absolute values: it can set some coefficients exactly to zero, which removes those features from the model. Choose L1 when you expect only a few features to matter and want a smaller model; choose L2 when many features each contribute a little. Both treat every coefficient alike, so put features on comparable scales first, and choose the penalty strength by cross-validation on the training data.

Follow-up: two features are almost identical copies of each other. What does lasso tend to do with them, and why should that make you cautious about reading its chosen features as "the important ones"?

Check your answers in Python

Interviews are mostly spoken, but checking arithmetic in code is how you catch your own mistakes while you practise. This script reproduces questions 3, 4 and 6 with scikit-learn:

from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error, precision_score, recall_score

# Question 3: 100 messages, 20 urgent; the model flags 15, of which 12 are urgent.
y_true = [1] * 20 + [0] * 80
y_pred = [1] * 12 + [0] * 8 + [1] * 3 + [0] * 77
print("precision:", precision_score(y_true, y_pred))
print("recall:", recall_score(y_true, y_pred))

# Question 4: a mean baseline, fitted on the training targets only.
baseline = DummyRegressor(strategy="mean").fit([[0]] * 5, [12, 14, 16, 18, 20])
held_out = [22, 24]
print("baseline predicts:", baseline.predict([[0]])[0])
print("baseline MAE:", mean_absolute_error(held_out, baseline.predict([[0]] * 2)))

# Question 6: one gradient descent step on loss = (w - 3) ** 2, from w = 0.
for lr in (0.1, 1.1):
    w = 0.0
    w -= lr * 2 * (w - 3)
    print(f"learning rate {lr}: w = {w:.1f}, loss = {(w - 3) ** 2:.2f}")

It prints:

precision: 0.8
recall: 0.6
baseline predicts: 16.0
baseline MAE: 7.0
learning rate 0.1: w = 0.6, loss = 5.76
learning rate 1.1: w = 6.6, loss = 12.96

DummyRegressor ignores the inputs, which is exactly what a baseline should do. Change one number in a prompt, predict the new output, then run the script to see whether you were right.

A practical revision loop

  1. Answer one prompt aloud before reading the worked answer.
  2. Write down the assumption you missed: time, grouping, units or decision cost.
  3. Run a small example and change one input while predicting the effect.
  4. Explain the new result as though another learner needs to reproduce it.
  5. Revisit the prompt later without looking at your earlier answer.

Keep a short record of errors rather than a long collection of memorised definitions. If you cannot calculate a baseline on five values, return to that calculation before adding more algorithm names.

Common questions

Should I memorise every algorithm?

No. Prioritise explaining the workflow and a few models well, then expand according to the role's stated scope. Explain your assumptions and limits when a question moves beyond what you have studied.

Do I need Python for an ML interview?

Requirements vary by role. For implementation-focused work, practise ordinary Python, tabular operations and the estimator workflow alongside theory. The Python for machine learning guide gives a focused foundation.

Are these actual company interview questions?

No. They are original learning exercises built around concepts you can verify. SchoolWhool does not claim that a particular employer uses them.

Prepare through lessons and practice

SchoolWhool's learning path connects the Python, Data Tools, Maths, Statistics and Machine Learning tracks, and every lesson ends with interview questions on what it taught. Use them to practise explanations, and the quizzes and exercises to check gaps.

For every topic in one place, see all interview questions by topic. For the tools and foundations questions that open many data science interviews, use the NumPy interview questions, the pandas interview questions, the probability interview questions and the Jupyter and Python basics interview questions.

Start with linear regression or the Statistics track, depending on which worked answers were difficult. The Machine Learning track teaches each model in order.

References

For the validation designs behind the split question, see scikit-learn's official cross-validation guide. The prompts, datasets and worked arithmetic are original practice material.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.