There are no slides this week. Work through the notebook as we talk, then we build a network live at the end.
Getting started (2 minutes)
- Open the notebook in Colab and save your own copy.
- Click the play button beside a code cell to run it. Work from top to bottom.
- Double-click text to edit an answer. Click outside when done.
The first cell loads the libraries from Workshops 1 and 2, then the California house prices from Workshop 1 into a table called housing.
This session introduces a new library, PyTorch, which provides the building blocks of a neural network.
# Libraries from Workshops 1 and 2.import pandas as pd # Stores data in tables.import numpy as np # Does maths on many numbers at once.import matplotlib.pyplot as plt # Draws graphs.from sklearn.datasets import fetch_california_housing # The house prices from Workshop 1.from sklearn.linear_model import LinearRegression # The straight line from Workshop 1.from sklearn.model_selection import train_test_split # Splits the data, as in Workshop 1.from sklearn.preprocessing import StandardScaler # Rescales inputs, as in Workshop 2.
# New this week: PyTorch.import torch # Tensors and automatic gradients.from torch import nn # Building blocks for neural networks.
housing = fetch_california_housing(as_frame=True).frame # Download the data as a table.housing.head() # Show the first five rows.Part 1: Solving versus training (8 minutes)
In Workshop 1 you fitted a straight line:
Run the cell to see it again. Expect a slope of about 0.42 and an intercept of about 0.45.
line = LinearRegression()line.fit(housing[["MedInc"]], housing["MedHouseVal"])print("slope:", line.coef_[0], "| intercept:", line.intercept_)scikit-learn can find the best line in one go because a straight line is a special case. Its two parameters each just get multiplied by the data, so the best values come from solving two simple equations.
In a neural network, thousands of parameters get multiplied by each other, layer after layer, and equations like that cannot be rearranged into an answer. So instead of solving for a network’s parameters, we train them. This means starting from random parameters and improving them in small steps, thousands of times. PyTorch gives you the model and the tools, and leaves the rest to you.
The cell below is our own fit. It takes any PyTorch model and improves it by repeating four steps: predict, measure the error, work out which way to nudge every parameter, nudge. There is a lot going on here. Run it for now, and we’ll explain what’s happening later!
def fit(model, inputs, targets): loss_fn = nn.MSELoss() # The loss from Workshop 1. optimizer = torch.optim.Adam(model.parameters(), lr=0.01) # Makes the improvements. for step in range(1000): optimizer.zero_grad() # Forget the last step. predicted = model(inputs) # Predict a value for every house. loss = loss_fn(predicted, targets) # Measure how wrong the predictions are. loss.backward() # Work out which way to nudge every parameter. optimizer.step() # Nudge them. return loss.item()We can build the same model in PyTorch, because linear regression is the simplest possible neural network. nn.Linear(1, 1) has one input and one output, and like LinearRegression it has a slope and an intercept, which PyTorch calls weight and bias. incomes and values are the two columns in PyTorch’s format. The cell below prints the slope and intercept before and after training.
incomes = torch.tensor(housing[["MedInc"]].to_numpy(), dtype=torch.float32)values = torch.tensor(housing[["MedHouseVal"]].to_numpy(), dtype=torch.float32)
line = nn.Linear(1, 1)print("before | slope:", line.weight.item(), "| intercept:", line.bias.item())fit(line, incomes, values)print("after | slope:", line.weight.item(), "| intercept:", line.bias.item())Side by side:
| scikit-learn | PyTorch | |
|---|---|---|
| Model | LinearRegression() | nn.Linear(1, 1) |
| Fitting | line.fit(...) solves | fit(line, ...) trains |
| Parameters | coef_, intercept_ | weight, bias |
The one difference that matters is that scikit-learn’s fit only works for its own models, and ours works for any PyTorch model. Swap in nn.Linear(5, 10), which takes 5 inputs and gives 10 outputs, and the same fit trains it. We now have a recipe for training any neural network we can imagine!
Part 2: What is a neural network? (20 minutes)
So far the only thing we have trained is a straight line. This part turns it into a neural network, one piece at a time. Each step has a diagram to play with and shows how to write the same thing in PyTorch.
1. Neurons
Theory
A neuron takes some inputs. It multiplies each one by its own weight, adds them up, adds a bias, then passes the result through an activation function. The weights and bias are the neuron’s parameters.
Reading left to right, each input is multiplied by its weight on the way in, the bias joins from above, everything is added up, and the activation function decides what comes out.
Let’s think about what the blue part is doing intuitively. Each input is some feature we are trying to reason about, like a house’s income or latitude. Each weight says how much that feature matters to this neuron, and which way. Adding the weighted features to the bias gives us the blue part’s output, which we’ll call .
Notice that is linear in its features. If we built a network out of neurons with just the blue part, the whole thing would be linear too, however many neurons we used. That’s what the green part is for. The activation function makes each neuron non-linear, so a network of them can follow curves. There are several to choose from. We use ReLU, the most common one. It turns every negative value into 0 and leaves positive values alone, like a hinge.
With one input, the blue part is , which is Part 1’s straight line, so a neuron is that line with ReLU on the end. Drag the sliders. The weight sets how steep the line is and which way it faces, and the bias moves the bend left and right.
In PyTorch
PyTorch has a building block for each coloured part of the diagram. The blue part is nn.Linear. nn.Linear(a, b) takes numbers in and gives numbers out, so one neuron with three inputs needs 3 in and 1 out.
nn.Linear(3, 1) # 3 numbers in, 1 number out.With one input it is nn.Linear(1, 1), the model from Part 1. The green part is the activation.
nn.ReLU() # Turns negative values into 0.nn.Sequential runs its pieces in order, so the output of the blue part goes into the green part.
neuron = nn.Sequential(nn.Linear(3, 1), nn.ReLU())Write the one-input neuron by hand using torch.relu, with a weight of 2 and a bias of −4, in one line. Expect tensor([0., 0., 4., 8., 12., 16.]).
x = torch.tensor([0.0, 2.0, 4.0, 6.0, 8.0, 10.0])... # One neuron: weight 2, bias -4.Answer
x = torch.tensor([0.0, 2.0, 4.0, 6.0, 8.0, 10.0])torch.relu(2 * x - 4) # One neuron: weight 2, bias -4.Where does this neuron bend?
Answer
At , where . Below 2 the neuron outputs 0. Above 2 its output grows by 2 for every 1 that grows, because its weight is 2.
Neurons are the building blocks of neural networks. Now we just need to combine them!
2. Layers
Theory
A layer is several neurons that all read the same inputs and give different outputs. Start with one neuron with three inputs. Put a second neuron beside it, reading the same three inputs with its own weights and bias, and you have two outputs. Keep going and you have a layer. Each neuron has its own weights and bias, so each one picks out something different from the same features.
In PyTorch
A layer is one nn.Linear with more outputs. PyTorch doesn’t write two neurons as two separate nn.Linear(3, 1)s. It writes the whole layer as one piece, with one output per neuron.
nn.Linear(3, 1) # One neuron. 3 numbers in, 1 out.nn.Linear(3, 2) # Two neurons side by side. 3 in, 2 out.nn.Linear(3, 3) # Three neurons. 3 in, 3 out.One nn.ReLU() bends every output at once, so a layer of three neurons is two pieces, the same as a single neuron.
layer = nn.Sequential(nn.Linear(3, 3), nn.ReLU())Press the buttons above to add neurons and watch the code change.
3. Neural networks
Theory
A neural network is layers chained together, so that each layer’s outputs are the next layer’s inputs. The layers in the middle are hidden layers. The last layer is a single neuron with no activation, and its output is the prediction. There is no ReLU on the end because a prediction can be any number, negative ones included.
Here is a network with one input, two hidden layers of three neurons each, and one output. Each circle is a neuron, blue add up then green ReLU. The output neuron is all blue because it has no activation.
What does a network compute? To see, take one hidden layer. The three hidden neurons below are already set to fit the dots. Add them one at a time and watch the line change. Each numbered dot on the line marks the bend made by the neuron with that number.
No neurons yet, so only the output's bias, a flat line at 1.
- What does each neuron add to the line?
- Untick ReLU and add the neurons again. What happens?
Answer
- Each neuron adds one bend, at the point where its is 0: at , and . Its output weight decides how much the line’s slope changes there: starts the climb, turns it into a fall, and levels it off. With all three, the line goes through every dot. Training finds weights and biases like these for you.
- Without ReLU, each neuron is just a straight line, so adding one only tilts the output and never bends it. Straight lines always add up to a straight line, however many you use.
That is the claim from section 1 made real. Without the green part, a network of any size is one straight line. The bends are what let it follow curves.
In PyTorch
There is nothing new to learn here. A network is layers from section 2 chained with nn.Sequential, each one’s output feeding the next, and one last nn.Linear with no nn.ReLU() after it for the output.
network = nn.Sequential( nn.Linear(1, 3), nn.ReLU(), # First hidden layer. nn.Linear(3, 3), nn.ReLU(), # Second hidden layer. Reads the first's 3 outputs. nn.Linear(3, 1), # Output layer. No ReLU, so the prediction can be any number.)The one-hidden-layer network from the graph above fits in one line of code: the output’s bias, plus each hidden neuron times its output weight. Write it and check that you get the dots: tensor([1., 1., 1., 2., 3., 4., 3., 2., 1., 1., 1.]).
x = torch.arange(0.0, 11.0) # 0, 1, 2, ..., 10... # The output's bias, plus each neuron times its output weight.Answer
x = torch.arange(0.0, 11.0) # 0, 1, 2, ..., 101 + torch.relu(x - 2) - 2 * torch.relu(x - 5) + torch.relu(x - 8) # The output's bias, plus each neuron times its output weight.4. Zooming out
If the pictures got confusing, here is the good news. In PyTorch you never draw neurons. You choose a shape, how many inputs, how many hidden layers, how many neurons in each and how many outputs, and nn.Sequential does the rest. We predict one number, the house value, so our networks have one output, but a network can predict several things at once.
Drag the sliders and watch the code and the parameter count change. Every arrow is a weight and every neuron has a bias, and together they are the network’s parameters, the numbers that training adjusts.
28 parameters, every weight and bias added up.
GPT-3 has 175 billion parameters, today’s largest models have trillions, and all of them were trained with the same kind of loop as fit. It goes the other way too. A few thousand parameters are enough to fly a drone, and a few million to walk a humanoid robot.
PyTorch can count them for you. example_network.parameters() gives every weight and bias, and p.numel() counts the numbers in each one. Count the parameters of a network with 8 inputs and two hidden layers of 64 neurons. Expect 4801.
example_network = nn.Sequential(nn.Linear(8, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1))... # Add up p.numel() for every p in example_network.parameters().Answer
example_network = nn.Sequential(nn.Linear(8, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1))sum(p.numel() for p in example_network.parameters()) # Add up p.numel() for every p in example_network.parameters().5. Another way to see it
Here is a second way to think about a network that only uses the building blocks of PyTorch.
nn.Linear(a, b) is a box that turns numbers into numbers. That’s all.
A network is boxes in a row, and the only rule is that the counts have to match up. Whatever comes out of one box goes into the next, so the second number of one nn.Linear must equal the first number of the next.
nn.Sequential( nn.Linear(8, 64), # 8 numbers in, 64 out. nn.ReLU(), nn.Linear(64, 64), # 64 in, 64 out. Starts with 64 because 64 just came out. nn.ReLU(), nn.Linear(64, 1), # 64 in, 1 out. Ends with 1 because we predict one number.)Between the boxes is an activation, which bends the numbers on their way through. nn.ReLU() is the usual choice. Two others you will see are nn.Sigmoid(), which squashes every number into the range 0 to 1, and nn.Tanh(), which squashes into −1 to 1. They each have their uses. What matters is that there is one between each pair of boxes and none after the last.
nn.ReLU()
nn.Sigmoid()
nn.Tanh()
So to build a network, write down the counts, chain the boxes, put a bend between each pair.
What goes wrong if the counts don’t match, say nn.Linear(8, 64) followed by nn.Linear(32, 1)?
Answer
PyTorch refuses to run it. The first box hands over 64 numbers and the second expects 32, so you get
RuntimeError: mat1 and mat2 shapes cannot be multiplied (5x64 and 32x1)where 5 is how many houses you passed in. If you see this error in the demo, a count is wrong somewhere.
6. Build one for real
House values go up and down with latitude, from San Diego in the south (33°) to the Oregon border (42°), so a straight line cannot follow them. The cell below rescales latitude, as in Workshop 2, and defines draw, which plots a model’s predictions over the houses. Run it.
latitude_scaler = StandardScaler()latitudes = torch.tensor(latitude_scaler.fit_transform(housing[["Latitude"]].to_numpy()), dtype=torch.float32)sample = housing.sample(2000, random_state=0) # Plot 2,000 houses so the graph draws quickly.
def draw(model): grid = np.linspace(32.5, 42, 400).reshape(-1, 1) # 400 latitudes from south to north. with torch.no_grad(): # Only predicting, not training. curve = model(torch.tensor(latitude_scaler.transform(grid), dtype=torch.float32)) plt.scatter(sample["Latitude"], sample["MedHouseVal"], s=3, alpha=0.3) plt.plot(grid, curve, color="black") plt.xlabel("Latitude (degrees north)") plt.ylabel("Median house value ($100,000s)") plt.show()Now the network from step 3 with 50 neurons instead of 3, trained on latitude with fit from Part 1. Expect a loss of about 1.11. A straight line gets 1.30.
model = nn.Sequential( nn.Linear(1, 50), # 50 neurons, each with its own weight and bias. nn.ReLU(), # Bend each one. nn.Linear(50, 1), # Combine them into one prediction.)print("loss:", fit(model, latitudes, values))draw(model)Los Angeles is at about 34° and San Francisco at about 37.8°. What has the model found?
Answer
Two peaks, Los Angeles and the San Francisco Bay Area. Between them is a dip for the cheaper Central Valley, and values fall again further north. Nobody told the model where the cities are, or where to bend. It found both from the data.
Before you run it, predict: what happens if you delete the nn.ReLU() line? Then delete it and run the cell again.
Answer
A straight line, with a loss of 1.30, the same as a single nn.Linear(1, 1). It is the untick from step 3 on real data. Two linear layers with nothing between them add up to one line, however many neurons are in the middle, so the 151 parameters do no more than 2.
In Workshops 1 and 2 you made lines bend by adding powers such as and . You chose the powers, and the powers decided the shape. A network learns its shape instead. Training moves every weight and bias until the bends fit the data, and Part 3 shows how.
Part 3: How a network learns (5 minutes)
Part 2 explains how to build a network but not how to train it. Training uses the fit function from Part 1, which we will now go through line by line. The cell builds a small network and trains it on income, so there is a model to talk about. Expect a loss of about 0.70.
def fit(model, inputs, targets): # Setup. loss_fn = nn.MSELoss() # The loss from Workshop 1. optimizer = torch.optim.Adam(model.parameters(), lr=0.01) # Makes the improvements.
# Loop. for step in range(1000): optimizer.zero_grad() # Forget the last step. predicted = model(inputs) # Predict a value for every house. loss = loss_fn(predicted, targets) # Measure how wrong the predictions are. loss.backward() # Work out which way to nudge every parameter. optimizer.step() # Nudge them. return loss.item()
model = nn.Sequential(nn.Linear(1, 10), nn.ReLU(), nn.Linear(10, 1)) # A small network.print("loss:", fit(model, incomes, values))Setup creates two things needed for training. loss_fn is the mean squared error from Workshop 1, which scores a set of predictions against the true values. optimizer is handed every weight and bias in the model, through model.parameters(), along with a learning rate, and updates them.
The loop then repeats the same steps a thousand times. Each pass uses the model’s current parameters. The first line, optimizer.zero_grad(), makes most sense last, so it comes last here.
-
predicted = model(inputs)runs the network on every house at once and gives a predicted value for each one. On the first pass the parameters are random, so the predictions are nonsense. -
loss = loss_fn(predicted, targets)compares those predictions with the true values and gives one number, the loss. A big loss means bad parameters. It says how bad they are, but not which way to change each one. -
loss.backward()works out, for every parameter, which way to nudge it to make the loss smaller, and how much that would help. That is the parameter’s gradient. -
optimizer.step()turns each gradient into an update. Every parameter moves a little, the other way from its gradient, so that the loss goes down.How big the update is depends on the optimiser.
SGDjust multiplies the gradient by the learning rate, as in the formula.Adam, whichfituses, also adapts the size of each parameter’s steps as it goes. -
optimizer.zero_grad()clears the gradients before the next step. PyTorch adds new gradients onto old ones unless you tell it not to, so without this line every step would be pushed by all the steps before it.
Picturing the whole loop. Think of the loss as a landscape and the current parameters as a dot on it. With one parameter the landscape is a curve, with two it is a surface, and with thousands it is something you cannot draw, but the picture is the same. It is a bowl, with the best parameters at the bottom. The gradient is how steep the bowl is under the dot and which way is uphill, and each step moves the dot the other way. For a straight line it is exactly a bowl. For a network it is a bumpier bowl, but the idea holds.
The diagram shows one parameter, the slope of the income line from Part 1, with the intercept fixed at 0.45. The best slope, 0.42, sits at the bottom, and the orange arrow is one step. Click Step to take it, and keep clicking. Then click Reset, set the learning rate to 0.05 and try again. The dot overshoots the bottom and zigzags before it settles. At 0.06 it overshoots further every time.
Step 0: slope 0.00, loss 3.95, gradient −15.5
That is the whole of fit. Predict, measure, find the gradients, step, a thousand times over, for every weight and bias at once. Now try the pieces yourself.
Try finding a gradient by adding the backward pass. The cell below makes a line with a random slope and intercept, and measures its loss on the house prices. Expect a slope gradient of about −15.2.
torch.manual_seed(0) # Start from the same random line every run.line = nn.Linear(1, 1) # A straight line with a random slope and intercept.loss = nn.MSELoss()(line(incomes), values) # How wrong it is.... # Find the gradient for every parameter.print("slope:", line.weight.item(), "| slope gradient:", line.weight.grad.item())Answer
torch.manual_seed(0) # Start from the same random line every run.line = nn.Linear(1, 1) # A straight line with a random slope and intercept.loss = nn.MSELoss()(line(incomes), values) # How wrong it is.loss.backward() # Find the gradient for every parameter.print("slope:", line.weight.item(), "| slope gradient:", line.weight.grad.item())Gradients add up. The cell below runs the backward pass twice on the same line, with nothing cleared in between. Predict what it prints, then run it. Then add one line at the top of the loop to fix it.
torch.manual_seed(0) # The same random line as above.line = nn.Linear(1, 1)for _ in range(2): # Two backward passes. loss = nn.MSELoss()(line(incomes), values) loss.backward()print("slope gradient:", line.weight.grad.item())Answer
About −30.3, double the gradient from before, because the second backward pass added its gradient onto the first. line.zero_grad() at the top of the loop clears it, and the cell prints −15.2 again. That is what optimizer.zero_grad() does in fit, for every parameter the optimiser holds.
torch.manual_seed(0) # The same random line as above.line = nn.Linear(1, 1)for _ in range(2): # Two backward passes. line.zero_grad() # Clear the last gradient first. loss = nn.MSELoss()(line(incomes), values) loss.backward()print("slope gradient:", line.weight.grad.item())The cell below is fit with SGD in place of Adam, so the learning rate is the only setting. Run it, then change learning_rate to 0.1 and run it again.
learning_rate = 0.01 # Then try 0.1.
line = nn.Linear(1, 1)optimizer = torch.optim.SGD(line.parameters(), lr=learning_rate)for step in range(101): optimizer.zero_grad() loss = nn.MSELoss()(line(incomes), values) loss.backward() optimizer.step() if step % 20 == 0: print("step", step, "| loss", loss.item())What happens to the loss with a learning rate of 0.1? Why?
Answer
At 0.01 the loss falls every step, heading for the 0.70 that Part 1 reached. At 0.1 it blows up, growing every step until it prints inf and then nan. The steps are too big, so each one overshoots the bottom of the bowl by more than the last, like 0.06 in the diagram.
Lab check (1 minute)
Explain in one sentence each:
- Why a network needs ReLU between its layers.
- What one step of
fitdoes.
Answer
- Without ReLU, every layer is a straight line, and lines added up are still a line, so extra layers add nothing. ReLU adds the bends.
- It predicts a value for every house, measures the loss, works out the gradient for every parameter with
loss.backward(), and moves each parameter a small step downhill.
Demo: all 8 inputs (5 minutes)
Now the task from Workshop 1: predict house values from all 8 inputs. The cell below makes Workshop 1’s split, so the scores compare, and rescales the inputs as in Workshop 2. Run it.
train, rest = train_test_split(housing, test_size=0.3, random_state=0) # The split from Workshop 1.val, test = train_test_split(rest, test_size=0.5, random_state=0) # The test set stays aside.input_columns = housing.columns.drop("MedHouseVal") # The 8 input columns.
scaler = StandardScaler() # Learns each column's average and spread from the training set only.X_train = torch.tensor(scaler.fit_transform(train[input_columns]), dtype=torch.float32)X_val = torch.tensor(scaler.transform(val[input_columns]), dtype=torch.float32)y_train = torch.tensor(train[["MedHouseVal"]].to_numpy(), dtype=torch.float32)y_val = torch.tensor(val[["MedHouseVal"]].to_numpy(), dtype=torch.float32)Then the 8-64-64-1 network whose parameters you counted in Part 2, trained with fit and scored on the validation set. We build it live: fill in the five layers. Expect a validation MSE of about 0.3.
torch.manual_seed(0)model = nn.Sequential( ..., # 8 inputs into 64 neurons. ..., # Bend them. ..., # A second hidden layer of 64 neurons. ..., # Bend them. ..., # One prediction.)print("training MSE:", fit(model, X_train, y_train))with torch.no_grad(): # Only measuring, not training. print("validation MSE:", nn.MSELoss()(model(X_val), y_val).item())Answer
torch.manual_seed(0)model = nn.Sequential( nn.Linear(8, 64), # 8 inputs into 64 neurons. nn.ReLU(), # Bend them. nn.Linear(64, 64), # A second hidden layer of 64 neurons. nn.ReLU(), # Bend them. nn.Linear(64, 1), # One prediction.)print("training MSE:", fit(model, X_train, y_train))with torch.no_grad(): # Only measuring, not training. print("validation MSE:", nn.MSELoss()(model(X_val), y_val).item())Compare it with Workshop 1’s models, all scored on the same validation set. (Workshop 1’s 0.52 for linear regression was scored on the data it trained on.)
| Model | Validation MSE |
|---|---|
| Always predict the average | 1.33 |
| Linear regression, 8 inputs | 0.54 |
| Decision tree, depth 9 | 0.43 |
| Random forest | 0.28 |
| This network | about 0.3 |
Five lines of PyTorch, trained with the same fit as the straight line in Part 1, land close to the random forest. The exact number depends on the random start and even on the machine: anywhere from about 0.28 to 0.34 is normal.