Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

4.7 Training and evaluating a network: the lab, the clinic and the rubric

A network that trains is not yet a network you can trust. This lab holds one task fixed and changes one decision at a time, so you see what each decision costs, measured with seeds and on a clean test set. The decisions fall under three pillars:

PillarStationQuestion you answer with a number
Data3What do wrong labels, a rare class, mixed sample quality and the amount of data cost?
Architecture4How wide, how deep, and is it better than a linear baseline?
Training5Starting weights, learning rate, batch size, and when to stop
(all three)6How much should you trust a prediction, inside and outside the training range?
7Six broken runs: diagnose them from the curves

The task is a synthetic lithology table, so every defect is planted by us and its cost can be measured exactly. The same decisions on real seismograms are the subject of the optional training clinic and of the homework (Homework_DL). Every training run takes about a second on a laptop CPU.

Two sessions. Sections 1 to 3 on Wednesday Nov 25, sections 4 to 7 on Monday Nov 30. To resume, run sections 1 and 2 again (a few seconds), then go to section 4.

🖥️ Training and evaluating any network: the loop and the leaderboard (reference slides)

🖥️ Lecture slides — Session 24 — lab I (Wed Nov 25)

🖥️ Lecture slides — Session 25 — lab II (Mon Nov 30)

1. The data: three lithologies from nine measurements

Classify rock samples as granite, basalt or andesite from 9 features: seven major-element oxides (wt%), density (g/cm3^3) and magnetic susceptibility (SI). The table comes from mlgeo_synth.geochem_table. A hidden differentiation index drives the oxides of each sample together (more evolved: more SiO2_2 and K2_2O, less FeO, MgO and CaO), and andesite is rare by construction (10% of samples).

The raw table is almost perfectly separable, which no field instrument delivers. Every dataset below therefore carries a measurement-noise floor of one standard deviation per feature, on the training, validation and test sets alike.

accelerator detected: cpu; using: cpu
(3000, 10)
Loading...
<Figure size 1000x350 with 2 Axes>

2. Train one network, step by step

The same order as notebooks 4.1 and 4.2: split the data, design the model, choose the loss and the optimizer, write the training loop, train and look at the learning curve, compare with a baseline. Every station below reuses these pieces and changes one of them.

2.1 Split the data first

make_data draws a table, splits it into training (75%) and validation (25%) sets, scales the features with statistics of the training set only, and adds the noise floor. The test set is drawn separately, with its own seed, and is always clean: no flipped labels and no defects beyond the noise floor, even when we corrupt the training data on purpose. That is how we measure what a defect costs.

The keyword arguments are the knobs of station 3: label_noise flips a fraction of labels, minority_keep keeps a fraction of the andesites, relabel applies structured label errors, hetero_sigma gives each training sample its own noise level.

train (2250, 9) | validation (750, 9) | test (1500, 9)

2.2 Design the model

A multilayer perceptron with depth hidden layers of width units, ReLU after each, and a last linear layer with one score per class. With depth=0 it is a single linear layer: multinomial logistic regression, the baseline of 2.6.

2.3 Loss and optimizer

Three classes: cross-entropy, with the softmax inside the loss (the network outputs three raw scores). The optimizer is Adam with a learning rate of 0.001, the default of this course. train_model below builds the optimizer itself, so a station can change the learning rate, the optimizer or the loss.

2.4 The training loop

One epoch is one pass over the training samples: shuffle their order, cut it into batches, and for each batch zero the gradients, compute the loss of the batch, the gradients, and one update. After each epoch the loop measures the training and validation loss and accuracy, and keeps a copy of the weights each time the validation loss reaches a new low: the checkpoint. At the end the model gets back the weights of its best epoch. The loss curves are the diagnostic instrument of the whole lab.

The loop every station of this lab changes one piece of (lecture 23)

Your turn (1): one epoch

one_epoch below already shuffles the samples and cuts them into batches. Write the four lines that go inside the loop, for the batch idx: zero the gradients with opt.zero_grad(), compute the loss of the batch with criterion (the network’s scores model(X[idx]) against the labels y[idx]), compute the gradients with .backward(), and update the weights with opt.step(). They are the four lines of the loop on the lecture 24a slide, and the same four in every notebook of this chapter.

Answer below (click to open it).

Notebook Cell

train_model wraps one_epoch with the optimizer, the curves and the checkpoint. Every station below calls it and changes one argument: the learning rate, the batch size, the optimizer, the loss (criterion), or the data. keep_best=False keeps the weights of the last epoch instead (section 5.4 compares the two).

2.5 Train, and plot the learning curve

