Twee halve manen en handgeschreven cijfers in PyTorch: zelf een neuron en een netwerk trainen, het netwerk uit de handschriftdemo nabouwen, kiezen hoe groot het moet zijn en zien welke cijfers het verkeerd leest.
Uitvoeren in Google ColabColab vereist een Google-account, maar je kan de notebook ook .
Leesmodus. Hieronder staat de hele notebook, met de uitvoer van de code erbij. Je kan de volledige inhoud dus gewoon hier lezen. Om code aan te passen en de gevolgen te zien, kan je naar Google Colab (externe link) gaan.
In the chapter Neural Networks, one neuron learned to recognize students from what was on their tray, and a network of neurons read handwriting. This notebook builds and trains such networks yourself, in PyTorch (externe link), the library behind most of today's neural networks.
You will:
- 🌙 train one neuron on two half-moons, and see why it needs a hidden layer;
- ✍️ rebuild the network from the handwriting demo, and train it on 50,000 digits;
- ⚖️ choose how big the network should be, weighing its size against its accuracy;
- 🔍 measure it once on the test set, and look at the mistakes it is most sure about.
Prior knowledge: the chapter Neural Networks. You can run the whole notebook without changing a single line.
Estimated time: about 40 minutes.
This notebook is part of AI voor Iedereen (KU Leuven). The latest version is always at ai.kuleuven.be/aivooriedereen/en/notebook/neural-networks, and you can open it directly in Google Colab (externe link).
🚀 First time in a notebook?
Then the short introductory notebook explains everything step by step. The most important things:
- Make your own copy: File → Save a copy in Drive (in the menu at the top left), and work in that copy.
- Run a cell by clicking in it and pressing Shift+Enter, or with the ▶ button to its left. The result appears below the cell.
- Run the cells in order, from top to bottom, because a cell uses what the cells above it made. Does something behave strangely? Choose Runtime → Restart session and run everything again from the top.
Prefer not to use Google? Download the notebook file and open it in Jupyter (externe link) or Visual Studio Code (externe link), with PyTorch (torch and torchvision), scikit-learn and matplotlib installed.
🐍 Python in this notebook
New to Python? The introductory notebook explains the basics: variables, lists, loops and functions. On top of those, this notebook uses:
| Code | Meaning |
|---|---|
torch.tensor(points, dtype=torch.float32) | A tensor: the way PyTorch stores numbers, as a table with rows and columns (or more dimensions, such as the 28 by 28 pixels of an image). Arithmetic on a tensor, such as / 255, applies to every number in it at once. |
nn.Linear(2, 1) | A layer of neurons: here one neuron with two inputs. It computes a weighted sum of its inputs plus a bias. |
nn.Sequential(layer, ..., layer) | A network: layers that the numbers pass through one after the other. |
model(X) | Runs every row of X through the network at once, and gives a score per row. |
loss.backward(), optimizer.step() | Works out for every weight in which direction the loss goes down, and then moves every weight a small step that way. |
DataLoader(..., batch_size=128, shuffle=True) | Cuts the examples into minibatches of 128, in a different order every time. |
with torch.no_grad(): | Only computes, without preparing to learn: faster, for measuring and predicting. |
scores.argmax(dim=1) | The position of the highest score in every row: the digit the network picks. |
🌙 A warm-up: two half-moons
Three hundred points in two colors, curled into each other like two half-moons. Every point is two numbers, its position from left to right (x) and from bottom to top (y), and the question is which color it has. scikit-learn makes such points with make_moons, with some noise so that they don't lie on perfect arcs.
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from sklearn.datasets import make_moons
points, labels = make_moons(n_samples=300, noise=0.2, random_state=0)
X_moons = torch.tensor(points, dtype=torch.float32) # 300 rows of two numbers
y_moons = torch.tensor(labels, dtype=torch.float32).view(-1, 1) # 0 = orange, 1 = blue
print(X_moons[:3])
print(y_moons[:3])
colors = np.array(["tab:orange", "tab:blue"])
plt.scatter(points[:, 0], points[:, 1], c=colors[labels], s=15)
plt.gca().set_aspect("equal")
plt.show()tensor([[ 0.8844, -0.6561],
[ 0.0747, -0.3058],
[ 0.8686, 0.6362]])
tensor([[1.],
[1.],
[0.]])🔌 One neuron
First one neuron, just like in the chapter: it gives each of its two inputs a weight, adds them up with a bias, and the sigmoid turns that score into the probability that the point is blue. A score above 0 means a probability above 50%: then the neuron says blue. In PyTorch, that neuron is nn.Linear(2, 1).
The neuron learns the way the chapter described: guess, compare, adjust. In code, that is five lines, which run once per epoch (one pass over all the points):
- guess:
neuron(X_moons)gives a score for all 300 points at once; - compare: the loss says in one number how far those guesses are from the labels;
optimizer.zero_grad()clears what the previous step computed;loss.backward()works out for every weight in which direction the loss goes down;- adjust:
optimizer.step()moves every weight a small step in that direction. The size of the step is the learning rate from the chapter.
The loss is the binary cross-entropy from logistic regression. For every point, it looks at the probability the neuron gives to the right color: close to 0 when the neuron is sure and right, and very large when it is sure and wrong. Why not simply count the mistakes? Because a small change in a weight hardly ever changes that count, so the count doesn't tell the neuron which way to go. The cross-entropy changes a little with every change in a weight, so it always points the way. BCEWithLogitsLoss applies the sigmoid itself, which is why the neuron gives a score and not a probability.
torch.manual_seed(0) # the same random start weights every time
neuron = nn.Linear(2, 1) # a weight for each input, and a bias
loss_function = nn.BCEWithLogitsLoss() # sigmoid and binary cross-entropy in one
optimizer = torch.optim.SGD(neuron.parameters(), lr=1) # gradient descent with learning rate 1
for epoch in range(300):
scores = neuron(X_moons) # 1. guess: a score for every point
loss = loss_function(scores, y_moons) # 2. compare with the labels
optimizer.zero_grad() # 3. clear the previous step
loss.backward() # 4. work out which way every weight should go
optimizer.step() # 5. adjust: a small step that way
if epoch % 50 == 0:
print(f"epoch {epoch}: loss {loss.item():.3f}")
correct = ((neuron(X_moons) > 0).float() == y_moons).float().mean()
print(f"correct: {correct:.0%}")epoch 0: loss 0.806 epoch 50: loss 0.320 epoch 100: loss 0.305 epoch 150: loss 0.301 epoch 200: loss 0.300 epoch 250: loss 0.300 correct: 85%
The loss drops quickly and then stays put. To see why, show_boundary colors every spot of the plane by what the neuron says there. And draw_network draws the neuron itself, the way the demos in the chapter draw a network: every weight is a line, blue when it is positive and orange when it is negative, and thicker when it is larger. You don't need to read how these two functions work.
from matplotlib.lines import Line2D
def show_boundary(model, title):
# Colors every spot of the plane by the color the model picks there, and draws the points on top
xs, ys = np.meshgrid(np.linspace(-2, 3, 250), np.linspace(-1.5, 2, 180))
grid = torch.tensor(np.column_stack([xs.ravel(), ys.ravel()]), dtype=torch.float32)
with torch.no_grad():
blue = torch.sigmoid(model(grid)).reshape(xs.shape) # the probability of blue, everywhere
plt.contourf(xs, ys, blue, levels=[0, 0.5, 1], colors=["moccasin", "lightblue"])
plt.scatter(points[:, 0], points[:, 1], c=colors[labels], s=15)
plt.title(title)
plt.gca().set_aspect("equal")
plt.show()
def draw_network(model):
# Draws every neuron as a circle and every weight as a line:
# blue for a positive weight, orange for a negative one, thicker for a larger one
layers = [layer for layer in model.modules() if isinstance(layer, nn.Linear)]
sizes = [layers[0].in_features] + [layer.out_features for layer in layers]
largest = max(layer.weight.abs().max().item() for layer in layers)
def spot(column, row):
return column, (sizes[column] - 1) / 2 - row # every column centered on the same height
plt.figure(figsize=(1.8 * len(sizes) + 1, 0.45 * max(sizes) + 1.5))
for column, layer in enumerate(layers):
for target in range(layer.out_features):
for source in range(layer.in_features):
weight = layer.weight[target, source].item()
(x0, y0), (x1, y1) = spot(column, source), spot(column + 1, target)
plt.plot([x0, x1], [y0, y1], color="#3b82f6" if weight > 0 else "#f97316",
linewidth=0.5 + 5 * abs(weight) / largest, zorder=1)
for column, size in enumerate(sizes):
for row in range(size):
plt.scatter(*spot(column, row), s=350, color="white", edgecolors="black", zorder=2)
plt.text(-0.2, spot(0, 0)[1], "x", ha="right", va="center", fontsize=12)
plt.text(-0.2, spot(0, 1)[1], "y", ha="right", va="center", fontsize=12)
plt.text(len(sizes) - 0.8, 0, "blue", ha="left", va="center", fontsize=12)
plt.legend(handles=[Line2D([], [], color="#3b82f6", label="positive weight"),
Line2D([], [], color="#f97316", label="negative weight")],
loc="upper center", bbox_to_anchor=(0.5, 0.02), ncol=2, frameon=False)
plt.xlim(-0.6, len(sizes) - 0.4)
plt.ylim(-max(sizes) / 2 - 0.1, max(sizes) / 2 + 0.1)
plt.axis("off")
plt.show()
show_boundary(neuron, "One neuron")
draw_network(neuron)One neuron always draws a straight line: blue on one side, orange on the other. However long it trains, the tips of the moons stay on the wrong side. In the drawing of the neuron, the thick orange line from y stands out: the lower a point lies, the more likely the neuron says blue.
🪜 A hidden layer
The chapter's answer was a layer of neurons in between: every hidden neuron draws its own line, and the output neuron combines them into a curved boundary. Here, there are 8 hidden neurons with the activation function tanh, the same one as in the demos of the chapter. nn.Sequential puts the layers one after the other.
The five lines are the same as for the neuron, so we put them in a function train_on_moons that returns the loss after every epoch.
def train_on_moons(model, epochs, learning_rate):
# The same five lines as for the neuron, for any model; returns the loss after every epoch
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
losses = []
for epoch in range(epochs):
loss = loss_function(model(X_moons), y_moons)
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.item())
return losses
torch.manual_seed(0)
network = nn.Sequential(
nn.Linear(2, 8), # the hidden layer: 8 neurons, each with two weights and a bias
nn.Tanh(), # their activation function
nn.Linear(8, 1), # the output neuron: a weight for every hidden neuron, and a bias
)
losses = train_on_moons(network, epochs=1000, learning_rate=1)
correct = ((network(X_moons) > 0).float() == y_moons).float().mean()
print(f"correct: {correct:.0%}, loss at the end: {losses[-1]:.3f}")
plt.plot(losses)
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()correct: 98%, loss at the end: 0.064
The loss first gets stuck for a while at about 0.3, the level of the single neuron, and then drops further as soon as the hidden neurons start to bend the boundary:
show_boundary(network, "8 hidden neurons")The boundary now curls around the tips of the moons. The few points that are still on the wrong side lie deep in the other color because of the noise; no sensible boundary gets those right. And this is the network that draws that boundary:
draw_network(network)Every hidden neuron has a weight for x and one for y, and the output neuron has a weight for every hidden neuron: 24 weights in all, plus a bias for every neuron, which the drawing leaves out. The thickest lines are the weights that count most.
Try it yourself
- Give the hidden layer 3 neurons instead of 8 (in both
nn.Linear(2, 8)andnn.Linear(8, 1)), and then 32. How do the boundary and the drawing of the network change? - Change the learning rate to
0.1and then to10. With the small steps, the boundary is still barely bent after 1,000 epochs; with the big steps, the loss jumps up and down.
✍️ Handwritten digits
Now the network from the handwriting demo in the chapter. It was trained on MNIST (externe link): 70,000 handwritten digits of 28 by 28 pixels, written by American students and employees of the US Census Bureau. The package torchvision downloads them the first time (about 12 MB).
We keep 10,000 of the 60,000 training digits apart as a validation set: the network never learns from them, so they show how well it does on digits it hasn't seen. The 10,000 digits of the test set are for the very end. Every pixel becomes a number from 0 (white) to 1 (black), and every image a row of 784 of those numbers, one per pixel.
from torch.utils.data import DataLoader, TensorDataset
from torchvision import datasets
train_set = datasets.MNIST(root="data", train=True, download=True) # 60,000 digits
test_set = datasets.MNIST(root="data", train=False, download=True) # 10,000 other digits
X = train_set.data.float().view(-1, 784) / 255 # every image: a row of 784 numbers from 0 to 1
y = train_set.targets # the digit that was written: 0 to 9
X_train, y_train = X[:50000], y[:50000] # the network learns from these
X_val, y_val = X[50000:], y[50000:] # and is checked on these while it learns
X_test = test_set.data.float().view(-1, 784) / 255
y_test = test_set.targets
print(f"{len(X_train)} digits to learn from, {len(X_val)} to check on, {len(X_test)} for the end")
fig, axes = plt.subplots(1, 10, figsize=(10, 1.4))
for ax, image, label in zip(axes, train_set.data, y):
ax.imshow(image, cmap="gray_r")
ax.set_title(label.item())
ax.axis("off")
plt.show()50000 digits to learn from, 10000 to check on, 10000 for the end
🧱 The network from the demo
The network in the demo has 784 inputs (one per pixel), a hidden layer of 16 neurons with tanh, and one output neuron per digit: 10 in total. The building blocks are the same as for the half-moons, only bigger.
The 10 output neurons give 10 scores, and the softmax turns those into 10 probabilities that add up to 100%. Before training, the weights are random, so the network gives every digit about the same probability.
torch.manual_seed(0)
digit_network = nn.Sequential(
nn.Linear(784, 16), # 16 hidden neurons, each with a weight for all 784 pixels
nn.Tanh(),
nn.Linear(16, 10), # 10 output neurons: a score for every digit
)
print(digit_network)
print(sum(p.numel() for p in digit_network.parameters()), "weights and biases")
with torch.no_grad():
# the 10 scores for the first digit, turned into 10 probabilities
probabilities = torch.softmax(digit_network(X_train[:1]), dim=1)
print("before training:", [f"{p:.0%}" for p in probabilities[0].tolist()])Sequential( (0): Linear(in_features=784, out_features=16, bias=True) (1): Tanh() (2): Linear(in_features=16, out_features=10, bias=True) ) 12730 weights and biases before training: ['10%', '11%', '8%', '10%', '12%', '9%', '11%', '10%', '10%', '8%']
Those are the "just over 12,700 weights" from the chapter, still random.
🔁 Training in minibatches
For the half-moons, every step looked at all 300 points at once. With 50,000 digits, that would make every step slow, so the network learns from minibatches of 128 digits: a step after every minibatch, and about 390 steps per epoch. DataLoader cuts the digits into minibatches, in a new order every epoch.
Three more changes compared to the half-moons:
- The loss is
nn.CrossEntropyLoss: the same idea as the binary cross-entropy, for ten classes. It applies the softmax itself and looks at the probability of the right digit. - The optimizer is Adam, the usual choice for neural networks: gradient descent that adapts the size of the step for every weight separately. A learning rate of 0.001 is its usual starting point.
- After every epoch, the function measures the loss on the training digits and on the validation digits. Those are the two learning curves. A network can also learn its training digits by heart: the training loss then keeps going down, but the validation loss goes up again. So the function keeps a copy of the weights of the epoch with the lowest validation loss, and puts those back at the end.
plot_curves draws the two learning curves, with a dashed line at the epoch whose weights train kept. You can copy both functions for a network of your own, and give train your own data.
import copy
import time
def train(model, X, y, X_val, y_val, epochs, learning_rate=0.001):
# Trains on X and y in minibatches and measures both losses after every epoch;
# at the end, the model gets the weights of the epoch with the lowest validation loss
batches = DataLoader(TensorDataset(X, y), batch_size=128, shuffle=True)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
loss_function = nn.CrossEntropyLoss() # softmax and cross-entropy in one
history = {"training": [], "validation": [], "accuracy": [], "seconds": []}
best_loss = float("inf")
for epoch in range(epochs):
start = time.perf_counter()
for X_batch, y_batch in batches:
loss = loss_function(model(X_batch), y_batch)
optimizer.zero_grad()
loss.backward()
optimizer.step()
history["seconds"].append(time.perf_counter() - start)
with torch.no_grad():
history["training"].append(loss_function(model(X), y).item())
val_scores = model(X_val)
history["validation"].append(loss_function(val_scores, y_val).item())
history["accuracy"].append((val_scores.argmax(dim=1) == y_val).float().mean().item())
# the best epoch so far: keep a copy of its weights
if history["validation"][-1] < best_loss:
best_loss = history["validation"][-1]
best_weights = copy.deepcopy(model.state_dict())
history["best_epoch"] = epoch + 1
model.load_state_dict(best_weights)
return history
def plot_curves(history):
# The two learning curves, with a dashed line at the epoch whose weights train kept
epochs = range(1, len(history["training"]) + 1)
plt.plot(epochs, history["training"], label="training digits")
plt.plot(epochs, history["validation"], label="validation digits")
plt.axvline(history["best_epoch"], color="grey", linestyle="--", label="lowest validation loss")
plt.xlabel("epoch")
plt.ylabel("loss (cross-entropy)")
plt.legend()
plt.show()history = train(digit_network, X_train, y_train, X_val, y_val, epochs=10)
print("validation accuracy per epoch:", ", ".join(f"{a:.1%}" for a in history["accuracy"]))
print(f"{sum(history['seconds']) / len(history['seconds']):.1f} seconds per epoch")
plot_curves(history)validation accuracy per epoch: 90.6%, 92.2%, 92.6%, 93.0%, 93.6%, 93.7%, 93.9%, 94.1%, 94.2%, 94.3% 0.4 seconds per epoch
After one epoch, the network already reads nine out of ten digits it has never seen correctly, and after ten epochs about 94%. Both curves go down and stay close together: the network learns patterns that also hold for digits it hasn't seen. With 16 neurons and 50,000 digits, it doesn't learn the training digits by heart, so here the last epoch is also the best one, and the dashed line sits at the end. (The demo in the chapter was trained longer, and gets about 95%.)
What does it look like when a network does learn its training digits by heart? Give it many more weights and far fewer examples: 1,024 hidden neurons, which learn from only 2,000 digits, for 30 epochs.
torch.manual_seed(0)
big_network = nn.Sequential(nn.Linear(784, 1024), nn.Tanh(), nn.Linear(1024, 10))
history = train(big_network, X_train[:2000], y_train[:2000], X_val, y_val, epochs=30)
best = history["best_epoch"]
print(f"lowest validation loss after epoch {best}")
print(f"validation accuracy: {history['accuracy'][best - 1]:.1%} after epoch {best}, "
f"{history['accuracy'][-1]:.1%} after epoch 30")
plot_curves(history)lowest validation loss after epoch 7 validation accuracy: 89.7% after epoch 7, 89.0% after epoch 30
The training loss keeps going down, to almost zero: the network knows its 2,000 digits by heart. The validation loss is lowest after a few epochs, and then goes up again. That is the moment to stop training, and the dashed line marks the epoch whose weights train kept. The accuracy on the validation digits hardly changes after that point. What keeps growing is how sure the network is of its answers, the wrong ones included, and that is exactly what the loss punishes.
⚖️ Choosing the size
More neurons usually means a better network, but also more weights: more memory, and slower training and predicting. Which size is right depends on where the network has to run. We train five sizes, from no hidden layer at all to 1,024 hidden neurons, five epochs each, and compare their size and their validation accuracy.
Without a hidden layer, every output neuron weighs the 784 pixels directly: ten loose neurons, which together are the same model as logistic regression for several classes.
results = []
for hidden in [0, 16, 64, 256, 1024]:
torch.manual_seed(0)
if hidden == 0:
model = nn.Linear(784, 10) # no hidden layer: the outputs weigh the pixels directly
else:
model = nn.Sequential(nn.Linear(784, hidden), nn.Tanh(), nn.Linear(hidden, 10))
history = train(model, X_train, y_train, X_val, y_val, epochs=5)
weights = sum(p.numel() for p in model.parameters())
with torch.no_grad():
accuracy = (model(X_val).argmax(dim=1) == y_val).float().mean().item()
seconds = sum(history["seconds"]) / len(history["seconds"])
results.append((hidden, weights, accuracy))
print(f"{hidden:>5} hidden neurons: {weights:>7} weights ({weights * 4 / 1000:>5.0f} kB), "
f"{seconds:.1f} s per epoch, validation accuracy {accuracy:.1%}")0 hidden neurons: 7850 weights ( 31 kB), 0.4 s per epoch, validation accuracy 92.4%
16 hidden neurons: 12730 weights ( 51 kB), 0.4 s per epoch, validation accuracy 93.6%
64 hidden neurons: 50890 weights ( 204 kB), 0.6 s per epoch, validation accuracy 96.2%
256 hidden neurons: 203530 weights ( 814 kB), 1.1 s per epoch, validation accuracy 97.1%
1024 hidden neurons: 814090 weights ( 3256 kB), 2.5 s per epoch, validation accuracy 97.1%
Every weight is a number of 4 bytes, so the size in kilobytes follows from the number of weights. The plot puts the five networks side by side, with the number of weights on a logarithmic axis. A network is on the Pareto front when no smaller network is at least as accurate. Only those are worth considering: for every other network, a smaller one does at least as well.
front, best_so_far = [], 0
for hidden, weights, accuracy in results: # from small to large
if accuracy > best_so_far: # better than every smaller network: on the front
front.append((weights, accuracy))
best_so_far = accuracy
plt.plot([w for w, a in front], [a for w, a in front], color="grey", zorder=0, label="Pareto front")
plt.scatter([w for h, w, a in results], [a for h, w, a in results])
for hidden, weights, accuracy in results:
plt.annotate(f"{hidden} hidden", (weights, accuracy), textcoords="offset points", xytext=(6, -12))
plt.xscale("log")
plt.xlabel("number of weights")
plt.ylabel("validation accuracy")
plt.legend()
plt.show()Without a hidden layer, the network already reads about 92% of the digits. Up to 256 neurons, every step adds something; from 256 to 1,024 neurons, four times as many weights hardly add anything.
The demo in the chapter uses 16 neurons. That isn't the most accurate choice, but the demo runs in your browser and shows every neuron, and 16 still fit on the screen. A machine that sorts letters by their postal code would rather take 256 neurons: it runs on a computer with plenty of memory, and every percent fewer mistakes is a letter less in the wrong place. Which one would you pick for an app on a cheap phone?
🔍 Looking at the mistakes
Now the test set, which the network hasn't seen at all yet: digits written by other people. We measure the demo network on it once, and look at the mistakes it was most sure about.
with torch.no_grad():
probabilities = torch.softmax(digit_network(X_test), dim=1)
confidence, guess = probabilities.max(dim=1)
wrong = (guess != y_test).nonzero().squeeze(1)
print(f"test accuracy: {1 - len(wrong) / len(y_test):.1%} ({len(wrong)} of {len(y_test)} digits wrong)")
# the ten mistakes the network was most sure about
most_sure = wrong[confidence[wrong].argsort(descending=True)][:10]
fig, axes = plt.subplots(1, 10, figsize=(10, 1.7))
for ax, i in zip(axes, most_sure):
ax.imshow(test_set.data[i], cmap="gray_r")
ax.set_title(f"{y_test[i]} → {guess[i]}\n{confidence[i]:.0%}", fontsize=9)
ax.axis("off")
plt.show()test accuracy: 94.0% (601 of 10000 digits wrong)
Above every digit: what was written, what the network read, and how sure it was. Some of these digits would make a person hesitate too. Others are clear, and still the network is almost completely sure of the wrong digit: neural networks are often more confident than they should be. Look out for a 7 with a stroke through the middle, the way many Europeans write it: the American writers of MNIST hardly ever did that, so the network has barely seen such sevens.
🧰 A neural network for your own problem
The recipe is the same as for the digits:
- Put your examples in a tensor
X, one row per example and one column per number, and their labels iny. Neural networks learn best when every column has a similar range: divide pixels by 255, and give a table whose columns have different units (degrees, kilometers, euros) aStandardScalerfrom scikit-learn, fitted on the training examples only. - Build the network with
nn.Sequential. The first layer gets as many inputs asXhas columns, the last layer as many outputs as you have classes, withnn.CrossEntropyLoss. To predict a number instead of a class, the last layer has one output and the loss isnn.MSELoss(), the squared error from regression. - Train with
train, and look at both learning curves withplot_curves: if the validation loss goes up while the training loss keeps going down, the copy of the best epoch is the network to keep. - Choose the size with the validation set, and measure the network you chose once on the test set.
Begin simple, as the chapter advises. On a table, a decision tree or a random forest is often just as good and much easier to read; a neural network pays off with thousands of numbers per example, such as pixels or sound, or with a smooth relation between the numbers, such as in physics. And for images, the convolutional networks of a later chapter do better than this network: they look at which pixels are neighbors.
PyTorch's own Learn the Basics (externe link) goes further, step by step.
By Thomas Winters (externe link) for AI voor Iedereen, KU Leuven. The latest version of this notebook: ai.kuleuven.be/aivooriedereen/en/notebook/neural-networks.
