Start here · Intermediate

Machine Learning, Foundations

Draft, open for academic review

The classical ground under modern AI, for someone who can read code.

Your progress here is recorded once you pass the How a Language Model Actually Works exam.

The film · 15 min

The classical ground under modern AI, for someone who can read code.

15:209 chapters

116 MB · captions in English · nothing downloads until you press play

Read the transcript

Narrated by a synthetic voice. Every timestamp starts the film there.

What this course is

This course is about how a machine learns from data. Not the marketing version, the mechanism. By the end of it you should be able to take a vague business question and state it as a dataset with a defined row, a defined target and a defined moment of prediction. Choose a loss that says what a mistake costs. Hold data out honestly. Measure the result without fooling yourself. And take the thing to a running service that somebody else can keep alive after you leave. Every tool in it is free. Over the next twelve minutes we walk the whole arc, module by module.

1. What learning is, and what it is not

What a machine actually learns

Start with four flats and their monthly rents. You write down a shape with blanks in it: rent equals some number times the floor area, plus another number. Those blanks are called parameters. Then you write down one number that says how wrong the current choice is, averaged over your data. That number is the loss. Learning is nothing more than moving the parameters until the loss gets smaller. Two numbers moved and a third number went down. Every model in this course, from a two-parameter line to a network with a trillion weights, is the same three-part machine: a shape, a loss, and a procedure for changing the shape to lower the loss.

The number you have to beat

Before you train anything, compute the number your model has to beat. Predict the most common class. Predict that tomorrow equals today. Implement the rule the operations team already uses and score it on the same data. A fraud model reporting ninety-four per cent accuracy sounds impressive until somebody points out that predicting no fraud for everything scores ninety-six. And report the gap rather than the score. Say that the baseline scores six thousand one hundred and the model scores four thousand three hundred, and you have a sentence a non-technical person can act on.

2. Linear models and the machinery of fitting

Walking downhill in fog

You are on a hillside in thick fog. You cannot see the bottom, but you can feel which way the ground slopes under your feet, so you step downhill and feel again. That is gradient descent, complete. The hill is the loss. The step size is the learning rate, and it is the single knob that decides whether the walk helps you or destroys you. Too small and it crawls. Too large and each step overshoots the bottom, lands further up the far side, and within thirty steps your loss prints as not a number. When training dies, lower the learning rate by a factor of ten and look again. That is the cause about eight times out of ten.

Paying for large coefficients

A model overfits by using large opposing coefficients to thread through individual training points. Regularisation makes that expensive. Add the size of the coefficients to the loss, and the optimiser has to justify every unit of coefficient it spends with a matching reduction in error. Ridge charges the square of a coefficient, so the push it exerts fades away as the coefficient shrinks and nothing quite reaches zero. Lasso charges the absolute value, whose push is exactly the same however small the coefficient gets, and that constant push drives small coefficients to zero and holds them there. That is why lasso selects features and ridge does not. Standardise your columns first, or the penalty lands on units of measurement rather than on contribution.

3. The data is the job

Features beat models

On table-shaped data, the features you hand over move the result more than the algorithm does. A raw signup timestamp is a large integer and almost useless. Hours between signing up and the first lesson, sessions in the first week, whether the signup happened at the weekend, the hour in the learner's own timezone rather than the server's. Same column, and now it carries most of the signal. Put the context into the number. Price divided by the median price within two kilometres beats price. Each of these is arithmetic a nine-year-old could do, and each is usually worth more than swapping in a fancier model.

The feature that already knows

Leakage is a feature whose value will not be available, in that form, at the moment you actually have to predict. It is the most expensive mistake in applied machine learning, because it does not look like a mistake. It looks like success. A hospital mortality model with discharge destination among its features, where one of the values is mortuary. The test is a question you ask about every column: at the exact moment I need this prediction, would this value already exist, with the value it has here? Both halves of that matter. And a correct split catches none of it, because the leaked column sits on both sides of the split.

4. Generalisation, and the discipline of held-out data

Two numbers, not one

You cannot diagnose a model from one score. You need training error and validation error side by side, and it is the gap between them that names the problem. Both high and close together means the model is not seeing enough, so the remedy is more capacity, better features or longer training. Training low and validation much higher means it has memorised, so the remedy is more data or less freedom. The word overfitting has drifted in casual use to mean the model is bad, so any disappointing score attracts it. If training accuracy is seventy-one per cent and validation is seventy, nothing is being memorised. Cutting the capacity there will make both numbers worse.

A validation set you used three hundred times

Now the part nobody warns you about. You split off a validation set, you never trained on it, and then over six weeks you compared three hundred and forty models against it. Every comparison used that set to make a decision, and the winner scored highest partly because its particular errors happened to miss those particular rows. The maximum of many noisy estimates is biased upward. With a two thousand row validation set and a hundred comparisons, the winner is inflated by roughly two and a half points, which is enough to turn no real improvement into a clear win. Keep a test set that nobody has touched, and report how many times you looked.

5. Measuring a model honestly

The four numbers

A thousand transactions. Forty of them are fraud. The model flags thirty and twenty-four of those are real. Accuracy is ninety-seven point eight per cent, and the model that flags nothing scores ninety-six, so accuracy has told you almost nothing. Precision is twenty-four divided by thirty, eighty per cent: of what we flagged, this much was real. Recall is twenty-four divided by forty, sixty per cent: of what was really there, this much was caught. Precision divides by what the model said. Recall divides by what was true. And precision is not a property of the model. Run the same model where fraud is one in a thousand instead of one in twenty-five, and precision falls from eighty per cent to nine.

The threshold is yours

The model produces a score. Something else turns that score into a decision, and that something is a threshold you chose. Zero point five is a default somebody typed into a library. It is correct only when the two kinds of error cost the same and the classes are balanced, which describes almost nothing. If a missed fraud costs eighteen thousand rupees and a review costs ninety, the break-even threshold is ninety divided by eighteen thousand and ninety, which is about half of one per cent. Or the constraint is capacity rather than cost. The team can review two hundred cases a day, so the threshold is whatever produces two hundred flags, and the metric is precision among those two hundred.

6. Trees, ensembles, and the algorithms that win on tables

Each model fixes the last one's mistakes

On tables, a linear model is your floor and gradient boosting is usually your answer. A random forest fits many strong trees in parallel and averages their variance away. Boosting does the opposite. Many deliberately shallow trees in sequence, each one fitted to what the previous ones got wrong, and only a fraction of each correction is added to the running prediction. That fraction is the learning rate, and it is why boosting accumulates accuracy instead of memorising immediately. Halve the learning rate and double the number of trees; the trade is exact. And unlike a forest, a boosted model gets worse with too many trees, because once the signal is used up the remaining residual is noise. Early stopping is not optional here.

The bar chart that misleads

Everybody prints the feature importance bar chart, and in its default form it is biased. Impurity importance rewards a column for offering many candidate thresholds, so a column of random integers between one and ten thousand will land in your top five. Permutation importance on held-out data measures what you probably meant. But both collapse when two columns carry the same information: shuffle one, the model reads the other, the score barely moves, and both look worthless. Cluster the correlated columns and permute the group together. And keep the standing rule in view. Importance describes the model, not the world, and a suspicious spike is a leakage alarm before it is anything else.

7. Learning without labels, and learning a representation

How many clusters, really

Clustering will always give you an answer, including from pure noise. The elbow plot rarely produces one anybody can defend. Silhouette is better, and you should read it per cluster rather than as a single mean. The gap statistic is the one measure that can tell you no clustering is appropriate at all, because it compares your result against random data with the same bounding box. And the most practical test is stability. Cluster two eighty per cent subsets and see how far the assignments agree. A structure that reproduces at zero point eight five is telling you something real. One that reproduces at zero point three is telling you about your own persistence.

Search that understands meaning

An embedding maps things to vectors so that geometric closeness means similarity in whatever sense the training task defined. Pretrained ones are free, small enough to run on an ordinary laptop processor, and good enough for most applications. Nothing has to leave the machine, which matters when the documents are confidential. Two warnings from practice. Chunking decides more than the choice of model does: too large and one vector averages several topics, too small and the text loses the context that made it interpretable. And pure embedding search fails on order numbers, on part codes and on negation, which is why production systems run keyword search alongside it and combine the two rankings.

8. Neural networks, built from what you already know

The bend is the whole idea

Stack fifty linear layers with nothing between them and you have one linear layer with a great deal of wasted arithmetic, because matrix multiplication is associative and the whole thing collapses. Every capability a network has beyond a straight line comes from the bend applied between the layers. Early networks used the sigmoid, whose derivative is at most a quarter. Backpropagation multiplies those derivatives layer by layer, so ten layers down the gradient is about a millionth of what arrived at the top, and the early layers stop learning. A rectified linear unit is a hinge: negatives to zero, positives through unchanged. Its derivative is exactly one where it is active. That crude thing replaced the elegant one, and deep networks became trainable.

