Try 50 settings that are all equally good, 70% accurate, and score each one on the same 500 dev examples. The best scores 74.6% on dev and 70.0% on a fresh test set. Those 4.6 points were luck.
Drag the slider to try more settings, then change the size of the dev set. Watch the gap between the best dev score and its test score. Then we build the habits that keep a number honest, from separate pots of data to a look at the errors.
You need a little Python, what a probability is and what training a network means (Lecture 3). We build the rest from zero.
Lecture 6, "Final Projects: Custom and Default; Practical Tips", of Stanford CS224N, Natural Language Processing with Deep Learning (Winter 2026, Diyi Yang and Yejin Choi). Its suggested reading is the "Practical Methodology" chapter of Goodfellow, Bengio and Courville's Deep Learning (2016), which gives this page its name. Before: Lecture 5, Transformers. Next: Lecture 7, Pretraining.
Illustrative simulation, computed live: every setting is exactly 70% accurate, and each score is a random draw of right and wrong answers. The test set has as many examples as the dev set. "Average best" is the exact average over all possible draws.
Chapter 0
Score a memorizer on the data it saw and on data it never saw, and see which number to trust
Your final project ends with one number: "our model gets 84% accuracy". The lecture's practical half asks one question. Is that number true?
Two things make it false. The model may not learn what you think it learns. Or the number may come from data that the model, or you, have already seen. The lecture puts the first one plainly: neural networks want to learn, so if yours does not, something you did stops it. Finding that thing takes debugging and tuning, and that often takes longer than writing the model.
Start with the oldest trap. A nearest-neighbour model labels a point with the label of the training points closest to it. With one neighbour, every training point is its own closest neighbour.
Filled and hollow dots are two classes of training points. Blue is where the model says "filled". Switch the number of neighbours, then show the new points.
Illustrative toy: two noisy half-moons, 30 training points (4 with flipped labels) and 400 new points from the same source. The page computes the model and both scores live. On 4,000 more points the two models tie, at 74.2% and 74.3%.
How do we score it? Call the number of examples N. For example i, call the true label yi and the model's guess ŷi. Accuracy counts the right guesses:
acc equals one over N, times the sum over i of one-if y-hat-i equals y-i.
Go through the N examples. Write 1 for each one where the guess ŷi equals the label yi, and 0 otherwise. Add them up and divide by N.
From the toy: one neighbour gets 30 of the 30 training points right, so acc = 30 / 30 = 100%. On the 400 new points it gets 294 right: acc = 294 / 400 = 73.5%. Thirteen neighbours score 20 / 30 = 66.67% on training and 308 / 400 = 77.0% on new points.
On the training points, 1 neighbour wins by 33 points. On new points the two are close, and 13 neighbours is ahead. A 33-point lead that vanishes on new data was never a lead. Only data the model never trained on tells you how it will do, and the rest of this lesson builds on that rule.
Symptom: the report says 100%, and the model does far worse on new text.
Measure: score it on examples it never trained on: 73.5% here.
Fix: keep separate pots of data, and report only a score from a pot the model never saw (Chapter 1).
Chapter 1
Give each pot one job, and see what happens when the training pot also sets a hyperparameter
The lecture names five pots of data. Each one trains something, so each must stay separate:
Many public datasets come split into train, dev and test. If there is no dev or tuning set, cut one from the training data. When data is scarce, cross-validation takes turns: each slice of the data sits out once, so every example does both jobs.
The page trains a 64-unit network six times, each with a different weight penalty λ. The dashed curve is its accuracy on the training pot, the solid one on the tuning pot. Choose which pot picks λ, or drag the cursor yourself.
Illustrative toy, trained live when you scroll here: the half-moons of Chapter 0, a network with 64 hidden units, 2,500 steps per run. On 4,000 more fresh points the two choices score 75.3% and 80.1%: the 400-point test pot widens the gap, but the order holds.
Take one hyperparameter: λ, how hard training pulls the weights toward zero (Chapter 6 builds it). Chosen on the training pot, the answer is λ = 0, because no penalty fits the training points best: 100%. Its test score is 73.25%. Chosen on the tuning pot, the answer is λ = 0.003, and the test score is 84.0%. Same network, same data; only the pot that chose differs.
Material must not cross pots in any form. A review posted twice, once in train and once in test, is a leak. So are two sentences cut from one document when the test asks about that document.
Symptom: the chosen hyperparameter is always the most flexible one: no penalty, no dropout, the longest training.
Measure: compare the choice's score on the pot that chose it with its score on a pot that did not.
Fix: choose hyperparameters on a tuning set the weights never trained on.
Chapter 2
Draw the same model's dev score again and again, and measure how far it wanders
Suppose a model is right on exactly 70% of all the reviews it could ever meet. Call that its true accuracy. You never see it. You see a dev score: its accuracy on the 500 reviews you happened to collect. Another 500 reviews would give another score.
Each bar counts dev sets that gave that score. The model never changes. Change the dev set's size and draw again.
Illustrative simulation: the model answers each dev example right with probability 0.70, independently. Computed live.
How far does a dev score wander? Call the true accuracy a and the number of dev examples n. The typical distance of a score from a is its standard error, SE:
SE equals the square root of a times one minus a, over n.
Multiply the true accuracy a by its complement, 1 − a. Divide by the dev size n. Take the square root. About 95% of dev scores land within 1.96 SE of a.
a = 0.70 and n = 500: 0.70 × 0.30 = 0.21, then 0.21 / 500 = 0.00042, and √0.00042 = 0.0205. SE is 2.05 points, so 95% of dev scores fall between 66.0% and 74.0%. With n = 2,000, SE is 1.02 points: four times the data halves the noise.
So two runs 1 point apart on 500 examples may not differ at all. The statistics of evaluation lesson shows how to compare two models on the same examples, which is less noisy than comparing two separate scores.
Symptom: you keep a change because the dev score went from 72.0% to 73.0%.
Measure: compare the gain with the SE, 2.05 points here. A 1-point gain is inside the noise of one score.
Fix: a larger dev set, several random seeds, or a paired comparison on the same examples.
Chapter 3
Keep the top dev score out of many, predict how much luck it holds, and check it on fresh data
Tuning means trying many settings and keeping the one with the best dev score. Each score is noisy, so the top score is the one with the luckiest draw. The lecture warns about this: if you keep running on the same evaluation set, you begin to overfit to it. This is a selection effect, sometimes called the winner's curse.
How much luck does the winner hold? Say you try K settings, all with true accuracy a, each scored on the same n dev examples, so each has standard error SE. Call cK the average size of the largest of K draws from a standard bell curve:
The best dev score is about a, plus c-K times S-E.
Look up cK for your number of tries K. Multiply it by the standard error SE. Add that to the true accuracy a. The growth with K is slow, so the first few tries add the most luck.
The hero's setting: K = 50, a = 0.70, SE = 2.05 points. best ≈ 70 + 2.25 × 2.05 = 74.6%. The exact binomial answer is 74.55%. The hero's default draw gave 74.6% on dev and 70.0% on test.
Real settings do differ, and then tuning helps: it tends to pick a better one. But the winner's dev score still overstates even that winner. The toy gives each setting a true accuracy of its own.
Each yellow dot is a setting: across is its true accuracy, up is its dev score. The diagonal is "dev equals truth". The ringed dot has the top dev score.
Illustrative simulation: each setting draws a true accuracy around 70% with the chosen spread. Then it gets a 500-example dev score and a 500-example test score. Computed live.
The fix is the dev2 and test pots of Chapter 1. Make your choices on dev. Confirm the winner on dev2, which the choosing never touched. Open the test set once, at the end, and report what it says.
Symptom: the test score comes in several points below your best dev score.
Measure: count the settings you scored on dev. cK × SE predicts the size of the drop.
Fix: confirm on dev2, report the test score as it is, and do not tune on it afterwards.
Chapter 4
Train on eight reviews, plant a bug, and see which bugs the tiny test catches and which one it misses
The lecture's experimental strategy starts small. Start with a simple model and get it to work, because a complex broken model is hard to fix. Then add one piece at a time.
Run the first model on a tiny amount of data: 4 to 8 examples is good. Bugs show up much more easily, and each run takes seconds. Make sure the model gets 100% on these examples, testing on the training data itself. If it cannot, the lecture says, the model is either not powerful enough or broken.
What does training make small? For each example i, call its input xi and its label yi. The model gives the probability P(yi | xi) to the right label. The loss L averages the surprise over the N examples:
L equals minus one over N, times the sum over i of log P of y-i given x-i.
For each example, take the probability the model gave its true label, and take minus its log. Average over all N examples. That average is L.
A model that says 0.5 for every review has −log 0.5 = 0.693 on each one, so L = 0.693. This is the "learned nothing" line for two classes. Our toy starts at 0.715 and, with no bug, falls to 0.001 by step 150.
Pick a bug and press Train. Each row is a review with its label. The blue bar is the model's probability that the review is positive. The pink curve is the loss.
Illustrative toy, trained live: a bag-of-words input over the 12 words of these reviews and 16 hidden units. Adam with learning rate 0.02 runs 150 full-batch steps from the same random start for every bug.
Three bugs fail the test loudly. An optimizer that never steps leaves the loss at its start. A flipped sign climbs the loss instead of lowering it. A featurizer that returns zeros makes every review look the same, so the loss sits at 0.693.
The fourth bug passes. A network can memorize random labels too: Zhang et al. (2017) trained image networks to zero training error on labels assigned at random. So the tiny test proves your code can learn. It does not prove your labels are right. That needs a look at the data (Chapter 8).
Symptom: on eight examples the loss stays near 0.693 and every probability sits at 0.50.
Measure: print the inputs. If every row is the same, the model has nothing to learn from.
Fix: fix the featurizer, then run the tiny test again before you touch the full data.
Chapter 5
Grow the hidden layer until the network fits its training set, and watch what the dev score does
Next, train on the full dataset. The lecture's test for this step: after training, the model should still score close to 100% on its training data. If it does not, consider a more powerful model.
A model's capacity is how many different patterns it can fit. In a network with one hidden layer, the number of hidden units sets it. Each hidden unit can add one bend to the boundary between the classes.
Pick a size and the network trains live. Left: its boundary over the 30 training points. Right: training accuracy (dashed) and dev accuracy (solid) as training goes on.
Illustrative toy, trained live: the half-moons of Chapter 0, with 30 training points and 400 dev points. ReLU hidden units; Adam with learning rate 0.02 runs 2,500 full-batch steps from one fixed random start.
Count the weights. A network with 2 inputs and H hidden units has 2H input weights and H hidden biases. Add H output weights and 1 output bias: 4H + 1 in all. Two units give 9 weights and cannot bend enough: training accuracy stops at 70.0%. Four units already reach 100%, and so do 64 units with 257 weights.
Now look at dev. The 64-unit network scores 76.0% on dev, lower than the 2-unit network's 77.75%. It bent its boundary around the 4 flipped labels. That is overfitting, and the next step treats it. The lecture says not to fear it at this stage: these models generalize well once you regularize them.
Symptom: after full training, training accuracy is stuck well below 100%, though the tiny test passed.
Measure: training accuracy at the end of training: 70.0% with 2 units here.
Fix: more hidden units or layers, longer training, or a better learning rate (Chapter 7).
Chapter 6
Switch on dropout, L2 or early stopping, and watch the gap between training and dev close
The 64-unit network overfits. The lecture's next step: regularize until it no longer overfits on dev data. L2 regularization can help, it says, but generous dropout is normally the secret to success. Regularization is any change that makes memorizing harder than learning the general pattern.
Dropout switches off random hidden units on every training step. Call the hidden layer's outputs h and the dropout rate p. Draw a mask m: one 0 or 1 per unit, each 1 with probability 1 − p. During training the layer passes on:
h-tilde equals m times h, element by element, divided by one minus p.
Zero each unit of h where the mask m is 0. Divide the survivors by 1 − p. At test time, use neither.
h = (2, 4, 1, 3), p = 0.5 and m = (1, 0, 1, 0). Then h̃ = (4, 0, 2, 0), which sums to 6. Each unit survives half the time at twice its size, so on average the sum is 10, the same as h.
PyTorch uses this "inverted" form. The original paper (Srivastava et al., 2014) scaled the weights at test time instead; the two agree on average.
L2 regularization adds a cost for large weights. Call the data loss L, each weight wj and the strength λ:
L-total equals L, plus lambda times the sum over j of w-j squared.
Square every weight wj and add the squares. Multiply by λ. Add the result to the data loss L. Training then keeps weights small unless they earn their cost.
With made-up numbers: weights (0.5, −1, 2) and λ = 0.01. The squares are 0.25, 1 and 4, which sum to 5.25, so the weight cost is 0.0525.
Pick a regularizer and the 64-unit network retrains. The pink tick on the dev curve marks the step with the best dev score: early stopping would keep that one.
Illustrative toy, trained live: the Chapter 5 network with 64 hidden units, the same data, start and training. The page checks dev accuracy every 25 steps.
Every regularizer lifts dev: from 76.0% to 81.0% with dropout 0.3, 81.25% with dropout 0.5 and 79.0% with L2. Dropout wins here, as the lecture says, and each one beats the small network's 77.75%. Early stopping keeps the step with the best dev score: with no regularizer, that was step 225, at 79.0%. The reading says to use early stopping almost always.
Symptom: training accuracy is 100% and dev accuracy falls as training goes on.
Measure: the gap between training and dev: 24 points with no regularizer.
Fix: dropout, L2 or early stopping; more data helps most when you can get it.
Chapter 7
Place the same number of trials on a grid and at random, and count how many learning rates each one tries
Which hyperparameter matters most? The lecture's reading answers: the learning rate, the size of each update step, is perhaps the most important. If you have time to tune only one, tune that. Too large, and training error can rise instead of fall. Too small, and training crawls. Training error plotted against the learning rate makes a U shape.
To tune several hyperparameters, place trials on a grid, every combination of a few values each. Or place them at random: each trial draws every value afresh. Bergstra and Bengio (2012) found that random search reaches a good setting with fewer trials. The reason: when one hyperparameter barely matters, a 3 × 3 grid tries only 3 learning rates in 9 runs, while 9 random trials try 9.
Brighter blue is a higher dev score. Across is the learning rate, on a log scale; up is dropout, which barely matters here. Yellow dots are trials. The ticks under the map are the distinct learning rates tried.
Illustrative map, made up to have one sharp ridge in learning rate and almost none in dropout. Random trials draw learning rates on a log scale, 10−5 to 10−1. Over 1,000 random draws, 9 random trials beat the 3 × 3 grid 78% of the time.
Draw learning rates on a log scale: pick a number u evenly between −5 and −1, and use 10u. A factor of 10 matters as much at the small end as at the large end.
How many random trials are enough? Say the good region covers a fraction q of the range, and you run K random trials:
P of a hit equals one minus, one minus q, to the power K.
Find the chance that one trial misses, 1 − q. Raise it to the power K: that is the chance every trial misses. Subtract from 1.
q = 0.05 and K = 60: 0.9560 = 0.046, so P(hit) = 0.954. With K = 9 it is only 0.37. This holds for random trials on any axis; a grid gives no such promise on the axis that matters.
Symptom: the best trial sits at the edge of your search range.
Measure: check whether the winning learning rate is the smallest or largest value you allowed.
Fix: widen the range on a log scale and search again around the winner.
Chapter 8
Move a spam filter's threshold and see how accuracy hides a class the model ignores
The lecture's last practical slide is "Details matter". Look at your data and collect summary statistics: how many examples, how long, how many of each label. Look at your model's outputs and do error analysis: read the mistakes and sort them into kinds. A shuffled label, a truncated input or a duplicated example shows up in minutes this way, and never in a loss curve.
Summary statistics also tell you when accuracy will lie. Take 1,000 messages, of which 20 are spam. A filter that never says "spam" is right on 980: 98.0% accuracy, and it catches nothing.
Count the four outcomes instead. A true positive (TP) is spam flagged as spam. A false positive (FP) is a normal message flagged. A false negative (FN) is spam let through.
Precision P = TP / (TP + FP) is the share of flags that are right. Recall R = TP / (TP + FN) is the share of spam caught. The F1 score combines them:
F-one equals two P R, over P plus R.
Multiply precision P by recall R and double it. Divide by their sum. A low value of either one drags F1 down.
With made-up counts: TP = 15, FP = 30, FN = 5, so P = 15 / 45 = 0.333 and R = 15 / 20 = 0.75. F1 = 2 × 0.333 × 0.75 / 1.083 = 0.462. Its accuracy is 96.5%, below the do-nothing filter's 98.0%, yet it catches 15 of 20 spam.
Each tick is a message, placed by the filter's spam score. The filter flags every message right of the line. Drag the threshold, or press "Never flag".
Illustrative toy: 1,000 made-up scores, built so that threshold 0.50 gives the counts above. The labels are what a person would mark.
Symptom: 98% accuracy, and users report that spam gets through.
Measure: recall on the spam class. Here it is 0 of 20.
Fix: report precision, recall and F1 for each class, choose the threshold on dev, and reweight the rare class in the loss.
Chapter 9
Train, score on dev as often as you like, then open the test set once and see what your tuning cost
This is a whole small project. Pick a size and a dropout rate; the network trains. Press "Score on dev" to log its dev score. Try a new random start too: the same setting can land a few points apart. When you finish, press "Open the test set". It scores the model with your best dev score, once, and locks.
Choose a size and a dropout rate, then score on dev. The strip logs every dev score you looked at. The test set opens once.
Illustrative toy, trained live: the half-moons (30 training, 400 dev, 400 test points), Adam with learning rate 0.02, 2,500 steps. We drew dev and test pots that are equally hard on average for these networks, so a gap you see is noise or selection. The test pot is never used for training or choosing.
What to look at. Here the settings differ, by more than the 2-point noise of a 400-example dev score. So choosing on dev mostly picks a better model, and its test score lands within about 2 points of its dev score, above or below. The hero's trap needs many settings that are close together. Real projects have both: a few big wins, then many small tweaks that are within the noise.
Check yourself. Why does a 2-unit network rarely win the dev race? Why does a new random start change the score of the same setting? If you scored 40 random starts of one setting and kept the best, how far above its test score would you expect it to be?
Chapter 10
Keep the recipe, the numbers and the code, and pick a project you can measure
Keep train, tune, dev, dev2 and test apart, and report only a number from a pot that made no decision. A dev score is noisy, and the best of many is too high, by about cK standard errors.
Start with a simple model on 4 to 8 examples and get 100%. Grow it until it fits the full training set. Regularize until dev stops overfitting. Tune the learning rate first, at random on a log scale. Then read the errors, class by class.
| Step | Do | It catches | It misses |
|---|---|---|---|
| 1. Tiny data | 4 to 8 examples, simple model, aim for 100% | code bugs: no step, wrong sign, empty inputs | wrong labels; generalization |
| 2. Full fit | all training data, grow the model until training accuracy is near 100% | too little capacity, a bad learning rate | overfitting |
| 3. Regularize | dropout, L2, early stopping, chosen on dev | a large train to dev gap | dev luck from many tries |
| 4. Search | learning rate first, random trials on a log scale | a learning rate off by 10 times | anything outside the range you searched |
| 5. Look | summary statistics, per-class precision and recall, read the errors | bad labels, imbalance, leaks, truncation | anything you did not look at |
| 6. Report | confirm on dev2, then open the test set once | selection luck | a test set unlike the real world |
| Number | Value | Where |
|---|---|---|
| 1 neighbour on train, then on 400 new points | 100% → 73.5% | Chapter 0 |
| Test score: λ chosen on train, chosen on tune | 73.25% → 84.0% | Chapter 1 |
| Standard error, a = 0.70, n = 500 | 2.05 points | Chapter 2 |
| Best of 50 equal settings on 500 dev examples | 74.55% on average (truth 70%) | Chapter 3 and the hero |
| Loss of a 50/50 guess on two classes | 0.693 | Chapter 4 |
| Weights, 2 inputs and 64 hidden units | 257 | Chapter 5 |
| Dev accuracy, 64 units: none, dropout 0.3, L2 | 76.0%, 81.0%, 79.0% | Chapter 6 |
| Chance 60 random trials hit the best 5% | 0.954 | Chapter 7 |
| Never flag spam (2% spam): accuracy, recall | 98.0%, 0 | Chapter 8 |
The core as code: the tiny-data check, the pots, a dropout network and a random search, in PyTorch.
python import math, random, torch, torch.nn as nn, torch.nn.functional as F def make_model(d_in, hidden=64, p=0.3): return nn.Sequential(nn.Linear(d_in, hidden), nn.ReLU(), nn.Dropout(p), # inverted dropout: scales by 1/(1-p) in train() nn.Linear(hidden, 2)) def tiny_check(model, x8, y8, steps=300, lr=1e-2): opt = torch.optim.Adam(model.parameters(), lr=lr) model.train() for _ in range(steps): loss = F.cross_entropy(model(x8), y8) # starts near log 2 = 0.693 opt.zero_grad(); loss.backward(); opt.step() model.eval() # no dropout when we score acc = (model(x8).argmax(1) == y8).float().mean().item() assert acc == 1.0, f"cannot fit 8 examples (acc {acc:.2f}): a bug or too small" # pots: split once, by document or user, never by sentence, and never reshuffle def split(ids, seed=0, frac=(.8, .05, .05, .05, .05)): ids = sorted(ids); random.Random(seed).shuffle(ids) cuts = [round(sum(frac[:i]) * len(ids)) for i in range(6)] return {name: ids[cuts[i]:cuts[i + 1]] for i, name in enumerate(["train", "tune", "dev", "dev2", "test"])} def random_search(train_and_score, trials=20, seed=0): rng, results = random.Random(seed), [] for _ in range(trials): cfg = {"lr": 10 ** rng.uniform(-5, -1), # log scale "dropout": rng.uniform(0.0, 0.5)} results.append((train_and_score(cfg, on="tune"), cfg)) return max(results, key=lambda r: r[0]) # confirm on dev2; test once, at the end
The lecture gives two starting points. A nail: start from a problem you care about and find a better way to solve it. A hammer: start from a method and extend it, understand it, or apply it somewhere new. Most projects are one of five kinds:
The lecture expects experiments with numbers and ablations in the first three.
For 2026 projects, the lecture recommends starting from a pretrained model and fine-tuning it, as most work now does.
The lecture says weak plans usually fail on nuts and bolts, so check three things. Do you have data, or a fast way to collect it? Do you have a realistic way to evaluate? Do you have baselines or ablations to compare against? Curated data comes from Hugging Face Datasets, the Linguistic Data Consortium, the WMT shared tasks at statmt.org, and Kaggle. The course's custom-project notes add one more check: a short, specific guiding question, and a clear metric to answer it.
Now teach it: press Present or Teach. Explain why the best dev score of many tries is too high. Explain why the tiny test cannot catch shuffled labels, and why a 98% filter can be useless. Then go back to the hero, set 2,000 dev examples and predict the gap before you look.