Neurons, Layers and the Forward Pass
Logistic regression is already a neural network: one neuron with a sigmoid. It is a good model as long as a straight line (a hyperplane, in more dimensions) separates the classes. Many problems are not like that. On two concentric rings of points no line does better than a coin toss, and no amount of training changes it, because the limitation is in the model's shape, not in its weights.
A neural network fixes this by stacking neurons into layers and putting a nonlinear activation between them. This lesson builds the forward pass the way every framework stores it: a layer is a matrix product applied to a whole batch at once. You will count parameters, see why the activation is not optional, and check that PyTorch's nn.Linear computes exactly the numbers your NumPy code does.
The math of the perceptron, the MLP forward pass and the XOR argument is in the Mathematics track (perceptron, MLP forward pass, XOR and depth); here the focus is the code and the shapes.
A straight line is not enough
The lab fits logistic regression to two rings. Its boundary is a line through the middle, and it gets 46 of 80 training points (57.5 %) and 110 of 200 new points (55.0 %) right, barely better than guessing. Switch the classifier to kNN or RBF SVM and the boundary bends around the inner ring (RBF SVM: 199/200 on the test points). A hidden layer gives a network the same freedom: it learns its own curved features instead of using a fixed kernel.
One neuron, one layer, one batch
A neuron takes an input vector , forms a weighted sum plus a bias and passes it through an activation :
A layer of neurons that all read the same input puts their weight vectors side by side as the columns of a matrix . Frameworks then process a batch of examples at once, one example per row of :
The bias is a vector of length , added to every row by broadcasting, and acts elementwise. A network chains such layers: the output of one is the input of the next, so the shapes must agree, . The batch size never appears in a weight shape, which is why the same model runs on 1 or 1000 examples.
A layer from inputs to outputs has weights and biases:
The figure is a 3-4-1 network. Every input feeds every hidden neuron (a fully connected or dense layer), so the 12 lines between the first two columns are exactly the 12 entries of .
Here is a neuron, then a layer applied to a batch of 5, checked against the double loop it replaces, and the parameter count of a 64-32-10 network, the size you would use on the 8 8 Digits images later in the course:
import numpy as np
# one neuron: a weighted sum of the inputs plus a bias, then an activation
x = np.array([0.5, -1.0, 2.0])
w = np.array([0.4, -0.3, 0.2])
b = 0.1
z = w @ x + b
print("neuron: z =", round(float(z), 4), " relu(z) =", round(float(max(z, 0.0)), 4))
# a layer of 4 neurons applied to a batch of 5 examples is one matrix product
rng = np.random.default_rng(0)
X = rng.normal(size=(5, 3)) # (n, d): 5 examples, 3 features
W = rng.normal(0, 0.5, size=(3, 4)) # (d, h): column j holds the weights of neuron j
b = np.array([0.0, 0.1, -0.1, 0.2]) # (h,): broadcast over the 5 rows
H = np.maximum(0.0, X @ W + b)
print("X", X.shape, "@ W", W.shape, "+ b", b.shape, "-> H", H.shape)
# the same numbers neuron by neuron, example by example
loop = np.zeros((5, 4))
for i in range(5):
for j in range(4):
loop[i, j] = max(0.0, sum(X[i, k] * W[k, j] for k in range(3)) + b[j])
print("loops equal the matrix product:", bool(np.allclose(loop, H)))
print("row 0 of H:", np.round(H[0], 4).tolist())
# parameters of a 64-32-10 network (Digits-sized)
sizes = [64, 32, 10]
total = 0
for d, h in zip(sizes[:-1], sizes[1:]):
print(f"layer {d:2d} -> {h:2d}: {d}*{h} weights + {h} biases = {d * h + h}")
total += d * h + h
print("total parameters:", total)neuron: z = 1.0 relu(z) = 1.0
X (5, 3) @ W (3, 4) + b (4,) -> H (5, 4)
loops equal the matrix product: True
row 0 of H: [0.0, 0.3636, 0.0, 0.0317]
layer 64 -> 32: 64*32 weights + 32 biases = 2080
layer 32 -> 10: 32*10 weights + 10 biases = 330
total parameters: 2410
The neuron computes . The layer turns a batch into a batch in one matrix product, and the triple loop gives the same 20 numbers. The 64-32-10 network has 2080 + 330 = 2410 parameters; almost all of them are weights, which is typical.
What the hidden layer buys
Back to the rings, now with the course's circles set (make_circles, 400 points, inner ring labelled 1). Instead of training (that needs backpropagation, three lessons from now), the weights below are chosen by hand to show what hidden units can do. Each of 8 ReLU neurons faces one of 8 directions and fires when a point lies beyond a line at distance 0.55 from the centre in that direction. The output neuron says "inner ring" when almost nothing fires.
import numpy as np
from sklearn.datasets import make_circles
from sklearn.linear_model import LogisticRegression
X, y = make_circles(n_samples=400, noise=0.1, factor=0.5, random_state=0)
print("classes:", np.bincount(y).tolist(), " radius of class 0:", round(float(np.hypot(*X[y == 0].T).mean()), 2),
" class 1:", round(float(np.hypot(*X[y == 1].T).mean()), 2))
# a single neuron (logistic regression) draws one straight line
lin = LogisticRegression().fit(X, y)
print("logistic regression accuracy:", round(lin.score(X, y), 3))
# hidden layer: 8 ReLU neurons, neuron k fires when x is beyond a line facing angle 2*pi*k/8
angles = 2 * np.pi * np.arange(8) / 8
W1 = np.stack([np.cos(angles), np.sin(angles)]) # (2, 8)
b1 = np.full(8, -0.55)
w2 = -np.ones(8) # output: "inner circle" when no neuron fires
b2 = 0.2
def net(X, act):
H = act(X @ W1 + b1) # (400, 8)
return H @ w2 + b2 # (400,) logit for class 1 (inner)
relu = lambda a: np.maximum(0.0, a)
z = net(X, relu)
print("2-8-1 ReLU network accuracy:", round(float(((z > 0) == y).mean()), 3))
print("hidden units active per point, inner:", round(float((relu(X @ W1 + b1) > 0).sum(1)[y == 1].mean()), 2),
" outer:", round(float((relu(X @ W1 + b1) > 0).sum(1)[y == 0].mean()), 2))
# without the activation the two layers collapse into one linear map
z_lin = net(X, lambda a: a)
w_eff, b_eff = W1 @ w2, b1 @ w2 + b2
print("no activation == one linear layer:", bool(np.allclose(z_lin, X @ w_eff + b_eff)),
" |w_eff| max:", round(float(np.abs(w_eff).max()), 6), " accuracy:", round(float(((z_lin > 0) == y).mean()), 3))classes: [200, 200] radius of class 0: 1.01 class 1: 0.51
logistic regression accuracy: 0.497
2-8-1 ReLU network accuracy: 0.993
hidden units active per point, inner: 0.33 outer: 2.5
no activation == one linear layer: True |w_eff| max: 0.0 accuracy: 0.5
Logistic regression scores 0.497, chance level. The 2-8-1 ReLU network scores 0.993: an inner point activates on average 0.33 hidden units, an outer point 2.5. Together the 8 half-planes form an octagon, and the output layer only has to ask "am I inside it?", a linear question about the hidden features. That is the general picture: hidden layers transform the representation until the last layer's job is linear.
The last line is the important control. Remove the ReLU and the same weights collapse to a single linear map, . Here the eight directions cancel exactly, the effective weight vector is zero, every point gets the same prediction, and accuracy falls to 0.5. In general:
so any stack of linear layers without activations is one linear layer. Depth without nonlinearity adds parameters but no power.
The same layer in PyTorch
nn.Linear(in_features, out_features) holds weight and bias as parameters and computes x @ weight.T + bias. Its weight is stored out in, the transpose of the above, because then row of weight is neuron . To reproduce the NumPy numbers you copy W.T. The example also counts parameters with numel() and checks PyTorch's default initialisation, a uniform distribution in (initialisation explains the scale). This is a recorded example: it ran on a CPU in the course's PyTorch image.
import numpy as np
import torch
from torch import nn
rng = np.random.default_rng(0)
X = rng.normal(size=(5, 3))
W = rng.normal(0, 0.5, size=(3, 4))
b = np.array([0.0, 0.1, -0.1, 0.2])
H_np = np.maximum(0.0, X @ W + b)
layer = nn.Linear(3, 4).double() # float64 like NumPy
print("weight", tuple(layer.weight.shape), " bias", tuple(layer.bias.shape))
with torch.no_grad():
layer.weight.copy_(torch.tensor(W.T)) # PyTorch stores (out, in): the transpose
layer.bias.copy_(torch.tensor(b))
H_t = torch.relu(layer(torch.tensor(X)))
print("max |torch - numpy| < 1e-12:", bool(np.abs(H_t.detach().numpy() - H_np).max() < 1e-12))
print("row 0:", [round(v, 4) for v in H_t[0].tolist()])
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
for name, p in model.named_parameters():
print(f"{name:9s} {str(tuple(p.shape)):9s} {p.numel()}")
print("total:", sum(p.numel() for p in model.parameters()))
bound = 1 / np.sqrt(64)
print(f"default init: |w| <= 1/sqrt(64) = {bound:.3f}:", bool(model[0].weight.abs().max() <= bound))
out = model(torch.zeros(7, 64))
print("batch in", (7, 64), "-> out", tuple(out.shape))weight (4, 3) bias (4,)
max |torch - numpy| < 1e-12: True
row 0: [0.0, 0.3636, 0.0, 0.0317]
0.weight (32, 64) 2048
0.bias (32,) 32
2.weight (10, 32) 320
2.bias (10,) 10
total: 2410
default init: |w| <= 1/sqrt(64) = 0.125: True
batch in (7, 64) -> out (7, 10)
The layer reproduces the NumPy batch to within (row 0 is again 0.0, 0.3636, 0.0, 0.0317), and the 64-32-10 nn.Sequential has the same 2410 parameters, listed per tensor: 0.weight is , out by in. A batch of shape goes in and comes out; PyTorch, like the NumPy code, treats the first dimension as the batch.
Pitfalls
- Transposed weights. NumPy code often writes
X @ WwithWof shape (in, out); PyTorch'snn.Linear.weightis (out, in). Copying weights between the two without.Teither crashes on a shape mismatch or, for square layers, silently computes something else. - A missing batch dimension. Layers expect
(n, d). A single example of shape(d,)happens to work withnn.Linear, but convolution and normalisation layers need the batch axis; usex[None]orx.unsqueeze(0). - Forgetting the activation. Two
nn.Linearlayers in a row are one linear layer with extra parameters, as the collapse above showed. A model that is no better than logistic regression is often missing a ReLU. - Bias broadcasting the wrong way. A bias of shape
(n, 1)instead of(h,)broadcasts over the wrong axis and adds one number per example. Keep biases one-dimensional, of lengthh. - Counting parameters by hand for big models. Use
sum(p.numel() for p in model.parameters()); for the arithmetic of larger architectures see parameter and FLOP counting.
Practice
- How many parameters does a 784-256-128-10 network have (the classic MNIST MLP)?
Answer
, and , in total 235,146. The first layer holds 85 % of them: the input width dominates.
- A batch
Xhas shape(32, 20). Give the shapes ofW1,b1,Hand the output for a 20-50-3 network written in NumPy style, and the shapes of the twoweighttensors in PyTorch.
Answer
NumPy style: W1 is (20, 50), b1 is (50,), H is (32, 50), W2 is (50, 3) and the output (32, 3). In PyTorch nn.Linear(20, 50).weight is (50, 20) and nn.Linear(50, 3).weight is (3, 50).
- Change
b1in the circles example tonp.full(8, -0.3)and predict what happens before running it.
Answer
The lines move closer to the centre (distance 0.3), so points of the inner ring (radius about 0.5) start firing hidden units too and the output threshold no longer separates the classes as cleanly; the accuracy drops. The hand-set weights only work because 0.55 lies between the two radii, which is exactly what training would have to discover.
- Show that adding a ReLU only after the last layer of a two-layer linear network does not help on the rings.
Answer
is a monotone function of one linear score, so its decision boundary (score above or below a threshold) is still a straight line. The nonlinearity has to sit between layers, where it changes the features the next layer sees.
Test yourself
A layer maps a batch X of shape (n, d) to (n, h). What is the shape of its NumPy-style weight matrix and of its bias?
(n, h)and(n,)(d, h)and(h,)(h, d)and(d,)(d, n)and(h,)
How many parameters does nn.Linear(64, 32) have?
- 2048
- 2080
- 96
- 2112
You copy a NumPy weight matrix W of shape (3, 4) into nn.Linear(3, 4). What must you assign to layer.weight?
WW.TW.reshape(4, 3)W.flatten()
Why does a network of three linear layers without activations fail on the two-rings data?
- It has too few parameters
- The layers compose into a single linear map, so its decision boundary is still a straight line
- Linear layers cannot be trained by gradient descent
- The bias terms cancel out