Standing on somebody else's compute

You are not going to train a vision model from scratch, and you do not need to. Somebody already spent the compute and released the weights, and the early layers of that model learned edges and textures, which are the same structures whether the picture is a dog, a chest scan or a defective weld. So start at the cheapest level of adaptation. Freeze the whole pretrained model, use it to turn each image into a vector, and fit a logistic regression on those vectors. On a few hundred images that is often within a couple of points of full fine-tuning, and it runs on a laptop processor. Escalate only when the measurement says your data supports it.

9. Into the world, and keeping it honest

The model is five per cent of it

The model is about five per cent of what you have to build. The rest is where the features come from at prediction time, how a prediction gets served inside a latency budget somebody agreed to, a version on everything, a path back to yesterday's model in minutes, and monitoring. Watch four layers, cheapest first. System health. Input distributions, where most problems appear first, because most problems are upstream data problems. Prediction distributions, which move before any accuracy metric can even be computed. And actual performance, which is the thing you truly care about and the slowest to arrive, because labels lag by weeks or by months.

The model changes its own data

One property makes this different from ordinary software. A deployed model acts on the world, and the world it acts on generates the data for the next model. Decline an applicant and you never learn whether they would have repaid, so next year's training data contains only the people the previous model approved. Rank an item first and it gets clicked more because it is first. Offline metrics then measure agreement with the previous model's choices rather than with anybody's preferences. What escapes the loop costs money and has no substitute: randomised exploration, a control group, and a logged probability for every action the system took. If you take one engineering habit from this course, log that probability.

Where that leaves you

So that is the arc. Frame the question as a row, a target and a moment. Choose a loss that says what a mistake costs. Spend your time on features. Hold data out in a way that matches how the model will actually be used. Measure with the metric that matches the decision, and choose the threshold yourself. Use a linear model as the floor and gradient boosting as the answer on tables. Then write down what you chose and why, because that is what turns a black box somebody inherited into a decision somebody can be accountable for. Go and run the whole loop once, end to end, on any dataset you can find.

9 modules. 92 lessons.

What learning is, and what it is not

9 lessons · 1 h 16

You will be able toTake a vague business question, state it as a dataset with a defined row, a defined target and a defined moment of prediction, name the loss and the baseline it must beat, and justify in one paragraph whether machine learning is the right tool at all.

  1. 1.1What a machine actually learnsStart8 min
  2. 1.2With answers, and without7 min
  3. 1.3What a row is, and why that decision is the whole project9 min
  4. 1.4The loss is where you state what a mistake costs9 min
  5. 1.5The number your model has to beat before anyone should care8 min
  6. 1.6Why a model that predicts well cannot tell you what to change9 min
  7. 1.7The problems where the right answer is a rule8 min
  8. 1.8The whole loop, once, before we slow down10 min
  9. 1.9A working setup that costs nothing8 min
An illustrative case, built from documented patternsTwo definitions of a dropout, in KotaA coaching centre in Kota with 2,300 students, two counsellors, and an analyst borrowed from the accounts department.

Vidya Path enrols 2,300 students across one-year and two-year programmes for the engineering entrance exam. Fees arrive in three instalments. A student who stops coming after the second instalment costs the centre the third, and costs the family a great deal more than that.

The management asked for a model that would “predict dropouts early enough to do something about it”. They had five years of attendance registers, weekly test scores, fee receipts and hostel allocations, and they had Reshma, moved across from accounts, who had worked through a free machine learning course on her phone over four months.

Her first week produced no code. It produced one sentence, and an argument about it.

The row was easy. One student-month. A student appears once for every month they were enrolled.

The target was not. Two definitions were available, and they were not variations on a theme.

Definition A: a student is a dropout if they do not re-enrol for the following term. Unambiguous, already recorded in the fee system, and exactly what the director meant by the word. It also produces one label per student per year: about 2,300 rows a year and roughly 180 positives.

Definition B: a student is a dropout if they attend no class for twenty-one consecutive days. One label per student-month, which over five years is about 27,000 rows and roughly 1,900 positives. It is also wrong sometimes. A student with dengue, or one who went home for a cousin’s wedding and came back, gets the same label as one who has left for good.

The director wanted A. “That is what a dropout is.” Reshma wanted B, for a reason that had nothing to do with elegance. With 180 positives and forty candidate features, the events-per-feature arithmetic said nothing she fitted would be stable, and a validation set holding thirty-six positives could not tell a good model from a lucky one.

The cost fell on both sides and neither was small. Definition A would produce a model whose per-student predictions could not be trusted, wearing a validation score with an interval wide enough to cover both success and failure. Definition B would produce a model that fired on students who were about to walk back through the gate, and every false alarm was a counsellor telephoning a family that had done nothing wrong. In Kota, where the pressure on these students is a matter of public concern, an unnecessary call from the institute is not a neutral event.

The moment of prediction settled less than either of them expected, and it settled it the same way for both definitions. Features had to be everything known as of the last day of the month and nothing else. That excluded refund_processed, hostel_vacated_date and final_instalment_status, all three of which were in the export the office had handed over, and all three of which are written after the outcome they would have been used to predict. Reshma put the exclusion list at the top of the notebook before she opened a single CSV.

The baseline took twenty minutes and changed the conversation. Predicting “nobody drops out” scored ninety-three per cent under definition A. More usefully, the rule the counselling team already used (flag any student whose attendance over the last fortnight fell below sixty per cent) caught forty-one per cent of eventual dropouts and produced about nine flags a day, which two counsellors could just about work through.

Nine flags a day was the real constraint, and nobody had written it down before. The question stopped being “can we predict dropouts” and became “can we beat forty-one per cent recall at nine flags a day, without asking the counsellors to make calls they do not have time to make”.

How it played out

They trained on definition B and evaluated on definition A. The noisy monthly label gave the optimiser enough events to learn from; the clean annual label, available for the two cohorts that had completed, was what they reported. At nine flags a day the model reached sixty-three per cent recall against the rule’s forty-one.

The first twenty calls found three students on recorded medical leave. Rather than retrain, the centre added a suppression rule outside the model (never flag a student with an approved leave record) which is the rule-and-model hybrid from lesson seven of the module, arrived at by being embarrassed rather than by design.

The director’s requirement, added late and kept since, was one line in the handover note: the model predicts a twenty-one-day absence, not a departure, and the counsellor is told which of those they are calling about.

Worth arguing about

  1. Definition B gave ten times as many labelled events. Why did that not simply make the model better?

    One answer

    Because the extra events are noisier. A twenty-one-day absence includes students who return, so a share of the positive labels do not correspond to the outcome anyone cares about. The model learns the label it is given, so it learns ‘who will disappear for three weeks’, which overlaps with dropping out without being it. The gain in estimation stability was real and the cost in label fidelity was real; the resolution was to train on the plentiful label and measure against the clean one.

  2. The refund column is strongly associated with dropping out. Why exclude it?

    One answer

    Because at the moment the prediction is made (the last day of a month, for a student still enrolled) the refund has not been processed. It exists in the training table only for students whose outcome is already known, so it is a consequence of the target rather than a predictor of it. Including it would raise every validation score and produce a model that has nothing to say about a student who is still attending, which is the only kind of student the counsellors can act on.

  3. Why was ‘nine flags a day’ a better target than ‘maximise AUC’?

    One answer

    Because the counsellors are the constraint, and the decision the model supports is which nine students get a call today. AUC averages the model’s behaviour over thresholds that will never be used. Precision and recall at the operating point of nine flags describe what will actually happen, they are comparable against the rule already in place, and they make the trade-off legible to a director who does not know what an ROC curve is.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    A delivery-time model is trained on data where most trips take 20 to 40 minutes and a handful take three hours because of a road closure. The team switches the training loss from squared error to absolute error and changes nothing else. What changes about the fitted model?

  2. 2

    A churn model reaches 0.99 AUC on its first run, with no tuning, on a problem the operations team finds genuinely difficult. What is the most likely explanation?

  3. 3

    A bank builds a default model where one row is one loan, and customers hold up to eleven loans each. The rows are split at random. What does the validation score actually measure?

  4. 4

    A telecom model finds that customers who call support are far more likely to churn. Management proposes making the support line harder to reach. What is wrong with that reasoning?

  5. 5

    A government office applies an eligibility rule written into a regulation: five conditions, each exactly specified. A team proposes training a classifier on past decisions instead. Why is that a worse design?

  6. 6

    A team evaluates on the test set, sees a disappointing number, changes two features, and evaluates again. What is the state of their test estimate now?

Linear models and the machinery of fitting

10 lessons · 1 h 26

