Interactive course · about 5 hours

Introduction to Machine Learning

A machine that learns sounds like something out of a film. The first working example is a straight line and a number that says how wrong the line is. You will place the dots yourself, drag the line yourself, and then hand the dragging over and watch the machine do it better than you did. By the end you will have grown a tree, lit up a small network of neurons, and caught a model cheating. You will also know which parts of the word learning are earned and which parts are borrowed.

Everything here is worked out live

No curve on this page was drawn in advance. When you place dots and press a button, the numbers you see were computed from those dots a moment earlier, and if you place different dots you get different numbers. The models really do train, on your data, in front of you. That includes the ones that fail, which are the interesting ones.

What you need to start

Arithmetic, fractions and percentages. The idea that a letter can stand for a number. No programming, no statistics, and no course before this one. People usually explain learning with calculus. There is none here: where a slope is needed, we measure one by nudging a number and seeing how much the error moves.

The steps

Step 1

Fit a line to dots you place, and count how wrong it is

Here is a grid. Each dot on it is one thing that was measured twice. Say a shop counted, on many different days, how warm it was and how many cold drinks it sold. Warmth goes across, drinks sold go up, and one dot is one day.

Now the question that all of this is about. Somebody asks how many drinks to expect on a warm day that nobody has measured yet. There is no dot for that day. What you can do is draw a straight line that runs through the middle of the dots you do have, find the warmth you were asked about, and read the answer off the line.

Two numbers describe any straight line. How steeply it climbs is its slope, and where it sits when you are at zero across is its height. These are the model's two adjustable numbers. A number the training procedure may change is called a weight. Fitting this line means choosing its slope and height to reduce the measured error.

What do you keep calling data, and what is a model?

Data is measurements that have already happened. Every dot is one measurement, and nothing about it is in doubt. Data is the past, written down.

A model is a rule short enough to write down that answers questions the data never asked. The line is a model: two numbers long, and it will give you an answer for any warmth at all, including warmths nobody has ever seen. That is the trade. Data is trustworthy and silent about anything it does not cover. A model always answers, and can be wrong.

Lab 1 · Your dots, your line
Try this firstDrag either of the two round handles on the line, and watch the row of numbers under the grid. Seven days are already plotted for you. A red stick runs from every dot to the line, and the pill marked loss changes as you drag. Then click anywhere on the grid to add days of your own, or press Clear the dots and place all of them yourself.
The number is doing the judging, not your eye. The stick from a dot to the line is how much that dot is missed by. Each miss is multiplied by itself, all of those are added up, and the total is divided by how many dots there are. That answer is called the loss. Training changes the model weights to reduce it. Dividing at the end means the number does not grow just because you placed more dots. Try to beat your own best by hand, then notice how hard it is to tell whether a small drag helped.
How do I read a slope off the widget?

A slope of 2 climbs 2 for every 1 you move to the right. A slope of 0.5 climbs half a step for every whole step across, so it looks gentle. A slope of 0 is flat, and the line answers the same number for every warmth. A negative slope goes downhill, which for this data would mean fewer drinks on warmer days.

The height is easier to spot: it is where the line crosses the left-hand edge, at zero across. Drag one handle and both numbers change, because tilting the line about one end moves the other end too. Drag both handles the same distance in the same direction and the height moves while the slope stays put. To store this model you do not keep the dots, you keep the two numbers.

Why multiply each miss by itself instead of just adding the misses up?

Because misses come in two directions. A dot above the line is missed by a positive amount and a dot below it by a negative amount, so adding the raw misses lets them cancel out. A terrible line with half the dots far above and half far below would score zero, which is nonsense. Multiplying a number by itself always gives something positive, so nothing can cancel.

It also decides what counts as bad. Multiplied by itself, a miss of 10 costs 100 while a miss of 1 costs 1. So one big miss costs more than ten small ones, and a line that fits everything roughly will beat a line that nails most dots and abandons one. Whether that is what you want is a real choice, and Step 11 is about the trouble it can cause.

Lab 2 · Which line is less wrong?
Try this firstThree lines are drawn over the same dots. Decide which one you would call the best fit and press its button. Then press Count it up, and the loss for all three appears so you can see whether your eye agreed with the counting.
Your eye is good, but it is not a number. Most people pick the right line here. What your eye cannot do is tell you the difference between two lines that are both nearly right, and that is exactly the judgement the machine has to make thousands of times in Step 2. Turning "that looks bad" into one number is what makes the rest possible.
Line A misses one dot by 10 and fits every other dot exactly. Line B misses ten dots by 1 each and fits the rest exactly. Which line has the smaller loss?
Line B, by a factor of ten. Line A's single miss of 10 costs 10 times 10, which is 100. Line B's ten misses of 1 each cost 1, so 10 in total. The raw misses do add up to 10 both ways, which is why the tie looks tempting, and it is also why the loss is not built from raw misses. Squaring is a decision about which failures you mind most, not a formality.
Step 2

Let the machine do the dragging

Dragging by hand got you a decent line. It also showed you the problem: after the first few drags you cannot tell whether a small move helped, so you stop. A machine has no eye at all, and it does not need one. It has the loss and one further idea.

The idea is a question you can ask about any single number in the model: if I nudge this a little, does the loss go up or down, and by how much? You can answer that by doing it. Nudge, measure, compare. That answer has a name, the slope of the loss, and measuring it is all the next lab does.

What is a slope, and how do you measure one?

A slope answers how steeply one thing changes when another changes. On a hill it is metres climbed per metre walked. Here it is loss gained per unit of weight added. To measure it you need two readings and a subtraction: change the weight by a small amount, see how much the loss moved, and divide the change in loss by the change in weight.

So a slope of minus 4 means: for every 1 you add to this weight, the loss drops by about 4. Negative says the loss falls when the weight rises, so raise it. Positive says the opposite. Zero says you are at the bottom and nothing local will help. Textbooks work slopes out with calculus instead of measuring them, which is faster and gives the same answer. Measuring is doing the same thing with arithmetic.

Lab 3 · Measure a slope by nudging
Try this firstPress Nudge the slope up. A row appears with the loss before, the loss after, the difference between them, and that difference divided by the size of the nudge. Press it a few more times and watch the last column shrink towards zero.
Read the last two columns together. While the answer is negative, adding to the weight lowers the loss. When it turns positive you have stepped past the bottom. When it is near zero you are at the bottom and no small change in that weight helps. The final column repeats each measurement with a nudge of 0.001 instead. Far from the bottom the two columns agree, so a rough nudge is good enough. Close to the bottom they come apart, because a long jump measures the average steepness across the jump and the hill curves along the way. That is why the nudge has to be small.

Knowing which way is downhill still does not say how far to go. So every round the machine multiplies each measured slope by one fixed number of its own, and moves the weight that far. That fixed number is the learning rate, and it is the step size. Nothing measures it and nothing works it out for you. Somebody picks it. Picking it badly is the fastest way to ruin a model that would have trained perfectly well.

What is the learning rate, and why is there one at all?

Knowing which way to move does not tell you how far. The slope says "downhill is that way", and it says nothing reliable about how long the hill stays that way. So a size has to be chosen. That size is the learning rate. Each round, every weight moves by the slope multiplied by the learning rate, in the downhill direction.

Small rate, small careful steps, slow but safe. Large rate, big strides, fast until it is not. Too large and each step flies past the bottom and lands further up the far side, so the next step is bigger still and the whole thing runs away. That is not a bug in the method. It is the method being handed a number that does not suit the problem, and it is the single most common thing to go wrong in real work.

