Module 09 · Lesson 1 of 11Free
Neurons and layers: the building blocks
- Level
- Beginner
- Topic
- Neural networks
- Reading time
- 13 min
When you finish this page you can
- Compute one neuron’s output by hand from its weights, bias and activation, and say how it relates to logistic regression.
- Write a layer as one matrix multiply plus a bias, and push a batch of customers through it in NumPy and PyTorch.
- Show why two layers with nothing between them act as one, and what a non-linear step adds.
- Count a network’s parameters from its layer sizes, and choose a first size that fits the data.
Builds on 3 lessons
Start with Module 07, lesson 213 minChapters
Show transcript
0:00 Every Monday, Joseph’s team at Kartly, our example online store, sends 100-rupee vouchers to the 20,000 customers most likely to churn, which means stop buying. Farah, an ML engineer, builds the model that ranks them. Some of these customers are newcomers. They joined less than 45 days ago. And they leave far more often: 36 percent of them, against about one in ten for everyone else. Yet Farah’s model, a logistic regression, puts only about 600 newcomers on the list. Why? It gives “days since the last order” one weight, the same for every customer. It can’t say that a quiet month means more for someone new. A neural network can. And it’s built from small parts you already know. So what does one neuron compute? And how do layers of neurons learn “new and quiet”, when one weighted sum can’t?
0:50 Start with one neuron. It takes a few inputs, like days quiet, recent orders and tenure: numbers that describe one customer, called features. It multiplies each one by its own weight, and adds them up. Then it adds one more number, called the bias. Last, the total goes through a fixed function, called the activation. Out comes one number. Now pick the sigmoid as the activation. It squashes any total into a chance between zero and one. Feed the neuron Farah’s 12 churn features, and you get logistic regression, exactly. One weight per feature, plus the bias: 13 numbers to learn. The bias is just the intercept, under the name networks use. So a single neuron adds nothing new, and keeps the same limit. The new power comes from using many neurons, and feeding their outputs into more neurons.
1:35 Put 16 neurons side by side. Each one reads every feature, with its own weights and bias. That’s a layer. It turns each customer into a new list of numbers, one per neuron. They’re called hidden values: the model works them out inside, and never shows them. Stack the weights of those 16 neurons, one row each, and you get a weight matrix. Now the whole layer, for all 200,000 customers at once, is one matrix multiply, plus the biases, then the activation. That’s exactly what PyTorch’s Linear layer computes. It stores its weights as outputs, then inputs. A second layer then reads the hidden values, the way logistic regression read raw features. Put a sigmoid at the end, and you get one chance per customer. So Farah’s network is logistic regression on features it learned itself. That’s the picture to keep.
2:22 What can a hidden value catch that a raw feature can’t? Shrink the problem to two inputs. Months since the last order. And a newcomer flag: one if the customer is new, zero if not. Farah sets two hidden neurons by hand. Both use ReLU as their activation. ReLU passes a positive total through unchanged, and turns any negative total into zero. It’s the simplest bend there is. Neuron one fires only after 2 months quiet. Neuron two is the same for a regular customer. But for a newcomer, it fires from the first quiet day. The output neuron weighs the two, adds its own bias, and applies the sigmoid to give a chance. Try a regular customer, quiet for one month. Neither neuron fires, so they get the base chance, about 0.12. Now a newcomer, quiet for the same month. Neuron two fires, and the chance jumps to even odds. For the regular, that month meant nothing. A regular quiet for three months makes both neurons fire, and the chance climbs to 0.27. And a newcomer who just ordered? Neuron two barely moves, so they stay near the base chance, at 0.17. So how much a quiet month matters now depends on who the customer is. For a newcomer, each quiet month adds 2 to the score. For a regular, nothing changes until month 2. Logistic regression gives months quiet one slope for everyone, so it can’t do this. One caution. Farah set these weights by hand, to teach. In a real network, training finds the weights, and hidden neurons rarely match a neat idea like “quiet newcomer”. This shows what a network can do, not what training will find.
3:52 Now Farah deletes the ReLU from both hidden neurons, and keeps every weight. Does a quiet month still count differently for newcomers? No. The score becomes one plain weighted sum. Months quiet gets the same slope for everyone, and being new just adds 4 to the score. Look at the newcomer who just ordered. With ReLU, their chance was 0.17. Without it, 0.55. The collapsed model flags every newcomer, active or not, and that costs Kartly vouchers. This holds for any sizes. Two layers with nothing between them multiply out into one weight matrix and one bias. That’s a single layer. More parameters, and no new behaviour. ReLU itself is almost a straight line, with one bend at zero. But many neurons, each bending in a different place, can build curves and interactions out of straight pieces. That’s why one small bend per neuron is enough.
4:43 So how many numbers does a network learn? Each layer adds one weight for every input and output pair, plus one bias per output. Farah’s churn network, with one hidden layer of 16, learns 225 in all. With 200,000 customers to learn from, Farah weighs three sizes. Option one is a single neuron: logistic regression again, with 13 parameters. Months quiet still gets one slope, so newcomers stay off the list. Option three is the other extreme: two wide layers, 256 neurons each. Width times width grows fast. The middle layer alone holds 95 percent of the parameters, about one for every three customers. That much room can fit quirks of this one sample that won’t hold next quarter. Option two sits in the middle: one small hidden layer, with 225 parameters. That’s enough to learn a bend like “new and quiet”, and it trains in seconds on a laptop. So the rule is: start with the smallest network that can express the pattern you suspect. Grow it only if a bigger one does better on customers it hasn’t seen.
5:46 A network isn’t always the right tool. On a small table with clear features, boosted trees, a model from earlier in the course, usually match or beat a small network, with less tuning. That’s why Kartly’s Monday list still runs on trees. Farah’s network is a comparison, not a replacement. Sometimes a person must read the weights. Logistic regression gives Joseph one clear effect per feature. A hidden layer mixes every feature into every neuron, so no single weight answers “why this customer?” And as with logistic regression, scale your features before the first layer.
6:19 Let’s recap. One: a neuron is a weighted sum plus a bias, passed through an activation. With the sigmoid, it’s logistic regression. Two: a layer is many neurons reading the same inputs, computed as one matrix multiply. Three: without a bend between them, stacked layers collapse into one. Four: count parameters from the layer sizes. Five: start with the smallest network that fits the pattern. On a small table, trees often still win. Farah used ReLU because it’s the simplest bend. But is it the right one? See you in Activation functions.
Newcomers slip off the Monday list
is our example online store. Every Monday, Joseph’s growth team sends ₹100 vouchers to the 20,000 customers most likely to : to stop buying. Farah, an ML engineer, builds the models that rank them.
In the notebook sample of 200,000 customers, about 20,000 are newcomers who joined under 45 days ago. They leave at 36%, against about 10% for everyone else. Yet Farah’s logistic regression puts only about 600 newcomers on the list.
The reason, from the churn design lesson: a weighted sum gives “days since last order” one weight for everyone. It can’t say “a quiet month means more for a newcomer”. Neural networks can, and they are built from small parts you already know.
This lesson answers one question: what does a neuron compute, and how does stacking neurons into layers learn “new and quiet” when one weighted sum can’t?
The newcomer numbers come from the made-up notebook data in Design: a churn prediction model for an online store. All weights in this lesson are set by hand for teaching, not learned.
One neuron is logistic regression
A neuron takes several inputs, multiplies each by a , adds them up, adds one more number called the bias, and passes the total through a fixed function called an activation.
- are the inputs, such as a customer’s .
- are the learned weights, one per input.
- is the bias: the intercept, under the name networks use.
- is the activation; is the neuron’s output.
A neuron reads Farah’s 12 churn features and uses the sigmoid as its activation. Which model from Module 07 is it?Show answer
With the sigmoid as f, this is logistic regression from Module 07.
So a single neuron adds nothing new. Logistic regression already showed how its weights move the odds. The new power comes from using many neurons, and feeding their outputs to more neurons.
A layer is many neurons sharing inputs
Put 16 neurons side by side, each reading all 12 features with its own weights and bias. That is a layer. Its 16 outputs form a new list of 16 numbers per customer, called hidden values: the model computes them inside and never shows them.
Stacking 16 weight rows gives a 16 × 12 . So the whole layer, for all 200,000 customers at once, is one matrix multiply, a bias and the activation:
- holds the customers, one row each: shape (200,000, 12).
- is the layer’s weight matrix, one row per neuron: shape (16, 12).
- holds the 16 biases, one per neuron.
- holds the hidden values: shape (200,000, 16).
This is exactly what PyTorch’s nn.Linear computes before any activation: , with its weight stored as (outputs, inputs).1 Matrix multiplication in practice covered why the transpose sits there.
A second layer then reads the 16 hidden values the way logistic regression read raw features. With the sigmoid at the end, Farah’s network is logistic regression on 16 features it learned for itself. That is the mental model to keep.
Farah’s 12 → 16 → 1 network
| shape | params | |
|---|---|---|
| X: customers | 200,000 × 12 | – |
| layer 1: W, b | 16 × 12, 16 | 208 |
| H: hidden | 200,000 × 16 | – |
| layer 2: W, b | 1 × 16, 1 | 17 |
| chances | 200,000 × 1 | – |
| total | 225 |
But what can a hidden value capture that a raw feature can’t? A small example shows it.
Two neurons that spot a quiet newcomer
Shrink the problem to two inputs per customer:
- g: months since the last order (days ÷ 30).
- n: 1 if the customer joined under 45 days ago, else 0.
Farah sets two hidden neurons by hand. Both use ReLU as the activation: it keeps a positive total and turns a negative one into 0. It is the simplest bend a neuron can have; Activation functions compares it with the others.
- Neuron 1: . It fires only after 2 months quiet.
- Neuron 2: . For a regular it equals neuron 1. For a newcomer, it fires from the first quiet day.
The output neuron weighs them and applies the sigmoid: , then chance .
Regular, 1 month quiet (g = 1, n = 0)
h₁ = 0, h₂ = 0 → z = −2 → chance ≈ 0.12
Neither neuron fires. The customer gets the base chance.
Regular, 3 months quiet (g = 3, n = 0)
h₁ = 1, h₂ = 1 → z = −2 − 1 + 2 = −1 → chance ≈ 0.27
Past 2 months, both fire, and the chance climbs.
Newcomer, 1 month quiet (g = 1, n = 1)
h₁ = 0, h₂ = max(0, 1 + 2 − 2) = 1 → z = 0 → chance = 0.50
The same month that meant nothing for a regular puts this newcomer at even odds.
Newcomer, 6 days quiet (g = 0.2, n = 1)
h₁ = 0, h₂ = 0.2 → z = −1.6 → chance ≈ 0.17
A newcomer who just ordered stays near the base chance.
Both hidden neurons use ReLU; the output uses the sigmoid.
The gap’s effect now depends on n. For a newcomer, each quiet month adds 2 to the score. For a regular, it adds nothing until month 2, then 1. Logistic regression gives the gap one slope for everyone, so it can’t do this. A textbook shows the same limit with XOR, which is 1 when exactly one of two inputs is 1: no linear model can fit it, and one hidden ReLU layer can.4
In a real network, training finds the weights, and hidden neurons rarely line up with a neat human idea like “quiet newcomer”. The hand-set version shows what is possible, not what training will find.
Without the bend, two layers are one
Farah deletes the ReLU from both hidden neurons and keeps every weight. Does the network still treat a quiet month differently for newcomers?Show answer
The algebra holds for any sizes. A layer without an activation is . Feed that into a second one:
- and are the two layers’ weights and biases.
- The right side is one weight matrix and one bias: a single layer.
Matrices as transformations of space showed this with points moving on a grid. Here it costs Kartly vouchers: the collapsed model flags every newcomer, active or not, and gives the gap one slope.
with ReLU
score z
months quiet, g
without ReLU
months quiet, g
Red dot: a newcomer who just ordered, flagged at a 0.5 chance. Newcomer lines stop at 45 days: no newcomer has been quiet longer.
ReLU itself is almost linear: a straight line with one bend at 0. Many neurons, each bending at a different place, can build curves and interactions out of these straight pieces. That is why one small bend per neuron is enough.
How big should the first network be?
Each layer adds (inputs × outputs) weights plus one bias per output. Farah’s 12 → 16 → 1 network has 225, as Models as functions with learnable parameters counted.
Logistic regression, 12 → 1
12 × 1 + 1 = 13
One neuron. No hidden values, no interactions.
One hidden layer, 12 → 16 → 1
(12 × 16 + 16) + (16 × 1 + 1) = 208 + 17 = 225
Sixteen learned features, then logistic regression on them.
Two wide layers, 12 → 256 → 256 → 1
(12 × 256 + 256) + (256 × 256 + 256) + (256 + 1) = 3,328 + 65,792 + 257 = 69,377
The middle layer alone holds 95% of the parameters: width times width grows fast.
Farah wants a first neural network on the 12 churn features and 200,000 customers. How big should it be?
12 → 1: one neuron, which is logistic regression
13 parameters and the same list as today. It still gives the gap one slope for everyone, so newcomers stay off the list.
12 → 16 → 1: one small hidden layer
225 parameters, against 200,000 customers to learn from. Sixteen hidden neurons are enough to learn bends like “new and quiet”. It trains in seconds on a notebook CPU, so trying it costs almost nothing.
12 → 256 → 256 → 1: two wide hidden layers
69,377 parameters, about one for every three customers. It can fit oddities of this one sample that won’t hold next quarter, and needs more care to train. Nothing in 12 tabular features calls for that much room.
Why this choice
Start with the smallest network that can express the pattern you suspect, then grow it only if it does worse on held-out customers than a bigger one. The choice changes with the input: hundreds of raw inputs, such as pixels or words, need wider and deeper layers. For this table, Farah’s boosted trees from the churn design lesson already learn interactions, so the small network is a comparison, not a replacement.
Is one hidden layer always enough?
In theory, nearly. Hornik, Stinchcombe and White proved in 1989 that one hidden layer with enough neurons can approximate any continuous function on a bounded range as closely as you like.5 The result says nothing about how many neurons that takes, or whether training will find the weights. In practice, deeper networks often reach the same accuracy with far fewer parameters, which is why image and text models stack many layers.
Where a network is the wrong tool
- Small tables with clear features. On a dozen tabular columns, boosted trees usually match or beat a small network and need less tuning. That is why Kartly’s Monday list runs on trees.
- When someone must read the weights. Logistic regression gives Joseph one odds ratio per feature. A hidden layer mixes all 12 features in every neuron, so no single weight answers “why this customer?”.
- Unscaled inputs. A weighted sum of days and rupees has the same problem it had in logistic regression. Scale features before the first layer.
In production
A forward pass, one run of inputs through every layer, is two matrix multiplies here. For 200,000 customers, layer 1 does 200,000 × 12 × 16 ≈ 38 million multiply-adds and layer 2 about 3 million: well under a second on a laptop CPU, as an estimate. The saved model is the 225 numbers plus the scaler. In PyTorch, nn.Sequential chains layers in the order given and passes each output to the next.2
How the 225 numbers get learned is the job of backpropagation, later in this module.
Try it yourself
This runs the hand-set network in NumPy, then takes the ReLU out to show the collapse. No seed is needed: nothing here is random.
import numpy as np
def relu(z: np.ndarray) -> np.ndarray:
return np.maximum(z, 0.0)
def sigmoid(z: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-z))
# Columns: months since last order, newcomer (1 = joined under 45 days ago)
X = np.array([[1.0, 0.0], [3.0, 0.0], [1.0, 1.0], [0.2, 1.0]])
W1 = np.array([[1.0, 0.0], # neuron 1: quiet for over 2 months
[1.0, 2.0]]) # neuron 2: the same, but fires early for newcomers
b1 = np.array([-2.0, -2.0])
W2 = np.array([[-1.0, 2.0]])
b2 = np.array([-2.0])
H = relu(X @ W1.T + b1) # hidden layer, shape (4, 2)
chance = sigmoid(H @ W2.T + b2) # output neuron, shape (4, 1)
print(H)
print(chance.ravel().round(2))
# Take the ReLU out: two layers become one weighted sum
no_relu = (X @ W1.T + b1) @ W2.T + b2
W, b = W2 @ W1, W2 @ b1 + b2
print(W, b, np.allclose(no_relu, X @ W.T + b))
print(sigmoid(no_relu).ravel().round(2))Expected, worked out by hand rather than from a run: hidden values (0, 0), (1, 1), (0, 1) and (0, 0.2); chances [0.12 0.27 0.5 0.17]. Without ReLU, [[1. 4.]] [-4.] True, then [0.05 0.27 0.73 0.55]. Look at the last customer: the newcomer who just ordered jumps from 0.17 to 0.55.
The same network in PyTorch, built from nn.Linear layers, then Farah’s 12 → 16 → 1 network with random starting weights. nn.Linear draws its starting weights and biases from a uniform range of ±√(1 ÷ inputs), about ±0.29 for 12 inputs, so the seed makes them repeatable.1
import torch
from torch import nn
torch.manual_seed(42)
# The same 2 → 2 → 1 network, with the hand-set weights copied in
net = nn.Sequential(nn.Linear(2, 2), nn.ReLU(), nn.Linear(2, 1))
with torch.no_grad():
net[0].weight.copy_(torch.tensor([[1.0, 0.0], [1.0, 2.0]]))
net[0].bias.copy_(torch.tensor([-2.0, -2.0]))
net[2].weight.copy_(torch.tensor([[-1.0, 2.0]]))
net[2].bias.copy_(torch.tensor([-2.0]))
X = torch.tensor([[1.0, 0.0], [3.0, 0.0], [1.0, 1.0], [0.2, 1.0]])
print(torch.sigmoid(net(X)).squeeze(1))
# Farah's churn network: 12 features -> 16 hidden values -> 1 score
churn_net = nn.Sequential(nn.Linear(12, 16), nn.ReLU(), nn.Linear(16, 1))
print([tuple(p.shape) for p in churn_net.parameters()])
print(sum(p.numel() for p in churn_net.parameters()))
with torch.no_grad():
print(churn_net(torch.randn(5, 12)).shape) # five made-up, already-scaled customersExpected, not from a run: tensor([0.1192, 0.2689, 0.5000, 0.1680]), matching NumPy. Then the shapes [(16, 12), (16,), (1, 16), (1,)], the count 225 and torch.Size([5, 1]). torch.sigmoid is the same function as torch.special.expit.3 Everything runs on a CPU in a free notebook.
Where this shows up
- Design: a classifier for product photos ends in a layer that maps image features to 20 category scores, the same
nn.Linearwith more inputs. - Design: product recommendations like Amazon ranks products with networks built from these layers.
Farah used ReLU because it is the simplest bend. The next lesson asks whether it is the right one, and what the sigmoid, tanh and others change.
Common mistakes
- Stacking layers with no activation between them. They collapse into one layer: more parameters, no new behaviour.
- Forgetting the biases when counting. Each layer adds one per output: 12 → 16 is 208, not 192.
- Writing the weight as (inputs, outputs). PyTorch stores (outputs, inputs) and computes x times the transpose.
- Reading a hidden neuron as a named rule. Trained neurons rarely mean one tidy thing; the quiet-newcomer neurons here were set by hand.
- Reaching for width first. A 256-wide layer has 65,536 weights to the next one. Start small and grow only when held-out results ask for it.
Check your understanding
A teammate’s network is 12 → 64 → 1 with no activation between the layers. How many parameters does it have, and what model does it behave like?Show answer
In the hand-set network, a regular customer is 2.5 months quiet. What are the two hidden values, the score and roughly the chance?Show answer
Farah’s layer has weight shape (16, 12). She applies it in NumPy as X @ W with X shaped (200000, 12). What happens?Show answer
Farah replaces every ReLU with a straight line, f(z) = 2z. Can the network still learn “new and quiet”?Show answer
Summary
- A neuron is a weighted sum plus a bias, passed through an activation; layers of neurons with a bend between them learn patterns like “new and quiet” that one weighted sum can’t.
- A layer is many neurons reading the same inputs: one matrix multiply, X times W transposed, plus a bias, then the activation.
- One neuron with the sigmoid is logistic regression. Without a non-linear activation, stacked layers collapse into one.
- Each layer adds inputs × outputs weights plus one bias per output: 12 → 16 → 1 has 225 parameters.
- Start with the smallest network that can express the pattern; on a small table, trees often still win.