You will be able toFit and diagnose a linear or logistic model end to end: compute its loss by hand on a handful of rows, tune the learning rate from the shape of the loss curve, state what a coefficient does and does not mean in the units of the data, and explain what ridge and lasso penalties change about the fitted parameters.

  1. 2.1Fitting a line to five points, by hand9 min
  2. 2.2There is an exact answer, and we usually refuse it8 min
  3. 2.3Gradient descent, or walking downhill in fog8 min
  4. 2.4Batches, epochs, and the two knobs that decide everything9 min
  5. 2.5Diagnosing a model from the shape of its loss curve8 min
  6. 2.6Logistic regression, built from odds rather than assumed10 min
  7. 2.7What a coefficient says, and the four ways it lies9 min
  8. 2.8Regularisation: paying for large coefficients9 min
  9. 2.9Making a straight-line model bend8 min
  10. 2.10More than two classes, and what changes8 min
An illustrative case, built from documented patternsThe coefficient that changed sign in MuzaffarpurA microfinance lender in Muzaffarpur with 41,000 active borrowers, a two-person analytics team, and forty field officers who have used the same paper scorecard for nine years.

Saathi Sahyog lends between twelve and sixty thousand rupees to women’s self-help groups across four districts of north Bihar. Repayment is weekly and collected in person. The decision they wanted to support is the one a field officer makes on a doorstep: recommend this group’s loan for approval, or refer it for a second visit.

The existing instrument is a paper scorecard with eleven questions and a total out of one hundred. It was built in 2017 by a consultant nobody can now reach, and everyone in the field trusts it: partly because they can see it work and partly because a number they can compute themselves is a number they can argue with.

The analytics team, Farhan and Kavya, fitted a logistic regression on 38,000 completed loans with fourteen features. The target was ninety days past due within the loan term. They fitted it in an afternoon and spent three weeks on what it said.

Two features were the problem: monthly_household_income, collected by asking, and weekly_instalment_as_share_of_income, computed from that same declared income and the loan amount. They are close to mechanically related. In the fitted model, income carried a coefficient of +1.9 on the log-odds of default and the instalment share carried −2.4. Read literally, that says richer households default more and larger instalments relative to income make default less likely. Both readings are absurd, and both are what the numbers said.

Kavya ran the diagnostic from the coefficients lesson: refit on five bootstrap samples. Income’s coefficient changed sign in two of them. The predictions barely moved across the five refits; the coefficients moved a great deal. That is multicollinearity behaving exactly as documented, and it is invisible in any accuracy score.

Now the decision, and it had a genuine cost on each side.

Option one: drop declared income. The instalment share carries most of the information, the remaining coefficients stabilise, and the model becomes explainable. The cost is that income is question three on the paper scorecard. Removing it from the model means the field officers’ instrument and the office’s instrument now disagree about what matters, and forty people who have collected that number every week for nine years are told it is no longer used. Farhan’s estimate, from two conversations in the field, was that a proportion of officers would conclude the office did not understand their job and would stop trusting the output entirely.

Option two: keep both columns and add a ridge penalty. Ridge shares the coefficient across correlated features rather than picking one arbitrarily, and the signs settle. The cost is that the individual coefficients no longer support the sentence the lender needs. A rejection notice under Reserve Bank of India expectations has to carry a reason, and “your score is low because of the combined weighting of two related fields” is not a reason a borrower can act on.

Option three: ship the boosted model instead. They had one. It scored 0.79 AUC against the linear model’s 0.74 and the paper scorecard’s 0.68. It also has no coefficient to read, and the field officer cannot compute it on a doorstep with no signal, which happens on roughly a fifth of visits.

Five points of AUC against forty people’s willingness to use the thing. Nobody in the room thought that was an obvious trade.

How it played out

They kept both columns, standardised the features, and used ridge with alpha chosen by cross-validation on a log scale. Then they did the part that mattered: they reported effects for grouped features rather than single ones. Income and instalment share are presented together as one “affordability” block with a combined contribution, and the rejection reason names the block.

The paper scorecard was left alone. Question three still asks about income and the field officers still compute their total, which the model now takes as one of its fourteen inputs. The office score and the doorstep score are two instruments that agree about what is being measured, and the officers were told in a district meeting how the two relate.

The boosted model was fitted, scored, written down and not deployed. The note recording that decision gives the reason as offline availability and the reason requirement, not accuracy, so that whoever revisits it in three years knows what would have to change for the answer to change.

Worth arguing about

  1. The predictions were stable across the five bootstrap refits while the coefficients were not. Why is that not a contradiction?

    One answer

    Because the two correlated columns carry almost the same information, so many different splits of the weight between them produce nearly the same weighted sum. The optimiser is free to choose any of those splits and picks one for reasons that have nothing to do with the world. The prediction depends on the sum; the interpretation depends on the split. A model can therefore be reliable to predict with and unreliable to read.

  2. Why was the ridge penalty applied only after standardising the features?

    One answer

    Because the penalty is applied to the coefficient values, and a coefficient’s size depends on the unit of its feature. Income in rupees has a naturally tiny coefficient and would escape the penalty almost entirely, while a nought-or-one flag has a naturally larger one and would be crushed. Standardising puts every feature on the same scale so the penalty falls on contribution rather than on unit of measurement.

  3. The boosted model was five points of AUC better and was not deployed. Was that the wrong call?

    One answer

    It is defensible, and the case for it is not accuracy. The instrument has to run on a doorstep with no connectivity and has to produce a stated reason for a refusal, and a five-point gain that the people carrying the device will not use is not a five-point gain. What makes the decision sound is that the reasoning was recorded: the constraint, not the score, is what would have to change.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    Training a linear model, the loss prints as NaN within a dozen steps. What is the first thing to change?

  2. 2

    Linear regression with squared error has an exact one-step solution. Why do courses teach gradient descent anyway?

  3. 3

    Lasso drives some coefficients to exactly zero and ridge does not. What is the mechanism?

  4. 4

    In a logistic model a coefficient of 0.7 on ‘has an overdraft’ exponentiates to 2.0. A manager reads this as doubling the chance of default. What is the correction?

  5. 5

    A logistic regression on age, from 18 to 80, and annual income, from 200,000 to 5,000,000, hits its iteration limit without converging. Which change addresses the cause rather than the symptom?

  6. 6

    A discount raises conversion much more for price-sensitive customers than for corporate accounts. A linear model has ‘discount’ and ‘is_corporate’ as separate columns. What has to be added for the model to express this?

The data is the job

12 lessons · 1 h 45

You will be able toTake a raw table with mixed types, missing values, high-cardinality categories, dates and free text, and produce a fitted preprocessing pipeline that leaks nothing from the held-out data, handles categories unseen at training time, and whose every transformation you can justify by what the downstream model requires.

  1. 3.1Features beat models9 min
  2. 3.2Scaling, and the transforms that change what a model can see9 min
  3. 3.3Turning categories into numbers without lying about them9 min
  4. 3.4When a column has thousands of levels8 min
  5. 3.5Missing values, and the information in the gap9 min
  6. 3.6Outliers: error, extreme, or the thing you are looking for8 min
  7. 3.7Dates, durations, and the trouble with midnight8 min
  8. 3.8Text as columns: counting words before you embed them9 min
  9. 3.9Leakage: a catalogue of the ways the answer gets in10 min
  10. 3.10Fit on train, transform everywhere: the contract that keeps you honest8 min
  11. 3.11Where the rows came from, and who is missing9 min
  12. 3.12When one class is 0.3% of the data9 min
An illustrative case, built from documented patternsThe 0.94 that had already been promised, in TiruppurA garment exporter in Tiruppur, 180 staff, shipping knitwear to three European buyers, with a two-month contract for a shipment-delay prediction model.

Aruna Knits ships about 900 export consignments a year. A consignment that misses its committed date triggers a penalty clause with two of the three buyers and, more expensively, moves the exporter down that buyer’s allocation list for the next season. The managing director wanted to know, at the moment a purchase order is confirmed, which consignments were at risk, so that the production plan could be arranged around them.

The work went to a two-person consultancy in Coimbatore. They were given a warehouse extract of 4,100 historical consignments with sixty-one columns, and four weeks.

Week two produced a gradient boosting model at 0.94 AUC on a held-out sample. The consultants sent a slide. The managing director sent it to his buyers’ merchandising contacts. The number was, by that point, a commitment.

Week three, one of the consultants ran the check from the leakage lesson: sort the features by importance and interrogate anything that dominates. One column did. courier_partner_assigned was carrying more than a third of the model’s gain.

The reconstruction took an afternoon. Consignments that were running on time were handed to the regular sea-freight forwarder and had that value from day one. Consignments that had slipped were reassigned to an air-freight partner, some days before the committed date, precisely because they were late. The column existed at prediction time (it was populated), but not with the value it holds in the training table. That is the second half of the leakage test, and it is the half people skip.

