Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 2: Neural Network Internals

Week 02 / Lesson 3

Training and comparing neural networks

Train a small network and choose settings using validation evidence.

Section 3.1 1 of 8

Overview

Focus

Train a small network and choose settings using validation evidence.

Your route through the lesson

  • 3.2 Data loaders and the optimization loop
  • 3.3 Learning rates, regularization, and early stopping
  • 3.4 Training and evaluation modes
  • 3.5 Comparing a linear classifier with a neural network
  • 3.6 Put it into practice
  • 3.7 Guided comparison
  • 3.8 A network that memorizes training records

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 3.2 2 of 8

Data loaders and the optimization loop

Focus

Implement the ordered steps of a small network training loop.

A training loop repeatedly selects examples, computes predictions, measures loss, computes derivatives, and updates parameters. A data loader groups examples into batches and can shuffle training order. Each epoch is one pass through the training examples; an iteration is one batch update. They are different units of work.

For each batch, clear accumulated gradients, compute model output, calculate a scalar loss, call backward, and step the optimizer. PyTorch optimizers hold references to the model's parameters. Calling step changes those parameters using their gradients and the optimizer's rule. Computing predictions without step performs no parameter update.

Use the appropriate loss for the output. A binary network may return one unrestricted score per example and use binary cross-entropy with logits, which combines the probability transformation and numerical loss stably. The word logits means scores before probability normalization. Supplying integer category numbers to the wrong loss or applying the probability transformation twice changes the calculation.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A dataset has 100 records processed in batches of 20. How many batch iterations are one epoch?
2. Which sequence updates a model from a batch?
3. A binary model supplies unrestricted scores to a loss that includes its own sigmoid. What should be passed?

Section 3.3 3 of 8

Learning rates, regularization, and early stopping

Focus

Select training settings with validation data and recognize overfitting.

Learning rate controls update size. Regularization discourages certain fitted solutions, for example by penalizing large weights. Early stopping chooses a saved model state using validation performance. These techniques can help generalization but do not repair leaking labels or an invalid split.

Suppose training loss over four epochs is 0.7,0.4,0.2,0.1 and validation loss is 0.72,0.50,0.55,0.68. The second epoch has the lowest validation loss. Saving the final epoch simply because it has the lowest training loss chooses a more overfit state for this evidence. Keep a copy of the epoch-two parameters and evaluate that selected state on the final test set.

A checkpoint is a saved state, not just a filename indicating an epoch. In Python, storing a reference to the live model does not freeze its weights; copy its state or save it so later updates cannot change the selected snapshot. Record the settings and seed alongside the checkpoint for a reproducible comparison.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Validation losses over four epochs are 0.72,0.50,0.55,0.68. Which epoch is chosen by minimum validation loss?
2. What does weight regularization change?
3. A saved “best model” is only a reference to the model still training. What is the danger?

Section 3.4 4 of 8

Training and evaluation modes

Focus

Use evaluation mode and disabled gradient recording for validation.

Some modules behave differently in training and evaluation. Dropout randomly sets some activations to zero during training as a regularizer. In evaluation mode it passes the represented activations without that random training mask. Batch normalization also uses different statistics depending on mode.

Call model.train() before training and model.eval() before validation or deployment inference. Separately, use with torch.no_grad(): around validation to avoid recording an unnecessary derivative graph. Evaluation mode controls module behavior; no_grad controls automatic differentiation. Neither means deleting learned weights.

For a dropout example, applying the same model twice to a fixed input during training may produce different outputs. After model.eval(), repeated runs of that model on the same input should agree under the controlled processor example. A validation score measured with active dropout can be noisy for the wrong reason. Mode changes must be restored when returning to training.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A dropout model must be evaluated without its random training masks. Which call changes its module behavior?
2. Why use a no_grad context during validation?
3. After validation with model.eval(), training resumes. What should be restored?

Section 3.5 5 of 8

Comparing a linear classifier with a neural network

Focus

Compare a linear classifier and a small neural network on the same data roles.

A fair comparison fixes the task, data partitions, preprocessing policy, and metric definition before comparing model families. Logistic regression learns a linear boundary in its input representation. A neural network with hidden nonlinear layers can represent more flexible boundaries, but additional flexibility can also fit noise.

