Lesson 1 · Building networks
From logistic regression to a neuron
The problem
Your pizza shop wants to know which deliveries will be late. For each delivery you know two numbers: the distance in km, and the time it was sent. You have 200 past deliveries, each marked on time or late.
Here they are. Most of the evening, trips over about 6 km run late. But around 19:00 the roads are jammed, and even short trips run late. The curve shows the rule that made this data. (Real data is noisy, so 5% of the labels were flipped.)
In ML fundamentals you met logistic regression, which turns a weighted sum of the inputs into a probability. On this data it gets 76% of the validation deliveries right. Its decision boundary is a straight line, and no straight line can follow that dip.
This lesson rebuilds logistic regression as a neuron, the building block of neural networks. Then it shows the one change that lets many neurons, working together, draw curves: a bend.
A neuron
A neuron does two things:
- It multiplies each input by a weight, adds the results, and adds a bias. This gives one number, .
- It passes through a fixed function (the Greek letter phi) that bends it.
Step 1 is the weighted sum from linear models. Step 2 is new in name only. The function is called an activation function. Logistic regression is a neuron whose activation function is the sigmoid.
Below is one neuron reading one delivery. The weights are 0.64 per km and −0.37 per hour, and the bias is 4.9: logistic regression's trained weights on this data, rounded. Move the sliders, and switch the activation.
z = 0.64 × 5.0 + (−0.37) × 18 + 4.9 = 1.44
sigmoid(1.44) = 0.808 → P(late) = 81%
Sigmoid output is a probability.
Things to notice:
- A longer trip raises , because its weight is positive. A later hour lowers , because its weight is negative.
- With the sigmoid, the output is a probability between 0 and 1.
- With tanh or ReLU (both coming up below), the output is a number for the next layer to use, not a probability.
Worked example
One neuron on a 5 km delivery sent at 18:00
Weighted sum: .
The maths
For inputs , weights and bias , a neuron computes
In words: take the dot product of the weights and the inputs, add the bias, and bend the result. In the figure, is what the Σ circle shows. is the curve in the box, and is the number that comes out on the right. The weights and bias are learned. The activation function is chosen by you, and it stays fixed.
In PyTorch, step 1 is an nn.Linear layer and step 2 is a function such as torch.sigmoid:
neuron = nn.Linear(2, 1) # 2 inputs (km, hour) → 1 output: weight (1, 2) and bias (1,)
with torch.no_grad(): # set the weights by hand, without recording a graph
neuron.weight.copy_(torch.tensor([[0.64, -0.37]]))
neuron.bias.fill_(4.9)
x = torch.tensor([[5.0, 18.0]]) # one delivery: 5 km, sent at 18:00 shape (1, 2)
z = neuron(x) # weighted sum plus bias: 0.64·5 − 0.37·18 + 4.9 shape (1, 1)
p = torch.sigmoid(z) # the bend: squash z into a probability
print(f"z = {z.item():.2f}, sigmoid(z) = {p.item():.2f}") # z = 1.44, sigmoid(z) = 0.81nn.Linear(2, 1) holds a weight of shape (1, 2) and a bias of shape (1,). The code sets them by hand inside torch.no_grad(), so autograd doesn't record the change.
One neuron is logistic regression
A sigmoid neuron and logistic regression are the same model, so they should learn the same thing. Train one below. It uses the shared rush-hour data, with each input standardised (mean 0, standard deviation 1), as the network sees it.
Step 0 · validation accuracy 57.0%
weights -0.33 (km), -0.71 (hour) · bias -0.39, on standardised inputs
Things to notice:
- The boundary is a straight line the whole time. Training only tilts and slides it.
- Validation accuracy settles at about 76%, the same as logistic regression.
- The line cuts across the dip. It gets the late short trips around 19:00 wrong, and it can't fix them without breaking something else.
Why a straight line? The sigmoid is exactly 0.5 when . So the boundary is the set of points where , and with two inputs, that's a line.
Predict first
You swap the neuron's sigmoid for tanh, and use 'tanh(z) > 0' to mean late. What shape is the boundary now?
The PyTorch version trains a nn.Linear(2, 1) with nn.BCEWithLogitsLoss, which applies the sigmoid inside the loss. It uses the course's defaults: the AdamW optimiser with learning rate 0.01, batches of 32 and seed 0. AdamW is a version of Adam (Lesson 5) with weight decay done its own way (Lesson 7). The data loaders come from the course's training template, which Lesson 4 explains line by line.
def logistic_regression_accuracy() -> float:
"""scikit-learn's logistic regression on the same standardised data, for comparison."""
x_train, y_train, x_val, y_val = load_rush_hour()
mean, std = x_train.mean(axis=0), x_train.std(axis=0)
model = LogisticRegression().fit((x_train - mean) / std, y_train)
return float(model.score((x_val - mean) / std, y_val))
if __name__ == "__main__":
neuron, acc = train_neuron()
print(f"one neuron: {acc:.1%} validation accuracy") # 76.5%
print(f"logistic regression: {logistic_regression_accuracy():.1%}") # 76.0%
print("weights", np.round(neuron.weight.detach().cpu().numpy(), 2), "bias", round(neuron.bias.item(), 2))one neuron: 76.5% validation accuracy
logistic regression: 76.0%
weights [[ 1.41 -0.59]] bias 0.02The neuron's weights, 1.41 for distance and −0.59 for hour, are close to scikit-learn's 1.37 and −0.56. By default, scikit-learn adds a small penalty on large weights, which pulls its weights a little towards 0. The two models disagree on only 3 of the 200 validation deliveries.
Activation functions: the bend
So one neuron can't bend its boundary. Many neurons can, as long as each one bends its own output. Lesson 2 shows how. First, here are the four activation functions you'll meet most often, each with its slope. The slope matters because training follows slopes: backpropagation multiplies by the activation's slope at every neuron.
sigmoid(2.5) = 0.924 · slope 0.0701
Solid: the function. Dashed: its slope. Drag the dot, or focus it and use the arrow keys.
Drag the dot out to on each tab, and watch the slope:
- Sigmoid squashes any number into . Its slope is at most 0.25, at , and fades towards 0 at both ends.
- tanh squashes into . Its slope is 1 at and also fades at both ends.
- ReLU keeps positive numbers and turns negative ones into 0. Its slope is exactly 1 for every positive input, and 0 for every negative one.
- GELU looks like ReLU with the corner rounded off.
| Function | slope at 0 | slope at 3 | ||
|---|---|---|---|---|
| sigmoid | 0.5 | 0.25 | 0.953 | 0.045 |
| tanh | 0 | 1 | 0.995 | 0.010 |
| ReLU | 0 | 0 | 3 | 1 |
| GELU | 0 | 0.5 | 2.996 | 1.012 |
ReLU has a corner at 0, so its slope there isn't defined. PyTorch uses 0.
Here are the three new ones, defined:
- ReLU (rectified linear unit) is . It's the default choice for hidden neurons, and the one this course uses.
- tanh (the hyperbolic tangent) is . It has the same S shape as the sigmoid, stretched to run from −1 to 1. In fact, .
- GELU (Gaussian error linear unit) is , where is the CDF of the standard normal. For large positive , is close to 1, so GELU is close to . For large negative , it's close to 0. In between, it dips slightly below 0. It's the usual choice inside transformers, the models behind most language models. You can treat it as a smooth ReLU.
In PyTorch: functions and layers
Every activation comes in two forms. torch.nn.functional, imported as F, holds plain functions: F.relu(x), F.gelu(x). The layer objects nn.ReLU(), nn.Tanh() and nn.GELU() wrap the same maths, so they can sit inside a model as one of its parts.
xs = torch.tensor([-2.0, -0.5, 0.0, 0.5, 2.0])
print(torch.sigmoid(xs)) # 0.12 0.38 0.50 0.62 0.88 squashed into (0, 1)
print(torch.tanh(xs)) # -0.96 -0.46 0.00 0.46 0.96 squashed into (-1, 1)
print(F.relu(xs)) # 0.00 0.00 0.00 0.50 2.00 negatives become 0
print(F.gelu(xs)) # -0.05 -0.15 0.00 0.35 1.95 a smooth ReLU
relu = nn.ReLU() # the same maths, as a layer object you can put inside a model
assert torch.equal(relu(xs), F.relu(xs))Which one to use:
- Inside
nn.Sequential(below), you need the layer form,nn.ReLU(), because every part must be a layer. - Inside a
forwardmethod you write yourself (Lesson 2),F.relu(x)is shorter and works the same. torch.sigmoidandtorch.tanhlive intorchitself.F.geluuses the exact form by default, as doesnn.GELU().
DeeperWhy ReLU wonIt costs one comparison, and its slope doesn't fade for positive inputs. · 3 min
For about 20 years, most networks used the sigmoid or tanh. Since the early 2010s, most hidden layers use ReLU or a smooth relative like GELU. There are two reasons.
It's cheap. ReLU is one comparison: is above 0? The sigmoid and tanh need an exponential. In a big network that runs billions of times, the saving adds up.
Its slope doesn't fade. Look at the gallery's table. At , the sigmoid's slope is 0.045 and tanh's is 0.010.
Training passes a signal back through every layer, and each layer multiplies it by the activation's slope. Ignoring the weights, ten sigmoid layers, each with a slope of at most 0.25, shrink the signal to at most of its size. That's about one millionth. ReLU's slope is exactly 1 for every positive input, so the signal passes through unchanged.
ReLU has its own weak spot. A neuron whose is negative for every example has slope 0 everywhere, so it never learns again. Lesson 6 covers both problems: signals that fade through many layers (vanishing gradients), and ReLUs that switch off for good.
DigressionFrom perceptrons to GELU: a very short historyA 1950s machine, a winter, and why today's neurons bend the way they do. · 2 min
The first trained artificial neuron was Frank Rosenblatt's perceptron, in 1958. It used a hard step as its activation: output 1 if , else 0. The step has slope 0 almost everywhere, so you can't train a stack of them by following slopes.
In 1969, Marvin Minsky and Seymour Papert published a book, Perceptrons. It showed that one such neuron can't learn simple patterns like "exactly one of two inputs is on". Interest in neural networks fell sharply for years after that.
The fix was a smooth activation. In 1986, David Rumelhart, Geoffrey Hinton and Ronald Williams popularised backpropagation with sigmoid neurons, which made stacks trainable.
ReLU took over around 2010 to 2012. Vinod Nair and Hinton used it in an influential 2010 paper. AlexNet, the image network that won the ImageNet competition in 2012, used it too. GELU was proposed by Dan Hendrycks and Kevin Gimpel in 2016, and BERT and the GPT models adopted it.
Stacking neurons without a bend
If one neuron draws a line, maybe two layers of them, one feeding the next, draw something richer. Try it with the simplest input, a single number . The first layer has two neurons with no activation. The second layer adds their outputs. Step through the figure, then tick the box and step through again.
Layer 1: two hidden numbers
Hidden unit 1 computes 1.5x − 0.5. Hidden unit 2 computes −x − 0.5. Both are straight lines.
Without the ReLU, the output is the straight line . Two layers did no more than one. Here's why, with the figure's numbers.
Worked example
Two linear layers are one linear layer
Layer 1 makes two numbers: and .
The maths
Write each layer as a matrix and a bias: , then . Substitute the first into the second:
That's one layer, with weight matrix and bias . Doing one linear map after another is composition, and its matrix is the product. In the figure, and .
This is linear layers collapse: any number of linear layers with nothing between them equals one linear layer. Depth adds nothing unless something bends between the layers. That's the activation function's whole job.
Predict first
A network has three linear layers with no activation between them. Can it fit a U-shaped curve?
The same check in PyTorch: two nn.Linear layers give exactly what one layer with weight second.weight @ first.weight gives.
first = nn.Linear(1, 2) # 1 input → 2 hidden numbers
second = nn.Linear(2, 1) # 2 hidden numbers → 1 output
with torch.no_grad():
first.weight.copy_(torch.tensor([[1.5], [-1.0]]))
first.bias.copy_(torch.tensor([-0.5, -0.5]))
second.weight.copy_(torch.tensor([[1.0, 1.0]]))
second.bias.fill_(0.5)
# One linear layer that does the same job: W = W2 W1 and b = W2 b1 + b2.
single = nn.Linear(1, 1)
with torch.no_grad():
single.weight.copy_(second.weight @ first.weight) # (1, 2) @ (2, 1) → (1, 1): 0.5
single.bias.copy_(second.weight @ first.bias + second.bias) # −0.5
x = torch.linspace(-2, 2, 5).unsqueeze(1) # five inputs shape (5, 1)
with torch.no_grad():
stacked = second(first(x)) # two layers, nothing in between
bent = second(F.relu(first(x))) # the same layers with a ReLU between them
print(torch.allclose(stacked, single(x))) # True: the two layers are one line
print(stacked.squeeze(1)) # -1.5 -1.0 -0.5 0.0 0.5 a straight line
print(bent.squeeze(1)) # 2.0 1.0 0.5 1.5 3.0 bent: down, then upPutting it together
You now have every part of a network: neurons, a bend after each one, and layers that feed the next. PyTorch's nn.Sequential chains layers in order, feeding each output into the next:
model = nn.Sequential(
nn.Linear(2, 16), # 16 neurons, each reading both inputs
nn.ReLU(), # bend each of the 16 numbers
nn.Linear(16, 1), # one output neuron reads all 16
)
print(model)
batch = torch.randn(5, 2) # five deliveries shape (5, 2)
print(model(batch).shape) # torch.Size([5, 1]): one number per deliveryRead it as a picture:
nn.Linear(2, 16)is 16 neurons side by side. Each one reads both inputs, with its own two weights and bias.nn.ReLU()bends each of the 16 sums.nn.Linear(16, 1)is one more neuron. It reads all 16 bent numbers and adds them up with its own weights.
That's numbers in the first layer and in the second: 65 parameters. Each of the 16 neurons draws one straight line across the plane. The ReLU lets the output neuron combine the pieces into a bent boundary that can follow the dip. Lesson 2 trains exactly this kind of network and watches it happen.
Common misconceptions
"A curved activation gives a neuron a curved boundary." One neuron's boundary is always the straight line , whatever the activation. Curves come from combining several neurons.
"More layers always means a more flexible model." Only with activations between them. Linear layers stacked directly collapse into one.
"Every activation outputs a probability." Only the sigmoid (and softmax, for several classes) do. ReLU outputs any number from 0 up, and tanh any number between −1 and 1.
"A neuron works like a brain cell." The name is a loose inspiration. A neuron here is a weighted sum and a bend, nothing more.
Recap
- A neuron computes , then bends it with an activation function: .
- A sigmoid neuron is logistic regression. On the rush-hour data both get 76%, because both draw one straight line.
- ReLU, , is the usual activation. Its slope is exactly 1 for positive inputs. The sigmoid's and tanh's slopes fade towards 0 at both ends.
- Linear layers with nothing between them collapse into one linear layer. Activations between layers are what make depth useful.
- PyTorch names in this lesson:
nn.Linear,torch.sigmoidandtorch.tanh,torch.nn.functional(F.relu,F.gelu),nn.ReLU,nn.Tanhandnn.GELU,nn.Sequentialandnn.BCEWithLogitsLoss.