Two more columns were in the same family, found by the same route: overtime_hours_sanctioned, approved when a line is behind, and fabric_reissue_count, which is incremented when a cut is rejected and the cutting has to be redone, an event that happens after the consignment is already in trouble.

Removing all three took the model from 0.94 to 0.71.

The decision was now uncomfortable in a specific way. 0.71 is not a bad model. Against the exporter’s existing practice, the production manager’s judgement, which had been scored on the same 4,100 consignments at roughly 0.63, it is a real improvement worth having. But 0.94 had been on a slide, and the slide had left the building.

Report the 0.71 and explain. The cost is a conversation the consultancy did not want to have, with an exporter who had already told his buyers something, and a real chance of losing the remaining fortnight of the contract and the referral behind it.

Keep the three columns and add a caveat. They could have argued, and it is the sort of argument that wins: the columns are in the operational system, a prediction can be produced from them, the model will run. It would run and it would be useless, because at the moment the managing director needs the answer (purchase order confirmed, twelve weeks out) every consignment has the regular forwarder, no overtime and no reissues, and the model would return the same low risk for all of them. It would fail quietly and it would fail in a way that looks like the world being unpredictable rather than the model being wrong.

Split the difference: build two models. One at order confirmation with the honest features, and one at week eight with everything then known. This is more work than the contract covers, and it is the only version where the reassignment column is a legitimate input, because by week eight it means what it appears to mean.

How it played out

They reported the 0.71, in a meeting, with the reconstruction of a single consignment on a sheet of paper: here is what the system held about consignment 3,318 on the day the order was confirmed, and here is what our training table held about it. The difference was the whole argument and it did not need any statistics.

The contract was extended rather than cancelled, and the extension paid for the two-model version. The order-confirmation model at 0.71 drives the production plan. A week-eight model at 0.86, which is allowed to know about overtime and reassignment, drives the decision about whether to book air freight early: a different decision, made by a different person, with a different cost of being wrong.

The buyers were told the corrected number by the managing director, who reported afterwards that the correction had cost him less than he expected and that being told in week three rather than month six was the part that mattered.

Worth arguing about

  1. The courier column existed at the moment of prediction. Why is it still leakage?

    One answer

    Because the leakage test has two halves: would the value exist, and would it exist with the value it has here. At order confirmation every consignment carries the regular forwarder, so the column exists and is uninformative. In the training table it carries the air-freight partner for exactly the consignments that later slipped. The model learns the second distribution and meets the first, so the column contributes nothing at serving time while contributing a third of the training gain.

  2. Why did the correct train-test split fail to catch any of this?

    One answer

    Because a split protects against memorising particular rows, and the leaked column is present on both sides of it. Held-out consignments carry the same after-the-fact courier assignment as training consignments, so the held-out score is inflated by the same mechanism. No amount of cross-validation detects a column that arrives from the future, because the future has arrived for every row in the table.

  3. What made the single reconstructed consignment more persuasive than the AUC comparison?

    One answer

    Because it turned a statistical claim into a factual one that the client could check himself. The reconstruction shows what the operational system actually held on a specific date for a specific order, against what the training table claimed. It requires no trust in the consultants’ methodology, and it is the only leakage check that finds the cases nobody thought to suspect.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    Target encoding replaces each category with the mean of the target for that category. Where does the leak come from?

  2. 2

    A loan dataset has ‘employer name’ blank for 12 per cent of applicants. Why add a missingness indicator before imputing?

  3. 3

    A sales model builds a 28-day rolling mean of each store’s sales as a feature, calling .rolling(28) without a preceding .shift(1). What goes wrong?

  4. 4

    A team scales the features once and then runs five-fold cross-validation on the scaled matrix. Why does moving the scaler into a Pipeline change the score rather than only tidying the code?

  5. 5

    Fraud is 0.3 per cent of rows. A model trained on log loss never predicts positive at a threshold of 0.5. What should be tried first?

  6. 6

    A model that will score new applicants includes ‘applicant_id’ as a feature, and a random row split shows excellent validation performance. What is the defect?

Generalisation, and the discipline of held-out data

10 lessons · 1 h 25

You will be able toDesign a validation scheme that matches the structure of the data (grouped, stratified or time-ordered as required) run a hyperparameter search inside it without contaminating the estimate, and state from a learning curve whether the next improvement should come from more data, better features or a different model.

  1. 4.1Train, validation, test, and the discipline of not looking9 min
  2. 4.2Overfitting, underfitting, and how to tell8 min
  3. 4.3Cross-validation: using every row twice, legally9 min
  4. 4.4Splits that respect the structure of the data9 min
  5. 4.5Bias and variance, with numbers attached9 min
  6. 4.6Would more data help? The curve that answers it8 min
  7. 4.7Searching hyperparameters without fooling yourself9 min
  8. 4.8A validation set you have used two hundred times8 min
  9. 4.9How much data do I need?8 min
  10. 4.10Double descent, and the picture that stopped being complete8 min
An illustrative case, built from documented patternsThe score that fell from 0.88 to 0.62 by being measured properlyAn agricultural advisory startup in Pune, eleven people, building pest-outbreak warnings for cotton growers in Vidarbha, four weeks before a funding round.

Kisan Drishti sends a weekly SMS to about 14,000 cotton farmers. The product they were building would upgrade that to a warning: pink bollworm pressure is rising on your plot, scout it this week. The data was three seasons of scouting records from 1,900 plots, each visited fortnightly by a field agronomist who counted larvae in ten randomly chosen bolls, plus weather, sowing date, variety and previous-season history.

The row was one plot-fortnight. The target was whether the next visit’s count crossed the economic threshold. About 78,000 rows and 6,300 positives.

The first model, a gradient boosting classifier with a random eighty-twenty split, scored 0.88 AUC. The deck was written. The number went on slide nine.

Their advisor, an agricultural statistician at a state university, asked one question: how many rows do you have per plot?

Forty-one, on average. Three seasons of fortnightly visits.

A random row split scatters a plot’s forty-one visits across training and validation. The model does not need to learn anything about pest pressure to score well; it needs to learn that plot 1,183 in Yavatmal tends to cross the threshold, which it can do from the other forty visits sitting in the training set. And every plot in the validation set is a plot the model has seen thirty-odd times.

There was a second problem underneath the first. Pest pressure moves regionally within a season. A random split lets the model train on the third week of August while predicting the second, in the same district, in the same year. Neither of those situations occurs when the product runs, because the product runs forward in time on plots whose future is unknown.

They rebuilt the evaluation properly: group by plot, and split by season, training on seasons one and two and validating on season three.

0.62.

Before accepting it they ran one more check, and it is the cheap one. They permuted the target column, retrained the whole pipeline, and looked at the score. Under the grouped, season-ordered split it collapsed to 0.50, which is what a correct pipeline does. Under the original random split it came back at 0.57: well above chance on shuffled labels, which is only possible if something in the pipeline is reaching the answer by a route nobody intended. The route was a per-plot aggregate feature, computed across the whole dataset before splitting, which carried a fingerprint of each plot’s own outcomes into every one of its rows.

0.62 was not a disaster. The baseline (warn everybody every fortnight during the known risk window) is what the extension service effectively does, and against a like-for-like measurement the model was still adding something. But 0.88 was on slide nine, four weeks out.

The decision the founders faced had two costs and no clean side.

Present 0.62 with the explanation. It is defensible, it is the number the product will deliver, and it invites a conversation about validation design with investors who may or may not want to have it. It also invites a comparison against competitors quoting 0.9-something on random splits, which several of them were.

Present 0.88 with a footnote. Nobody would have caught it in the room. The cost arrives later, when the pilot in a fourth district produces field results nowhere near the slide, at which point the gap has to be explained to people who have already given money.

Delay the round by a season and collect a fourth year on new plots. Cleanest evidence, and the runway did not obviously cover it.

How it played out

They presented 0.62, next to the like-for-like baseline of 0.51, and next to the 0.88 with an explanation of why it was wrong. The slide was titled “the number we would have shown you”.

Two investors’ technical advisors said afterwards that the slide was the reason they recommended proceeding. The round closed smaller than the founders had hoped and at terms they described as fair.

The engineering that followed came out of the same afternoon. They kept a fixed reference set (one full season, one district, never touched) and promoted the label-shuffle check from something they had run once to a standing test in the training pipeline: permute the target, retrain, fail the build if anything scores above chance. It earned its place eight months later, on a change by a new joiner who added a rainfall aggregate computed over the whole dataset instead of inside the fold. Nobody reading that pull request would have caught it, and the build did.