4995 weights; best epoch 14, validation accuracy 0.944
last epoch: training loss 0.115, validation loss 0.153
<Figure size 500x300 with 1 Axes>

Both curves fall together and flatten after about 10 epochs. The small gap that opens after that (at the last epoch, training loss 0.115 and validation 0.153) is the start of fitting the training samples rather than the classes; at 25 epochs it is still small. The validation loss was lowest at epoch 14 (counted from 0), so train_model gave the model back the weights of that epoch.

2.6 Compare with a baseline

A score means something only next to a simpler model on the same data. For classification, that is multinomial logistic regression: our MLP with depth=0.

logistic baseline (   30 params): test acc 0.876
MLP 64x2          ( 4995 params): test acc 0.953

The gap is real but modest, typical of well-behaved tabular data. If a deep model cannot beat the linear baseline, the problem is the data or the features, not a missing layer.

3. Station 1: the data

No architecture rescues a corrupted training set. Here the generator controls each defect exactly, and the test set stays clean, so each curve isolates what the defect costs.

3.1 Wrong labels, at random

Analyst picks disagree, catalogs inherit old errors, field classifications get revised. We flip a fraction of the training labels at random and retrain, with 3000 and with 600 training samples. Each point averages three seeds.

Prediction (before you run): with 30% of the labels wrong, how many accuracy points do you lose with 3000 samples? With 600?

3000 training samples            label noise   0%  ->  clean-test accuracy 0.949  (seeds span 0.948-0.951)
3000 training samples            label noise   5%  ->  clean-test accuracy 0.948  (seeds span 0.946-0.951)
3000 training samples            label noise  15%  ->  clean-test accuracy 0.947  (seeds span 0.943-0.952)
3000 training samples            label noise  30%  ->  clean-test accuracy 0.943  (seeds span 0.937-0.948)
600 training samples             label noise   0%  ->  clean-test accuracy 0.940  (seeds span 0.938-0.943)
600 training samples             label noise   5%  ->  clean-test accuracy 0.944  (seeds span 0.937-0.951)
600 training samples             label noise  15%  ->  clean-test accuracy 0.938  (seeds span 0.935-0.941)
600 training samples             label noise  30%  ->  clean-test accuracy 0.924  (seeds span 0.911-0.934)
600, last epoch (no checkpoint)  label noise   0%  ->  clean-test accuracy 0.934  (seeds span 0.929-0.940)
600, last epoch (no checkpoint)  label noise   5%  ->  clean-test accuracy 0.934  (seeds span 0.926-0.943)
600, last epoch (no checkpoint)  label noise  15%  ->  clean-test accuracy 0.923  (seeds span 0.919-0.929)
600, last epoch (no checkpoint)  label noise  30%  ->  clean-test accuracy 0.878  (seeds span 0.865-0.895)
<Figure size 550x340 with 1 Axes>

With 3000 samples even 30% of random flips costs little (0.949 to 0.943): the flips point in all directions, and the correct majority still pins the class boundaries. With 600 samples, the dashed curve keeps the weights of the last epoch: by then the network has memorized the flipped labels, and 30% of them cost 5.6 points (0.934 to 0.878). The checkpoint cuts that cost to 1.6 points (0.940 to 0.924), because it returns the weights from before the memorizing started. The checkpoint is a defense against wrong labels, not only against overfitting. The shaded bands are the spread over three seeds; read them before trusting any difference between two points.

3.2 Wrong labels, with a pattern

Real label errors come from people, and people disagree in patterns. Two simulated geologists split a field area. Each mislabels 30% of their samples, the same rate as the harshest experiment above, but only ever between adjacent lithologies on the differentiation axis: granite to andesite, basalt to andesite, andesite to either neighbor. Nobody calls a basalt a granite.

no label errors                 : clean-test accuracy 0.949  (seeds span 0.948-0.951)
30% uniform flips               : clean-test accuracy 0.943  (seeds span 0.937-0.948)
30% adjacent-class disagreement : clean-test accuracy 0.922  (seeds span 0.919-0.927)
               granite  basalt  andesite
true granite      0.97    0.00      0.02
true basalt       0.01    0.90      0.09
true andesite     0.20    0.07      0.73
<Figure size 440x360 with 2 Axes>

Same error rate, more than four times the damage, checkpoint included: 30% uniform flips cost 0.6 accuracy points (0.949 to 0.943), 30% adjacent-class disagreement costs 2.7 (0.949 to 0.922), and the seed spans do not overlap. The errors sit on the two boundaries of andesite, the class both mappers argue about: 20% of the true andesites come back granite and 9% of the true basalts come back andesite, while granite and basalt are confused 1% of the time or less.

