Python for AI Engineers · Part C · Lesson 24 of 26
Your first neural network in PyTorch: the training loop, line by line
Build and train a small neural network in PyTorch, step by step: nn.Module and nn.Linear, ReLU, logits and softmax, CrossEntropyLoss, the Adam optimizer, the five-line training loop, DataLoader batches, eval mode and no_grad, validation accuracy, seeds, and saving a state_dict.
⏱ 45 min3 exercises that check your codeRuns in your browser
By the end you can
- Explain what a layer computes (
x @ W.T + b, then an activation like ReLU) and run a forward pass by hand - Define a model as an
nn.Modulewithnn.Linearandnn.ReLU, and read its parameters - Score a batch with
CrossEntropyLoss, and write the training loop:zero_grad, forward, loss,backward,step - Feed batches with
DataLoader, measure validation accuracy undermodel.eval()andtorch.no_grad(), and make runs repeatable withtorch.manual_seed - Save the trained weights as a
state_dictand load them again to make predictions
1What you will build, and the data
In the PyTorch basics lesson you trained a single weight by hand: compute the loss, call backward(), nudge the weight, zero the gradient. A neural network is the same loop with a few hundred (or a few billion) weights, so PyTorch gives you building blocks for the parts you would otherwise write again and again: layers, a loss function, an optimizer that does the nudging, and a DataLoader that feeds the data in small batches.
The task is a classic toy problem: two moons. Each point has 2 numbers (its x and y position) and belongs to class 0 (the upper half circle) or class 1 (the lower one, shifted right). The two half circles hook into each other, so no straight line separates them. A model that only draws straight lines, like logistic regression from the scikit-learn lesson, gets about 88% of these validation points right and cannot do better; a small network learns the curve and gets 97%. scikit-learn makes the points for us, and splits them into 800 for training and 200 for validation (points the model never trains on, used to check it on unseen data).
Create a project with PyTorch, NumPy and scikit-learn, pinned so your output matches this page. uv init makes the folder and its pyproject.toml; uv add installs the packages into the project's .venv. On Linux without an NVIDIA GPU, first add the CPU-only index to pyproject.toml exactly as shown in the PyTorch basics lesson, or uv downloads several gigabytes of GPU libraries.
uv init moons --python 3.12
cd moons
uv add torch==2.15.0 numpy==2.5.5 scikit-learn==1.9.1 + numpy==2.5.5 + scikit-learn==1.9.1 + scipy==1.18.1 + torch==2.15.0 (plus helper packages such as joblib, sympy and networkx)
import torch
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
def load_data():
"""Two interleaving half circles: 1,000 points with 2 features each, labelled 0 or 1."""
X, y = make_moons(n_samples=1000, noise=0.2, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
return (
torch.from_numpy(X_train).float(), # features: float32, like the model's weights
torch.from_numpy(y_train).long(), # labels: int64 class numbers 0 and 1
torch.from_numpy(X_val).float(),
torch.from_numpy(y_val).long(),
)
if __name__ == "__main__":
X_train, y_train, X_val, y_val = load_data()
print(X_train.shape, X_train.dtype)
print(y_train.shape, y_train.dtype)
print(X_val.shape, y_val.shape)
print(X_train[:3])
print(y_train[:3])
print("class counts:", torch.bincount(y_train).tolist()) Xis a NumPy array of shape(1000, 2)(one row per point),yholds 1,000 labels, 0 or 1.noise=0.2scatters the points a little so the moons overlap at the edges;random_state=0makes the same points every time.line 8train_test_splitshuffles and cuts the data:test_size=0.2keeps 20% (200 points) aside. It returns four arrays, unpacked here in one line.stratify=ykeeps the 50/50 class balance in both parts.line 9- NumPy makes float64; model weights are float32.
.float()converts, so the data and the model agree (the dtype trap from the last lesson).line 13 CrossEntropyLosswants the right answers as whole class numbers of type int64, which PyTorch calls **long**..long()makes sure.line 14- This block runs only when you run
data.pydirectly. Whentrain.pylater doesfrom data import load_data, it is skipped. It plays the role ofpublic static void mainin Java.line 20 bincountcounts how often each class number appears: 400 of each, thanks tostratify.line 27
torch.Size([800, 2]) torch.float32
torch.Size([800]) torch.int64
torch.Size([200, 2]) torch.Size([200])
tensor([[ 0.0829, 0.1291],
[ 0.0154, 0.3640],
[ 0.9253, -0.2784]])
tensor([1, 1, 1])
class counts: [400, 400] Run it with uv run python data.py (uv run runs a command inside the project's environment). The features are a (800, 2) float32 tensor: a batch of 800 rows with 2 numbers each. The labels are a flat (800,) int64 tensor, one class number per row. Every model in PyTorch follows this convention: the first dimension is the batch.
2Inside a layer: a forward pass by hand (runs here with NumPy)
A network is a chain of layers. The most common one, a linear layer (also called dense or fully connected), turns n input numbers into m output numbers: each output is a weighted sum of all the inputs plus a constant, the bias. For a whole batch at once that is one matrix multiply: x @ W.T + b, where W has one row of weights per output.
Stacking linear layers alone gains nothing: a linear function of a linear function is still a straight line. So between layers you put an activation, a simple non-linear function applied to every number. The usual one is ReLU, max(0, x): negative numbers become 0, positive ones pass through. That kink is what lets the network bend its decision boundary around the moons.
The last layer gives one raw score per class, called logits. They can be any number, positive or negative. Softmax turns them into probabilities that add up to 1, and the prediction is the class with the biggest one. Run this tiny network: 2 inputs, 3 hidden numbers, 2 classes, with weights picked by hand.
import numpy as np
x = np.array([[0.5, 0.25], # a batch of 2 points, 2 features each: shape (2, 2)
[1.0, -0.5]])
# Layer 1: 2 numbers in, 3 out. One row of weights per output, like nn.Linear stores them.
W1 = np.array([[1.0, -1.0],
[0.5, 2.0],
[-1.0, 0.5]]) # shape (3, 2)
b1 = np.array([0.0, -0.5, 0.25]) # shape (3,)
# Layer 2: 3 numbers in, 2 out (one score per class).
W2 = np.array([[1.0, -1.0, 0.5],
[-1.0, 1.0, 1.0]]) # shape (2, 3)
b2 = np.array([0.1, -0.1])
def linear(x, W, b):
return x @ W.T + b # what nn.Linear computes
def relu(z):
return np.maximum(z, 0.0) # negative numbers become 0
def softmax(z):
e = np.exp(z - z.max(axis=1, keepdims=True)) # subtract the max: same result, no overflow
return e / e.sum(axis=1, keepdims=True)
h = relu(linear(x, W1, b1))
print("hidden:")
print(h)
logits = linear(h, W2, b2)
print("logits:")
print(logits)
probs = softmax(logits)
print("probabilities:")
print(probs.round(4))
print("predicted classes:", probs.argmax(axis=1).tolist())
Expected output
hidden: [[0.25 0.25 0. ] [1.5 0. 0. ]] logits: [[ 0.1 -0.1] [ 1.6 -1.6]] probabilities: [[0.5498 0.4502] [0.9608 0.0392]] predicted classes: [0, 0]
Follow the shapes: (2, 2) @ (2, 3) (that is W1.T) gives (2, 3), 3 hidden numbers per point; (2, 3) @ (3, 2) gives (2, 2), 2 logits per point. The bias (3,) is added to every row by broadcasting. For the first point, the third hidden number was -1.0 * 0.5 + 0.5 * 0.25 + 0.25 = -0.125, and ReLU turned it into 0.
softmax computes e to the power of each score, divided by the row total. keepdims=True keeps the row sums as a column of shape (2, 1) so the division broadcasts row by row. Subtracting each row's largest score first changes nothing in the result but stops exp from overflowing on big scores like 1000. argmax(axis=1) gives the position of the biggest value in each row.
Change a weight and run it again: this is all a trained network is, a set of numbers that happen to give the right logits. Training is the search for those numbers. An LLM is this same idea at a huge scale: its last layer turns each position into one logit per token in its vocabulary, and softmax turns them into the probabilities it samples the next token from.
3A model is an nn.Module
In PyTorch every model, and every layer inside it, is a subclass of nn.Module. You write a class with two methods: __init__ creates the layers (Python's constructor), and forward(x) says how input flows through them. nn.Linear(2, 16) is the linear layer from the box above with 16 outputs; it creates its own weight and bias, filled with small random numbers, and registers them so the optimizer can find them later.
nn.Sequential chains layers so each output feeds the next, which saves writing every step in forward. Our model has two hidden layers of 16 numbers each, a common shape for a small MLP (multi-layer perceptron, the name for a stack of linear layers and activations).
import torch
from torch import nn
class MoonNet(nn.Module):
"""A small MLP: 2 input features -> 16 -> 16 -> 2 scores, one per class."""
def __init__(self, hidden: int = 16):
super().__init__() # always first: sets up PyTorch's bookkeeping
self.layers = nn.Sequential(
nn.Linear(2, hidden), # 2 numbers in, 16 out
nn.ReLU(), # max(0, x) on every number
nn.Linear(hidden, hidden),
nn.ReLU(),
nn.Linear(hidden, 2), # one score (logit) per class
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.layers(x)
if __name__ == "__main__":
torch.manual_seed(0) # the starting weights are random
model = MoonNet()
print(model)
for name, p in model.named_parameters():
print(f"{name:16} {tuple(p.shape)}")
print("parameters:", sum(p.numel() for p in model.parameters()))
x = torch.tensor([[0.0829, 0.1291],
[0.9253, -0.2784]]) # a batch of 2 points
logits = model(x) # calls forward() for you
print(logits)
print(logits.shape) class MoonNet(nn.Module)means MoonNet extends nn.Module, likeclass MoonNet extends Modulein Java or JavaScript.line 5- Calls the parent constructor, like
super()in Java. Forget it and the next line fails with "cannot assign module before Module.__init__() call".line 9 - Assigning a layer to
self.somethingregisters it, and with it all its weights. That is howmodel.parameters()finds them.line 10 - No softmax at the end: the model returns raw logits, because the loss function applies its own (section 4).line 15
forwardtakes a batch(N, 2)and returns(N, 2)logits. It is the only method you must write; PyTorch works out the backward pass by itself.line 18named_parameters()lists every trainable tensor with its name.f"{name:16}"pads the name to 16 characters so the shapes line up.line 27numel()is the number of elements in a tensor; the sum counts every weight and bias in the model.line 29- Call the model like a function, never
model.forward(x)directly:model(x)runsforwardplus the hooks PyTorch adds around it.line 33
MoonNet(
(layers): Sequential(
(0): Linear(in_features=2, out_features=16, bias=True)
(1): ReLU()
(2): Linear(in_features=16, out_features=16, bias=True)
(3): ReLU()
(4): Linear(in_features=16, out_features=2, bias=True)
)
)
layers.0.weight (16, 2)
layers.0.bias (16,)
layers.2.weight (16, 16)
layers.2.bias (16,)
layers.4.weight (2, 16)
layers.4.bias (2,)
parameters: 354
tensor([[-0.0546, 0.1247],
[-0.0727, 0.1656]], grad_fn=<AddmmBackward0>)
torch.Size([2, 2]) The weight of nn.Linear(2, 16) has shape (16, 2): one row per output, exactly like W1 in the NumPy box, and the layer computes x @ W.T + b. The ReLU layers (1 and 3) have no parameters, so they are missing from the list. 354 parameters is 2 x 16 + 16, plus 16 x 16 + 16, plus 16 x 2 + 2. A small LLM has a few billion, built from the same nn.Linear layers.
The untrained model gives almost the same logits for both points, a coin flip. grad_fn=<AddmmBackward0> shows that PyTorch recorded the computation (Addmm is "add plus matrix multiply", the linear layer), ready for backward().
Tip Print model and the parameter shapes whenever you build or load one. It is the fastest way to catch a wrong layer size before a shape error deep inside training.
4The loss: cross-entropy (runs here with NumPy)
Training needs one number that says how wrong the model is on a batch: the loss. For classification it is cross-entropy: for each point, take the probability the model gave to the right class and compute -log(p). If the model gives the right class 0.99, the loss is about 0.01; if it gives it 0.08, the loss is about 2.5. Confident mistakes cost the most. The batch loss is the average over its points.
In practice you compute the log of softmax directly (log_softmax), which is more accurate than taking log of a tiny probability. This box does exactly what PyTorch's nn.CrossEntropyLoss does.
import numpy as np
logits = np.array([[2.0, 0.5], # point 1: confident it is class 0
[0.2, 1.2], # point 2: leans to class 1
[1.5, -1.0]]) # point 3: confident it is class 0
labels = np.array([0, 1, 1]) # the right answers (point 3 is really class 1)
def log_softmax(z):
z = z - z.max(axis=1, keepdims=True) # stability: largest score becomes 0
return z - np.log(np.exp(z).sum(axis=1, keepdims=True))
logp = log_softmax(logits) # log of each class's probability
per_point = -logp[np.arange(len(labels)), labels] # pick the right class in each row
print("probabilities:")
print(np.exp(logp).round(4))
print("loss per point:", per_point.round(4))
print("loss (mean):", round(float(per_point.mean()), 4))
print("guessing 50/50 costs:", round(float(-np.log(0.5)), 4))
Expected output
probabilities: [[0.8176 0.1824] [0.2689 0.7311] [0.9241 0.0759]] loss per point: [0.2014 0.3133 2.5789] loss (mean): 1.0312 guessing 50/50 costs: 0.6931
logp[np.arange(3), labels] is NumPy's fancy indexing: it picks row 0 column 0, row 1 column 1, row 2 column 1, so one value per row, the log probability of the right class. The wrong answer on point 3 makes up most of the loss. The last line is worth remembering: an untrained two-class model guesses about 50/50, so its loss starts near 0.693. If your first loss is far from log(number of classes), something is wrong before training even starts.
The same numbers from PyTorch. nn.CrossEntropyLoss() takes the raw logits and the int64 labels; reduction="none" returns the loss per point instead of the mean:
import torch
from torch import nn
logits = torch.tensor([[2.0, 0.5], # point 1: confident it is class 0
[0.2, 1.2], # point 2: leans to class 1
[1.5, -1.0]]) # point 3: confident it is class 0
labels = torch.tensor([0, 1, 1]) # the right answers (point 3 is really class 1)
loss_fn = nn.CrossEntropyLoss()
print(loss_fn(logits, labels))
print(nn.CrossEntropyLoss(reduction="none")(logits, labels))
print(torch.softmax(logits, dim=1))
try:
loss_fn(logits, labels.float())
except RuntimeError as e:
print("error:", e)
tensor(1.0312)
tensor([0.2014, 0.3133, 2.5789])
tensor([[0.8176, 0.1824],
[0.2689, 0.7311],
[0.9241, 0.0759]])
error: expected target dtype to be Long or Byte, but got Float
The last line is the error you get when the labels are floats instead of class numbers; .long() in data.py prevents it. LLMs are trained with exactly this loss: at every position, cross-entropy between the predicted next-token logits and the token that really came next.
Watch out Do not put a softmax at the end of the model and then use CrossEntropyLoss. The loss applies its own log-softmax, so the model would be squashed twice: it still trains, but slowly and badly, with no error to warn you. Return logits from forward, and call torch.softmax only when you want probabilities to show or threshold.
5The training loop, line by line
Now the pieces come together. A DataLoader cuts the training set into batches of 32 points and, with shuffle=True, mixes the order every epoch (one full pass over the training data). Updating the weights after every small batch, instead of once per pass, means 25 updates per epoch instead of 1, so the model learns much faster. TensorDataset simply pairs row i of the features with row i of the labels.
The optimizer does the "nudge every weight" step you wrote by hand last lesson. Adam is the usual default: it keeps a running average of each weight's recent gradients and adapts the step size per weight, so it needs much less tuning than plain gradient descent (torch.optim.SGD). lr is the learning rate. Then every batch runs the same five lines. Learn them by heart: every PyTorch training script, up to fine-tuning an LLM, has them.
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from data import load_data
from model import MoonNet
def accuracy(model: nn.Module, X: torch.Tensor, y: torch.Tensor) -> float:
model.eval() # evaluation behaviour (matters for dropout)
with torch.no_grad(): # no graph: we only look at the answers
predictions = model(X).argmax(dim=1) # the class with the highest score
return (predictions == y).float().mean().item()
def main() -> None:
torch.manual_seed(0) # same weights and same shuffles on every run
X_train, y_train, X_val, y_val = load_data()
loader = DataLoader(TensorDataset(X_train, y_train), batch_size=32, shuffle=True)
model = MoonNet()
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
print(f"before training: val accuracy {accuracy(model, X_val, y_val):.3f}")
for epoch in range(1, 21): # one epoch = one pass over all 800 points
model.train() # training behaviour
total = 0.0
for xb, yb in loader: # 25 batches of 32 points
optimizer.zero_grad() # 1. clear the old gradients
logits = model(xb) # 2. forward: scores for this batch
loss = loss_fn(logits, yb) # 3. how wrong, as one number
loss.backward() # 4. a gradient for every weight
optimizer.step() # 5. nudge every weight
total += loss.item() * len(xb)
if epoch % 4 == 0:
train_loss = total / len(X_train)
print(f"epoch {epoch:2}: train loss {train_loss:.4f}, val accuracy {accuracy(model, X_val, y_val):.3f}")
torch.save(model.state_dict(), "moons.pt")
print("saved moons.pt")
if __name__ == "__main__":
main() argmax(dim=1)picks the column with the biggest logit in each row: the predicted class. No softmax needed, since the biggest logit is also the biggest probability.line 12predictions == ygives a tensor of True/False;.float()makes them 1.0 and 0.0, so the mean is the fraction correct..item()turns it into a Python float.line 13- Seeds PyTorch's random generator, which decides both the starting weights and the DataLoader's shuffles. Same seed, same run (section 7 has the fine print).line 17
- Yields
(features, labels)pairs of up to 32 rows. With 800 rows that is exactly 25 batches; otherwise the last batch is smaller.line 20 model.parameters()hands the optimizer every weight and bias to update.lr=0.01suits this tiny problem; Adam's default is 0.001.line 23- Gradients **add up** across
backward()calls (last lesson), so clear them first. It resets every parameter's.grad.line 30 - The forward pass on one batch:
(32, 2)in,(32, 2)logits out, with the graph recorded for backward.line 31 - Averages the cross-entropy over the batch into one number (a 0-dimensional tensor).line 32
- Walks the recorded graph backwards and fills
.gradon all 354 parameters.line 33 - Adam reads each
.gradand changes every weight a little. This is the only line that changes the model.line 34 loss.item()is the batch mean, so multiply by the batch size to add up a total, then divide by 800 for the epoch's average.line 35- Validation accuracy on the 200 points the model never trains on: the honest score.line 38
before training: val accuracy 0.500 epoch 4: train loss 0.1936, val accuracy 0.935 epoch 8: train loss 0.1068, val accuracy 0.965 epoch 12: train loss 0.1219, val accuracy 0.960 epoch 16: train loss 0.0960, val accuracy 0.980 epoch 20: train loss 0.0861, val accuracy 0.970 saved moons.pt
Run it with uv run python train.py; it takes a few seconds on a laptop CPU. Before training the model is a coin flip (0.500); after 20 epochs it gets 97% of the unseen points right. The train loss does not fall smoothly (epoch 12 is worse than epoch 8): each batch is a small, noisy sample, so steps sometimes overshoot. That is normal; look at the trend.
Validation accuracy wobbles between 0.96 and 0.98: the 200 points are few, so one point is half a percent. In real projects you keep the weights from the epoch with the best validation score (early stopping) rather than simply the last one, and you report a final number on a separate test set, as in the overfitting and leakage lesson.
The order of the five lines matters. step() before backward() uses stale or missing gradients; skipping zero_grad() lets each batch's gradients pile on top of the last. Neither raises an error: the loss just behaves strangely. The rest of the file is bookkeeping around those five lines.
Watch out Forgetting optimizer.zero_grad() is the classic silent bug: training runs, but every step uses the sum of all previous gradients, so the loss jumps around or blows up. If a loss curve looks wrong, check the five lines and their order first.
6eval mode and no_grad: two different switches
Two things look alike in the accuracy function but do different jobs, and you need both whenever you use a model rather than train it.
model.eval() switches layers that act differently while training into their evaluation behaviour. Our MoonNet has none, but many models do: dropout randomly zeroes some numbers during training so the network cannot lean on any single one (it fights overfitting), and batch norm uses statistics of the current batch. At prediction time you want neither randomness nor batch-dependence. model.train() switches back. torch.no_grad() is about autograd only: it stops recording the graph, which saves memory and time.
import torch
from torch import nn
torch.manual_seed(0)
drop = nn.Dropout(p=0.5) # randomly zeroes half the numbers while training
x = torch.ones(8)
drop.train()
print(drop(x))
print(drop(x))
drop.eval()
print(drop(x))
model = nn.Sequential(nn.Linear(2, 4), nn.Dropout(0.5), nn.Linear(4, 2))
print(model.training)
model.eval()
print(model.training, model[1].training)
x = torch.ones(1, 2)
print(model(x).requires_grad)
with torch.no_grad():
print(model(x).requires_grad) p=0.5is the chance that each number is set to 0 in training mode.line 5- Training mode: about half the ones become 0 and the rest are doubled to 2, so the average stays about the same. Each call drops different numbers.line 9
- Evaluation mode: dropout does nothing, every input passes through unchanged.line 12
- Every module starts in training mode;
.trainingis the flag thattrain()andeval()set.line 15 eval()on the model sets the flag on every layer inside it, here the dropout at index 1.line 17- Eval mode alone still records the graph: the output requires grad.line 20
- Under
no_grad, nothing is recorded. You want both switches for inference.line 22
tensor([0., 0., 2., 0., 0., 0., 2., 2.]) tensor([0., 2., 2., 2., 2., 0., 2., 2.]) tensor([1., 1., 1., 1., 1., 1., 1., 1.]) True False False True False
This is why train.py calls model.train() at the start of each epoch: accuracy() put the model in eval mode, and without switching back, dropout would stay off for the rest of training. In an AI app the rule is simple: load a model, call .eval() once, and run every request under torch.no_grad() (or torch.inference_mode(), a stricter and slightly faster version of the same thing). An embedding service that forgets .eval() on a model with dropout returns slightly different vectors for the same text on every call.
Tip eval() is not "turn off gradients" and no_grad() is not "evaluation mode". Remember them as a pair: model.eval() for layer behaviour, torch.no_grad() for memory and speed.
7Save, load and predict
A trained model is just its numbers. model.state_dict() returns them as an ordered dict from parameter name (layers.0.weight and so on) to tensor, and torch.save writes it to a file, about 4 KB here. To use it, create the same class again and call load_state_dict: the fresh random weights are replaced by the trained ones. The file holds no code, so the class must be importable wherever you load it.
This file loads moons.pt (made by train.py) and classifies three new points, with softmax to show how sure the model is.
import torch
from model import MoonNet
state = torch.load("moons.pt", weights_only=True) # a dict: parameter name -> tensor
print(list(state.keys()))
model = MoonNet() # same class, fresh random weights...
model.load_state_dict(state) # ...replaced by the trained ones
model.eval()
points = torch.tensor([[0.0, 1.0], # top of the upper half circle
[1.0, -0.5], # bottom of the lower one
[0.5, 0.25]]) # in between
with torch.no_grad():
probs = torch.softmax(model(points), dim=1)
for point, p in zip(points.tolist(), probs.tolist()):
print(point, "-> class", p.index(max(p)), f"({max(p):.2f})") .ptfiles use Python's pickle format, which can run code when loaded.weights_only=True(the default since PyTorch 2.6, written out here to be clear) only accepts tensors and plain containers, so a malicious file cannot run anything.line 5- Names and shapes must match the class exactly. A different hidden size raises "size mismatch for layers.0.weight"; a renamed layer raises "Missing key(s) in state_dict".line 9
- Eval mode before predicting, every time.line 10
- Softmax over
dim=1turns each row of 2 logits into 2 probabilities that add up to 1.line 16 .tolist()turns tensors into Python lists, sozippairs each point with its probabilities.line 17p.index(max(p))is the position of the highest probability: the predicted class.line 18
['layers.0.weight', 'layers.0.bias', 'layers.2.weight', 'layers.2.bias', 'layers.4.weight', 'layers.4.bias'] [0.0, 1.0] -> class 0 (1.00) [1.0, -0.5] -> class 1 (0.96) [0.5, 0.25] -> class 0 (0.72)
Run uv run python train.py first, then uv run python predict.py. Points deep inside a moon get confident answers; the point between the moons gets a hesitant 0.72. That confidence is useful in an app: below a threshold, hand the case to a human or to a bigger model, like the router in the scikit-learn lesson.
About reproducibility. torch.manual_seed(0) made the starting weights and the shuffles identical, so train.py prints the same numbers on every run on this machine. PyTorch only promises that for the same version on the same kind of hardware: on a Mac, on a GPU or with another torch version the last digits can differ, because floating-point sums done in a different order round differently. Set the seed at the top of every experiment anyway; it turns "the score changed" from a mystery into a real signal.
Saving the state_dict instead of the whole model object (torch.save(model)) is the recommended way: the file stays plain data and survives refactoring your code. Hugging Face models are stored the same way, as named tensors, usually in the .safetensors format, which cannot contain code at all.
Watch out Loading weights and forgetting .eval(), or loading a file from the internet with weights_only=False. The first gives wobbly predictions on models with dropout or batch norm; the second lets a pickle file run any code on your machine. Only turn weights_only off for files you made yourself.
Common mistakes
- Putting a softmax at the end of
forwardand also usingCrossEntropyLoss, which applies its own log-softmax. Return raw logits. - Forgetting
optimizer.zero_grad(), or callingstep()beforebackward(). Training runs without errors but learns badly. - Passing float labels to
CrossEntropyLoss: "expected target dtype to be Long". Class numbers must be int64 (.long()). - Evaluating without
model.eval()andtorch.no_grad(), then forgettingmodel.train()before the next epoch. - Judging the model by its training loss. Only accuracy on data it never trained on (validation, then test) tells you how it will do on new input.
- Loading a
state_dictinto a model built with different layer sizes, which fails with "size mismatch". Build exactly the same architecture first.
Practice
Write the code, then press Check. Your work is saved in this browser.
1Accuracy from logits
Write accuracy(logits, labels) in plain Python: logits is a list of rows (one list of class scores per example) and labels the list of right class numbers. The prediction for a row is the position of its biggest score. Return the fraction of rows predicted correctly as a float, and 0.0 for an empty list.
def accuracy(logits, labels):
# the predicted class is the position of the biggest score in each row
return 0.0
print(accuracy([[2.0, 0.5], [0.2, 1.2], [1.5, -1.0]], [0, 1, 1]))
Hint
For one row, `row.index(max(row))` is the predicted class. Count the rows where it equals the label, then divide by `len(labels)`.
2Count the parameters
Write count_parameters(sizes) for an MLP made of nn.Linear layers. sizes lists the numbers of features from input to output, so [2, 16, 16, 2] means Linear(2, 16), Linear(16, 16), Linear(16, 2). Each Linear(n, m) has an (m, n) weight and an (m,) bias. Activations have no parameters.
def count_parameters(sizes):
return 0
print(count_parameters([2, 16, 16, 2]))
Hint
Walk over neighbouring pairs `(n, m)` with `zip(sizes, sizes[1:])` and add `n * m + m` for each.
3Cross-entropy for one example
Write cross_entropy(logits, label) with the math module: the loss for one example is -log(softmax(logits)[label]). Make it stable: subtract the largest logit before calling math.exp, so huge logits such as [1000.0, 0.0] do not overflow.
import math
def cross_entropy(logits, label):
probs = [math.exp(z) for z in logits]
total = sum(probs)
return -math.log(probs[label] / total)
print(round(cross_entropy([2.0, 0.5], 0), 4))
Hint
Let `top = max(logits)`. Then `log(softmax[label]) = (logits[label] - top) - log(sum(exp(z - top) for z in logits))`. Return its negative.
Interview questions
Q1Walk me through a PyTorch training loop.
For each epoch, put the model in train mode and loop over batches from a DataLoader. For each batch: optimizer.zero_grad() to clear old gradients, a forward pass to get logits, the loss (for example CrossEntropyLoss(logits, labels)), loss.backward() to compute a gradient for every parameter, and optimizer.step() to update them. After each epoch, evaluate on a validation set under model.eval() and torch.no_grad().
Q2Why do neural networks need activation functions?
A stack of linear layers is still one linear function, so it can only draw straight decision boundaries. A non-linear activation such as ReLU between layers lets the network represent curved boundaries and, with enough units, approximate almost any function.
Q3What are logits, and why does CrossEntropyLoss take them instead of probabilities?
Logits are the raw, unnormalised scores the last layer outputs, one per class. CrossEntropyLoss combines log-softmax and negative log-likelihood in one numerically stable step, so it expects logits; applying softmax yourself first squashes them twice and hurts training.
Q4What is the difference between model.eval() and torch.no_grad()?
model.eval() switches layers like dropout and batch norm into inference behaviour; it does not affect gradients. torch.no_grad() stops autograd from recording the graph, saving memory and time; it does not change layer behaviour. For inference you use both.
Q5Why train in mini-batches instead of on the whole dataset or one example at a time?
A batch gives a gradient estimate that is good enough and cheap to compute, and you get many updates per epoch. The whole dataset per step is slow and may not fit in memory; single examples give very noisy gradients and use the hardware poorly. Batch sizes of 32 to a few hundred are typical; GPUs like powers of two.
Q6How do you save and load a PyTorch model?
Save the state_dict (a dict of parameter names to tensors) with torch.save(model.state_dict(), path). To load, construct the same model class and call model.load_state_dict(torch.load(path, weights_only=True)), then model.eval(). Saving the state_dict rather than the pickled object keeps the file independent of your code layout and safer to load.