Reuse the generated dataset recipe and split seeds from Week 1. Fit preprocessing on training rows and use that same preparation contract for both models. Choose each model's settings with validation data; preserve the final test partition until those choices are fixed. Compare a majority baseline as well so the more complicated model must justify its value.

Record validation and test accuracy, the confusion matrix, and training behavior. A neural network does not have to beat the linear model. A smaller model may be sufficient, faster, or easier to reproduce. If a network improves training loss but not validation outcomes, that is evidence about this configuration and data, not proof that neural networks never help.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Two classifiers are compared using different test records. What weakens the comparison?
2. A nonlinear network has lower training loss but worse validation accuracy than a linear baseline. What conclusion fits?
3. What should remain fixed when choosing between the two models?

Section 3.6 6 of 8

Put it into practice

Focus

Run a checked training loop and preserve the validation-selected state.

Download week02.py. With NumPy, scikit-learn, and PyTorch installed, run python week02.py --lesson 3. The lab rebuilds the Week 1 generated data and exact split, fits training-only standardization, trains a small nonlinear classifier, and compares the selected model with logistic regression.

Read the loop: optimizer.zero_grad clears storage, model(features) performs a forward pass, loss.backward computes derivatives, and optimizer.step updates weights. Validation runs under evaluation mode with disabled gradient recording. A copied state dictionary stores the best validation checkpoint; a state dictionary maps parameter names to tensors.

Inspect the printed train/validation losses and final confusion counts. The lab checks finite losses, shape agreement, and stable evaluation behavior; it reports actual classification scores rather than asserting a preferred winner. Save the commands and output. Extend this same artifact by comparing two learning rates on validation data and then report the final selected configuration once on test data.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A PyTorch state dictionary is copied when validation improves. Why copy it?
2. A lab prints a neural-network score below logistic regression. Must the reference score be edited?
3. A training loop uses validation data to choose learning rate. When should the final test result be reported?

Section 3.7 7 of 8

Guided comparison

Focus

Interpret the selected checkpoint and verify evaluation behavior.

In a correct comparison, both models see the same training examples and their final scores refer to the same untouched test examples. Standardization is fitted before either model using only training values. The nonlinear model's recorded best state is selected from validation loss, not from the final test score.

If validation loss is best at epoch 20 but training continues to epoch 40, load the copied epoch-20 state before final evaluation. Otherwise the report describes one model while executing another. Run model.eval() and no_grad, then compute predictions and confusion counts using the declared threshold.

The lab's deterministic seed and processor execution improve reproducibility for the checked environment, but library versions and numerical kernels can still affect training. Record versions with observed output. The important invariant is that preparation, selection, and evaluation roles remain valid even when a measured accuracy changes slightly on another machine.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Validation selected epoch 20, but the live model is at epoch 40. Which state should final evaluation use?
2. Both models share a scaler fitted on all training and test records. Is the comparison leakage-safe?
3. A repeated run changes accuracy slightly after a library upgrade. What should the report retain?

Section 3.8 8 of 8

A network that memorizes training records

Focus

Recognize memorization and preserve evidence when a model overfits a tiny sample.

Take only twelve labeled training examples and fit a flexible network for many epochs. It may reach near-perfect training accuracy by fitting accidental details. If performance on a separate validation set stays poor, memorization has not delivered useful generalization.

Compare training and validation curves together. Early stopping can select an earlier state; weight regularization or a smaller hidden layer may help. Check data quality and the split before attributing every failure to architecture. If duplicated records occur across partitions, even good validation performance can be misleading.

Do not repair the experiment by moving hard validation cases into training after inspecting them while keeping the old validation claim. Create a new development version and reserve a fresh final test if the evaluation process has been used for adaptation. Preserve the tiny overfitting case as a diagnostic demonstration: it teaches the gap between fitting supplied examples and predicting new ones.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A network fits twelve training examples perfectly but performs poorly on separate validation data. What is illustrated?
2. Which intervention can be selected using validation evidence to address overfitting?
3. Why keep the tiny overfitting example after finishing the lab?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Turning text into model inputs →