Every label in a geoscience dataset is an interpretation: a map records what one mapper concluded, a phase pick where one analyst decided the wave arrived. Random errors cancel; errors with a pattern push the same boundary the same way, and more data makes the model more confident in the shared mistake. How often two experts agree on your labels is a ceiling on the accuracy any model can show.

3.3 A rare class

Andesite is already rare. We shrink it further and watch the recall of each class, not the overall accuracy.

               overall acc  recall granite  recall basalt  recall andesite
minority kept                                                             
1.00                 0.945           0.972          0.962            0.742
0.50                 0.951           0.984          0.975            0.697
0.20                 0.894           0.985          0.979            0.123
0.05                 0.881           0.985          0.979            0.000
<Figure size 550x320 with 1 Axes>

Overall accuracy drifts down a few points, nothing alarming on a dashboard. Andesite recall collapses to zero: the model stops predicting the class. In geoscience the rare class is usually the one you care about (the eruption, the induced earthquake, the landslide).

Your turn (2): weight the rare class

Cross-entropy counts every sample alike, so the many granites dominate the loss. Write class_weights, a tensor of three numbers, one per class in the order of CLASSES: the number of training samples divided by (3 × the number of samples of that class). Use torch.bincount(data_rare[1], minlength=3) for the counts. The cell after it trains with nn.CrossEntropyLoss(weight=class_weights) on the 20% case.

Answer below (click to open it).

Notebook Cell
class weights: {'granite': np.float32(0.56), 'basalt': np.float32(0.87), 'andesite': np.float32(14.96)}
                        overall acc  recall granite  recall basalt  \
loss                                                                 
cross-entropy                 0.894           0.985          0.979   
weighted cross-entropy        0.947           0.960          0.958   

                        recall andesite  
loss                                     
cross-entropy                     0.123  
weighted cross-entropy            0.839  

Question: what did the weights buy for andesite, and what did they cost the other two classes? Check that a fix shows up in the recall, not only in the loss.

3.4 Mixed sample quality

Half of a geochemistry table from a laboratory XRF with small analytical error, half from a portable field unit several times worse: the metadata usually says which is which. Cross-entropy treats every sample as equally trustworthy. If the variance of each sample is known, weight its loss by 1/σi21/\sigma_i^2, the classification version of weighted least squares. Each training sample draws its noise level from {0.5, 4.0} standard deviations; the same model trains once without the weights and once with them.

ignore the metadata       : clean-test accuracy 0.936  (seeds span 0.934-0.937)
inverse-variance weights  : clean-test accuracy 0.946  (seeds span 0.939-0.951)
all lab-grade (reference) : clean-test accuracy 0.949

The mixed table costs 1.3 points against the all-lab-grade reference (0.936 against 0.949). Giving the model the variance it already had in the metadata recovers 1.0 of them (0.946), with no new data and one line of loss code. Any column named uncertainty, std_err, quality or pick_weight is an invitation to weight the loss; most pipelines drop it at ingest.

3.5 How much data is enough?

The learning curve: test accuracy against the number of training samples. It answers “would more data help?” with a measurement.

<Figure size 500x320 with 1 Axes>

The curve rises steeply, then flattens. If it is still rising at your data size, collect more before tuning anything else. If it has flattened, more of the same data will not help; better labels or better features might.

Write your rules for station 1 (section 8).

4. Station 2: the architecture

Same clean data (the reference dataset of section 2), different models.

4.1 Width

Prediction: from 4 to 256 units per layer, where does the test accuracy stop improving?

   width  params  test acc
0      4      75  0.850667
1     16     483  0.882667
2     64    4995  0.952667
3    256   69123  0.950000
<Figure size 500x320 with 1 Axes>

Accuracy saturates within a factor of a few of the smallest adequate width. Past that point, weights cost training time, memory and, on small datasets, overfitting, and buy no accuracy.

4.2 Depth at a fixed number of weights

Spend about 5,000 weights on 1, 2 or 4 hidden layers.

   depth  width  params  test acc
0      1    385    5008  0.954000
1      2     65    5138  0.953333
2      4     39    5190  0.945333

On nine features, depth buys little: the structure the generator planted is simple, and a shallow, wide network represents it as well as a deep one. Depth pays when the data are built of parts of parts: edges, textures and objects in images (4.3), samples, motifs and phrases in sequences (4.4).

Write your rule for station 2 (section 8).

5. Station 3: training

Same data, same architecture; only the way we train changes.

5.1 Starting weights