Lab 4 · Let it roll, then break it
Try this firstLeave the learning rate at 0.02 and press Run. The line swings into place on its own and the loss curve on the right drops. Then set the rate to 0.6, press Reset, and press Run again to watch it come apart. Each run stops on its own, either at the bottom or when the numbers run away.
Same data, same method, one number different. Nothing about the model or the dots changed between the run that worked and the run that exploded. Only the step size did. When the numbers run away, the widget stops and says so rather than showing you a blank grid, which is more than most real tools will do for you. This whole procedure is called gradient descent, and almost every model you will hear about is trained by some version of it.
Could we not just work out the best line directly?

For a straight line, yes. There is a formula that takes the dots and hands back the best possible slope and height in one go, with no stepping and no rate to choose. Fitting a line is a solved problem and has been since the early 1800s. If your task really is a line, use the formula.

The reason to learn the slow way is that the formula stops existing almost immediately. The tiny network in Step 9 has no such shortcut, and neither does anything larger. Rolling downhill is the method that keeps working when the model gets complicated, which is why it is the one worth understanding on something simple enough to watch. Safe to skip: nothing later depends on this note.

Someone trains a model, sees the loss get worse every single round instead of better, and concludes the data is unlearnable. What is the more likely explanation?
The rate is too big. A loss that rises steadily, often doubling, is the signature of steps that overshoot. Each step lands further up the far side than the last one started. So the next slope is steeper and the next step is longer. A sign error would also climb, but it climbs smoothly towards a ceiling rather than running away. The first thing to try is dividing the rate by ten.
Step 3

More than one input

One input across, one answer up. Real questions are rarely that tidy. The price of a flat depends on its floor area and on how old it is, and probably on ten other things. A model with several inputs needs one weight for each of them, plus the height, and it adds up the results.

Each thing you measure and feed in is called a feature. So the model becomes: multiply the area by its weight, multiply the age by its weight, add both, then add the height. One number comes out. Nothing new has been invented, there are simply more knobs.

Feature, input, column: are those all the same thing?

Near enough, yes. If you wrote your data as a table with one row per flat, then each column is a feature: area, age, floor number, distance to the station. The thing you are trying to predict gets its own column and is not a feature. It is called the target, or when it is a yes-or-no answer, the label.

Choosing which features to measure is the part of this work that machines are worst at and people are best at. A weak model on well-chosen features usually beats a strong model on careless ones, and Step 5 is a whole step built on that fact.

Lab 5 · Three knobs, by hand
Try this firstDrag the top slider, the weight on floor area, up and down slowly. The loss under it moves, and the bars redraw. Get the loss as low as you can with all three sliders, then press Let the machine finish it and see how close you got.
Three knobs are much harder than one. With one weight you can feel which way is downhill. With three, lowering the loss by moving one often means another needs moving too, and by hand you go round in circles. The machine does not mind. It measures the slope for every weight separately in the same round, then moves all of them at once.
Why is there no picture of this model?

Because there is nowhere to draw it. One input and one answer make a flat picture with dots and a line. Two inputs and one answer would need a solid picture with a tilted sheet floating in it, which is already awkward on a screen. Three inputs needs a direction that does not exist.

So past two features, pictures stop being the tool and numbers take over. That is why this lab shows you bars for the weights and one loss number instead of a scatter. Getting comfortable reading a model you cannot see is not a loss of understanding. It is most of the job, since real models have hundreds of features.

Lab 6 · The same data in different units
Try this firstPress Run, with age in years and the features as measured. It uses up its 900 rounds and is still nowhere near the bottom, which is what crawling looks like. Now press age in days, then Reset, then Run: identical facts, and this time it runs away in a single round. Then press Rescale both features and rate 0.05, Reset, and Run again.
The facts did not change, only the units did. A flat that is nine years old is 3287 days old, and both are true. But the weight on a number around 3000 has to be about a thousand times smaller than the weight on a number around 9. So the loss slopes down very gently in one direction and very steeply in another, and one learning rate cannot suit both. Pressing rescale both features squeezes every feature to a similar size first, which is the standard fix and takes one line of real code.
What does rescaling actually do to the numbers?

It works out the average of a feature and how spread out it is, then rewrites every value as how many spreads it sits away from that average. Floor areas that ran from about 30 to about 120 come out running from roughly minus one and a half to plus one and a half. Ages do the same. Both features now live on the same scale, so one step size suits both.

Nothing about the flats changed. A flat that was the third largest is still the third largest, and the ordering and the spacing are untouched. What changed is the size of the numbers the model is handed and the weights come out correspondingly bigger or smaller to compensate. If you want the weights back in pounds per square metre afterwards, you undo the same arithmetic.

A model predicting house prices has features measured in square metres, in years, and in pounds. Training is very slow and jitters. What is the most likely cause?
The features are on different scales. A step big enough to move the weight on years is far too big for the weight on pounds, so that one overshoots while the other crawls. Rescaling every feature to a similar range fixes it, and it is the first thing to try when training limps. The size of the target is not the problem, and three features is nothing at all.
Step 4

Yes or no: drag a boundary

So far the answer has been a quantity. Often the answer you want is a decision. Is this email junk. Is this photo a cat. Did this patient recover. Instead of a number, each dot now carries one of two labels, and the two labels are drawn as two different shapes here so you never have to rely on colour.

Predicting a label is called classification, and each possible label is a class. The model is still a line, used differently. The arithmetic is the same as Step 3: multiply each measurement by its weight, add them up, add the height, and one number comes out. That number is called the score, and its sign says which side of the line the dot fell on. A line that keeps the circles on one side and the squares on the other is a good model, and squashing the score to between 0 and 1 turns it into something you can read as a probability.

Class, label, and what a classifier is

A class is one of the answers allowed. In this lab there are two, and they are drawn as circles and squares. A label is the true answer attached to one particular dot, which somebody had to find out and write down. Labelled data is expensive: somebody read the email and said junk or not junk. A model that predicts labels is called a classifier.

This step uses two classes, so one boundary is enough. A multiclass classifier can produce one score per class and select the largest, or combine several binary decisions. Later courses cover those designs.

Lab 7 · Drag the line that separates them
Try this firstDrag either handle on the boundary until the counts underneath say you have everything right. Every dot on the wrong side is ringed. You can also pick a class and click the grid to add awkward dots of your own.
Accuracy is a fraction, and it is a blunt one. The count of correct dots out of all dots is the first thing anyone measures, and Step 11 shows how badly it can mislead. Try adding one square deep inside the circles. No straight line can fix that, and no amount of dragging will. What the model does then is the interesting question, and Step 5 answers it.
How does a line turn into a yes or a no?

The same arithmetic as Step 3, one step further. Multiply each feature by its weight, add them up, add the height. Call the result the score. Dots on one side of the line give a positive score, dots on the other give a negative one, and dots exactly on the line score zero. So the line is not really the model; the model is the score, and the line is where the score happens to be zero.

A raw score is awkward to talk about, because it can be 0.3 or 400 and neither means much on its own. So the score gets squashed into a number between 0 and 1 by a fixed rule. Large positive scores come out near 1 and large negative ones near 0, and a score of zero comes out at exactly one half. That squashed number is read as a probability and the next lab shows it.

What does an answer of 0.7 actually mean?

It means the model is on the circle side of the fence but not far from it. If the score is well calibrated, then among many dots scored near 0.7, about seven in ten are circles. Test calibration by grouping held-out dots with similar scores and comparing each group's mean score with its observed rate.

