The ML interview playbook: structure, answer method, debugging procedures, estimates and project defence
- Production
- 1 h 30 min
- Lesson 3 of 3 in ML systems and interviews
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:The learning problem: generalization, bias-variance and regularizationML foundations
- Completed:Training deep networks: normalisation, regularisation, AdamW and debuggingDeep learning and transformers
- Completed:Evaluation, leakage and imbalance: validation design, metrics, thresholds and rare classesEvaluation, statistics and data
- Completed:Statistics and experimentation: intervals, tests, power, A/B tests and fair model comparisonEvaluation, statistics and data
- Completed:Data, features and production ML: preprocessing, encodings, point-in-time features, skew, drift and operationsEvaluation, statistics and data
- Completed:ML system design: framing, budgets, two-stage retrieval, serving, rollout and monitoring
You will be able to
- Describe how ML interviews are commonly structured (fundamentals, coding, system design, applied case, project, behavioural) and match each round to the method that fits it.
- Answer an open ML question with the ten-step method (clarify, assumptions, baseline, metric, data, model, evaluation, failure modes, trade-offs, monitoring) and explain a concept with the intuition, maths, code and pitfall ladder.
- Turn a model-debugging symptom (flat or NaN loss, a train-validation gap, suspected leakage, an offline and online mismatch) into an ordered first step, and say which earlier lesson fixes it.
- Do quick estimates and sanity checks (base rates, majority baseline, label-shuffle check, parameters and FLOPs) and state how uncertain a metric is with an interval.
- Defend a past project with the STAR structure, measured numbers and what you would change, avoid the common traps, and run a repeatable mock-interview routine.
Concept
The earlier lessons gave you the material: the learning problem, training deep networks, evaluation and leakage and system design. This lesson is about delivery. In this course’s judgment, an interview grades less what you know than what a listener can hear you work out in a short time, with someone free to interrupt. Knowing the answer and showing the reasoning that reaches it are different skills, and the second can be practised.
| Question | Tool in this lesson |
|---|---|
| What kinds of rounds should I expect? | A common-pattern map of six round types, each with a method |
| How do I answer an open question without freezing? | The ten-step answer method |
| How do I explain a concept so it sticks? | The ladder: intuition, maths, code, pitfall |
| The model misbehaves. What do I check first? | An ordered debugging procedure for five symptoms |
| Does this number make sense? | Base rates, baselines, a label-shuffle check, parameter and FLOP estimates |
| How sure am I? | Intervals and plain-language uncertainty |
| How do I talk about my own project? | STAR with measured numbers and what I would change |
| How do I practise? | A repeatable mock routine |
Why It Matters
A strong candidate and a weak one often know the same facts. What differs is structure. Chip Huyen, author of a free book on ML interviews, writes that interviewers “often care more about the way you go about answering than the actual objective correctness of your answers” (Huyen, 2019). That is one author’s experience, not a measurement, but it matches how the work is done: on the job nobody hands you the answer either, they want to see whether your process is safe to trust.
The same post says that almost all the companies she talked to ask at least one open-ended systems design question, and that candidates often find these the hardest. It also says the book covers the different ML roles and the skills each requires. Treat everything below as a common pattern, not a description of any named company. No company-specific claim is made in this lesson, and none of the practice questions is a verified question from a real interview.
Mental Model
Think of an interview answer as a visible chain of decisions. Each link is a choice you can defend and an interviewer can redirect. A wrong turn that you notice and fix aloud scores better than a lucky right answer you cannot explain. Silence hides the chain, a stream of facts hides it too, and a numbered structure shows it.
How ML interviews are usually structured
Loops differ by company and level, so use this as a map rather than a promise. It lists six kinds of round that appear across applied ML hiring (common industry pattern). Your recruiter’s description of the loop beats any list here.
| Round | What it tests | Method that fits | Where to practise it |
|---|---|---|---|
| ML fundamentals | Whether you understand the standard models, losses and trade-offs | The ladder: intuition, maths, code, pitfall | Learning problem, linear models, trees |
| ML coding | Turning an idea into correct code under time pressure | Clarify, simple version, test edge cases, then speed it up | The homework of this lesson |
| ML system design | End-to-end thinking under constraints | The nine-step framework from the system design lesson | That lesson |
| Applied or case | A vague business problem with data | The ten-step answer method below | This lesson |
| Project deep dive | Whether your claimed work is real and well understood | STAR with measured numbers | The project section below |
| Behavioural | How you work with people and handle mistakes | STAR, with an owner and a lesson learned | The project section below |
Two cautions. First, a real loop often mixes these inside one conversation: a coding question can turn into “how would you evaluate this?”. Second, the names vary: Huyen notes that some companies call their open-ended design questions “machine learning systems design” (Huyen, 2019). Ask the recruiter what each round covers and prepare for that.
The answer method
Open questions such as “how would you predict churn?” or “our model got worse, why?” have no single right answer. The method below gives you a path to follow so you never face a blank. It extends the nine design steps of the system design lesson to any applied question.
| Step | What you say | Why it helps |
|---|---|---|
| 1. Clarify | Who uses the output, what decision does it drive, how much data, what latency | The problem usually has hidden constraints |
| 2. State assumptions | “I will assume labels arrive within a week and errors cost more than alerts” | You are graded on reasoning and a wrong assumption is cheap to correct |
| 3. Baseline | A rule, the majority class or a linear model | Sets the bar. Google’s guide says not to be afraid to launch without ML (rule 1) and that the first model does not need to be fancy (rule 4) (Rules of ML) |
| 4. Metric | One primary metric, one guardrail, the cost of each error | “Better” has no meaning without it |
| 5. Data | Sources, labels, delay, leakage risks, split by time or group | Most failures start here |
| 6. Model | The simplest model that could meet the metric, and why | Shows judgment, not a catalogue |
| 7. Evaluation | Validation design, error analysis, confidence in the number | Separates a result from a guess |
| 8. Failure modes | Two or three ways it breaks, said before you are asked | Shows you have shipped things |
| 9. Trade-offs | What you gave up for what | Every real choice has a price |
| 10. Monitoring | What you watch after launch and what triggers a retrain | A model is a service, not a file |
Say the step number or its name aloud. It lets the interviewer jump in (“go deeper on the metric”) without derailing you. If you run low on time, say which steps you are compressing. That is a better signal than silently skipping them.
A suggested split (this course’s suggestion, not a rule) is to keep the first three or four minutes for steps 1 to 4, because a good frame makes the rest short. A candidate who jumps to a model in the first minute has to defend a choice made before the constraints were known.
When you are stuck
Restate the question in your own words. Start from the smallest case (“take two classes and one feature”). Say your assumptions. Name a baseline. Ask a clarifying question. If you cannot remember a formula, say so and derive the idea: “I do not remember the exact constant, but the shape is…”. Inventing a formula you half remember is worse than admitting the gap, because the interviewer can usually tell, and honesty about a gap is cheap to recover from (common practice).
Explain a concept: the ladder
A fundamentals question usually asks you to explain something you could recite. Reciting is the weakest answer. Climb a four-rung ladder and stop where the interviewer signals enough.
| Rung | You say | Test |
|---|---|---|
| 1. Intuition | One sentence a smart non-specialist would follow | Could a friend repeat it? |
| 2. Maths | The one formula that carries the idea, with each symbol named | Can you say what happens when a term grows? |
| 3. Code | How you would check it in a few lines, or what the library call does | Could you write it on a whiteboard? |
| 4. Pitfall | When it fails or is misread | Can you give a concrete failure? |
For example, “precision against recall”. Intuition: precision asks “of what I flagged, how much was right”, recall asks “of what was there, how much did I find”. Maths: and . Code: count four cells of a confusion matrix, which is the first homework function. Pitfall: both are undefined when a denominator is zero, and a model that never predicts positive gets recall 0 and a precision you must define by convention (the homework returns 0.0).
The pitfall rung is what separates levels. Anyone can define dropout. Saying “it is switched off at inference, and forgetting eval() mode gives noisy predictions” shows you have run it.
Debugging a model: an ordered procedure
“Your model is broken. What do you do?” is a favourite because it is open and honest. A list of ideas is a weaker answer than an order (this course’s judgment): the cheapest check that splits the possibilities in half, then the next. Karpathy’s recipe makes the point that neural net training “fails silently”, so you need checks that make failures loud (Karpathy, 2019).
The first four rows follow the rule order of first_step in the homework, so you can run it. The last two rows are the ordinary bias-or-variance reading of the learning curve, which is what first_step falls back to when no earlier rule matched.
| Symptom | First step | Why this one first | Where it is taught |
|---|---|---|---|
| Loss becomes NaN | Find the first step with a non-finite value. Check inputs and labels, then the learning rate | Bad data and a too-high learning rate are common causes, and finding the first bad step localises the cause (common practice) | Debugging a NaN loss |
| Loss flat from step 1 | Try to overfit a tiny batch. If it cannot, suspect a pipeline bug. If it can, tune the optimiser | One run splits “code is wrong” from “training is badly tuned” | A flat loss |
| A score that is too good | Audit the split and the features with three checks, each catching a different leak (next section) | Leakage is a common cause of a surprisingly large gain (common practice) | Leakage and its main forms |
| Offline metric up, A/B flat | Check the experiment itself, then compare logged serving features with training features | Cheap checks of the test and the data come before a theory about the model | Offline and online metrics disagree, training-serving skew |
| Train error low, validation error high | Confirm with a learning curve that this is variance, then add data or regularisation | The learning curve shows whether more data helps (scikit-learn) | Bias, variance and learning curves |
| Train error itself high | Treat it as bias: a bigger model, better features, longer training | Regularising a model that already underfits makes it worse | Same section |
The tiny-batch test and the first checks
Karpathy’s recipe lists, among its first steps, to verify that the loss starts at the correct value and to overfit a single batch of a few examples, possibly as few as two (Karpathy, 2019). A model that cannot memorise two examples usually has a bug rather than a tuning problem. That is the cheapest binary test in deep learning and a good opening line when asked about a loss that will not move. For a softmax classifier with classes, a uniform prediction gives a starting loss of (derived here), and Karpathy’s recipe is the source for checking the starting loss against the value you expect. A wildly different first number points at the output layer, the labels or the loss code.
Leakage and the too-good-to-be-true rule
When a score is far above what simple baselines reach, doubt it before you celebrate. Scikit-learn’s pitfalls guide says to split before any preprocessing and never to fit on test data (scikit-learn). Three quick checks help, and each catches a different kind of leak. None replaces the others.
| Check | What it catches | What it misses |
|---|---|---|
| Shuffle the labels and rerun the whole pipeline, preprocessing included | A step that uses the labels it should not: target encoding or feature selection fitted on all rows, resampling before the split. The score stays well above chance | A feature that is itself a copy of the outcome. It stops working once the labels are shuffled, so the score falls to chance |
| Count shared ids between training and validation | Group leaks: the same patient, user or document on both sides | Leaks that do not go through an id |
| Look at the top feature | Proxy features, such as a field written after the outcome | Leaks inside preprocessing, where no single feature looks suspicious |
The script runs all three on simulations. The chance baseline is an honest feature against shuffled labels, an AUC of 0.503. A proxy feature written after the outcome scores an AUC of 1.000 and falls to 0.469 on shuffled labels, so the shuffle does not expose it, but the top-feature check would. A pure-noise category encoded with its own label mean on all rows scores 0.758, and still 0.784 with shuffled labels, because the encoding re-learns whatever labels it is given. Encoded out of fold it scores 0.443, which is chance-level. The shuffle does expose that second leak. A random row split put a patient of the validation set in training for 0.950 of validation rows, against 0.000 when the split was by patient, and only the shared-id check shows this one directly.
Two splitters belong in your toolkit, and both are in the homework. Scikit-learn’s KFold splits the data into k consecutive folds without shuffling by default, and when n is not divisible by k the first n_samples % n_splits folds are one row larger (scikit-learn, KFold). For time-ordered data, TimeSeriesSplit exists because other cross-validation methods “would lead to training on future data and evaluating on past data”, and in its k-th split the training set is the first k folds (scikit-learn, TimeSeriesSplit). Knowing which splitter fits the data’s structure is a one-sentence answer to “how did you validate?”.
Offline and online disagree
An offline gain that does not show online has a short list of causes, which you check from cheap to expensive. Is the experiment itself sound (assignment, sample ratio, enough power)? Are the features at serving the same as in training? Google’s guide splits skew into three differences: training against holdout, holdout against “next-day” data, and next-day against live data. For the last, it says the same example should give exactly the same result in training and at serving, so a discrepancy probably indicates an engineering error (Rules of ML, rule 37). Its rule 29 suggests saving the features used at serving time and logging them for use in training. Is the offline metric even the one the business wants? Only after these do you suspect novelty effects or interference between users.
Estimation and sanity checks
A sanity check is a calculation you can do in your head that tells you whether a result is plausible. It takes seconds and avoids the worst mistakes.
Base rate. A test with sensitivity and false-positive rate on a population with prevalence has positive predictive value
where is the share who truly have the condition, the share of them flagged, and the share of the others flagged by mistake. Natural frequencies make it easy: with 10,000 people, 1% sick, 99% sensitivity and a 5% false-positive rate, 99 sick people test positive and 495 healthy people do too, so only 99 of 594 positives, which is 16.7%, are sick. The same arithmetic is why a fraud model that is “99% accurate” can be useless.
Majority baseline. Before praising an accuracy, compute the accuracy of always predicting the commonest class. Scikit-learn’s DummyClassifier exists as a “simple baseline to compare against other more complex classifiers” (scikit-learn). In the script, 100 frauds among 10,000 give a baseline of 0.99, so a real model at 0.992 accuracy is only 0.002 above doing nothing, and its precision and recall of 0.60 each are what tell its story.
Shuffled labels. Rerun the whole pipeline on shuffled labels. A score near chance (AUC about 0.5) is the expected result. A score well above chance means a step is using labels, such as target encoding or feature selection fitted on all rows. A leaky feature that copies the outcome is not caught this way.
Parameters and FLOPs. A dense layer with inputs and outputs has parameters, and a forward pass over a batch of costs about floating-point operations (one multiply and one add per weight, biases and activations ignored). For widths 784, 256, 128, 10 that is 235,146 parameters, which is 0.94 MB at 4 bytes each, and 469,504 operations per example. You can then say whether a model fits a device or a latency budget, and name the assumption (here, an assumed 10 GFLOP/s sustained gives about 3.0 ms for a batch of 64).
Say what you assumed and give a range, not a false decimal. “About 0.9 MB” is a better answer than “0.940584 MB”.
Communicating uncertainty and trade-offs
Every metric from a finite sample has noise. An answer that quotes “91%” as if exact invites the follow-up “how sure are you?”. Prepare a one-line reply.
For a proportion such as accuracy, a Wilson score interval is a common choice for small samples (common practice). With and for about 95%:
where is the number of correct cases and the test-set size. The statsmodels documentation lists it as one of the methods for a binomial proportion interval, next to the normal approximation (statsmodels). The script gives 182 correct out of 200 (0.910) the interval 0.862 to 0.942, and the old model’s 176 of 200 (0.880) the interval 0.828 to 0.918. They overlap heavily, so “3 points better” is not yet a claim. Intervals that do not overlap imply a difference, but some overlap does not rule one out, so the direct check is a test of the difference itself. A two-proportion z test that treats the two scores as independent gives z = 0.98 for 0.91 against 0.88 on 200 items each, well below 1.96. With ten times the data the intervals are 0.897 to 0.922 and 0.865 to 0.894, which no longer overlap, and z = 3.09. At these accuracies the script finds that z first passes 1.96 at 803 items per model.
Two cautions. The intervals and the z test above treat each model separately, but both are scored on the same test items, so the proper comparison is a paired one on the items where they disagree, which is covered in comparing models fairly. And an interval is about sampling noise only. It says nothing about leakage or a test set that does not look like production.
Sentences that carry trade-offs
Good phrasing names the price of each choice. Compare “I would use gradient boosting” with “I would start with logistic regression for a baseline, then try gradient boosting because the features are tabular and mixed, accepting more tuning and a less direct explanation”. Useful frames: “The cost of this is…”, “I would pick X unless Y”, “I am not sure, and I would find out by…”. Saying “I do not know, but here is how I would find out” is acceptable. Pretending is not.
Discussing past projects
A project deep dive checks that you did the work. The interviewer will push on one detail until they reach the edge of your knowledge, so claim only what you measured and be ready to say where your knowledge ends. A model answer is not a story you invent. It is a structure you fill with true details.
The STAR structure (Situation, Task, Action, Result) is the standard shape for behavioural questions. One university career centre suggests roughly 20% of your time on the situation, 10% on the task, 60% on your own actions and 10% on results, and says to include quantifiable results where you can (University of Washington). For ML work, add three things the generic guide does not: the baseline, the evaluation design, and what you would change.
A fill-in skeleton, to complete with your own facts:
| Part | Fill in with a true detail |
|---|---|
| Situation and task | What was the problem and what were you responsible for? |
| Data | How many rows, what label, how was it split (by time or group?), what leakage did you check? |
| Baseline | What did you compare against (a rule, the majority class, a simple model)? |
| Action | What did you try, in what order, and what did you drop? |
| Result | Which metric, on which split, what number, with what uncertainty? |
| Honest account | What failed, what is still weak, what would you do with ten times the data or a tenth of the latency? |
Be ready for “why this metric?”, “what was your baseline?”, “how did you avoid leakage?”, “what would break in production?” and “what would you do differently?” (common industry pattern for project deep dives). If you used a random row split on data with repeated users, say so and say what you would do now. Admitting a flaw you found is a strength. A flaw the interviewer finds, which you had defended, is not.
A rule worth stating plainly: never present a number you did not measure, and never imply a result came from a setting you did not use. If a figure came from a tutorial’s dataset, say it did.
Common traps
| Trap | What it looks like | Fix |
|---|---|---|
| Hand-waving | “We would just use deep learning and tune it” | Name the model, the metric and the reason |
| A metric without a baseline | “Accuracy was 92%” | “Against 89% for always predicting the commonest class” |
| Ignoring leakage | A random split on repeated users or time | Say the split design and why |
| Jumping to the model | Naming a transformer in the first minute | Frame, baseline and metric first |
| False precision | “0.9405 accuracy” on 200 examples | A rounded number with an interval |
| Reciting | Definitions with no failure case | Climb to the pitfall rung |
| Silence | Thinking for two minutes unspoken | Narrate: “I am weighing X against Y because…” |
| Bluffing a formula | Half-remembered constants | “I do not recall the exact form, here is the idea” |
| Over-claiming | Taking credit for a team’s work | Describe your own part exactly |
A practice routine
Interviewing is a skill, and skills improve with repetition and feedback. A routine of this shape is common practice, and it has three parts.
- Short daily drills. Pick five or ten questions from the practice lists below, set a 90-second timer, and answer aloud. Saying it aloud reveals gaps that reading hides.
- A weekly full mock. A suggested 45-minute split (this course’s suggestion, not a rule): 5 minutes for the introduction and one project, 12 minutes of fundamentals, 25 minutes of design or coding, 3 minutes for your questions. Record yourself or use a partner.
- Turn each miss into a one-line rule. After a mock, write one sentence for each gap: “Quote a baseline whenever I quote a metric”. Re-answer the same question cold a few days later. If you slip again, the rule is too vague.
Weight the time. Spend most of it on the rounds that your target role emphasises, and practise the weakest area first. Do not memorise answers word for word: a memorised answer breaks the first time the interviewer changes one detail.
Twelve worked answers
These are model answers in the order you would speak them, with the reason each works. Every question carries a provenance label. None is Verified company-specific, because none is tied to a named company with a source. Common industry pattern means a topic that applied ML interviews cover widely. Generated practice means written for this course. The numbers come from the script at the end of the lesson.
1. Explain bias and variance (fundamentals)
Provenance: Common industry pattern.
“Intuition: bias is how wrong a model is on average because it is too simple, variance is how much it changes when the training sample changes. For squared error, expected error splits as
where is noise nobody can remove. In practice I plot a learning curve: if training and validation error are both high and close, it is bias, and more data will not help. If training error is low and validation error is far above it, it is variance, and more data, regularisation or a simpler model help. The pitfall is that the split is exact for squared error only, and that fixing one often worsens the other.” Why it works: all four rungs, with the practical test, in under a minute. See the learning problem.
2. The training loss does not move (debugging)
Provenance: Generated practice.
“First I check the starting loss: for classes a uniform prediction gives about . Then I try to overfit a single small batch. If it cannot memorise two or three examples, I have a pipeline bug, so I check that labels line up with inputs, that the loss gets logits and not probabilities if it expects logits, that gradients reach the weights and that the optimiser step runs. If it can overfit, the pipeline works and the problem is tuning: learning rate, initialisation, normalisation. I change one thing at a time.” Why it works: one test splits two very different causes. See a flat loss.
3. The loss turns NaN after fifty steps (debugging)
Provenance: Generated practice.
“I first find the step where something first goes non-finite, before changing anything. If it was NaN at step 0, I look at the inputs and labels and at the loss code for a log of zero or an overflow in the softmax. If the loss rose for several steps before, the learning rate is too high, so I lower it, add warmup and clip gradients. If it jumped suddenly, a bad batch or a division by a zero variance is likely, so I inspect the batch that triggered it. Afterwards I confirm with the tiny-batch test.” Why it works: it is a branch, not a list. See debugging a NaN loss.
4. Training error 2%, validation error 25% (debugging)
Provenance: Common industry pattern.
“A gap of 23 points with a low training error looks like high variance, which is overfitting. Before fixing it I would check two things: that validation comes from the same distribution as training, because a shifted validation set looks like variance, and that the labels are not noisier there. Then the fixes, in order of cost: more data or augmentation, stronger regularisation or dropout, a simpler model, early stopping. If the gap appeared right after a pipeline change, I would also look for a leak or a bug.” In the script the curve check on training errors 0.30, 0.12, 0.04, 0.02 against validation errors 0.40, 0.33, 0.28, 0.25 returns high variance. Why it works: it checks the premise before prescribing.
5. “Our fraud model is 99% accurate” (evaluation)
Provenance: Common industry pattern.
“Not enough information. With 1% fraud, always predicting legitimate scores 0.99 accuracy and catches nothing, so I need the base rate and the confusion matrix. In my simulation a model at 0.992 accuracy had precision and recall of 0.60 each. I would report precision, recall and a precision-recall curve, then pick a threshold from the cost of a missed fraud against a false alarm, using a calibrated score.” Why it works: it uses a baseline, then names the right metrics. See metrics for classification.
6. Offline AUC improved but the A/B test shows no lift (evaluation)
Provenance: Common industry pattern.
“I would go from cheapest to most expensive. First the experiment: was assignment random, is the sample ratio as designed, was the test long enough to have power for the effect I expected? Second the data: do logged serving features match the training features, because skew silently erases offline gains. Third the metric: does the offline metric measure what the business metric rewards, or is the offline data biased, for example by position? Fourth the world: novelty, seasonality, or interference between users. I would not extend the test until it turns significant, since that is peeking.” Why it works: ordered by cost, and each cause names a check. See the statistics lesson.
7. Validation AUC is 0.99 on a hard task (debugging)
Provenance: Generated practice.
“I distrust it, and I run three checks that each catch a different leak. Shuffle the labels and rerun the whole pipeline: a score well above chance means a step such as target encoding is using labels, and a feature that copies the outcome would not show here. Count ids on both sides of the split, which catches the same patient in training and validation. List the top feature and ask if it could be known at prediction time, which catches proxies. In my simulation the proxy fell to chance on shuffled labels, while the target-encoded noise feature stayed well above it. The fix is a split that respects the unit, with preprocessing fitted on training data only.” Why it works: it says what each check can and cannot see. See leakage.
8. Why do we divide attention scores by the square root of d (fundamentals)
Provenance: Common industry pattern.
“Intuition: dot products grow with dimension, which pushes the softmax into a region where it is almost one-hot and gradients vanish. Maths: if the components of a query and a key are independent with mean 0 and variance 1, then the dot product has variance , so its standard deviation is , and dividing by restores unit variance (the paper’s footnote makes the same argument). Code: print the standard deviation of random dot products for two values of . Pitfall: the argument assumes the components behave like unit-variance noise, which real trained activations need not.” Why it works: each rung adds something. The variance argument is the one in a footnote of the original paper (Vaswani et al., 2017). See scaled dot-product attention.
9. Code precision, recall and F1 from two lists (coding)
Provenance: Common industry pattern.
“Let me confirm the input: two equal-length lists of 0 and 1, with 1 the positive class? What should I return when no positives are predicted? I will return 0.0 and say so. Simple version first: a loop that counts true positives, false positives and false negatives, then three divisions guarded against a zero denominator. Edge cases I would test: empty lists, no predicted positives, no actual positives, all correct, mismatched lengths. Then, if asked for speed, I would vectorise with array comparisons.” Why it works: clarify, simple, edge cases, then optimise. This is the second function of the homework.
10. Design a card-payment fraud detector (system design)
Provenance: Common industry pattern.
“First minutes only, as I would say them. Clarify: payments per second, the allowed decision time, the cost of a missed fraud against a declined good customer, how fast labels arrive (chargebacks lag by weeks). Assume a 1% fraud rate, so accuracy is meaningless and I will use precision and recall at a cost-based threshold. Baseline: a few rules, such as velocity and amount limits. Then data and labels, with a time-based split because fraud patterns drift, and I will say the failure mode early: delayed and selective labels. Then model, serving and monitoring as in the nine steps.” Why it works: it spends the opening on the frame. See the system design lesson.
11. Will a small dense network fit and how fast will it run (estimation)
Provenance: Generated practice.
“Widths 784, 256, 128, 10. Each layer has in x out weights plus out biases: 200,960, then 32,896, then 1,290, so 235,146 parameters, which is 0.94 MB in 32-bit floats. Memory is not a concern. A forward pass costs about two operations per weight, 469,504 per example. Assuming the machine sustains 10 GFLOP/s on this workload, a batch of 64 takes about 3.0 ms. The assumption is the weak part, so I would measure.” Why it works: a clear formula, stated assumptions and an offer to verify.
12. The new model scores 91% against the old one’s 88% on 200 examples (uncertainty)
Provenance: Generated practice.
“I would not call it a win yet. The 95% Wilson intervals for 182 and 176 correct out of 200 overlap a lot, and a direct test of the difference gives z = 0.98, below 1.96. Both models are scored on the same items, so I would use a paired test on the items where they disagree. More test data would help: at these accuracies the independent z test passes 1.96 at about 803 items per model. I would also confirm that the test set looks like production, and weigh the cost of switching.” Why it works: it respects uncertainty without refusing to answer. See comparing models fairly.
Code
This standard-library script produced every number in the lesson that is computed here. The first part is the helper code from homework/solution.py without docstrings. The rest runs the experiments. It has fixed seeds and runs in well under a second (Python 3.14.6, run with python3 -I). Another Python version may draw different random numbers, which moves the simulated figures (the AUCs of section 3 and the leakage fractions) slightly but not their pattern. The closed-form numbers do not depend on the version.
import math
def confusion_counts(y_true, y_pred):
if len(y_true) != len(y_pred):
raise ValueError('length mismatch')
tp = fp = fn = tn = 0
for t, p in zip(y_true, y_pred):
if t not in (0, 1) or p not in (0, 1):
raise ValueError('labels must be 0 or 1')
if p == 1 and t == 1:
tp += 1
elif p == 1:
fp += 1
elif t == 1:
fn += 1
else:
tn += 1
return (tp, fp, fn, tn)
def precision_recall_f1(y_true, y_pred):
tp, fp, fn, _ = confusion_counts(y_true, y_pred)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
return (precision, recall, f1)
def majority_baseline_accuracy(y):
if len(y) == 0:
raise ValueError('empty labels')
counts = {}
for v in y:
counts[v] = counts.get(v, 0) + 1
return max(counts.values()) / len(y)
def auc_from_scores(y_true, scores):
if len(y_true) != len(scores):
raise ValueError('length mismatch')
if any((t not in (0, 1) for t in y_true)):
raise ValueError('labels must be 0 or 1')
pos = [s for t, s in zip(y_true, scores) if t == 1]
neg = [s for t, s in zip(y_true, scores) if t == 0]
if not pos or not neg:
raise ValueError('need both classes')
wins = 0.0
for a in pos:
for b in neg:
if a > b:
wins += 1.0
elif a == b:
wins += 0.5
return wins / (len(pos) * len(neg))
def kfold_indices(n, k):
if k < 2 or k > n:
raise ValueError('need 2 <= k <= n')
base, extra = divmod(n, k)
out = []
start = 0
for i in range(k):
size = base + 1 if i < extra else base
val = list(range(start, start + size))
train = list(range(0, start)) + list(range(start + size, n))
out.append((train, val))
start += size
return out
def forward_chain_splits(n, n_splits):
if n_splits < 1:
raise ValueError('n_splits must be at least 1')
test_size = n // (n_splits + 1)
if test_size < 1:
raise ValueError('too few rows')
out = []
for i in range(n_splits):
start = n - (n_splits - i) * test_size
out.append((list(range(0, start)), list(range(start, start + test_size))))
return out
def leak_fraction(train_ids, val_ids):
if len(val_ids) == 0:
return 0.0
seen = set(train_ids)
return sum((1 for v in val_ids if v in seen)) / len(val_ids)
def diagnose_curves(train_err, val_err, target_err, gap_tol):
if len(train_err) == 0 or len(train_err) != len(val_err):
raise ValueError('need two curves of the same non-zero length')
tr, va = (train_err[-1], val_err[-1])
bias = tr > target_err
var = va - tr > gap_tol
if bias and var:
return 'high-bias-and-variance'
if bias:
return 'high-bias'
if var:
return 'high-variance'
return 'ok'
def first_step(s):
if s.get('loss_nan'):
return 'check-data-and-lr'
if s.get('loss_flat'):
tiny = s.get('overfits_tiny_batch')
if tiny is None:
return 'overfit-tiny-batch'
return 'tune-optimiser' if tiny else 'fix-pipeline-bug'
if s.get('leakage_suspected') or s.get('suspiciously_good'):
return 'audit-leakage'
if s.get('offline_online_gap'):
return 'check-experiment-then-features'
for key in ('train_err', 'val_err', 'target_err', 'gap_tol'):
if key not in s:
raise ValueError('missing ' + key)
verdict = diagnose_curves([s['train_err']], [s['val_err']], s['target_err'], s['gap_tol'])
return {'high-bias': 'fix-bias', 'high-variance': 'fix-variance', 'high-bias-and-variance': 'fix-bias-first', 'ok': 'error-analysis'}[verdict]
def ppv_from_rates(prevalence, sensitivity, fpr):
for v in (prevalence, sensitivity, fpr):
if not 0 <= v <= 1:
raise ValueError('rates must be in [0, 1]')
tp = prevalence * sensitivity
fp = (1 - prevalence) * fpr
return tp / (tp + fp) if tp + fp > 0 else 0.0
def wilson_interval(successes, n, z=1.96):
if n < 1 or successes < 0 or successes > n:
raise ValueError('bad counts')
p = successes / n
denom = 1 + z * z / n
centre = (p + z * z / (2 * n)) / denom
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
return (max(0.0, centre - half), min(1.0, centre + half))
def mlp_params(sizes):
if len(sizes) < 2 or any((s < 1 for s in sizes)):
raise ValueError('need at least two positive sizes')
return sum((a * b + b for a, b in zip(sizes[:-1], sizes[1:])))
def mlp_forward_flops(sizes, batch):
if len(sizes) < 2 or any((s < 1 for s in sizes)) or batch < 1:
raise ValueError('bad sizes or batch')
return sum((2 * batch * a * b for a, b in zip(sizes[:-1], sizes[1:])))
import random
print("== 1. Base rates: why the first number needs a denominator")
people, prevalence, sens, fpr = 10_000, 0.01, 0.99, 0.05
sick = round(people * prevalence)
tp_n = round(sick * sens)
fp_n = round((people - sick) * fpr)
print(f"of {people:,} people {sick} are sick and the test finds {tp_n}; of {people - sick:,} healthy people it flags {fp_n}")
print(f"P(sick | positive) = {tp_n} / {tp_n + fp_n} = {tp_n / (tp_n + fp_n):.4f} (ppv_from_rates {ppv_from_rates(prevalence, sens, fpr):.4f})")
print(f"alerts: per 100,000 payments {100000 * 0.001 * 0.8:.0f} real and {100000 * 0.999 * 0.03:.0f} false, real share {ppv_from_rates(0.001, 0.8, 0.03):.4f}")
y = [1] * 100 + [0] * 9_900
never = [0] * 10_000
tp, fp, fn, tn = confusion_counts(y, never)
print(f"always-legit model: accuracy {(tp + tn) / len(y):.4f} precision, recall, f1 {precision_recall_f1(y, never)} baseline {majority_baseline_accuracy(y):.4f}")
model = [1] * 60 + [0] * 40 + [1] * 40 + [0] * 9_860
tp, fp, fn, tn = confusion_counts(y, model)
print(f"a real model: tp {tp} fp {fp} fn {fn} tn {tn} accuracy {(tp + tn) / len(y):.4f} precision {precision_recall_f1(y, model)[0]:.2f} recall {precision_recall_f1(y, model)[1]:.2f} f1 {precision_recall_f1(y, model)[2]:.2f}")
print("\n== 2. How sure are you of a number?")
for k, n in ((182, 200), (176, 200), (1820, 2000), (1760, 2000)):
lo, hi = wilson_interval(k, n)
print(f"{k}/{n} = {k / n:.3f} 95% Wilson interval [{lo:.3f}, {hi:.3f}] width {hi - lo:.3f}")
def two_prop_z(p1, n1, p2, n2):
pooled = (p1 * n1 + p2 * n2) / (n1 + n2)
return (p1 - p2) / math.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2))
print(f"difference test, 0.91 against 0.88 with 200 items each: z = {two_prop_z(0.91, 200, 0.88, 200):.2f}")
print(f"difference test with 2000 items each: z = {two_prop_z(0.91, 2000, 0.88, 2000):.2f}")
n_sig = next(n for n in range(2, 100_000) if two_prop_z(0.91, n, 0.88, n) > 1.96)
print(f"smallest items per model for z above 1.96 at these accuracies: {n_sig}")
print("\n== 3. Too good to be true: three leak checks and what each catches")
rng = random.Random(5)
n = 400
labels = [rng.randint(0, 1) for _ in range(n)]
honest = [0.8 * t + rng.gauss(0, 1) for t in labels]
proxy = [t + rng.gauss(0, 0.05) for t in labels]
shuffled_labels = labels[:]
rng.shuffle(shuffled_labels)
print(f"honest feature AUC {auc_from_scores(labels, honest):.3f}")
print(f"proxy feature (written after the outcome) AUC {auc_from_scores(labels, proxy):.3f}")
print(f"chance baseline, honest feature against shuffled labels AUC {auc_from_scores(shuffled_labels, honest):.3f}")
print(f"proxy feature against shuffled labels AUC {auc_from_scores(shuffled_labels, proxy):.3f} (a proxy does not survive the shuffle)")
def target_encode(cats, ys, fit_rows, apply_rows):
total, count = {}, {}
for i in fit_rows:
total[cats[i]] = total.get(cats[i], 0) + ys[i]
count[cats[i]] = count.get(cats[i], 0) + 1
prior = sum(ys[i] for i in fit_rows) / len(fit_rows)
return [total[cats[i]] / count[cats[i]] if cats[i] in count else prior for i in apply_rows]
r2 = random.Random(9)
cats = [r2.randrange(100) for _ in range(n)]
noise_labels = [r2.randint(0, 1) for _ in range(n)]
rows = list(range(n))
leaky_te = target_encode(cats, noise_labels, rows, rows)
print(f"pure-noise category, target-encoded on all rows: AUC {auc_from_scores(noise_labels, leaky_te):.3f}")
shuf2 = noise_labels[:]
r2.shuffle(shuf2)
leaky_te_shuf = target_encode(cats, shuf2, rows, rows)
print(f"same encoding with shuffled labels: AUC {auc_from_scores(shuf2, leaky_te_shuf):.3f} (label-using preprocessing survives the shuffle)")
oof = [0.0] * n
for tr, va in kfold_indices(n, 5):
for i, v in zip(va, target_encode(cats, noise_labels, tr, va)):
oof[i] = v
print(f"same category, encoded out of fold: AUC {auc_from_scores(noise_labels, oof):.3f}")
patients = [i // 4 for i in range(n)]
rows_val = set(rng.sample(range(n), 80))
tr_ids = [patients[i] for i in range(n) if i not in rows_val]
va_ids = [patients[i] for i in range(n) if i in rows_val]
print(f"random row split: {leak_fraction(tr_ids, va_ids):.3f} of validation rows have a patient who is also in training")
val_patients = set(rng.sample(range(100), 20))
tr_ids = [p for p in patients if p not in val_patients]
va_ids = [p for p in patients if p in val_patients]
print(f"split by patient: {leak_fraction(tr_ids, va_ids):.3f}")
print("\n== 4. Split generators")
print("kfold n=10 k=3 validation folds:", [v for _, v in kfold_indices(10, 3)])
for tr, te in forward_chain_splits(12, 3):
print(f"forward chain n=12: train rows 0..{tr[-1]} test rows {te[0]}..{te[-1]}")
print("\n== 5. Debugging as a decision procedure")
print("learning-curve check:", diagnose_curves([0.30, 0.12, 0.04, 0.02], [0.40, 0.33, 0.28, 0.25], 0.05, 0.05))
cases = [
("loss is NaN after 50 steps", {"loss_nan": True}),
("loss flat, tiny batch not tried", {"loss_flat": True}),
("loss flat, tiny batch cannot overfit", {"loss_flat": True, "overfits_tiny_batch": False}),
("loss flat, tiny batch overfits", {"loss_flat": True, "overfits_tiny_batch": True}),
("validation AUC 0.99 on a hard task", {"suspiciously_good": True}),
("offline win, A/B flat", {"offline_online_gap": True}),
("train 2%, validation 25%", {"train_err": 0.02, "val_err": 0.25, "target_err": 0.05, "gap_tol": 0.05}),
("train 20%, validation 22%", {"train_err": 0.20, "val_err": 0.22, "target_err": 0.05, "gap_tol": 0.05}),
("train 20%, validation 45%", {"train_err": 0.20, "val_err": 0.45, "target_err": 0.05, "gap_tol": 0.05}),
("train 3%, validation 6%", {"train_err": 0.03, "val_err": 0.06, "target_err": 0.05, "gap_tol": 0.05}),
]
for name, s in cases:
print(f"{name:<40} -> {first_step(s)}")
print("\n== 6. Estimation")
sizes = [784, 256, 128, 10]
print(f"parameters of {sizes}: {mlp_params(sizes):,} fp32 {mlp_params(sizes) * 4 / 1e6:.2f} MB")
print(f"forward FLOPs per example {mlp_forward_flops(sizes, 1):,} batch of 64 {mlp_forward_flops(sizes, 64):,}")
print(f"at an assumed sustained 10 GFLOP/s a batch of 64 takes {mlp_forward_flops(sizes, 64) / 10e9 * 1000:.1f} ms")What to look for: section 1 (a test’s positive predictive value, and accuracy against the majority baseline), section 2 (interval width falls as the test set grows, and a direct test of the difference), section 3 (the three leak checks: which leaks the shuffle exposes and which it does not), section 4 (the split generators), section 5 (the debugging procedure applied to ten symptom sets), section 6 (parameter and FLOP estimates).
Output of the script as run for this lesson:
== 1. Base rates: why the first number needs a denominator
of 10,000 people 100 are sick and the test finds 99; of 9,900 healthy people it flags 495
P(sick | positive) = 99 / 594 = 0.1667 (ppv_from_rates 0.1667)
alerts: per 100,000 payments 80 real and 2997 false, real share 0.0260
always-legit model: accuracy 0.9900 precision, recall, f1 (0.0, 0.0, 0.0) baseline 0.9900
a real model: tp 60 fp 40 fn 40 tn 9860 accuracy 0.9920 precision 0.60 recall 0.60 f1 0.60
== 2. How sure are you of a number?
182/200 = 0.910 95% Wilson interval [0.862, 0.942] width 0.080
176/200 = 0.880 95% Wilson interval [0.828, 0.918] width 0.090
1820/2000 = 0.910 95% Wilson interval [0.897, 0.922] width 0.025
1760/2000 = 0.880 95% Wilson interval [0.865, 0.894] width 0.028
difference test, 0.91 against 0.88 with 200 items each: z = 0.98
difference test with 2000 items each: z = 3.09
smallest items per model for z above 1.96 at these accuracies: 803
== 3. Too good to be true: three leak checks and what each catches
honest feature AUC 0.718
proxy feature (written after the outcome) AUC 1.000
chance baseline, honest feature against shuffled labels AUC 0.503
proxy feature against shuffled labels AUC 0.469 (a proxy does not survive the shuffle)
pure-noise category, target-encoded on all rows: AUC 0.758
same encoding with shuffled labels: AUC 0.784 (label-using preprocessing survives the shuffle)
same category, encoded out of fold: AUC 0.443
random row split: 0.950 of validation rows have a patient who is also in training
split by patient: 0.000
== 4. Split generators
kfold n=10 k=3 validation folds: [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]
forward chain n=12: train rows 0..2 test rows 3..5
forward chain n=12: train rows 0..5 test rows 6..8
forward chain n=12: train rows 0..8 test rows 9..11
== 5. Debugging as a decision procedure
learning-curve check: high-variance
loss is NaN after 50 steps -> check-data-and-lr
loss flat, tiny batch not tried -> overfit-tiny-batch
loss flat, tiny batch cannot overfit -> fix-pipeline-bug
loss flat, tiny batch overfits -> tune-optimiser
validation AUC 0.99 on a hard task -> audit-leakage
offline win, A/B flat -> check-experiment-then-features
train 2%, validation 25% -> fix-variance
train 20%, validation 22% -> fix-bias
train 20%, validation 45% -> fix-bias-first
train 3%, validation 6% -> error-analysis
== 6. Estimation
parameters of [784, 256, 128, 10]: 235,146 fp32 0.94 MB
forward FLOPs per example 469,504 batch of 64 30,048,256
at an assumed sustained 10 GFLOP/s a batch of 64 takes 3.0 msReal-World Application
On the job the playbook becomes a habit. Before presenting a number, name its baseline and its uncertainty. Before trusting a good score, run the shuffled-label check and count shared ids. Before debugging a training run, overfit a tiny batch. Before a design review, write assumptions at the top of the document. Teams that do these things find problems in the notebook that others find in production (common practice).
Interview Perspective
Expect fundamentals questions that start short and get deeper, a coding question on a metric or a model from scratch, a design or case question that tests structure, “tell me about a project”, and “what went wrong?”. A strong answer clarifies first, states assumptions, names a baseline and a metric, says the failure mode before being asked, and gives numbers with their uncertainty. A weak answer names a model and stops, or recites a definition.
Provenance: Common industry pattern. Only two points rest on a source: Huyen (2019) reports that almost all the companies she talked to ask at least one open-ended ML systems design question, and that interviewers often care more about how you answer than about the objective correctness of the answer. The list of formats and the description of strong and weak answers are this course’s judgment of widely seen patterns for applied ML roles. It is not a verified description of any named company’s process.
Practice Questions
- Basic (Common industry pattern): Explain regularisation with the ladder: intuition, maths, code and pitfall.
- Basic (Generated practice): Your training loss starts at 2.30 for a 10-class problem and never moves. Say whether the starting value is plausible, and what you check next.
- Basic (Generated practice): A classifier scores 97% accuracy. What three things do you ask before you call that good?
- Intermediate (Common industry pattern): A model’s validation error is far above its training error. Walk through your diagnosis and the fixes in order of cost.
- Intermediate (Generated practice): Your validation AUC is 0.98 on a task where a simple baseline gets 0.70. List three checks and what each would show.
- Intermediate (Common industry pattern): An offline metric improved and the A/B test did not move. List four explanations and how you would tell them apart.
- Intermediate (Generated practice): A test has 1% prevalence, 90% sensitivity and a 10% false-positive rate. What fraction of positives are true? Show it with natural frequencies.
- Advanced (Common industry pattern): Describe a project you shipped. Cover the baseline, the split, the metric, what failed and what you would change.
- Advanced (Generated practice): A colleague reports an accuracy of 91% on 200 test examples against 88% for the old model. How do you respond, and what would change your mind?
- Advanced (Common industry pattern): Run the ten-step answer method on “predict which customers will cancel next month”.
- Product-Company (Generated practice): You have a 45-minute round, with 5 minutes for introductions and 3 for your questions. Plan how you would split the rest for an applied ML case.
Activity
Run the script, then change four things. In section 1, change the prevalence to 0.001 and predict, before running, whether the positive predictive value rises or falls. In section 2, find the number of items per model at which the difference test between 91% and 88% accuracy first becomes significant (z above 1.96). Predict it from the formula for z, check it against the script’s last line of section 2, then change the accuracies to 92% and 88% and find the new value. In section 3, change the noise of the proxy feature from 0.05 to 1.0 and watch its AUC fall, then say what that tells you about how obvious a leak is. In section 6, change the widths to 784, 512, 512, 10 and recompute the parameters and the forward FLOPs for a batch of 64.
Then record yourself answering worked question 6 aloud in under two minutes, without notes. Listen back and count the steps you named.
Homework
Build the interview sanity-check toolkit with the standard library only: the confusion counts and precision, recall and F1, the majority-baseline accuracy, AUC from scores, a k-fold index generator, a forward-chaining splitter for time data, a leakage fraction, a curve diagnosis, a decision function that returns the first debugging step for a set of symptoms, a base-rate calculator, a Wilson interval, and parameter and FLOP counters for dense networks. The code is in homework/; run the tests until they pass.
Quick Revision
- Interviews, as a common pattern, mix fundamentals, coding, system design, applied cases, project deep dives and behavioural rounds. Match the method to the round and ask the recruiter what each covers.
- The answer method: clarify, assume, baseline, metric, data, model, evaluation, failure modes, trade-offs, monitoring. Say the steps aloud. Baseline and metric come before the model.
- Explain a concept on a ladder: intuition, maths, code, pitfall. The pitfall rung shows experience.
- Debug in an order. NaN loss: find the first non-finite step. Flat loss: overfit a tiny batch. Gap: read the learning curve. Too good: shuffle labels (catches label-using preprocessing), count shared ids (group leaks), check the top feature (proxies). Offline up and online flat: check the experiment, then serving features.
- Sanity checks: base rate (1% prevalence, 99% sensitivity, 5% false-positive rate gives 0.1667), majority baseline (0.9900 against a model at 0.9920), chance baseline on shuffled labels (0.503), parameters (235,146) and FLOPs (469,504 per example).
- Uncertainty: 182 of 200 gives 0.862 to 0.942 and 176 of 200 gives 0.828 to 0.918, so they overlap, and the difference test gives z = 0.98. With ten times the data the intervals do not overlap (0.897 to 0.922 and 0.865 to 0.894). Compare models with a paired test.
- Projects: STAR with a baseline, an evaluation design and what you would change. Claim only what you measured.
- Traps: hand-waving, a metric without a baseline, ignoring leakage, false precision, bluffing a formula.
- Practice: daily 90-second drills, a weekly 45-minute mock (a suggested split), one-line rules from each miss.
Check yourself
- Walk-through: Without notes, answer “your model’s validation AUC is 0.99” in two minutes, naming the three checks and what each shows.
- Variation: The same symptom, but the model is a large language model fine-tune and the data is text. Say which checks carry over and which need a new version.
- Common misconception: “A good answer is the one that names the best model”, “a bigger accuracy gain is always a real gain”, and “a project story should hide what failed”.
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Common pitfalls and recommended practices (data leakage) (opens in a new tab)
The standard checklist for leakage in a scikit-learn workflow.
Validation curves: plotting scores to evaluate models (opens in a new tab)
How to read learning curves for bias and variance.
proportion_confint (opens in a new tab)
The interval methods for a proportion, for when you need to put a range on an accuracy.
Further reading
Update on Machine Learning Interviews Book (opens in a new tab)Essential
A practitioner's account of what ML interviews look like and what interviewers look for, with a pointer to a free book of questions.
A Recipe for Training Neural Networks (opens in a new tab)Essential
The best short guide to debugging neural network training in a sensible order.
Rules of Machine Learning: Best Practices for ML Engineering (opens in a new tab)
Practical rules on baselines, metrics and skew that make good talking points in design and case rounds.
STAR Method of Interviewing (opens in a new tab)
A short guide to the STAR structure for project and behavioural answers.
More for this module: ML systems and interviews resources
Practice
Test what you just read. Quizzes and cards are grouped by module: ML systems and interviews.
Check yourself16 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.