Why Start With a Whole Script
The next fourteen lessons take a training script apart and teach each piece properly: tensors, gradients, models, data, losses and the loop. Pieces are easier to learn when you have seen where they fit. This lesson runs one complete, short training script so you can watch a network improve, name the five parts every training script has, and see what the printed numbers do and do not tell you. You are not expected to understand every line yet; the lesson tells you where each part is taught.
The Problem the Script Solves
The script generates 200 points along a wavy curve, the sine function, with a little random noise added. A neural network starts with random internal numbers, called weights, so its first guesses are poor. Training means repeatedly comparing its guesses with the true values and adjusting the weights to make the error smaller. The single number that measures the error is the loss; lower is better.
Exercise: Run a Training Script
Starting state: the course environment from the setup lesson, active in
your terminal (the prompt shows (.venv)).
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/pytorch-practice/first-training-run cd ~/pytorch-practice/first-training-runWindows PowerShell:
mkdir $HOME\pytorch-practice\first-training-run cd $HOME\pytorch-practice\first-training-run -
Save this as
tour.pyin that folder:"""A first look at a network learning: fit a curve from generated points.""" import matplotlib matplotlib.use("Agg") # save charts to files; no window is needed import matplotlib.pyplot as plt import torch from torch import nn torch.manual_seed(0) # the same random numbers on every run # 1. Data: 200 points along a wavy curve, with a little noise added. x = torch.linspace(-3, 3, 200).unsqueeze(1) y = torch.sin(x) + 0.1 * torch.randn_like(x) # 2. Model: a small network with one hidden layer of 32 units. model = nn.Sequential(nn.Linear(1, 32), nn.Tanh(), nn.Linear(32, 1)) # 3. Loss: the mean squared error between predictions and targets. loss_fn = nn.MSELoss() # 4. Optimiser: changes the model's weights to reduce the loss. optimizer = torch.optim.Adam(model.parameters(), lr=0.01) # 5. Loop: predict, measure the error, work out each weight's change, apply it. STEPS = 300 history = [] for step in range(1, STEPS + 1): prediction = model(x) loss = loss_fn(prediction, y) optimizer.zero_grad() loss.backward() optimizer.step() history.append(loss.item()) if step == 1 or step % 50 == 0: print(f"step {step:3d} loss {loss.item():.4f}") plt.plot(range(1, STEPS + 1), history) plt.xlabel("step") plt.ylabel("training loss") plt.savefig("tour-loss.png") print("Saved tour-loss.png") -
Before running it, predict: will the loss go up, go down, or stay about the same over the 300 steps? Then run it (well under 30 seconds):
python tour.pyOutput on Linux (illustrative; the last digits can differ on your computer, but a rerun on the same computer repeats exactly):
step 1 loss 0.8052 step 50 loss 0.0487 step 100 loss 0.0232 step 150 loss 0.0176 step 200 loss 0.0129 step 250 loss 0.0101 step 300 loss 0.0093 Saved tour-loss.pngThe script also saves
tour-loss.pngin the folder: a line falling steeply over the first 50 steps and then flattening. Open it in an image viewer: the chart shows every step, while the printed lines show only every 50th, and question 4 below asks you to read it.
Success: the loss falls from its first value to less than half of it,
and tour-loss.png exists. Here it falls from 0.8052 to 0.0093.
The Five Parts of a Training Script
Every training script you write in this course has the same five parts.
Here is what each does in tour.py and where the course teaches it.
1. Data. torch.linspace(-3, 3, 200) makes 200 evenly spaced numbers
from -3 to 3; .unsqueeze(1) turns that list into a column of 200 rows and 1
column, the layout a model expects. y is the sine of each x plus noise:
torch.randn_like(x) draws random numbers centred on 0, and multiplying by
0.1 keeps them small. These are tensors, PyTorch's arrays. The tensor
module teaches shapes like (200, 1); Write a dataset and batch it teaches
proper data handling.
2. Model. nn.Sequential runs three layers in order: nn.Linear(1, 32)
turns each single input into 32 numbers using 64 learnable numbers (32 weights
and 32 biases),
nn.Tanh() bends them so the network can represent curves, and
nn.Linear(32, 1) combines the 32 numbers into one prediction. Build models
with nn.Module teaches this.
3. Loss. nn.MSELoss() is the mean squared error: the average of
(prediction − target)² over all 200 points. Match losses and outputs to the
task explains how to choose a loss.
4. Optimiser. torch.optim.Adam(model.parameters(), lr=0.01) is the
object that changes the weights. lr is the learning rate, the size of
each change (S47). You
will write this update by hand in Write gradient descent by hand, and
compare optimisers in module 6.
5. Loop. Each of the 300 steps does four things in order: predict
(model(x)), measure the error (loss_fn), work out how each weight should
change (zero_grad then backward), and apply the change (step).
loss.item() turns the one-number loss tensor into an ordinary Python
number for printing and for the chart's list. Write the training loop
explains every line of this pattern.
Two further lines support the run rather than the learning.
torch.manual_seed(0) fixes the random numbers, so the noise and the
starting weights are the same on every run. matplotlib.use("Agg") selects
Matplotlib's non-interactive backend, which writes charts to files without
opening a window (S93).
What the Falling Loss Shows, and What It Does Not
The loss fell from 0.8052 to 0.0093, so the network now fits these 200
points closely. Notice where it levels off. The noise added to y has a
typical size of 0.1, and its square, about 0.01, is an error no model could
remove, because noise is random by definition. A loss near 0.01 means the
network has captured the curve and little else.
It does not show that the network would predict new points well. Every number in the loss was measured on the same points the network learned from. A model can score very well on its training data and badly on data it has not seen. Checking that needs data held back from training, which the course introduces in Write the training loop and examines closely in Diagnose underfitting and overfitting.
Your Turn
Make each change, predict first, run, then change it back:
- Change
lr=0.01tolr=0.0001. Predict the loss at step 300. - Change
STEPS = 300toSTEPS = 1000. Predict whether the loss keeps falling towards zero.
Then label each of the five numbered comments in tour.py with the lesson
title that teaches it, using the section above.
Clean Up
cd ~/pytorch-practice
ls
rm -r first-training-run
ls
Windows PowerShell:
cd $HOME\pytorch-practice
ls
Remove-Item -Recurse first-training-run
ls
Keep .venv.
Check Your Understanding
- A friend's model reaches a training loss of 0.0001 on this task. Is it a better model than yours?
- Which line would you change to make each weight change smaller?
- What would happen to the printed losses if you deleted
torch.manual_seed(0)and ran the script twice? - Open
tour-loss.png. Read the loss at step 100 from the chart and compare it with the printed value. What happens between steps 5 and 15 that the printed lines do not show?
Answer and Reasoning
Your turn
- With
lr=0.0001each weight change is a hundred times smaller, so after 300 steps the loss has only reached about 0.25 instead of 0.0093 (illustrative: 0.2534 on the author's run). The network is learning, but too slowly for this number of steps. - With 1,000 steps the loss settles at about 0.0089 from step 900 onwards and does not approach zero. The remaining error is the noise, which no model can predict; going slightly below 0.01 means the network has begun to fit a little of that noise.
The five comments map to: data, Write a dataset and batch it; model, Build models with nn.Module; loss, Match losses and outputs to the task; optimiser, Write gradient descent by hand and module 6; loop, Write the training loop.
Understanding check
- Not necessarily. A training loss far below the noise level (about 0.01 here) means the model is memorising the noise in these particular points, which usually makes it worse on new points. Only data held back from training can show which model is better.
- The optimiser line: lower
lr. - The noise and the starting weights would differ, so the two runs would print different losses, though both would fall to about the same level.
- The chart shows about 0.02 at step 100; the printed value is 0.0232. A chart gives a quick, approximate reading, and the printed number is exact. Between steps 5 and 15 the loss falls to about 0.12 (0.1158 at step 6), rises to about 0.22 (0.2254 at step 10) and then falls again: a short overshoot that printing every 50 steps hides. Early wobbles like this are common; the overall trend is what this run shows.