It does not mean the model has thought about it, and it does not mean there is a seven in ten chance for this particular dot, which either is or is not a circle. Nor does the number know whether the dot is anything like the data the model was trained on. That last gap is where Step 11 lives.

Lab 8 · Let it learn the boundary
Try this firstPress Run and watch the boundary swing round by itself. The background shading shows what the model would answer for every point on the grid, and the probe dot you can drag reports the model's squashed answer for wherever you put it.
Same method, different loss. The rolling downhill is exactly Step 2. What changed is the number being pushed down. Instead of squared misses it counts how confidently wrong each answer was. A dot on the wrong side and far from the line hurts a great deal. A dot barely on the wrong side hurts hardly at all. Drag the probe from one corner to the other and watch the reported number slide from near 0 to near 1, passing one half exactly on the fence.
A classifier reports 0.99 for a dot. Which statement is safe to make?
It says where the dot sits relative to this model's boundary. That is all the arithmetic supports. The number can be read as a rate over many similar dots, but only for dots like the training data, which is the missing condition in the third option. And a confident number can be flatly wrong, as the first option assumes it cannot be. Step 11 is built out of exactly this mistake.
Step 5

Look at the same dots differently

Some data has no line that separates it, and no amount of learning will conjure one up. The next lab gives you a ring of squares with a blob of circles inside it. Drag the boundary anywhere you like. Any straight line cuts through both groups, so it will always get a large share of the dots wrong.

You could reach for a bendier model. There is a cheaper move first, and it is one of the most useful ideas in the subject: change what you measure.

What does adding a feature actually mean?

It means working out a new number from the ones you already have, and handing that to the model as well. Say each dot has an across value and an up value. You can work out how far it sits from the middle of the grid, and hand the model that distance as a third thing to look at. No new measurement was taken. The distance was always implied by the two numbers; the model simply could not see it, because a model that multiplies and adds cannot work out a distance.

This is called feature engineering, and for most of the history of this subject it was where the skill lived. Somebody who understood the problem invented the right thing to measure, and then a simple model was enough.

Lab 9 · A ring no straight line can cut
Try this firstDrag the boundary handles and try to get above 80 percent correct. You will not manage it. Then press Try ten thousand lines, which really does test that many, each one both ways round, and reports the best score any straight line can reach here.
That was not you failing. The search tried ten thousand different lines and the best of them was still poor, so the ceiling belongs to the model and not to your dragging. Knowing the difference between "I have not found the answer" and "this shape of model cannot express the answer" saves an enormous amount of wasted effort.
Lab 10 · Measure the distance instead
Try this firstPress Add distance from the middle. The dots jump to a new grid where distance from the middle runs up the side. The boundary is a flat line now, and it starts too high, so drag it down until the counts say every dot is right. Then press Show it back on the first grid.
A straight cut in the new picture is a circle in the old one. Nothing was added to the data and nothing was learned that the dots did not already contain. The model is still a line, still doing nothing but multiplying and adding. What changed is what it was shown. The lesson generalises: when a model cannot express what you need, changing the features is often cheaper and more reliable than changing the model.
Did the dots move, or did I move?

Neither, strictly. Every dot has the same two measurements it started with. The second grid is a picture of a third number computed from them, so the same dot appears in a different place because it is being plotted against something different. Think of photographing a crowd from the side rather than from above: nobody moved, and now you can see who is tall.

That is why the circle appears when you map the answer back. The model's rule, in the new picture, is "distance from the middle is less than about four". Written back in the original two numbers, that sentence describes a circle. Same rule, two languages.

Does this trick have a name?

Several. Computing new features and handing them over is a feature map. There is a family of methods called kernel methods that get the effect of an enormous pile of extra features without ever computing them. That was the state of the art for years and is still worth knowing about.

And there is the other answer, which is Step 9. Instead of inventing the useful features yourself, you build a model with a layer whose job is to invent features, and let it discover the distance idea on its own. That is what the word deep in deep learning refers to. Safe to skip: later steps do not depend on the names.

A model has to spot fraudulent card payments. The data holds the amount and the time of each payment, and no straight rule works. Which extra feature is most likely to help?
Distance from that cardholder's usual amount. It is worked out from data you already hold, and it says something the raw columns cannot: unusual for this person. The other two options are the same column again in different clothes. A model that multiplies and adds gets nothing from either, exactly as multiplying the distances in Lab 10 by ten would have changed nothing. A useful feature carries something the model could not have worked out for itself.
Step 6

Memorising is not learning

If bendy models beat straight ones, why not use the bendiest model available? The next lab lets you. Instead of a straight line, it fits a curve, and a slider controls how many wiggles the curve is allowed. Push the slider up and the loss on the dots falls, and keeps falling, every single notch, until the curve is passing so close to the twelve dots that the misses barely register.

Zero loss sounds like a triumph. Look at what the curve is doing to get it. Every real measurement carries some amount of randomness that has nothing to do with the pattern, called noise, and a curve with enough freedom will chase that as eagerly as it chases the pattern.

What is noise, and how do you know it is there?

Noise is the part of a measurement that has nothing to do with what you are trying to predict. The shop sold three extra drinks on Tuesday because a coach party stopped. Warmth did not cause that, and nothing about warmth will ever predict it. Real measurements always carry some, from rounding, from mistakes, from a hundred causes nobody recorded.

You cannot see which part of a single dot is noise, which is precisely the difficulty. What you can see is that it does not repeat: a pattern caused by noise in these dots will not appear in the next batch, while a real pattern will. That is the whole basis of every honest test in this course, and Step 7 turns it into a procedure.

Lab 11 · Turn up the wiggle
Try this firstDrag the wiggle slider from 1 up to 9, one notch at a time. The curve is refitted at every notch, and the loss pill under the buttons falls each time. Then press Same pattern, fresh noise and watch what the high-wiggle curve does with a new batch.
The wiggly curve is not describing the pattern, it is reciting the dots. Press the fresh-noise button a few times with the slider at 1 and then at 9. At 1 the line barely moves, because it is tracking something that is really there. At 9 the curve thrashes about completely differently each time, because it is tracking accidents. A model that changes its mind when the noise changes has learned the noise.
What is a wiggly curve, and what does the number mean?

A straight line is built from one multiply: the input times its weight, plus a height. Allow the input multiplied by itself as a second feature and the model can bend once, into an arch or a bowl. Allow it multiplied by itself again and it can bend twice, and so on. The slider is choosing how many of those extra features to hand over. That count is the curve's degree.

So a wiggly curve is not a new kind of model. It is the linear model from Step 3, given features that were computed from the one input by multiplying it by itself repeatedly. All the machinery is the same, which is why the slider can go up without anything else changing. Weights are what buy the bending: a curve of degree 9 has ten of them, and ten weights aimed at ten dots can be made to pass exactly through every one. The lab gives it twelve dots and stops the slider at nine, so it never quite gets to thread them all. It gets close enough to make the point, and the point is that being able to is not a virtue.

Lab 12 · Hide some dots before you start
Try this firstPress Hide a third of the dots, then walk the wiggle slider up from 1. The hidden dots become hollow rings and are kept out of the fitting. Two losses are reported: one on the dots the curve saw, one on the dots it did not.
Two numbers, and they disagree on purpose. The loss on the dots it fitted falls forever, because more wiggles can always chase more dots. The loss on the hidden dots falls at first, because early wiggles are picking up real shape, and then climbs, because later ones are chasing noise that the hidden dots do not share. The lowest point of that second number is the model you actually want. Chasing noise like this is called overfitting, and its opposite, a model too stiff to follow the real shape, is underfitting. Press Find the best wiggle and it searches every setting and reports the winner.
Why does the wiggly curve shoot off the screen just past the last dot?

