Lesson 2 of 187 min
Layers and networks
One neuron draws one straight line; a layer of neurons draws several, and the next layer joins them into a shape, but only with a bend between the layers.
After this lesson you can stack layers, say what depth and width add, and explain why a network needs a non-linear step.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Write the network as a class
nn.Sequential works well when each part hands its output straight to the next. A class lets you say exactly where each result goes. Here forward still has the same three steps as the stack in the video.
import torch
from torch import nn
class DigitNet(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Linear(64, 32)
self.readout = nn.Linear(32, 10)
def forward(self, x):
return self.readout(torch.relu(self.hidden(x)))print(DigitNet()(torch.zeros(1, 64)).shape)torch.Size([1, 10])
Read one layer
model[0] is the first Linear in the stack. Each row of its weight table belongs to one of its 32 neurons. Each column belongs to one of the 64 inputs. The bias has one number for each row.
model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
print(model[0].weight.shape, model[0].bias.shape)torch.Size([32, 64]) torch.Size([32])
Try the digits without the bend
Keep 360 pictures aside. On this split, the 32-wide stack got the same number right with and without ReLU. Those two models can still miss different pictures. The darts were made up to give us a clear case where one straight cut falls short.
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.set_num_threads(4)
digits = load_digits()
x = torch.tensor(digits.data / 16, dtype=torch.float32)
y = torch.tensor(digits.target)
x_train, x_test, y_train, y_test = train_test_split(
x, y, test_size=0.2, stratify=y, random_state=0
)def fit_digits(net):
opt = torch.optim.Adam(net.parameters(), lr=0.001)
for _ in range(30):
for rows in torch.randperm(len(x_train)).split(32):
loss = nn.functional.cross_entropy(net(x_train[rows]), y_train[rows])
opt.zero_grad()
loss.backward()
opt.step()
with torch.no_grad():
return int((net(x_test).argmax(1) == y_test).sum())torch.manual_seed(0)
print("one layer", fit_digits(nn.Linear(64, 10)))
for bend in (nn.Identity, nn.ReLU):
torch.manual_seed(0)
net = nn.Sequential(nn.Linear(64, 32), bend(), nn.Linear(32, 10))
print(bend.__name__, fit_digits(net))one layer 333 Identity 343 ReLU 343
Try another starting point
On the darts, three hidden neurons can find the round center. Give the same network the same darts twice, with different starting weights, and see what training finds. The test darts stay fixed, so the starting weights are the only change.
draw = torch.Generator().manual_seed(1)
thrown, fresh = (torch.rand(1000, 2, generator=draw) * 2 - 1 for _ in range(2))
hit = (thrown.square().sum(1) < 0.25).float()
fresh_hit = fresh.square().sum(1) < 0.25def fit_darts(seed):
torch.manual_seed(seed)
net = nn.Sequential(nn.Linear(2, 3), nn.ReLU(), nn.Linear(3, 1))
opt = torch.optim.Adam(net.parameters(), lr=0.02)
for _ in range(3000):
loss = nn.functional.binary_cross_entropy_with_logits(net(thrown).flatten(), hit)
opt.zero_grad()
loss.backward()
opt.step()
return int(((net(fresh).flatten() > 0) == fresh_hit).sum())for seed in (0, 1):
print(seed, fit_darts(seed))0 807 1 981
Pick a width to try
Start small. Try another width on the same validation split and compare the scores before growing again. Keep the test pictures for the final check. Here each Linear creates one layer of weights and the size of its output gives its width.
def digit_stack(width):
return nn.Sequential(nn.Linear(64, width), nn.ReLU(), nn.Linear(width, 10))
for width in (8, 16, 32):
print(width, sum(p.numel() for p in digit_stack(width).parameters()))8 610 16 1210 32 2410
Make a peak with one hidden layer
A wide enough ReLU layer can approximate a continuous function as closely as you like on a closed, bounded range. Here three ReLUs make a small peak from three straight ramps. Training is a separate job. Leshno and colleagues.
t = torch.tensor([-1.0, 0.0, 0.5, 1.0, 1.5, 2.0, 3.0])
bends = torch.relu(t[:, None] - torch.tensor([0., 1., 2.]))
peak = bends @ torch.tensor([1., -2., 1.])
print(peak.tolist())[0.0, 0.0, 0.5, 1.0, 0.5, 0.0, 0.0]
Run on Python 3.13.3, PyTorch 2.15.0 and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Matrix multiplication
Three friends' ratings are the rows of M: Sam [2, 1], Kai [-1, 2], Ola [-2, -1]. Your ratings are you = [2, 1]. What is the third number of M @ you?
2 of 3
A network has two layers, with no bend between them. It can't find the round center of the dart board. Someone makes its first layer 100 neurons wide. Will it find the center now?
3 of 3
A smaller digits network: nn.Sequential(nn.Linear(64, 16), nn.ReLU(), nn.Linear(16, 10)). Its hidden layer is 16 wide. How many weights does it have, with the biases too?
The ideas in this lesson
- Hidden layer
- Neurons side by side between the inputs and the output: each draws its own straight line, and the next layer joins them.
- Why a network needs its bend
- Without a bend, layer after layer is one matrix and one straight line; the bend lets the next layer join lines into shapes.
- Depth and width
- Width is how many neurons a layer has; depth is how many layers there are in a row.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Layers and networks
Here's a challenge. Darts land all over a board. A few of them hit the round center. One neuron can't tell a hit from a miss. So how many neurons does it take?
Keep your guess
Hold on to your guess.
Here's the board. It's made up for this lesson. A thousand darts, thrown at random. A hundred and eighty-six of them hit the round center. Each network learns from these darts.
Then we score it on a thousand new ones, and a hundred and ninety-three of those hit.
One neuron, one straight line
A neuron multiplies its inputs by its weights, adds a bias, and bends the total. This one reads where a dart landed, across and up, and gives the chance of a hit. Over one half, it says hit. The places where the neuron says exactly one half make a straight line across the board. The darts that hit sit in a round center. Spot the problem.
No straight line has all the hits on one side and all the misses on the other. So after training, the neuron gives every dart about nineteen percent: the share of darts that hit. It says miss every time. That gets the eight hundred and seven misses right, and every hit wrong: the same as never saying hit at all.
A layer of neurons
So what if we use more neurons?
Put three of them side by side, in between.
Each one reads both inputs, and each one has its own straight line. With ReLU, each is zero on one side of its line, and climbs on the other side.
Their three numbers go into one last neuron, which gives the chance of a hit.
Neurons side by side make a layer. The last neuron is a layer too, a layer of one. And the layer in between... is called a hidden layer.
The last neuron joins the lines
But how do three straight lines make a round area? The last neuron gives each of them a minus weight, and it has a big plus bias.
At the center, all three are zero, so its total is just the bias: a hit.
As those numbers climb, the total falls. Once it drops to zero or below, the network says miss. So it says hit in an area around the center, with straight edges along the lines.
How many of the new darts does it get right?
Nine hundred and eighty-one. With one or two neurons in between, it's still eight hundred and seven. With eight, the area has more edges and gets rounder: nine hundred and eighty-four. So the answer is three neurons in between, and the last one.
Take the bend away
Neurons in a hidden layer, each with ReLU, feeding one last neuron, can find the round center.
So is it the number of neurons that does it?
Take ReLU away. Now each neuron in between has no flat side: its number just keeps going down past zero, in a straight line. When the last neuron adds those numbers up, the result is one straight line again.
With a hundred neurons in between, how many darts will it get right?
Eight hundred and seven. With three, eight or a hundred in between, it's the same.
Fold each network into one neuron, and round its weights and bias to three decimal places. They match what the single neuron learned.
Two layers in a row are one
Why?
A layer is a matrix times its input, plus its biases.
And one matrix after another is one matrix. The two sets of biases fold into one too.
With nothing between them, these two layers act like one neuron. It draws one straight line, no matter how many neurons are in between. Watch the darts network with eight in between and no bend. Its two layers multiply out to one neuron, and PyTorch gives the same outputs both ways.
The bend keeps the layers apart. That's what lets the next layer join their lines into a shape.
Width and depth
A network puts its neurons in layers. Here, each hidden layer has ReLU. This one reads the handwritten digits from Python for AI, small pictures of eight by eight pixels. Sixty-four pixels go in. Thirty-two neurons sit in its hidden layer. And ten neurons give the output, one score for each digit. The largest score is its answer. The width of a layer is how many neurons it has: here, thirty-two. The depth is how many layers there are, counting the output layer: here, two. A deeper network has more hidden layers in a row.
In code
In PyTorch, you write a network as layers in a row. Sequential takes them in order. First, a Linear layer with sixty-four inputs and thirty-two outputs. Then ReLU. Then a Linear layer with thirty-two inputs and ten outputs. Printing the model lists its three parts in order: two layers, with ReLU between them. How many weights does it have, with the biases too?
Two thousand four hundred and ten. Each neuron has one weight for each of its inputs, and one bias. Give it the whole set of digit pictures at once. You get one row for each digit, with ten scores in it.
Each layer hands its output to the next. That's where Sequential fits. For a network with branches, you can write its own forward method.
Three ideas
So, one neuron draws one straight line. A hidden layer draws several, and the next layer joins them into a shape. And the bend between them is what keeps two layers from being one.
Layers need a bend
Layers can join straight lines, but only with a bend between them. Now try it on this lesson's page, and take the quiz. Add a second hidden layer, and do better.
You use this lesson in Lab 1: A digit reader, part by part, after Softmax and cross-entropy.
Facts last checked on .