Worth arguing about

  1. Both changes were made at once. How would you tell how much of the fall came from grouping and how much from time?

    One answer

    Run the two splits separately. Group-by-plot with a random season allocation isolates the entity effect; a season-ordered split that still allows a plot to appear on both sides isolates the temporal effect. Doing so is worth an hour, because the two have different remedies: an entity effect says the model is memorising plots and needs features that generalise across them, while a temporal effect says the relationship moves between seasons and may need recent data or a rolling training window.

  2. Was 0.62 the honest number, or is it now pessimistic in some way?

    One answer

    It is the honest number for the product as described (new plots, a future season) and it may be pessimistic in one respect: it is measured on a single held-out season, so it carries that season’s particular weather. Reporting it with the spread across several forward-chaining splits, rather than one number, would describe the uncertainty better. What it is not is pessimistic because of the grouping; that constraint matches how the product runs.

  3. Why does a label-shuffle test belong in the training pipeline rather than in a checklist?

    One answer

    Because the failure it catches is added by future changes, not by the original author. Permuting the target should collapse every score to chance, and anything above chance means some path in the pipeline reaches the answer. A checklist is run by whoever remembers it; a test in the build runs on the change that a new joiner makes eight months later, which is exactly when this class of bug is introduced.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    Training accuracy is 71 per cent and validation accuracy is 70 per cent. A colleague proposes reducing the tree depth to fight overfitting. What is wrong with that?

  2. 2

    A team tunes 200 configurations with five-fold cross-validation and reports the best cross-validated score as its estimate of performance. Why is that number optimistic?

  3. 3

    A default label becomes known 30 days after the application. A team uses a time-ordered split with no gap between training and test windows. What does the training window contain that it should not?

  4. 4

    A learning curve shows validation score flat from 40 per cent of the data onward, with the training score far above it. What does that say about collecting more rows?

  5. 5

    A 2,000-row validation set gives a standard error of about 0.8 points. After comparing 100 models that are genuinely equivalent, roughly how inflated is the winner’s score?

  6. 6

    A colleague cites double descent to argue that a gradient boosting model with 5,000 trees at a learning rate of 0.3 cannot overfit. What is wrong with the argument?

Measuring a model honestly

11 lessons · 1 h 37

You will be able toGiven a fitted classifier and a stated cost of each kind of error, compute the confusion matrix at a chosen threshold, defend that threshold by expected cost, say whether the model’s probabilities are calibrated, decide with an interval whether one model genuinely beats another, and report per-group performance with a defensible fairness criterion and its known trade-offs.

  1. 5.1When accuracy lies9 min
  2. 5.2The four numbers, worked through9 min
  3. 5.3The threshold is a business decision, not a default9 min
  4. 5.4ROC and precision-recall: every threshold at once9 min
  5. 5.5Does 0.7 mean seventy per cent?9 min
  6. 5.6Metrics for a number, and what each one hides8 min
  7. 5.7Is that improvement real?9 min
  8. 5.8From a probability to a decision worth making8 min
  9. 5.9Fairness as arithmetic: the definitions and what each one demands10 min
  10. 5.10Why you cannot have all three8 min
  11. 5.11The average is hiding the failure9 min
An illustrative case, built from documented patternsSix analysts, one threshold, and a second bank’s portfolioA co-operative bank in Kolhapur with 1.6 million card transactions a month, a fraud desk of six analysts, and a newly acquired portfolio from a smaller bank.

The fraud desk at Janseva Sahakari Bank reviews flagged card transactions and telephones the cardholder. Six analysts, each managing about forty reviews in a shift, which is a hard ceiling of roughly 240 reviews a day including the ones that arrive from other channels.

Their model, built the previous year, scored transactions and flagged anything above 0.5. That produced about 90 flags a day at 31 per cent precision, and caught an estimated 54 per cent of fraud by value.

Three things happened in one quarter.

First, the risk committee asked why the threshold was 0.5. Nobody could answer. It was the library default, applied by a contractor who had left. The analyst who inherited the model, Meghana, worked the arithmetic from the cost-sensitive lesson. A missed fraud on this portfolio costs the bank ₹14,200 on average once the chargeback and the investigation are counted. A review costs about ₹110 of analyst time. The break-even threshold is 110 divided by 14,310, which is 0.0077.

At 0.0077 the model flags roughly 2,400 transactions a day. The desk can review 240.

That is not a modelling failure and it is not a mistake in the arithmetic. It is two constraints that do not both fit, and Meghana wrote both numbers on the whiteboard rather than choosing between them quietly. The cost-optimal threshold says the bank is under-investing in the fraud desk by a factor of ten. The capacity threshold says today’s flag list has to be 240 long.

Second, she computed the per-row threshold instead. Review cost divided by review cost plus the transaction amount. A ₹110 review against a ₹4,80,000 transaction gives a threshold near 0.0002: flag on almost any suspicion. Against a ₹900 transaction it gives 0.109. Applied at a fixed capacity of 240 flags a day, ranked by expected loss rather than by probability, the recovered value rose by 38 per cent on a back-test with no change to the model and no extra analyst.

Third, and this is the part that nearly went wrong, the bank absorbed the card portfolio of a smaller co-operative bank in a neighbouring district. Forty thousand new cards, a different customer profile, and a fraud base rate of 0.09 per cent against Janseva’s own 0.31 per cent.

The model was scored on the new portfolio and its AUC held: 0.91 against 0.92. The committee read that as the model transferring cleanly and asked for it to go live on the new cards at the same operating point.

Meghana’s objection was the base rate. Precision is not a property of a model. On the acquired portfolio, at a threshold producing the same flag rate, precision would fall from 31 per cent to roughly 9 per cent: three times as many wrongly telephoned customers per genuine case, on a customer base that had just been told its bank had been taken over.

The decision had a cost either way. Running it as-is meant a queue that was 91 per cent wrong, on new customers, with analysts who would learn within a fortnight to distrust the flags. Not running it meant the acquired portfolio was covered by nothing but the old bank’s rules for at least a quarter.

How it played out

The model went live on the acquired portfolio at a threshold set by expected value per row rather than by probability, and the two portfolios were given separate flag budgets (200 and 40) so that the new customers’ queue could not be crowded out by the larger book.

The committee also funded two additional analysts, which was the first time the fraud desk’s size had been argued for with a number rather than a feeling. The paper Meghana took to them contained the break-even calculation, the capacity constraint, and the value recovered per additional analyst-shift at the current model quality.

Six months later the acquired portfolio’s precision had risen to 19 per cent, mostly because a hundred confirmed cases from that book had entered the training data. The AUC was unchanged throughout, which is the point: the thing that improved was not the model’s ranking.

Worth arguing about

  1. AUC was almost identical on the two portfolios. Why was that not evidence that the model would work on the new one?

    One answer

    Because AUC measures ranking only: the probability that a random fraud outscores a random legitimate transaction. It is insensitive to the base rate. Precision divides by what the model flagged, so when fraud falls from 0.31 per cent to 0.09 per cent the same ranking quality produces roughly a third of the precision. The model was equally good at ordering and much worse to work a queue from, and only one of those is what the analysts experience.

  2. The cost-optimal threshold and the capacity threshold differed by a factor of ten. What does that gap actually mean?

    One answer

    It means the bank’s own numbers say a reviewed case is worth far more than it costs to review, so the constraint is staffing rather than the model. Writing both thresholds down converts an invisible operational limit into a budget question that somebody can answer. Choosing the capacity threshold quietly would have hidden the fact that the fraud desk is the binding constraint on recovered losses.

  3. Ranking by expected loss recovered 38 per cent more value with the same model. Where did that come from?

    One answer

    From information the global threshold was discarding. A fixed probability cut treats a ₹900 case and a ₹4,80,000 case as equally worth a slot in the queue. Ranking by probability multiplied by amount spends the day’s 240 reviews where the losses are. It requires the probabilities to be roughly calibrated, since an uncalibrated score multiplied by an amount is not an expected loss.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    A model with 60 per cent recall and 99.4 per cent specificity moves from a population where fraud is 4 per cent to one where it is 0.1 per cent. What happens to precision?

  2. 2

    A missed fraud costs ₹18,000 on average and a review costs ₹90. For a well-calibrated model, what is the cost-minimising threshold?

  3. 3

    On 100,000 transactions containing 100 frauds, a model flags 900 legitimate ones. Why does the ROC curve barely register that?

  4. 4

    A team applies isotonic regression to a random forest’s outputs and reports that AUC improved. What should you conclude?

  5. 5

    Two models are compared by running ten-fold cross-validation on each and applying a paired t-test to the ten pairs of fold scores. What is the defect?

  6. 6

    Two groups have different base rates. A vendor claims their tool delivers calibration within groups and equal false positive and false negative rates. What should you conclude?

Trees, ensembles, and the algorithms that win on tables

10 lessons · 1 h 29