Because nothing was holding it down out there. The fitting only cares about the loss on the dots it was given, so beyond the last dot the curve is free to do whatever the weights happen to imply, and at nine wiggles those weights are large and fighting each other. One step past the data the fight stops cancelling out.

Answering a question inside the range of your data is called interpolating; answering one outside it is extrapolating, and it is far less safe. A straight line at least goes somewhere sensible out there. A high-wiggle curve can predict a shop selling minus four hundred drinks. Safe to skip: nothing later depends on the words.

A student reports a model with zero error on all the data it was given. What should you conclude?
Nothing yet, and ask what was held back. Zero error on data a model was fitted to is easy: give it enough wiggles and it will thread every dot, noise and all. The number says how well it memorised, not how well it will do next Tuesday. The only figure worth quoting comes from dots the model never saw during fitting, which is what the next step is about.
Step 7

Three piles, and why three

Holding data back works. Step 6 used two piles: dots the model fitted, called the training set, and dots kept aside, called the test set. Then Lab 12 did something that quietly spoiled it. Look again at what Find the best wiggle did: it tried every setting and picked the one that scored best on the held-back dots.

Once you choose a setting by looking at the test score, the test score is no longer a fair test. You fitted to it. Not with weights, with a choice, and a choice is still fitting.

So three piles are needed rather than two. The training set sets the weights. A second pile, the validation set, is the one you look at while making choices, as often as you like. The test set is opened once, at the very end, to report a number.

What makes a test fair in the first place?

A test tells you something only if the answers were not available while you were preparing. That is why exams are not handed out in advance. The same reasoning applies here, and the thing being tested is the weights and every decision that went into the model, including which wiggle setting you chose and how many things you tried.

So the question to ask about any reported score is simple. Was any of this data used, in any way, to make any decision about this model? If yes, the score is optimistic, and usually by more than people expect.

Lab 13 · Choosing with the test set, and paying for it
Try this firstPress Pick the best wiggle using the test pile. It reports a fine-looking score. Then press A fresh batch arrives, which draws new dots from the very same pattern, and compare the two numbers.
The drop between those two numbers is the size of the lie. Nothing cheated and nothing was faked. The setting was chosen because it happened to suit the particular noise in the test pile, so the score it earned there was partly luck, and luck does not travel. Now press A fresh batch arrives several times over. Each press really is a new batch, and the gap jumps about: sometimes large, sometimes small, occasionally the wrong way round with the fresh dots scoring better. That is the trap. On any single batch the flattery is invisible, so you cannot catch it by looking once, which is what Run it 40 times and average is for.
So what is the middle pile for, exactly?

Three jobs, three piles. The training set sets the weights. The validation set is what you look at while making choices: how many wiggles, which features, which learning rate. You may look at it as often as you like, and its score will slowly become flattering for exactly the reason Lab 13 shows. The test set is opened once, at the end, to report a number.

That is the whole rule. Choose on validation, report on test, and if you go back and change the model after seeing the test number, then you have used it for choosing and it is now a validation set. Real teams cheat at this constantly and mostly by accident.

Lab 14 · Three piles, done properly
Try this firstPress Split into three piles, then use the wiggle slider while watching the middle number only. When you like it, press Open the test pile. You get one look, and the widget will remind you of that if you go back and fiddle.
The test number is usually a little worse than the validation number, and that is normal. You chose the setting that suited validation, so validation flatters slightly. A test score far below validation means too many things were tried, or the piles are not alike, or the split was not random. The widget counts how many settings you looked at and tells you, because that count is the honest measure of how much flattery to expect.
What if I do not have enough data for three piles?

Then you reuse it carefully. Cut the training data into five equal parts, fit five times, each time holding out a different part and scoring on it, and average the five scores. Every dot gets used for fitting four times and for scoring once, and you get a steadier estimate than any single small pile would give. This is cross-validation. It is what most careful small-data work does.

The test pile stays out of it either way. Cross-validation replaces the validation pile, not the test pile. Safe to skip: nothing later needs it.

A team tries 200 different models, reports the best test score of the 200, and calls it the expected performance. What is wrong?
Choosing the winner by test score is using the test set. With 200 attempts, one will suit that pile's noise by chance, and it is the one that gets reported. The fix is to compare the 200 on validation, then take the single winner to the test pile once. A small test pile makes the problem worse but is not the fault, and comparing many models is fine as long as you do not compare them on the pile you will quote.
Step 8

A tree built by splitting

Every model so far has been a weighted sum. Here is a different shape entirely, and it is the one people find easiest to read. Ask a question with a yes-or-no answer, such as whether the across value is less than 5. That divides the dots into two groups. Then ask another question inside each group, and keep going.

The result is a set of nested questions called a decision tree, and it does not multiply anything by anything. It just asks. Each question is a node, and each place where the questions stop and an answer is given is a leaf. The skill is in choosing which question to ask and the way to choose is to try them all and measure.

Why is this called a tree?

Because of its shape when you draw it. One question sits at the top. Its two answers lead to two more questions, each of those to two more, and the thing spreads out downwards like a family tree. Each question is a node. A place where the questions stop and an answer is given is a leaf.

To use the tree on a new dot you start at the top, answer each question with the dot's own numbers, and follow that branch until you reach a leaf. The leaf's answer is the prediction. That is the whole of it, and it is why a tree can be explained to somebody who does not want to hear about weights.

Lab 15 · Pick the cut
Try this firstDrag the dashed cut line left and right. The two mixedness numbers under the grid update as it moves. Get them both as low as you can, then press Try every cut, which really does test every position and reports the best one.
Low mixedness means one side is nearly all one class. The number shown is the chance that two dots picked at random from that side disagree with each other, so 0 means completely pure and 0.5 means an even mix. Trying every cut and keeping the best is a plain algorithm: a recipe with no cleverness in it, that always finishes and always gives the same answer for the same dots.
How can mixedness be a number?

Pick two dots at random from a group and ask whether their labels differ. If the group is all circles, they never differ, so the chance is 0. If it is half circles and half squares, the chance is one half. If it is nine circles to one square, they differ rarely, so the chance is low again. That single number captures how mixed a group is, and a tree tries to make it small on both sides of every cut.

The same idea is used with a different bit of arithmetic under the name entropy, and the two mostly agree about which cut is best. Whichever you use, the point is that "this cut looks tidier" has been turned into a number a machine can compare, which is the same move that made Step 1 possible.

Lab 16 · Grow the tree
Try this firstSet the depth slider to 1 and press Grow. One question, two boxes, and the tree written out underneath. Then raise it one notch at a time and watch both accuracy numbers, the one on training dots and the one on held-back dots.
You have met this shape before. Training accuracy climbs to a perfect 100 percent, held-back accuracy peaks a notch or two before that and then sags. Watch how the perfect score gets bought. The deeper cuts stop carving out useful regions. Instead they carve private little boxes, each one built to hold a single awkward dot that disagrees with its neighbours. Those odd dots are the noise, and a box drawn round one of them is memorising. That is Step 6 wearing a different costume. Overfitting is not a property of curves. It is what happens whenever a model has enough freedom to describe the noise.
Why are the regions always boxes with square corners?

Because every question the tree is allowed to ask is about one measurement on its own: is across less than 3.4, is up less than 7.1. A question like that draws one straight line parallel to an edge of the grid, so every region it can produce is a box with corners at right angles.