Notebook 4.0 started from random weights drawn with a seed, never from zeros. Test it.

Prediction: with every weight and bias at zero, what is the validation accuracy after 25 epochs? With the default random weights multiplied by 10?

Your turn (3): two ways to start

Write init_scaled(model, factor): inside with torch.no_grad():, loop over model.parameters() and multiply each one by factor in place (p.mul_(factor)). A factor of 0 sets every weight to zero.

Answer below (click to open it).

Notebook Cell
random (default)  validation accuracy 0.938  (seeds 0.937, 0.939)
all zeros         validation accuracy 0.560  (seeds 0.560, 0.560)
random x 10       validation accuracy 0.817  (seeds 0.821, 0.813)
<Figure size 600x350 with 1 Axes>

Questions. With zero starting weights, every hidden unit computes the same thing and receives the same gradient: why does it never stop being identical to its neighbors? What fraction of the samples is granite, and how does that compare with the zero-start accuracy?

5.2 The learning rate

Three runs that differ only in the learning rate.

<Figure size 1200x330 with 3 Axes>

Three signatures to memorize:

  • Too high: the loss oscillates or explodes (log axis); each step overshoots the valley.

  • Too low: both curves creep down a nearly straight line; training “works” but would need hundreds of epochs.

  • Well chosen: a fast early drop, then a smooth flattening.

Sweep the learning rate in powers of 10 first; nothing else in this station matters until it is roughly right.

5.3 Batch size

<Figure size 550x340 with 1 Axes>

Small batches take many noisy steps per epoch: fast progress per epoch, with jitter. Large batches take few smooth steps, so at a fixed number of epochs their curve lags. Compare at an equal number of updates before concluding that one batch size is better. In practice the batch is the largest that fits comfortably in memory, with the learning rate tuned again when the batch changes.

5.4 Overfitting, and when to stop

A large model, a small noisy training set, and a long run.

val loss at best epoch 16: 0.380
val loss at final epoch:  1.349
validation accuracy, weights of the last epoch: 0.850
validation accuracy, weights returned (epoch 16): 0.900
<Figure size 500x300 with 1 Axes>

The training loss falls toward zero while the validation loss reaches a minimum and climbs. The checkpoint in train_model (section 2.4) already keeps the weights of the epoch with the lowest validation loss, so the model it returns is the one at the dashed line, not the one at epoch 150. Early stopping goes one step further: stop the run when the validation loss has not improved for a set number of epochs (the patience), and save the time of the remaining epochs.

Write your rule for station 3 (section 8).

6. Station 4: how much to trust a prediction

6.1 Deep ensembles: uncertainty from disagreement

Train the same architecture from five seeds. The runs agree on easy samples and disagree near class boundaries, and that disagreement is an uncertainty estimate (Lakshminarayanan et al., 2017). Two separate questions: does disagreement rank samples by their risk of error (discrimination), and when the ensemble says 80%, is it right 80% of the time (calibration)?

member accuracies: [0.951 0.951 0.951 0.951 0.951]
ensemble-mean accuracy: 0.952
<Figure size 1050x360 with 3 Axes>

The samples where the members disagree are the ones the ensemble gets wrong most often, and they sit on class boundaries. In a workflow you would send them to an analyst. This is discrimination: only the order matters.

6.2 Calibration

Calibration asks whether the probability itself is right. The reliability diagram bins samples by stated confidence and plots the observed accuracy in each bin; the expected calibration error (ECE) is the average gap, weighted by the number of samples per bin. With three classes, the confidence of the predicted class lies between 1/3 and 1.

single member    accuracy 0.951   ECE 0.010
ensemble mean    accuracy 0.952   ECE 0.010
<Figure size 500x360 with 1 Axes>

Here a single member is already nearly calibrated (ECE 0.010) and the ensemble mean gains nothing measurable (0.010). Deep ensembles improve calibration on large networks, especially under distribution shift; a two-layer network on nine features is not miscalibrated enough to fix. “Well calibrated” is a number you attach to a model after running this cell, not a property of a method.

6.3 MC dropout: an uncertainty estimate from one model

Five training runs are expensive when one run takes a week. Monte Carlo dropout trains one network with dropout, then leaves dropout on at prediction time and runs each sample through it T=50T = 50 times (Gal & Ghahramani, 2016). The mean of the passes is the prediction; their spread is the uncertainty.

                           test accuracy    ECE  models trained  \
deep ensemble (5 members)          0.952  0.010             5.0   
MC dropout (T=50)                  0.953  0.017             1.0   

                           prediction passes  
