Learning path: Prepare for ML Engineer Interviews · Step 10 of 13
The ML Coding Round: K-Means, Logistic Regression and a Top-k Metric From Scratch
Three methods you may write from nothing against a clock: k-means (inertia 448.5 vs 1121.3 from a bad start), logistic regression (loss 0.679 to 0.316, and a climb to 21.55 with an unscaled feature) and precision at k (0.667, or 0.333 sorted the wrong way).
What you will learn
- Run any from-scratch coding question in four moves: plan, check, core, awkward case
- Use falling inertia as the check for k-means, and explain why it can converge in the wrong place
- Use falling loss as the check for logistic regression, and spot unscaled features when the loss climbs
- Check a top-k metric on a small case worked by hand
Before you start
- K-Means Clustering
- Gradient Descent Explained
- Logistic Regression and the Sigmoid
In the ML coding round you write a method from nothing while a clock runs. Three come up a lot: k-means, logistic regression with gradient descent, and a top-k metric. You've met each one before (K-Means, Gradient Descent, Logistic Regression), so this article is about what each one asks of you in the room, and where it goes wrong.
Imagine a baker whose bread machine has been taken away. Anyone can press the button, so they ask you to make it by hand: flour, water, yeast. They aren't short of bread. They want to see that you know why the dough rises, and what you'd check when it goes flat.
Four moves, every time
- Say your plan: what goes in, what comes out.
- Decide how you'll check it, before you build anything.
- Build the core loop, and keep it small.
- Try the awkward case before they ask you about it.
K-means: two moves, downhill only
K-means groups points around centres, and the whole method is two moves, repeated until nothing changes. Pseudocode:
pseudocode
pick k starting centres
repeat until no point changes centre:
assign: each point goes to its nearest centre
update: each centre moves to the mean of its points
inertia = sum of squared distances from each point to its centre
Here's your check. Neither move can push inertia up, so it only ever goes down. You can say that before you've typed a line: if my inertia goes up, I've got a bug.
Converged, in the wrong place
In a small simulation with 500 synthetic points in 5 clusters, ten random starts were tried:
Nine starts finish at an inertia of 448.5. One finishes at 1121.3, about two and a half times worse. Downhill only means it can't climb back out. On this data most starts are fine, to be honest. But the fix is worth saying: try all ten and keep the lowest, at ten times the work, and with no promise it's the best answer.
The awkward case: what if a centre ends up with no points at all? You'd be averaging nothing. Decide what happens there, and say it before they ask.
Logistic regression: predict, measure, nudge
pseudocode
repeat for a number of steps:
predict: chance = sigmoid(weights . features)
measure: loss = how wrong those chances are (log loss)
nudge: each weight takes a small step that lowers the loss
Your check is that the loss falls. In a small simulation on synthetic data it starts at 0.679 and falls through 0.434 and 0.353 to 0.316. Then the test rows, used once, give an accuracy of 0.89.
When the loss goes the wrong way
Here's what can happen in the room. In the same small simulation, the first of two features was multiplied by 1000. The loss starts at 6.08, shoots up to 21.55, and finishes at 6.08. Nothing gained. Same data, scaled, and it falls from 0.679 to 0.316 as before.
Why? Each weight's step is multiplied by its feature, so the big feature takes giant steps and overshoots, and the small one hardly gets a say. So if your loss climbs in a coding round, stay calm and look at the step size and the scale of the features first (Feature Scaling). Saying that out loud is worth marks too.
Top k: sort, take, count
The shortest of the three. For illustration, six items with scores, three of them relevant:
Sort high to low, take the top three (A, C, E), and count: two of those three are relevant, so precision at 3 is 0.667. Now sort the wrong way round, low to high, and you get the bottom three instead (F, B, D). Precision drops to 0.333.
Nothing crashes. You get a perfectly normal-looking number. So check a metric on a small case you can work out by hand, which is exactly where those six items come from. Top-k metrics in a real recommender: Recall@k and nDCG.
Follow-ups and a rubric
- How would you pick better starts?
- How do you choose k? (the elbow and silhouette)
- When do you stop the loop?
- What if two items tie in the top k?
It's fine to say: "I haven't tried that; here's how I'd test it." Then mark yourself, one point each, out of 4:
| Row | You get the point if... |
|---|---|
| Works | it runs and your check passes |
| Talk | you said your reasoning as you went |
| Check | you chose it before you built |
| Awkward case | you raised it yourself |
And practise with a clock, out loud, because being watched is the part you can't get used to in your head.
Recap
| Method | Core | Check | Where it goes wrong |
|---|---|---|---|
| K-means | Assign, update, repeat | Inertia only goes down | Settles in the wrong place; empty centre |
| Logistic regression | Predict, measure, nudge | Loss falls | Loss climbs with unscaled features |
| Top k | Sort, take, count | A case worked by hand | Wrong sort order still looks normal |
Try it yourself
Set a clock, write one of these three from nothing, and say your check out loud first.
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
The ML Engineer Interview Loop: Five Rounds, What Each One Looks For, and a Simple Rubric
The rounds you go through for one ML engineer job: recruiter screen, coding, ML depth, ML system design and behavioural. What each round looks for, the follow-up it brings, and a four-check rubric for your own answers.
The Answer Framework for Technical Interviews: Five Moves, Scored Out of 24
Good interview answers share one shape: a 30-second answer, the mechanism, the trade-off, the metric and the failure test. Worked on one question about a batch job starving everyone else, with a 24-point example rubric.
From Symptom to Pattern: How to Answer "Which Pattern Would You Use?" in an Interview
Start from what you can see, not from the pattern you know. A four-step rule (symptom, cost, metric and failure test, ship first), a symptom table, one worked answer for 429s at peak, and the trap of using a prompt as a lock.
The ML System Design Framework: Eight Steps, in Order, on a Spam Filter
One repeatable route through any ML system design question: goal, metric, data, features, model, serving, monitoring and failure. Worked on an email spam filter, with the follow-ups and a three-check rubric.