That is a real limit. A boundary running diagonally has to be approximated by a staircase of boxes, and the tree needs many questions to build one. The straight boundary from Step 4 draws that diagonal with three weights. Neither shape of model is better; they are bad at different things, which is the reason for having more than one.

A tree grown to full depth gets every training dot right and does poorly on new data. What is the sensible fix?
Limit the depth, and choose the limit on validation. Full depth means one dot per leaf, which is a lookup table of the training set rather than a rule. Cutting the tree short forces each leaf to cover several dots, so it can only describe patterns that several dots share. More features and more depth both give it more freedom, which is the opposite of what is needed here.
Step 9

A tiny network that lights up

Step 5 needed somebody to notice that distance from the middle was the useful thing to measure. That somebody was you. A neural network is a model built so that the useful features get invented by the training instead.

The part it is built from is a neuron, and you have already built one. Multiply each input by a weight, add them up, add one extra number, then squash the result to between 0 and 1. That is the classifier from Step 4 with a new name. The extra number added before squashing is traditionally called the neuron's bias. It is the same thing Step 1 called the height. A row of neurons is a layer and the neurons sitting between the inputs and the final answer are called hidden, because nothing outside the network ever reads what they say.

Is a neuron anything like a brain cell?

Barely. The name comes from a 1940s guess about brain cells: something adds up its incoming signals and fires if the total is large enough. That much is a fair sketch of a real neuron and it inspired the arithmetic. The resemblance stops there. A real brain cell is a living thing with chemistry and timing and structure, and nothing in this widget has any of it.

Take the word as a label for a small piece of arithmetic, the way a computer's memory is not the kind you have. Reading more into the name is where most of the overclaiming about these systems starts.

Lab 17 · One neuron, three knobs
Try this firstDrag the first weight slider from one end to the other. The line on the grid swings round as you do. Then drag the bias slider and watch the same line slide across without turning.
The two weights aim the line and the bias slides it. The neuron's output for the probe dot is printed and its circle fills in proportion, so a bright neuron means a number near 1. One neuron gives you one straight fence, exactly as in Step 4, so the ring data from Step 5 is still out of reach. The next lab is what changes that.
Why does the squashing matter?

Because without it a stack of neurons collapses. Feed the output of one weighted sum into another weighted sum and the result is still a weighted sum of the original inputs, so a hundred layers would have exactly the power of one. Something that is not a straight multiply has to happen in between, and squashing is the cheapest thing that qualifies.

Squashing also makes each neuron behave like a soft decision rather than a dial. Well away from its line the output sits near 0 or near 1 and stops responding, which is what lets one neuron in a layer specialise in one region and ignore everything else. That specialising is what you can watch happen in the next lab.

Lab 18 · Four neurons, and the ring falls
Try this firstPress Run and leave it for a few seconds. The shaded background starts as a straight fence and bends into a closed shape. The four hidden neurons fill and empty as they specialise, and each one's own line is drawn faintly on the grid.
Four straight fences, combined, make a curved one. Look at the four faint lines when it has settled: they usually end up boxing the inner blob in from four sides. The output neuron then learns a rule like "inside all four". Nobody told it to do that, and nobody told it to measure distance from the middle. It found something that works, which is the appeal, and it is also why explaining what one of these has learned is so hard. Press Reset and Run again. Reset deals the seventeen weights a fresh set of random starting values. From there the four neurons usually settle into a different arrangement that boxes the blob in just as well. There is no single right answer for it to find.
Is this what people mean by deep learning?

It is the same machinery, at a size you can watch. One layer of four neurons is shallow. Stack ten or a hundred layers and each one gets to build features out of the features the layer below invented, which is where the word deep comes from. The arithmetic in each neuron does not change at all.

Two things do change with size. The slopes are worked out by a bookkeeping trick rather than by nudging every weight one at a time, because a network with a billion weights would need two billion measurements per round. And the inputs stop being two numbers on a grid and become the brightness of every point in a picture, or one number per word. Safe to skip: nothing later needs it.

Why can a network of neurons separate the ring when a single neuron cannot?
The squashing is what makes combining worthwhile. Several straight fences, each squashed into a soft yes-or-no, can be added up into a rule like "inside all four", which is a closed shape. Without the squashing the whole stack would flatten back into one straight fence no matter how many neurons you used. Every neuron does see the whole grid, and more weights alone would only buy overfitting.
Step 10

Bias in, bias out

A model fitted to past decisions predicts past decisions. If those decisions were unfair, the model learns the unfairness, and it now has the manner of arithmetic, which people find harder to argue with than a person.

This step works one example all the way through. Forty past job applicants, each with a test score and a number of years of experience, each marked hired or not by whoever was doing the hiring at the time. Every number in the lab is computed from that table, which you can read in full.

Careful: bias means two different things here

In Step 9, bias was the plain number a neuron adds before squashing. It carries no opinion about anything. That is the technical sense, and it is unfortunate.

In this step, bias means systematic unfairness towards a group of people. Same word, unrelated meaning, and both are standard. When you read about a model's bias you have to work out from context which one is meant, and people sometimes get that wrong in public.

Lab 19 · Learn from the old decisions
Try this firstPress Read the table, then press Train. The model reaches a high accuracy against the old decisions. Then look at the two acceptance-rate bars underneath, which count what it does to each group.
It is accurate and it is unfair, at the same time. Accuracy here measures agreement with the old decisions, and the old decisions had a gap in them, so a model that reproduces the gap scores well. Nothing malfunctioned. The model did exactly what it was asked, which was to predict this label from these features, and nobody asked it whether the label deserved predicting.
What is a proxy?

A feature that stands in for something you did not measure, or did not want to use. If applicants from one area mostly belong to one group, then the area column carries group information whether you wanted it to or not. Postcode, school, name, the hour someone submits a form: all of these have served as proxies in real systems.

This is why deleting the sensitive column is weaker than it sounds. The model is searching for anything that predicts the label, and a proxy predicts the label for exactly the reason you were worried about. The next lab does the deletion and then measures what is left.

Lab 20 · Delete the column and measure again
Try this firstPress Hide the group column and then Train. The model can no longer see which group anyone is in. Read the gap between the two acceptance bars, and compare it with the gap you saw in Lab 19.
Blindness is not fairness. With the group column gone the model leans on the area column, which happens to line up with the group, and a large slice of the gap survives. Read the two gap numbers rather than trusting the word. Deleting the column shrinks the gap a long way without closing it. What is left is still a double-figure difference in who gets accepted. A column that stands in for one you took away is called a proxy. Now try the third option, which drops the area column as well. The gap all but disappears, and the accuracy against the old decisions drops too. Some of what made those decisions predictable was the unfairness in them. That trade is real, it is a decision for people rather than for arithmetic, and pretending it does not exist is the most common failure in this area.
So what do people actually do about it?

Several things, none of them a cure. Measure outcomes for each group and publish them, which at least makes the gap visible. Rebalance or reweight the training data so the model is not rewarded for copying the gap. Predict something less tainted where you can: whether somebody did the job well, rather than whether somebody was hired. Keep a person in the loop for decisions that matter, with the model's reasoning shown.

And several definitions of fairness exist that cannot all hold at once, which is a proved result and not a shortage of effort. So part of the work is choosing which one you mean, in public, before you build. Safe to skip: no later step depends on this.

A team removes gender from their data and states that their model cannot be biased by gender. What is the flaw?
Proxies. A model hunting for anything that predicts the label will happily use columns that happen to line up with gender. The effect on the people applying is the same as if it had been handed gender directly. The only way to know is to measure outcomes per group after training, which requires keeping the sensitive column for measurement even when you keep it out of the model.
Step 11

