Neural-net foundations1 / 15

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.)

on time late P = 0.5
The rush-hour data: 200 deliveries, ○ on time and × late. The line is the rule that made the data. Late trips sit above it. It dips to 0 km at 19:00.

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:

  1. It multiplies each input by a weight, adds the results, and adds a bias. This gives one number, zz.
  2. It passes zz through a fixed function ϕ\phi (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 ϕ\phi 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.

× 0.64× −0.37+ 4.9 (bias)5.0km18:00hourΣz = 1.44sigmoid0.808

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.

One neuron. Solid lines carry positive weights, dashed lines negative ones. The Σ adds the weighted inputs and the bias; the box bends the sum.

Things to notice:

  • A longer trip raises zz, because its weight is positive. A later hour lowers zz, 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

  1. Weighted sum: 0.64×5+(−0.37)×18=3.2−6.66=−3.460.64 \times 5 + (-0.37) \times 18 = 3.2 - 6.66 = -3.46.

The maths

For inputs x\mathbf{x}, weights w\mathbf{w} and bias bb, a neuron computes

z=w⋅x+b,a=ϕ(z).z = \mathbf{w} \cdot \mathbf{x} + b, \qquad a = \phi(z).

In words: take the dot product of the weights and the inputs, add the bias, and bend the result. In the figure, w⋅x+b\mathbf{w} \cdot \mathbf{x} + b is what the Σ circle shows. ϕ\phi is the curve in the box, and aa 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:

One neuron, by hand
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.81

nn.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.

on time late P = 0.5

Step 0 · validation accuracy 57.0%

weights -0.33 (km), -0.71 (hour) · bias -0.39, on standardised inputs

024681000.20.40.60.8steplossbest val 0.74502468100%50%100%stepaccuracy
train 0.811 (52%)validation 0.745 (57%)
One sigmoid neuron training live on the rush-hour data. Shading shows the neuron's P(late); the dark line is where it equals 0.5. Below: the loss and accuracy on the training (solid) and validation (dashed) deliveries.

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 z=0z = 0. So the boundary is the set of points where w⋅x+b=0\mathbf{w} \cdot \mathbf{x} + b = 0, 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.

One neuron against scikit-learn's logistic regression
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.02

The 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.

−4−3−2−101234−0.200.20.40.60.811.2input zsigmoid(z)−4−3−2−10123400.51input zslope

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.

Four activation functions (solid) and their slopes (dashed). Drag the dot along the input axis.

Drag the dot out to z=3z = 3 on each tab, and watch the slope:

  • Sigmoid squashes any number into (0,1)(0, 1). Its slope is at most 0.25, at z=0z = 0, and fades towards 0 at both ends.
  • tanh squashes into (−1,1)(-1, 1). Its slope is 1 at z=0z = 0 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ϕ(0)\phi(0)slope at 0ϕ(3)\phi(3)slope at 3
sigmoid0.50.250.9530.045
tanh010.9950.010
ReLU0031
GELU00.52.9961.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 ReLU(z)=max⁡(0,z)\text{ReLU}(z) = \max(0, z). It's the default choice for hidden neurons, and the one this course uses.
  • tanh (the hyperbolic tangent) is tanh⁡(z)=(ez−e−z)/(ez+e−z)\tanh(z) = (e^{z} - e^{-z}) / (e^{z} + e^{-z}). It has the same S shape as the sigmoid, stretched to run from −1 to 1. In fact, tanh⁡(z)=2σ(2z)−1\tanh(z) = 2\sigma(2z) - 1.
  • GELU (Gaussian error linear unit) is z⋅Φ(z)z \cdot \Phi(z), where Φ\Phi is the CDF of the standard normal. For large positive zz, Φ(z)\Phi(z) is close to 1, so GELU is close to zz. For large negative zz, 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.

Activations as functions and as layers
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 forward method you write yourself (Lesson 2), F.relu(x) is shorter and works the same.
  • torch.sigmoid and torch.tanh live in torch itself. F.gelu uses the exact z⋅Φ(z)z \cdot \Phi(z) form by default, as does nn.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 zz 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 z=3z = 3, 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 0.25100.25^{10} 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 zz 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 z>0z > 0, 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 xx. 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.

−2−1.5−1−0.500.511.52−3−2−10123input xvalueh₁h₂

Layer 1: two hidden numbers

Hidden unit 1 computes 1.5x − 0.5. Hidden unit 2 computes −x − 0.5. Both are straight lines.

Stage 0 of 3
A single input x through two layers: 1 → 2 → 1. Without an activation, every stage is a straight line, and so is the output. With a ReLU between the layers, the output bends.

Without the ReLU, the output is the straight line 0.5x−0.50.5x - 0.5. Two layers did no more than one. Here's why, with the figure's numbers.

Worked example

Two linear layers are one linear layer

  1. Layer 1 makes two numbers: h1=1.5x−0.5h_1 = 1.5x - 0.5 and h2=−x−0.5h_2 = -x - 0.5.

The maths

Write each layer as a matrix and a bias: h=W1x+b1\mathbf{h} = W_1 \mathbf{x} + \mathbf{b}_1, then y=W2h+b2\mathbf{y} = W_2 \mathbf{h} + \mathbf{b}_2. Substitute the first into the second:

y=W2(W1x+b1)+b2=(W2W1) x+(W2b1+b2)multiply out\begin{aligned} \mathbf{y} &= W_2 (W_1 \mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2 \\ &= (W_2 W_1)\, \mathbf{x} + (W_2 \mathbf{b}_1 + \mathbf{b}_2) && \text{multiply out} \end{aligned}

That's one layer, with weight matrix W2W1W_2 W_1 and bias W2b1+b2W_2 \mathbf{b}_1 + \mathbf{b}_2. Doing one linear map after another is composition, and its matrix is the product. In the figure, W2W1=1×1.5+1×(−1)=0.5W_2 W_1 = 1 \times 1.5 + 1 \times (-1) = 0.5 and W2b1+b2=−0.5−0.5+0.5=−0.5W_2 \mathbf{b}_1 + b_2 = -0.5 - 0.5 + 0.5 = -0.5.

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.

Two linear layers collapse into one
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 up

Putting 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:

A first network
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 delivery

Read 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 2×16+16=482 \times 16 + 16 = 48 numbers in the first layer and 16+1=1716 + 1 = 17 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 w⋅x+b=0\mathbf{w} \cdot \mathbf{x} + b = 0, 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 z=w⋅x+bz = \mathbf{w} \cdot \mathbf{x} + b, then bends it with an activation function: a=ϕ(z)a = \phi(z).
  • A sigmoid neuron is logistic regression. On the rush-hour data both get 76%, because both draw one straight line.
  • ReLU, max⁡(0,z)\max(0, z), 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.sigmoid and torch.tanh, torch.nn.functional (F.relu, F.gelu), nn.ReLU, nn.Tanh and nn.GELU, nn.Sequential and nn.BCEWithLogitsLoss.