Lesson 13 of 186 min
What hidden layers learn
A hidden layer turns each input into a few numbers, a description the network learned for its task, in which inputs with the same answer land close together.
After this lesson you can read a hidden layer as a learned description of the input.
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.
The network from the video
Here is the network from the video, with its layer of 3 just before the ten scores. The course's digits are split the same way, with 360 set aside. The same seed and the same loop give the same network, so you get the numbers the video shows.
import torch, torch.nn.functional as F
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
digits = load_digits()
x = torch.tensor(digits.data / 16, dtype=torch.float32)
x_train, x_val, y_train, y_val = train_test_split(
x, torch.tensor(digits.target), test_size=0.2, stratify=digits.target, random_state=0)def train(make, lr=0.01, epochs=30):
torch.manual_seed(0)
model = make()
opt = torch.optim.Adam(model.parameters(), lr=lr)
loader = DataLoader(TensorDataset(x_train, y_train), batch_size=32, shuffle=True)
for epoch in range(epochs):
for xb, yb in loader:
loss = F.cross_entropy(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
return model.eval()make = lambda: nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 3), nn.Linear(3, 10))
model = train(make)
right = (model(x_val).argmax(1) == y_val).float().mean().item()
print(f"named right: {right:.1%}")named right: 92.5%
Count the nearest points
The video's count asks one thing of every picture: of its 10 nearest points, how many are the same digit? NearestNeighbors finds them. Ask for 11, because each point's nearest is itself, and drop that one.
from sklearn.neighbors import NearestNeighbors
def same(points, k=10):
near = NearestNeighbors(n_neighbors=k + 1).fit(points).kneighbors(points, return_distance=False)[:, 1:]
return (y_val.numpy()[near] == y_val.numpy()[:, None]).mean()
with torch.no_grad():
print(f"{same(model[:3](x_val)):.1%}")87.3%
The first layer's neurons as pictures
Each of the first layer's 32 neurons has one weight for each of the 64 pixels. Put them back in 8 rows of 8 and draw them. You won't find a neuron for each digit: each is a patch of light and dark that several digits share. Nine of them never say more than 0 for these pictures.
import matplotlib.pyplot as plt
w = model[0].weight.detach().reshape(32, 8, 8)
fig, axes = plt.subplots(4, 8, figsize=(8, 4))
for ax, picture in zip(axes.flat, w):
ax.imshow(picture, cmap="RdBu")
ax.axis("off")
with torch.no_grad():
on = (model[:2](x_val) > 0).any(0)
print(int(on.sum()), "of 32 say more than 0 for some picture")23 of 32 say more than 0 for some picture
Draw the layer of 32 with t-SNE
The layer of 3 was added so we could draw it. The layer of 32 before it can be drawn too, with t-SNE from the Machine Learning course. Its 32 numbers already put the same digits together, and the flat map shows ten groups.
from sklearn.manifold import TSNE
with torch.no_grad():
h32 = model[:2](x_val).numpy()
flat = TSNE(n_components=2, random_state=0).fit_transform(h32)
plt.scatter(*flat.T, c=y_val, cmap="tab10", s=8)
print(f"32 numbers: {same(h32):.1%}, drawn flat: {same(flat):.1%}")32 numbers: 88.3%, drawn flat: 90.0%
A bend after the layer of 3
The video's layer of 3 has no ReLU after it, so its numbers can be anything. Add one, and every number below 0 becomes 0: the cloud is pressed into one corner, and 162 of the 360 pictures have a 0 among their three numbers. The digits gather all the same.
bent = train(lambda: nn.Sequential(
nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 3), nn.ReLU(), nn.Linear(3, 10)))
with torch.no_grad():
h = bent[:4](x_val)
print(f"{same(h):.1%} of the nearest are the same digit")
print((h == 0).any(1).sum().item(), "of 360 pictures have a 0 among their 3 numbers")87.6% of the nearest are the same digit 162 of 360 pictures have a 0 among their 3 numbers
Why Adam at 0.01
Earlier lessons trained with Adam at 0.001. A layer of only 3 neurons learns slowly at that rate: after 30 epochs it names fewer pictures right, and it needs about 100 epochs to get as far. So this network uses 0.01.
for epochs in (30, 100):
slow = train(make, lr=0.001, epochs=epochs)
right = (slow(x_val).argmax(1) == y_val).float().mean().item()
print(f"lr 0.001, {epochs} epochs: {right:.1%} named right")lr 0.001, 30 epochs: 82.2% named right lr 0.001, 100 epochs: 89.7% named right
Run on Python 3.13.3, PyTorch 2.15.0, scikit-learn 1.9.1 and matplotlib 3.11.2. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Layers and networks
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?
2 of 3
The network was trained only to name the digits. Yet its layer of 3 now puts each digit in a region of its own. Why did it group them, when nobody asked?
3 of 3
A network's hidden layer has 16 neurons. You run the network up to that layer, on all 1,437 pictures it learns from. What shape comes out?
The ideas in this lesson
- Hidden representation
- A hidden layer's numbers for one input: a description the network learned, where inputs with the same answer land close.
- Learned for the task
- The last layer cuts straight, so training moves each kind into a region of its own, keeping what tells them apart.
- One neuron, many things
- Read alone, one neuron mixes several things; the meaning is in all the numbers together, the input's place.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
What do they learn?
Here's a mystery. A network has hidden layers between its input and its answer. Nobody tells them what to do. So what do they learn?
Every picture, a point
Here's a way to look inside. Give the network one more layer, with only three neurons, just before its ten scores, one for each digit. Then every digit set aside becomes three numbers: a point. Before training, the points make one mixed cloud. Now the network only learns to name the digits. After thirty epochs, where will the points be? The same digits together, still mixed, or in a line from zero to nine?
Three numbers, a point
A hidden layer gives each picture one number for each of its neurons. The thirty-two neurons in between give thirty-two numbers.
Keep those thirty-two.
Then add one more layer, with only three neurons, just before the ten scores.
Now each picture is three numbers: a point.
Two of the numbers make a flat picture.
The third number lifts the picture into a space we can turn.
Before training
Before training, the cloud is mixed. Take any picture, and its ten nearest points. How many of them are the same digit? On average, about three in ten: twenty-nine percent. Points thrown at random would give one in ten. So before training, there's only a little order.
After training
Now train it, only to name the digits.
After one epoch, fifty-two percent of the nearest points are the same digit.
After thirty... eighty-seven percent. And the network names over ninety-two percent of the pictures right. Each digit has a region of its own, with a few in the wrong place. And nobody asked for groups.
The layer's numbers are a description that the network learned for its task. That's its hidden representation.
A place for each digit
Turn it. The sevens are up here, the fours down there. A picture's place in the cloud says which digit it is.
Why they gather
A hidden layer gives each picture one number for each neuron, and after training, the same digits sit together. But why, if nobody asked?
The last layer gives each digit a score from the three numbers, and the biggest score is the answer. Each score is a neuron's total of the three numbers.
Look at two digits, the fours and the ones.
Their scores are equal along this flat sheet. On one side, the fours' score is bigger. On the other side, the ones' score is. So a four is only named right when its point sits on the fours' side. Training moves the fours there, and every digit into a region of its own.
Kept what matters
But are these three numbers just the picture, made smaller?
Squash the sixty-four pixels to three numbers the PCA way, which keeps as much of their spread as it can. Many digits still overlap: sixty-two percent. PCA never sees the names. It keeps whatever varies most, like how thick the stroke is.
The trained layer's three numbers: eighty-seven percent. Measured the same way on all sixty-four pixels, it's only eighty-four. It's like sorting vacation photos into beach and snow. You notice what matters for sorting, and stop seeing the rest.
And digits that look alike sit close: the zeros by the sixes. The threes by the fives.
One neuron alone
A hidden layer gives each picture one number for each neuron: a description. So does each neuron hold one idea, like "a loop"?
Take neuron two of the layer of three, alone. Find the forty pictures it gives the highest numbers to. Is that one digit?
Twenty are twos, and eighteen are fives.
One neuron mixes things. The meaning is in all the numbers together: the picture's place.
An embedding is a hidden layer
So where will you come across this?
An embedding model gives each sentence a long list of numbers. Those numbers come from its last hidden layer. That layer gives one row for each token, each small piece of the sentence.
The rows are averaged into one. There, close means alike, because the model was trained for that. In the same way, our layer of three was trained to name digits.
In code
In code, run the network up to its layer of three, on the pictures set aside. What shape comes out?
Three hundred and sixty rows of three. One point for each picture. Picture thirteen is a four. Its five nearest points are all fours.
An embedding model's encode gives the same kind of numbers, for sentences.
Seven hundred and sixty-eight for each one.
A description
So, a hidden layer is a description the network learned for its task. Inputs that are alike land close together. And the meaning is in the place, not in one neuron.
The lab
That's the end of this unit. In its lab, you train an MLP and a CNN, move the digits, and look inside each one.
A description
A hidden layer is a description the network learned. Now try it on this lesson's page, and take the quiz. Find a picture that sits in the wrong group.
You use this lesson in Lab 5: Who reads a moved digit, which comes next.
Facts last checked on .