Confidently wrong

Two failures are left, and they are the ones that fool people rather than models. The first is a number that looks excellent and means nothing. The second is a model reporting near-certainty about something it has no business having an opinion on.

Start with the first. Out of a thousand people, ten have a rare illness. Here is a model: answer healthy, always, for everybody. It never looks at anything. Work out its accuracy before you press anything.

What accuracy counts, and what it quietly ignores

Accuracy is the number it got right divided by the number it was asked. That treats every mistake as equally bad, which is almost never true. Telling a healthy person they are ill costs them a worrying week. Telling an ill person they are healthy can cost them far more than that.

Accuracy also gets easier as the thing you are looking for gets rarer, which is backwards. When only one in a hundred cases is the interesting one, ignoring the problem entirely scores 99 percent. Any time you see a high accuracy on a rare event, the first question is what the always-say-no model would have scored.

One more word before the lab. A classifier hands back a number between 0 and 1, but an action is not a number: somebody either gets called back for a test or they do not. So a line has to be drawn, and anybody scoring above it is flagged. That line is the threshold. Moving it changes nothing about the model and everything about who gets caught, which is why it is a separate control on the next lab.

Lab 21 · The model that scores 99 percent and catches nobody
Try this firstPress Score the always-healthy model. Its accuracy appears next to a table counting the four possible outcomes. Then press Train a real one and move the threshold slider to see what it costs to catch more of the ill.
Two numbers say what accuracy hides. Of the people it flagged, what fraction were really ill: that is precision. Of the people who were really ill, what fraction did it flag: that is recall. The always-healthy model has no precision at all, since it flagged nobody, and zero recall. Its accuracy still beats the trained model at every threshold low enough to catch most of the ill. Drag the threshold and watch the two trade off against each other, because they always do, and choosing where to sit is a decision about consequences.
Precision and recall, in words that stick

Imagine fishing with a net. Precision asks: of everything you pulled up, how much was fish and not old boots. Recall asks: of all the fish in the lake, how many did you get. A tiny net in one perfect spot has high precision and terrible recall. Dragging the whole lake has perfect recall and dreadful precision.

You cannot have both at once, and the threshold slider is where you choose. Screening for a treatable illness wants recall, because a missed case is the expensive one. A system that deletes suspected junk mail wants precision, because deleting a real letter is the expensive one. The arithmetic will not choose for you.

Where does the threshold come from, and why is one half not special?

The model hands back a number between 0 and 1. Turning that into an action needs a line in the sand: flag anybody above this number. One half looks natural because it is the middle, and that is the only thing recommending it. Nothing about the arithmetic makes it the right place to stand.

The right place depends on the two costs. If missing an ill person is a hundred times worse than alarming a healthy one, the line belongs far below one half, and the slider shows exactly what that trade buys and what it costs. Choosing it deliberately, and writing down why, is a decision people often forget they are making.

Lab 22 · Far from anything it has ever seen
Try this firstPress Train the model, which has to come first because there is no model to ask until you do. Shading appears. Then drag the orange probe out into an empty corner, or press Send the probe to the far corner. Its answer and its distance to the nearest training dot are printed side by side: watch the distance grow while the answer stays just as certain.
Confidence is a report about the boundary, not about the evidence. The squashed score says how far you are from the fence and on which side. Nothing in that arithmetic knows whether anybody has ever measured a dot anywhere near you, so it cannot get less sure as it leaves the data behind. Distance to the training data is a separate warning signal. Check it before accepting a high model score, especially when the new input may lie outside the measured region.
A model that spots a rare machine fault reports 99.4 percent accuracy. Faults occur in about 1 case in 200. What should you ask first?
Ask what the do-nothing model scores. One fault in 200 means always saying no fault is right 199 times out of 200, which is 99.5 percent, so the clever model is doing worse than nothing. Without that comparison the figure is unreadable. Checking which pile it was measured on is a good question too, and it is the second one to ask, since here the number is uninformative even if the split was faultless.
Step 12

A project ladder

Back to the question on the cover. Can a machine really learn, or is it fancy averaging? Fancy averaging is closer, and it is not an insult. Every model here found a pattern that held across many measurements and used it to answer a question about a measurement it had never seen. That is a real and useful thing. It also involved no understanding, no goals, and no idea that the dots meant anything at all.

What you have now is a set of habits, and the last lab is somewhere to keep using them.

Where would I get data of my own?

Start with data you generate, because you will understand it. Your own step count or sleep hours by day. Match results for a team you follow. How long your walk to school takes against the weather. Twenty rows recorded by hand in a spreadsheet is enough to fit a line and to hold six rows back.

After that, public collections. Governments publish weather, transport and census figures. Sports and chess sites publish results. Several sites host thousands of small tables specifically for practice. The first honest question about any of them is who measured this and what did they leave out, and it is worth more than any model choice.

What are the words I will meet, for the things I have already built?

Rolling downhill is gradient descent, and one full pass over the training data is an epoch. A setting you choose rather than fit, like the learning rate or the number of wiggles, is a hyperparameter. The do-nothing model is a baseline. Doing well on data you have never seen is generalisation, and failing at it because you memorised is overfitting.

Predicting a quantity is regression; predicting a label is classification. The squashing rule from Step 4 is called the logistic, or sigmoid, curve, and that whole model is logistic regression. None of these are new ideas. They are the names for what you have already made work, and knowing them is what lets you read anything else on the subject.

Lab 23 · The playground
Try this firstIt opens on the two clean groups from Step 4, so press Learn straight away to see the straight boundary appear. Then press Clear and build something of your own: click the grid to place dots, using the class buttons to choose which shape you are placing. Nothing here is marked and nothing is checked. Switch models on the same dots to see which shapes each one can and cannot make.
Things worth trying. Put a small island of one class inside the other and see which models cope. Place two clean groups, hold data back, and grow the tree to full depth to watch held-back accuracy fall while training accuracy rises. Put one stray dot far from its group and see how much each model bends to accommodate it. Every number is computed from your dots, so a surprising result is a real result and worth chasing.
How do I know when a model is good enough?

Not by the loss, which has no natural scale, and not by comparison with the best model in the world. By comparison with two things: what the do-nothing answer scores, and what the decision actually needs. A weather model that beats "same as yesterday" is doing something. One that does not is a waste of electricity however impressive its inner workings.

Then ask what a mistake costs, and whether the model's mistakes are the affordable kind. A model with lower accuracy that fails safely often beats a sharper one that fails in the expensive direction.

Lab 24 · Pick your first project
Try this firstPress Check my plan before you tick anything, and read what it refuses. Then work back up: three projects for the first rung are already listed, the first of them open, and Open this one shows the other two. Pick one, tick the checklist honestly, and press Check my plan again.
The checklist is the point, not the project. Every rung uses something built in this course. Every one can also be done badly in the same three ways: no held-back data, a number quoted from the wrong pile, and no comparison against doing nothing. If you can only do one thing from this course from memory, make it the split before the fit.
You finish a project, and your validation accuracy is 88 percent while your test accuracy is 81 percent. Which number goes in the write-up?
Quote 81 percent, and say how many things you tried. The validation number is partly a reward for suiting that pile, since it is the pile you chose on. Averaging the two invents a quantity that measures nothing. Saying how many settings were compared lets a reader judge how much flattery to suspect, and reporting the gap honestly is more convincing than reporting the higher figure.
How this changes with foundation models