You will be able toChoose between a linear model, a random forest and a gradient boosting library for a given tabular problem and defend the choice, tune the four hyperparameters that actually matter in each, and explain why impurity-based feature importance is biased and what permutation importance and SHAP replace it with.

  1. 6.1The classic algorithms, and when each is right10 min
  2. 6.2How a tree chooses where to cut9 min
  3. 6.3Bagging: many unstable models, averaged9 min
  4. 6.4Boosting: each model fixes the last one’s mistakes9 min
  5. 6.5XGBoost, LightGBM, CatBoost: what actually differs9 min
  6. 6.6k-nearest neighbours, and why distance stops meaning anything8 min
  7. 6.7Naive Bayes: wrong assumptions, useful results8 min
  8. 6.8Support vector machines and the kernel trick9 min
  9. 6.9Feature importance, and the ways it misleads9 min
  10. 6.10Explaining one prediction, and the shape of one feature9 min
An illustrative case, built from documented patternsThe bar chart that nearly rebuilt three warehousesA grain storage company in Madhya Pradesh with 46 warehouses, and a board paper due in eleven days recommending where to spend a ₹9 crore refurbishment budget.

Annadhan Warehousing stores wheat, gram and soya for traders and for the state procurement agency. Spoilage (grain downgraded on outward inspection) costs the company between two and four crore rupees a year and costs it customers, which is worse.

They had four years of records: 310,000 stack-months, one row per stack per month, with moisture at intake, variety, stack height, days in store, fumigation history, ambient humidity from the nearest weather station, warehouse identifier, and whether the stack was downgraded at outward inspection.

A gradient boosting model reached 0.83 AUC against a baseline of 0.61. That part was uncontroversial and useful: the model was going into the fortnightly inspection schedule, deciding which stacks got opened first.

The controversy was the second slide. Somebody had printed model.feature_importances_ and the top feature, well clear of everything else, was warehouse_id. The operations director read that as the model saying the warehouses themselves were the problem, and the refurbishment paper was drafted around the three warehouses whose identifiers the model split on most often. Nine crore rupees.

The analyst, Devika, had been in the job four months and asked for a week.

Her first test took an hour and is the one from the importance lesson. She added a column of random integers between one and ten thousand, with no relationship to anything, and refitted. The random column came fourth. Nothing was broken. Impurity importance rewards a feature for offering many candidate thresholds, and warehouse_id has forty-six levels while variety has four and fumigated_last_30d has two. A high-cardinality column accumulates gain by having more chances to reduce impurity, whether or not it carries signal.

Permutation importance on held-out data told a different story: moisture at intake first, days in store second, ambient humidity third, warehouse identifier seventh and with an interval that crossed zero.

Then the correlated-feature problem arrived, because these two are not independent. Warehouses in the Hoshangabad belt receive grain from a catchment with systematically higher moisture at intake. Permuting warehouse_id alone barely moved the score, because the model simply read moisture instead. Permuting moisture_at_intake alone barely moved it either, because the model read the warehouse. Both looked unimportant, which is the failure the lesson warns about, and taken literally it would have said nothing mattered.

Devika clustered the correlated columns and permuted the group. Moisture-and-location together accounted for most of the model’s dependence. Which of the two is doing the work is not a question the model can answer, because in this data they never move independently.

The decision, with eleven days left, was genuinely hard.

Recommend the refurbishment as drafted. The three warehouses are in the high-moisture belt and they do have the worst spoilage. Something is wrong there. Spending nine crore on ventilation and flooring is not obviously wasted, and the paper is written.

Recommend intake moisture control instead: testing at the gate, rejection thresholds, a drying arrangement with the procurement agency. Cheaper, and it is what the permutation grouping points at. It is also an intervention, and the model is an association. Nothing in the analysis establishes that lowering intake moisture at those sites lowers spoilage, because intake moisture has never varied at those sites independently of everything else about them.

Ask for the board paper to be delayed by a season and run the only thing that would settle it.

How it played out

The paper went to the board with the refurbishment reduced to one warehouse and an explicit statement that the model could not distinguish between the building and the grain arriving at it.

The remainder of the budget funded a trial. Nine warehouses were fitted with intake moisture meters and a rejection threshold at fourteen per cent, with the sites chosen so that the high-moisture belt and the rest of the network were both represented, and the assignment within each group made at random. That is the experiment the module recommends, and it cost less than a fifth of the original proposal.

After two seasons the trial showed a real reduction in downgrading at the treated sites, larger in the Hoshangabad belt, which is the answer neither the bar chart nor the permutation grouping could have given.

The bar chart is still produced. It now carries a printed line underneath it saying what it measures and what it does not, because Devika found that removing it altogether simply meant somebody generated their own.

Worth arguing about

  1. Why did a column of random integers rank fourth?

    One answer

    Because impurity importance sums how much each feature reduced impurity across all splits, and a feature with ten thousand distinct values offers a very large number of candidate thresholds. Some of them will separate the training rows by chance. The metric is measuring what it claims to measure (contribution to fitting the training data) and that is not the same as carrying signal. High-cardinality columns and continuous columns accumulate importance for structural reasons.

  2. Permuting either the warehouse or the moisture column alone barely moved the score. What would you have concluded if you had stopped there?

    One answer

    That neither mattered, which is exactly backwards. When two features carry nearly the same information, shuffling one leaves the model able to read the other, so the score holds and both appear unimportant. The remedy is to cluster correlated columns and permute the group together, which measures what the group is worth. That is usually the question anyone actually has.

  3. The permutation grouping pointed at intake moisture. Why was that still not enough to spend the budget on moisture control?

    One answer

    Because importance is a statement about the model, and the proposal is an intervention in the world. In this data intake moisture never varies independently of the site, so the association cannot separate ‘wet grain causes spoilage’ from ‘these buildings cause spoilage and also receive wet grain’. Only an experiment that varies intake moisture while holding the site fixed can answer it, and that is what the randomised trial did.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    A node holds 20 rows, 6 of them positive. A candidate split sends 8 rows left with 5 positives and 12 right with 1 positive. How does the tree score that split?

  2. 2

    Why does a random forest consider only a random subset of the features at each split?

  3. 3

    Adding trees never makes a random forest worse, but it does make a boosted model worse. Why?

  4. 4

    In 1,000 raw dimensions a point’s nearest neighbour is only about 20 per cent closer than its farthest. Which methods does that break?

  5. 5

    Naive Bayes classifies documents well while reporting probabilities above 0.99 for most of them. What produces that combination?

  6. 6

    Two columns hold the same measurement in different units. Permutation importance reports near-zero importance for both. What is the correct reading?

Learning without labels, and learning a representation

10 lessons · 1 h 27

You will be able toCluster a dataset and defend the number of clusters with more than an elbow plot, reduce dimensionality with PCA and state how much information the reduction discarded, explain what an embedding is as a geometric object, and build a working nearest-neighbour search over pretrained embeddings without a GPU.

  1. 7.1k-means, and what it assumes about your data9 min
  2. 7.2Choosing k, and why the elbow rarely helps8 min
  3. 7.3DBSCAN and hierarchical clustering: when shape and structure matter8 min
  4. 7.4PCA: fewer columns, and what you gave up9 min
  5. 7.5t-SNE and UMAP, and how they mislead8 min
  6. 7.6What an embedding actually is10 min
  7. 7.7Building a working semantic search with no GPU9 min
  8. 7.8Recommendation: learning a vector per user and per item9 min
  9. 7.9Anomaly detection, and the base rate that ruins it8 min
  10. 7.10Self-supervised learning: making labels out of the data itself9 min
An illustrative case, built from documented patternsThe segmentation that was not thereA state women’s helpline in Kerala with 62,000 call records, a research officer, and a proposal to reorganise counsellor training around caller segments.

The helpline receives calls about domestic violence, workplace harassment, legal questions, mental distress and a long tail of everything else. Counsellors record a structured summary at the end of each call: category, district, caller age band, whether a referral was made, duration, time of day, whether the caller had called before, and a free-text note.

A proposal had been funded to redesign counsellor training around “caller segments”: the idea being that a small number of recognisable caller types exist, that each needs a different opening approach, and that training modules could be built for each. The proposal named six segments as a target, because six is the number of training modules the calendar could absorb.

Nandana, the research officer, was asked to find them. She had 62,000 records, no labels, and a genuine question with money behind it.

She did the work properly. Categorical fields one-hot encoded, duration log-transformed, everything standardised, k-means for k from two to ten, with n_init left at ten because lowering it to save time was not something she had measured.

The elbow plot was a smooth decay with no corner. Three colleagues looking at it picked three different values.

Silhouette scores ran between 0.11 and 0.17 across every k she tried. The rough guide in her notes said above 0.5 is solid structure, 0.25 to 0.5 is weak, and below 0.25 means there is probably nothing worth naming.

The gap statistic, which is the only one of these that is allowed to answer “one”, preferred k equal to one. She checked it the cheap way as well, clustering a shuffled copy of the data and comparing, and the shuffled version looked much like the real one.