deep ensemble (5 members)                5.0  
MC dropout (T=50)                       50.0  
<Figure size 1050x360 with 2 Axes>

One dropout model matches the five-member ensemble on accuracy (0.953 against 0.952, inside the spread between seeds) and on discrimination, for one training run instead of five. Its calibration is a little worse (ECE 0.017 against 0.010).

6.4 Out of range

Every score so far assumed the test samples come from the same ranges as the training samples: the model interpolates. Deployment breaks this: the mapped area ends, the next pluton is more evolved than anything in the survey. Predicting there is extrapolation. We train an ensemble only on samples within one standard deviation of each unit’s typical composition (the field campaign mapped only typical rocks), then test on a fresh draw over the full range.

training keeps 2723 of 4000 samples (|z| <= 1: the central ~68% of each unit's compositional range)
                                      n  error rate  mean disagreement
range                                                                 
in range (|z| <= 1)                2046       0.050              0.011
near extrapolation (1 < |z| <= 2)   824       0.076              0.015
far extrapolation (|z| > 2)         130       0.085              0.019

out-of-range errors: 74 on 954 out-of-range samples
silent failures (wrong AND disagreement at or below the in-range median): 1 of 74 (1% of out-of-range errors)
<Figure size 1050x360 with 2 Axes>

The error rate rises by more than half across the training bound: 5.0% in range, 7.6% just past it, 8.5% beyond two units. Mean disagreement rises with it. Of the 74 errors out of range, one is a silent failure: wrong, yet with disagreement at or below the in-range median. Its composition landed in a neighboring class’s familiar territory, so all five members agreed on the same wrong label. Disagreement flags unfamiliar regions of feature space; it cannot flag a sample that came to look familiar.

The in-range and out-of-range disagreements also overlap heavily: no threshold on the spread recovers the training bound. The bound is metadata only you have. State the ranges your training data covered next to every score you report.

Write your rule for station 4 (section 8).

7. Six broken training runs

Six runs, each broken in a different way. The pathologies, in shuffled order: learning rate too high, learning rate too low, overfitting, underfitting, heavy label noise, and validation data easier than the training data (the signature of leakage). For each run write the pathology, the evidence in the curves, and the first fix you would try, before reading the code or opening the solution.

<Figure size 1200x650 with 6 Axes>

8. Your rules

One rule per station, in the format of the class rubric (section 9 and The rubric): what to do, how someone else checks it, and the number from your run that justifies it.

StationRule (what to do)Check (how someone else verifies it)Evidence (your number, with seeds)
1 data
2 architecture
3 training
4 trust

Example: “Report the recall of every class, not the accuracy. Check: the table of recall per class in the results. Evidence: with 5% of the andesites kept, accuracy 0.881 while andesite recall is 0.000.”

9. The rubric

The checklist of this section is the companion page The rubric. Every item has an identifier, a check, and the evidence that shows it passed; coding agents read the same page as their specification. Its six sections:

  • A. Framing, before any model. Name the data sample, the input, the quantity to predict and how the model will be used, split along that deployment axis, and compute baselines without learning.

  • B. Choosing the network from the structure of the data. A table of features, a grid, a sequence in time or a set of linked stations each calls for the layer whose assumption matches it.

  • C. Design checks, by network. The checks specific to each kind of network of this chapter, such as the receptive field of a convolution against the physical scale of the pattern, or causal input windows for a recurrent network.

  • D. Training. Random starting weights with a recorded seed, a loss that fits the errors, both loss curves at every epoch, at least three seeds, and the test set used once.

  • E. Evaluation. Errors in physical units, recall and precision per class, differences within the seed spread reported as ties, error against a physical variable, and one test along the deployment axis.

  • F. Reporting, for students and agents. Every number traced to a script, the baselines, loss curves and seed spread shown before any claim, and the items that could not be checked listed.

The stations of this lab measure items D5 (learning rate), D6 (regularization and early stopping), D7 (seeds) and E5 (a test outside the training range).

The real-data companion of this lab is the training clinic, optional practice in the same 4.7 block: one small convolutional network that detects events in 30 s of three-component miniPNW records, and six stations (the split and leakage, starting weights, learning rate and batch size, model size and amount of data, augmentation, the loss). Each station ends with a rule in the format of section 8, to be checked against this rubric.

10. Reflection

Two or three sentences each.

  1. What you learned. Which result surprised you most, and what did you expect instead?

  2. What you learned from the agents. If an assistant helped you write a cell, which decision did it make that you would not have made, and how did you check it?

  3. How to improve it. Which station would you change, or which decision is missing, to make this lab more useful for your project?