A foundation model begins with a large model trained on broad data, then adapts it to a narrower task by prompting it, retrieving relevant examples, training a small adapter, or changing more of its weights. This saves work when a useful representation has already been learned, but it does not remove the rules in this course.

You still need a baseline, separate training and evaluation data, a metric tied to the decision, and tests for important groups and conditions. The later courses on Making Training Work, Language Models, and Computer Vision apply those rules to current pretrained models.

Core modelling checkpoint

  • Turn "that fit looks bad" into one number, and know what squaring the misses decides.
  • Measure a slope by nudging a weight, and use it to roll a model downhill.
  • Recognise a learning rate that is too large from the shape of the loss alone.
  • Rescale features, and say why training limps without it.
  • Read a probability from a classifier without believing more than it says.
  • Invent a feature that makes an impossible problem easy.
  • Spot memorising, and catch it by holding data back.
  • Keep three piles apart, and report the number from the right one.
  • Grow a decision tree by measuring mixedness, and prune it for honesty.
  • Explain what a neuron is, what the squash is for, and why a layer of them can bend a fence.
  • Measure outcomes per group, and explain why deleting a column does not make a model fair.
  • Ask what the do-nothing model scores before believing any accuracy figure.

Courses used so far

  • Mathematics for Computer Science. The counting and chance behind the honesty rules here, worked out rather than asserted, including why held-back scores wobble and by how much.
  • Linear Algebra. What happens when a model has a thousand weights instead of three, and the arithmetic that makes handling them all at once possible.
  • Introduction to Algorithms. Trying every cut worked on forty dots. What to do when there are forty million, and how to know in advance whether an approach will finish.
Step 13

State the decision before choosing a model

“Use machine learning” is not a problem statement. Name the person or system making a decision, the information available at that moment, the output needed, and the cost of each kind of mistake. Then ask whether a rule, search, calculator or database query solves it more directly.

Labelled examples support supervised regression or classification. Unlabelled examples can be grouped or compressed, but the groups have no built-in meaning. Reinforcement learning uses consequences from actions. These families answer different questions and need different evidence.

Write one testable requirement

“Estimate tomorrow’s bus delay in minutes at 07:00, using only information available by 06:55; beat the same-as-yesterday baseline on held-out school days; report larger errors during snow separately.” This states the target, time boundary, baseline, test data and important condition.

Lab 25 · Match a question to its learning family
Try this firstOpen each question and name the feedback it would require.
Model choice follows the question. If the decision cannot be stated, no metric can say whether the model helped.
What should be written before collecting training data?
Frame the decision first. It determines what data and evaluation mean.
Step 14

Ask how every row and label came to exist

Data is produced by a measuring process. Sensors drift, people disagree, forms omit inconvenient cases, and a label may be a later decision rather than the fact you meant to predict. Keep the source, unit, collection time and missing-value reason beside each field.

Inspect examples where two labelers disagree and measure agreement. Sample important conditions on purpose instead of accepting whatever was easiest to collect. A model trained on a broken label can reproduce it efficiently; more epochs do not repair the definition.

Missing is sometimes information

A blank value may mean a sensor failed, a question was skipped, or the value was below a detection limit. Replacing every blank with zero merges different events. Add a missingness indicator when the reason matters, and test whether missingness differs across groups or time.

Lab 26 · Corrupt labels and watch the ceiling fall
Try this firstMove label error from 0 to 20 percent and explain what training cannot recover.
Investigate the measuring process. A ceiling from label disagreement is not an invitation to use a larger model.
Two experts disagree on many labels. What is the first engineering action?
Repair the specification and process. The disagreement may reveal an ambiguous target.
Step 15

Why a held-out score still wobbles

Test accuracy is a fraction from a sample. Sixteen correct answers out of twenty gives 80%, but another twenty examples from the same population may give a noticeably different result. Report the numerator, denominator and an interval, not only a decimal with impressive digits.

The interval in the lab is a Wilson interval for a binomial proportion. It estimates sampling uncertainty under independent representative examples. It does not cover dataset shift, wrong labels, repeated measurements from one person, or a test set chosen after seeing results.

What if examples are related?

Split and resample at the independent unit: by person, patient, machine, location or time block. Treating 1,000 frames from one video as 1,000 independent cases makes the interval falsely narrow. The Training and Evaluation course develops grouped splits and uncertainty further.

Lab 27 · Put an interval around accuracy
Try this firstCompare 16 of 20 with 400 of 500 at the same 80 percent.
The rate is the same; the evidence is not. More independent test cases narrow sampling uncertainty.
Two models both score 80%. One used 20 independent test cases and one used 2,000. What differs?
The second estimate is more precise. Neither one automatically covers a changed field population.
Step 16

Let nearby examples vote

k-nearest neighbours stores the labelled examples. For a new point it measures distance, selects the nearest k, and lets their labels vote. There is almost no training, but prediction must search stored data and depends completely on the distance definition.

Small k follows local detail and noise. Large k smooths the boundary and can erase a small class. Put features on comparable scales, handle ties, choose k on validation data, and measure prediction cost when the collection becomes large.

How does search stay fast?

Spatial indexes can prune exact searches in low dimensions. In high-dimensional embedding spaces, approximate-nearest-neighbour indexes trade a little recall for speed and memory. Measure index recall, latency and downstream task quality separately.

Lab 28 · Move a query through its neighbours
Try this firstUse k=1 and k=7 at the same point. Find where the vote changes.
Distance is part of the model. A feature measured in thousands can dominate one measured from zero to one.
Why scale features before Euclidean nearest-neighbour search?
Distance uses the numerical scale. Units should not decide importance by accident.
Step 17

Clustering returns the groups you asked for

K-means starts with k centres, assigns every point to its nearest centre, then replaces each centre with its group mean. It repeats until assignments stop changing. The result minimizes a particular squared-distance objective locally; it does not discover the one true set of kinds.

Results depend on scaling, k, initialization, outliers and whether round equal-sized groups fit the data. Run several starts, compare stability, inspect examples, and judge usefulness in the downstream task. Do not attach human meanings to clusters from a picture alone.

What about density and curved groups?

Density-based methods can find irregular shapes and mark sparse points as noise. Hierarchical clustering builds nested groups. Each method encodes a different meaning of “together,” so select it from the data geometry and use, not from a colourful plot.

Lab 29 · Ask the same points for two or three groups
Try this firstSwitch k. Notice that error falls because the question became easier.
Lower within-cluster error always rewards more centres. Validation needs a use beyond the objective itself.
K-means returns four clusters. What has it proved?
It solved the requested geometric objective. Meaning requires outside evidence.
Step 18

Compress many measurements into a useful view

Principal component analysis finds directions with large variance, then projects data onto them. Correlated measurements can often be represented with fewer numbers. This helps plots, compression and some models, but a component is a weighted direction, not automatically a named physical cause.

Centre the features and usually scale them when units differ. Fit the projection on training data only, then apply the same transformation to validation, test and field data. Otherwise the held-out piles leak information into the representation.

How are the directions computed?

The covariance matrix records which centred features vary together. Its eigenvectors give principal directions; singular value decomposition obtains the same geometry more robustly from the data matrix. Linear Algebra builds both ideas.

Lab 30 · Rotate a one-dimensional view
Try this firstFind the angle that keeps the largest spread.
Maximum variance is a geometric criterion. Check whether it preserves what the real decision needs.
When should PCA be fitted?
Fit preprocessing on training data only. The test distribution must remain unseen.
Step 19

Prefer a smaller fit when it predicts just as well

Regularisation adds a penalty for model complexity to the training objective. Ridge regression penalizes squared weights, pulling a fitted line toward a flatter one. The penalty can reduce sensitivity to noise and correlated features, but too much creates underfitting.