The stability test was the clearest. Two random eighty per cent subsets, clustered separately, compared on the rows they shared with the adjusted Rand index. At k equal to six the agreement was 0.31. Rerunning with a different seed produced six different groups containing largely different callers, all of which could be described and named, none of which reproduced.

She also ran HDBSCAN, which is allowed to decide the count itself and to label points as noise. It found two small dense groups (repeat callers from two districts with an unusual referral pattern, about 900 records between them) and called everything else noise.

Now the decision.

Deliver six segments. She could. k-means returns six clusters from anything, the centres are describable, and a page of prose about “the hesitant first-time caller” and “the informed repeat caller” would read well and would survive a steering committee. The training modules would be built and would probably do some good, because good counsellor training does some good regardless of whether its organising scheme is real.

Report that there are no segments. True, defensible, and it terminates a funded project. It also tells a room of people who have committed to a plan that the plan’s premise does not hold, which is a specific kind of unpopular.

Deliver the two small dense groups and nothing else. Honest, and 900 records out of 62,000 is not a training programme.

How it played out

She reported that the data did not support caller segments, and she brought the evidence in an order the committee could follow: the shuffled-data comparison first, because it needs no statistics, then the stability numbers, then the silhouette values.

The recommendation that replaced the segments was to organise the training around the two things that did vary and could be measured: call category, which is recorded, and whether the caller had called before, which is also recorded. Both are known at the start of a call, which the cluster assignment would not have been.

The two dense groups from HDBSCAN went to the operations team rather than the training team. Both turned out to be a single referral pathway in two districts that was sending callers back to the helpline because a partner office had changed its intake hours. That was a fixable process fault, found by the method that was permitted to say “most of this is noise”.

The proposal document was rewritten rather than abandoned, and the sentence Nandana asked to have kept in it is that a clustering that does not reproduce across subsamples describes the analyst’s persistence rather than the callers.

Worth arguing about

  1. k-means returned six clusters that could be named. Why is that not evidence that six segments exist?

    One answer

    Because k-means partitions whatever it is given. It will return six tidy groups from uniform random noise, with a respectable inertia, and the centres of those groups can always be described in words. Describability is a property of humans, not of the data. The test is whether the same structure appears when the algorithm sees a different sample, and at an adjusted Rand index of 0.31 it did not.

  2. Why does the gap statistic matter more here than the silhouette score?

    One answer

    Because the silhouette is only defined for two or more clusters and never questions whether any clustering is appropriate. It can only tell you which k is least bad. The gap statistic compares the achieved inertia against what would be achieved on random data with the same bounding box, so it is able to conclude that one cluster is best, which is the finding this dataset actually supported.

  3. The recommendation ended up using two recorded fields rather than a learned segmentation. What did that buy beyond honesty?

    One answer

    It buys availability at the moment of use. A cluster assignment has to be computed from the full record, most of which is written after the call. Category and repeat-caller status are known as the call begins, which is when a counsellor needs to choose an approach. A segmentation that only exists after the conversation cannot change the conversation.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    k-means is run on two long, parallel, elongated groups of points and returns clusters that cut across both of them. Why?

  2. 2

    Silhouette scores hover near 0.14 for every k from 2 to 10. Which measure is able to tell you that no clustering is appropriate at all?

  3. 3

    A team reduces 200 features to 30 components retaining 95 per cent of the variance, and the downstream supervised model gets worse. What is the most likely explanation?

  4. 4

    A t-SNE plot shows two tight clusters at opposite ends of the picture and one large diffuse blob. Which reading is supportable?

  5. 5

    Sentence embeddings are compared by cosine similarity rather than by Euclidean distance. What does that choice deliberately discard?

  6. 6

    A detector catches 90 per cent of the 100 daily frauds among a million transactions, with a 1 per cent false positive rate. What does the alert queue look like?

Neural networks, built from what you already know

10 lessons · 1 h 27

You will be able toExplain why a multi-layer network with no non-linearity collapses to a single linear model, trace one backpropagation step through a two-layer network by hand, diagnose a training failure from the loss curve and the gradients, and fine-tune a pretrained model on a few hundred labelled examples using free compute.

  1. 8.1Neural networks as the natural next step9 min
  2. 8.2XOR, and why the bend is the whole idea8 min
  3. 8.3The bends: ReLU, and why sigmoid stopped being used inside networks8 min
  4. 8.4Backpropagation, traced through one tiny network10 min
  5. 8.5Starting well, and staying well-behaved9 min
  6. 8.6Momentum, Adam, and what the optimiser is doing for you8 min
  7. 8.7Keeping a large network from memorising8 min
  8. 8.8Convolution: the same detector, everywhere in the image9 min
  9. 8.9Sequences: from recurrence to attention9 min
  10. 8.10Standing on somebody else’s compute9 min
An illustrative case, built from documented patternsThree hundred and forty leavesA district agriculture office in Belagavi, one extension officer with a laptop and a free Colab account, and 340 labelled photographs of diseased chilli leaves sent in by farmers over one season.

Farmers in the district send photographs to a WhatsApp number when a crop looks wrong. An officer looks at each one and replies. The volume had grown to about ninety photographs a day in the season, against one officer, and the reply time had stretched to two days, by which point spraying advice is worth much less.

The proposal was a classifier that would sort incoming photographs into five classes (leaf curl virus, anthracnose, thrips damage, nutrient deficiency, and healthy or unclear) so that the officer worked the queue in a sensible order rather than in arrival order.

The labelled set was 340 photographs, labelled by the officer himself over one season. Not thousands. Three hundred and forty, unevenly split, with the smallest class holding 31.

Prakash had worked through the transfer learning lesson and knew the recipe: feature extraction first, then last-block fine-tuning, then full fine-tuning, stopping at whichever step stopped improving. He also had a free GPU quota and an understandable wish to use it.

Step one took forty minutes. A pretrained ResNet-50 with the classifier head removed, run in evaluation mode over the 340 images to produce 2,048-dimensional feature vectors, then a logistic regression on top. Grouped five-fold cross-validation, grouped by the farmer who sent the photograph, because eleven farmers had sent more than five images each and several had photographed the same plant repeatedly. Macro F1 of 0.71.

Step two, fine-tuning the last block, took two hours including the mistakes. Macro F1 of 0.74, with a spread across folds wide enough that he could not be confident the improvement was real.

Step three, full fine-tuning, produced 0.62 and a training curve that fell off a cliff in the first epoch. That is catastrophic forgetting with the learning rate set too high, and dropping it by a factor of thirty recovered to 0.73: no better than step two, at eight times the training time and with a model he could no longer explain the behaviour of.

So the measurement said step one or step two, and the difference between them was inside the noise. That was not the hard decision.

The hard decision was what the grouped cross-validation had exposed on the way. Every photograph in the training set came from a smartphone camera, in daylight, held about thirty centimetres from the leaf, by somebody who had been told by the officer how to take the photograph. The officer had, in effect, curated his own training distribution over a season of replying to people.

The incoming queue is not that. It contains photographs taken at dusk, at two metres, of a whole plant, through a polythene tunnel, and by farmers who have never been told anything about how to hold a phone.

Deploy the 0.74 model on the whole queue. It is a triage aid, not a diagnosis, and a wrong ordering is not a wrong prescription. The cost is that its confidence on out-of-distribution photographs is not lower than on good ones (a network is typically over-confident, and increasingly so as it gets larger) so the queue would be ordered wrongly with no signal that anything was amiss.

Deploy it only on photographs that resemble the training set, using reconstruction error or a simple image-quality check as a gate, and route everything else to the officer in arrival order. Less coverage, and it requires building the gate.

Spend the season collecting a representative labelled set first. Correct, and it means the reply time stays at two days for another year.

How it played out

He shipped step one (the frozen backbone plus logistic regression) with a gate in front of it, and he shipped it with an abstention band. Photographs whose predicted probability did not exceed 0.55 for any class were not ordered at all; they joined the arrival-order queue.

The gate was crude and worked: image size, blur estimate, and the fraction of the frame occupied by green pixels. Photographs failing it went straight to arrival order. About a third of the incoming queue failed it in the first month, which is roughly what he had expected from looking at fifty images by hand.

The logistic regression was chosen over the fine-tuned model for a reason that had nothing to do with the scores. It runs on a CPU on the office laptop, it retrains in ninety seconds when the officer adds new labels, and he does add them: he labels the abstentions as he works them, which is uncertainty sampling arrived at by accident, and the labelled set passed 900 by the end of the following season.

Reply time for the photographs the system ordered fell to under four hours. For the third it declined to order, it did not change.