The penalty strength is a hyperparameter. Compare values on validation data or within cross-validation folds, keeping all preprocessing inside each training fold. After choosing it, refit according to the declared procedure and use the untouched test set once.

Other ways to control complexity

Lasso can set some weights to zero. Trees can limit depth or leaf size. Neural networks use weight decay, data augmentation, dropout and early stopping. Each changes the training process differently; validation measures whether the change improves the target population.

Lab 31 · Trade fit for a smaller weight
Try this firstRaise lambda and watch slope size and training error move in opposite directions.
The penalty is not free accuracy. It is a bias chosen because it may improve new-data performance.
Where should the regularisation strength be chosen?
Choose without spending the final test.
Step 20

Probability and decision thresholds are different

A calibrated model that says 70% for many comparable cases should be right about seven times in ten. Accuracy cannot test that claim. Reliability diagrams, log loss and the Brier score compare probability forecasts with outcomes.

The threshold turns a probability into an action. Choose it from false-alarm and missed-event costs, capacity and safety rules. Changing the threshold changes decisions but does not recalibrate the probabilities. Recheck both calibration and decision cost for important groups and field conditions.

Can probabilities be repaired?

Platt scaling and isotonic regression fit a calibration map on held-out predictions. Temperature scaling is common for neural classifiers. Fit the map without using the final test set, and recheck it after population or model changes.

Lab 32 · Change confidence, threshold and miss cost
Try this firstRaise miss cost, then find the threshold with the lower displayed decision cost.
One model can support different decisions. Document the cost table and threshold beside the model version.
Lowering a classifier threshold mainly changes what?
It changes the action rule. Calibration is a separate property.
Step 21

Do not train with information from the future

Target leakage occurs when an input contains the answer or information produced after the prediction moment. A hospital invoice code, final repair note or “days until failure” field can make a model look excellent in a notebook and impossible to run honestly.

Draw a timeline for every feature. Rebuild each value using only records available at the decision time. Split by person, machine or time before fitting imputers, scalers, vocabularies and feature selectors. A random row split can also leak nearly identical neighbours across piles.

Leakage can enter during evaluation

Choosing features after looking at test performance, fitting normalization on all rows, or retrieving documents that contain the reference answer all spend test information. Put the entire learned pipeline inside the training fold and audit data lineage.

Lab 33 · Check whether a feature exists in time
Try this firstFind the two fields created only after diagnosis.
A timestamped feature contract catches leakage early. “Present in the table” does not mean “available to the real decision.”
A model predicts equipment failure using the technician's final repair code. What is wrong?
The feature arrives too late.
Step 22

Prediction does not say what an intervention will cause

A prediction model learns associations. Umbrellas predict rain because rain causes people to carry umbrellas; banning umbrellas does not change the weather. Acting on a predictive feature can fail when a common cause, selection process or feedback loop produced the association.

Random assignment makes treatment and control groups comparable on average and supports causal estimates under stated assumptions. When experiments are unsafe or impossible, causal diagrams, natural experiments and adjustment methods make assumptions explicit. They do not turn any large dataset into an experiment.

Why deployment creates feedback

A model changes which cases receive attention, so later labels are observed under its own policy. Credit, policing, recommendations and predictive maintenance all have this problem. Record the action policy and preserve suitable exploration or comparison groups where safe.

Lab 34 · Separate association from intervention evidence
Try this firstExplain why removing the predictor need not remove the outcome.
Ask two different questions. “What will happen?” and “What happens if we change this?” need different evidence.
A feature strongly predicts an outcome. What may you conclude?
Association supports prediction under assumptions. Intervention needs causal evidence.
Step 23

The field keeps changing after release

Covariate shift changes inputs, label shift changes class proportions, and concept drift changes the relationship between input and target. A new sensor, season, user group or policy can create any of them. Monitor data quality, input ranges, prediction mix, latency and delayed outcome metrics by important slice.

A drift score is an alarm, not a verdict. Investigate the cause and measure task performance where labels arrive. Define warning and stop thresholds, a safe fallback, model and data versions, rollback, and the evidence required before retraining. Do not let an automatic retraining loop learn from its own unchecked decisions.

Use a shadow and a canary

A shadow model receives live inputs but does not control outcomes, which reveals latency and prediction differences. A canary serves a small representative cohort with rollback ready. Neither replaces a controlled comparison when the new policy changes which labels become visible.

Lab 35 · Move one feature away from training
Try this firstCross the simple 1.5-standard-deviation alarm and state what it does not prove.
Monitor the outcome that matters. An input alarm helps diagnose change but is not a substitute for field performance.
An input drift alarm fires. What should happen first?
Investigate. Drift and failure overlap, but neither proves the other.
Step 24

Pretraining changes the starting point

A foundation model learns reusable representations from broad data. A project can prompt it, retrieve relevant records into its context, train a small adapter, or update more weights. Embeddings support semantic search and grouping; generative models produce open-ended text, images, audio or actions.

Evaluate the whole system on a fixed task set with rubrics and repeated runs. Separate retrieval failure from generation failure. Treat generated claims as unverified, retrieved text as data rather than instructions, and tool calls as requests through typed, least-privilege guards. Pin model and prompt versions and keep regression cases.

What is different in 2026?

Multimodal models can accept several media, smaller models can run on devices, and inference-time search can spend more computation on hard tasks. Parameter-efficient adapters and synthetic data reduce some collection costs. None removes held-out evaluation, provenance, privacy, latency, cost or failure containment.

Lab 36 · Choose a pretrained-model adaptation path
Try this firstOpen each method and name the new component that must be evaluated.
Evaluate the system you ship. A benchmark for the base model does not measure your retrieval, prompt, tools or users.
A language model may call a thermostat tool. What is the safest boundary?
Put ordinary software controls around the model.
Step 25

Learning from consequences changes the data

In reinforcement learning, an agent observes a state, chooses an action, receives a reward and reaches another state. A policy maps states to actions. The return adds future rewards, often discounting later ones. Exploration gathers information, which means the learner helps create its own training data.

Reward is a measurement, not the full goal. An agent can exploit a shortcut in it, so test invariants and side effects outside the reward. Use simulators and offline logs before physical trials, constrain actions, separate training from evaluation seeds, and compare with a fixed rule or controller. High-consequence exploration needs a safety supervisor.

Where do modern models fit?

Large pretrained models can represent observations, propose plans or supply a policy starting point. Preference feedback can shape behaviour. The same concerns remain: coverage of states, reward misspecification, off-policy evaluation, distribution shift and a deterministic boundary around dangerous actions.

Lab 37 · Discount a short reward sequence
Try this firstMove gamma from zero to one and see which future rewards count.
Discount changes the stated objective. It does not decide which actions are safe enough to explore.
A robot earns reward for moving fast and learns to ignore a safety stop. What failed?
The reward was incomplete. Safety must not depend on the agent discovering the intended interpretation.

What you can do now

  • Frame supervised, unsupervised and reinforcement problems from a decision and feedback source.
  • Audit data origin, labels, missingness, sampling and time availability.
  • Report scores with baselines, denominators, intervals, slices and mistake costs.
  • Explain neighbours, clustering, projection and regularisation, including their assumptions.
  • Separate calibration from thresholds, prediction from causation, and drift alarms from outcome evidence.
  • Use pretrained and generative models behind fixed evaluations and deterministic tool guards.
  • Define reward, policy, evaluation seeds, fallback and safe exploration for reinforcement learning.

Continue the learning path