Worth arguing about

  1. Full fine-tuning did worse than a frozen backbone. What does that tell you about the dataset rather than about the method?

    One answer

    That 340 images across five classes do not support updating twenty-five million parameters. Each level of adaptation needs more data than the last, and full fine-tuning has enough freedom to reshape the pretrained features around a small sample. The first-epoch collapse was the learning rate destroying representations that took a great deal of compute to build, and even with the rate corrected there was not enough data to earn back the freedom.

  2. Why group the cross-validation by farmer?

    One answer

    Because several farmers sent multiple photographs, sometimes of the same plant, and a random image split would put near-duplicates on both sides. The model would be recognising the plant rather than the disease and the score would be inflated by an amount nobody could estimate. The product runs on photographs from farmers whose other photographs are not in the training set, so the split has to match that.

  3. The abstention band lowered coverage. Why was that a better design than ordering the whole queue?

    One answer

    Because the model’s confidence carries no information about whether a photograph resembles the data it was trained on, and networks are typically over-confident. Ordering a queue wrongly with no signal is worse than not ordering part of it, since the officer would learn to distrust the whole ranking. Abstaining is the reject option from the cost-sensitive lesson: a system that is right on the cases it chooses to decide and defers the rest is a usable product.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    Fifty linear layers are stacked with no activation function between them. What function does the network compute?

  2. 2

    Why did the sigmoid stop being used inside hidden layers?

  3. 3

    During a backward pass the gradient arriving at a hidden unit is 0.78 and that unit’s pre-activation was negative. With a plain ReLU, what gradient continues below it?

  4. 4

    Why does AdamW apply weight decay outside Adam’s adaptive scaling?

  5. 5

    A PyTorch model returns a different prediction each time it is called on the same row. What is the most likely cause?

  6. 6

    With 300 labelled images, full fine-tuning of a ResNet scores worse than a frozen backbone with logistic regression on top. What does that indicate?

Into the world, and keeping it honest

10 lessons · 1 h 24

You will be able toTake a fitted model to a running service with a versioned artefact, a reproducible training run, monitoring that distinguishes covariate shift from concept drift, a stated retraining trigger, and a written record of what the model was trained on and who it should not be used for.

  1. 9.1The model is about 5% of what you have to build8 min
  2. 9.2Batch, online, and the latency budget8 min
  3. 9.3When training and serving quietly disagree9 min
  4. 9.4Monitoring: what to watch, and in what order9 min
  5. 9.5When to retrain, and what breaks when you do8 min
  6. 9.6Being able to build the same model twice8 min
  7. 9.7AutoML: what it automates, and what it cannot8 min
  8. 9.8Making a model small enough to be affordable8 min
  9. 9.9When the model changes the data it will be trained on9 min
  10. 9.10What you owe the people in the data9 min
An illustrative case, built from documented patternsA week of retraining that fixed nothingA pharmacy chain in Hyderabad with 212 branches, a four-person data team, and a demand forecast that started missing badly in the second week of March.

Sanjeevini Pharmacy forecasts daily demand per stock-keeping unit per branch, about 1.4 million forecasts a night, feeding an automatic replenishment order. When the forecast is low, a branch runs out and a customer walks to the shop next door. When it is high, slow stock ages towards expiry.

The model had been stable for fourteen months. Weighted mean absolute percentage error sat between 18 and 21 per cent. In the second week of March it went to 34 and stayed there.

The commercial director asked for a retrain by Friday. The reasoning was not unreasonable: the model is stale, the world has moved, retrain it on recent data. The data team’s lead, Anwar, asked for two days to diagnose first, and had to argue for them, because two days is two days of stockouts.

The monitoring told him something before he opened a notebook. System health was clean. Prediction distributions had shifted downward: the model was forecasting less than it had. Input distributions had a specific and loud alarm: for one feature, pack_size_units, the missing rate had gone from under one per cent to 23 per cent on the eighth of March and stayed there.

That is a covariate shift in the monitoring’s language and a data fault in reality. Twenty-three per cent is not a population moving. It is something upstream breaking on a particular day.

The trace took four hours. The procurement team had migrated their supplier master to a new system on the seventh of March. In the new system pack size for one category of products is recorded in a separate strength field, and the old column is null for anything created after the migration. Nobody told anyone, because from procurement’s point of view nothing had broken.

There was a second effect stacked on the first, and it is the one that would have made a retrain actively harmful. The imputer in the pipeline filled the missing pack size with the training median. For the affected category (largely paediatric syrups) the median across the whole catalogue is meaningfully smaller than the true value, so the forecast for those lines was systematically low, which is exactly the error pattern the branches were reporting.

Now the decision, and both options had a cost that landed on somebody.

Retrain on recent data, as asked. It would have produced a better-scoring model, because a model trained on the last twelve weeks learns that pack size is missing for a quarter of rows and adapts to predict without it. The score recovers. The forecasts stay wrong in a new way, the fault stays in the upstream system, and the next person to look at it inherits a model that has quietly encoded a broken join. Retraining teaches the model the broken data.

Fix the upstream mapping. Correct, and it required a change from a procurement team in the middle of a migration, with no incentive and no spare week, and it would take longer than Friday.

Patch the pipeline to read the new strength field when the old column is null, and leave the model alone.

How it played out

They patched the pipeline, in an afternoon, and the error was back under 22 per cent within four days with no retraining at all.

The procurement mapping was fixed six weeks later through the normal change process, and the patch was left in place because a fallback that costs nothing and covers a class of failure is worth keeping.

Three things changed permanently as a result. Unseen-category and missing-rate alerts were promoted from the weekly report to the pager, with a stated action next to each: a jump in the missing rate for any feature is an upstream investigation, not a modelling one. The team wrote down a rule that no retrain ships without a diagnosis naming which of covariate shift, label shift or concept drift it is a remedy for. And the retraining pipeline gained the gate it had been missing: performance on a fixed reference period against the current production model, a prediction distribution comparison, and slice checks by branch and by category.

Anwar’s note to the commercial director afterwards made the argument that the two days had been the cheapest part of the incident: a retrain on the Friday would have hidden the fault, restored the metric, and left the paediatric lines under-ordered for as long as anyone cared to look.

Worth arguing about

  1. A retrain would have restored the error metric. Why would that have been the wrong outcome?

    One answer

    Because the metric would have recovered while the forecasts stayed wrong for a specific category. A model trained on data where pack size is missing for a quarter of rows learns to predict without it and scores well on data with the same fault. The remedy matches the diagnosis only when the relationship in the world has genuinely changed. Here an upstream field had moved, and retraining converts a visible fault into an invisible one.

  2. Why did input monitoring find this before the performance metrics did?

    One answer

    Because input monitoring needs no labels and moves first. Actual demand takes a day or more to arrive, and the error metric is a weighted average over 1.4 million forecasts, so a fault confined to one category moves it slowly. A missing rate jumping from one per cent to twenty-three on a single day is unambiguous, visible within hours, and points at a date that can be matched against a change log.

  3. The imputer turned a missing value into a wrong value. What would have made that failure louder?

    One answer

    Adding a missingness indicator alongside the imputed value, as the missing-values lesson recommends, so the model and the monitoring both see that the value was absent rather than small. Beyond that, letting the gradient boosting model handle nulls natively would have avoided substituting a catalogue-wide median into a category where it does not apply. Either way, the fix is to make absence visible rather than to replace it with a plausible number.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    An online scoring service must answer within 100 milliseconds at the 99th percentile and is over budget. Where does the time most often go?

  2. 2

    Which test catches a feature that is computed differently in the serving path from in training?

  3. 3

    The base rate of fraud rises from 1 per cent to 4 per cent while the model’s ranking quality is unaffected. What is the cheapest correct remedy?

  4. 4

    A retrained model scores better on the fixed reference set and ships with the old decision threshold unchanged. What is likely to happen?

  5. 5

    A team runs AutoML on a table that contains a leaked column. What is the effect?

  6. 6

    A lender wants to estimate offline how a different approval policy would have performed. What must have been logged at the moment each decision was made?

What this course is

How a machine actually learns from data: what fitting means mechanically, why the features you choose matter more than the algorithm you pick, how to hold out data honestly, why accuracy lies on rare events, what the classic algorithms are good at, and how gradient descent and neural networks follow from all of it. You should be able to read code. You do not need calculus, statistics, or a maths degree. Every idea arrives with real numbers attached.

Who wrote it

Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Exam keys checked blind by a second model: 3,665 of 3,666 agreed. Academic review invited.

More in Start here

  1. AI, Safety and What Goes Wrong73 lessonsThe failure modes of AI, stated plainly, with the numbers.
  2. AI, Actually Explained92 lessonsFor someone who was never told what this thing is.
  3. Getting Real Work out of a Model72 lessonsYou already use ChatGPT, Claude or Gemini. This is how to stop getting average answers.
  4. How a Language Model Actually Works78 lessonsThe machinery under the chat box, explained without matrices.