Learning path: Neural Networks from Scratch to Embeddings · Step 2 of 9
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
What you will learn
- Run a whole layer on many examples at once with X @ W + b
- Compare sigmoid, tanh and ReLU and say which range each one gives
- Turn output scores into probabilities with softmax
- Count the weights and biases of a network: 17 for a tiny one, 101,770 for the digit network
Before you start
- Why Neural Networks: Pixels, One Neuron and Layers
- NumPy arrays and the @ operator
Imagine water flowing through three pipes, and every pipe has a tap. One tap is wide open, one is open a little, one is closed. The water that gets through fills a tank. At the outlet of the tank sits a one-way valve: water can go forward, never back.
That's a neuron. The taps are the weights, the tank is the neuron, and the valve is the activation. Training will later learn how far to open each tap. Today we just let the water flow, from the inputs to the outputs. That trip is called the forward pass.
A tiny network you can follow by hand
The digit network from Why Neural Networks has 784 inputs, 128 hidden neurons and 10 outputs. That's too big to follow, so we build a tiny one with the same shape of ideas: 3 inputs, 2 hidden neurons, 3 outputs (one score per class).
Hidden neuron 1 is our old friend from the last article: weights 0.4, -0.2, 0.9 and bias -0.3.
A whole layer in one line: X @ W + b
Put two examples in X, one per row. Put the weights in W1, where every column is one neuron. Then one matrix product runs every neuron on every example at once.
import numpy as np
X = np.array([[0.0, 0.5, 1.0],
[1.0, 1.0, 0.0]])
W1 = np.array([[ 0.4, 0.3],
[-0.2, 0.8],
[ 0.9, -0.5]])
b1 = np.array([-0.3, 0.2])
print(X.shape, W1.shape, b1.shape)
(2, 3) (3, 2) (2,)
Two examples with three inputs, three inputs into two neurons, two biases. The shapes line up. Now the layer:
Z1 = X @ W1 + b1
H = np.maximum(0, Z1)
print(Z1.round(2).tolist())
print(H.round(2).tolist())
[[0.5, 0.1], [-0.1, 1.3]]
[[0.5, 0.1], [0.0, 1.3]]
The first value of Z1 is 0.5, the same as our hand calculation last time. np.maximum(0, Z1) is ReLU: the -0.1 becomes 0, everything else passes through. H is what the hidden layer hands to the next layer.
Three activation functions
There are a few kinds of valve, and you need three of them:
def sigmoid(z): return 1 / (1 + np.exp(-z))
def tanh(z): return np.tanh(z)
def relu(z): return np.maximum(0, z)
z = np.array([-2.0, 0.0, 2.0, 10.0])
print("z ", z.tolist())
print("sigmoid", sigmoid(z).round(2).tolist())
print("tanh ", tanh(z).round(2).tolist())
print("relu ", relu(z).tolist())
z [-2.0, 0.0, 2.0, 10.0]
sigmoid [0.12, 0.5, 0.88, 1.0]
tanh [-0.96, 0.0, 0.96, 1.0]
relu [0.0, 0.0, 2.0, 10.0]
Draw them from -4 to 4:
import matplotlib.pyplot as plt
zz = np.linspace(-4, 4, 81)
for f, name in [(sigmoid, "sigmoid"), (tanh, "tanh"), (relu, "ReLU")]:
plt.plot(zz, f(zz), label=name)
plt.legend()
plt.show()

- Sigmoid squeezes any
zinto 0 to 1. You met it in Logistic Regression and the Sigmoid. - Tanh has the same S shape, but squeezes into -1 to 1.
- ReLU: negative becomes 0, positive passes as it is. Its range is 0 to infinity.
ReLU has no top limit. At z = 10, sigmoid and tanh stop at 1, but ReLU gives 10. It is not squeezed into 0 to 1.
Scores in, probabilities out: softmax
The output layer works the same way: H @ W2 + b2.
W2 = np.array([[ 1.0, -0.5, 0.2],
[-0.4, 0.9, 0.3]])
b2 = np.array([0.1, 0.0, -0.1])
scores = H @ W2 + b2
print(scores.round(2).tolist())
[[0.56, -0.16, 0.03], [-0.42, 1.17, 0.29]]
Scores can be negative, and they don't add up to anything in particular. Softmax fixes both. np.exp makes every score positive, then we divide each one by its row total:
e = np.exp(scores)
print(e.round(2).tolist())
P = e / e.sum(axis=1, keepdims=True)
print(P.round(2).tolist())
print(P.sum(axis=1))
[[1.75, 0.85, 1.03], [0.66, 3.22, 1.34]]
[[0.48, 0.23, 0.28], [0.13, 0.62, 0.26]]
[1. 1.]
For example two, the scores -0.42, 1.17 and 0.29 become the probabilities 0.13, 0.62 and 0.26. Every row adds up to 1, and example two picks the second class with 62%.
Which activation goes where
| Where | Use | Why |
|---|---|---|
| Hidden layers | ReLU | Fast, simple, the usual default |
| Yes/no output | Sigmoid | One probability between 0 and 1 |
| One-of-many output | Softmax | Probabilities that add up to 1 |
| Older networks | Tanh | You'll mostly see it in older code |
So the digit network uses ReLU inside and softmax over the 10 digits.
Counting the knobs
How many numbers sit inside a network? Count every weight and every bias:
params = {"W1": W1, "b1": b1, "W2": W2, "b2": b2}
for name, a in params.items():
print(name, a.shape, a.size)
W1 (3, 2) 6
b1 (2,) 2
W2 (2, 3) 6
b2 (3,) 3
tiny = W1.size + b1.size + W2.size + b2.size
digit = (784 * 128 + 128) + (128 * 10 + 10)
print(f"tiny network : {tiny:,}")
print(f"digit network: {digit:,}")
tiny network : 17
digit network: 101,770
The tiny network has 17 knobs. The digit network has 101,770: 784 x 128 weights plus 128 biases, then 128 x 10 weights plus 10 biases. Far too many to set by hand, so the network has to learn them. That's the next step: Loss and Backpropagation.
Common mistakes
- Mixing up the weight layout. Here every column of
W1is one neuron, soX(examples x inputs) timesW1(inputs x neurons) gives examples x neurons. - Thinking ReLU outputs are between 0 and 1. They aren't; only sigmoid (and softmax) give probabilities.
- Softmax over the wrong axis. Each row (one example) must add up to 1, hence
axis=1. - Forgetting the biases when counting parameters.
Quick recap
| Step | Code | Tiny network |
|---|---|---|
| Multiply and add the bias | X @ W1 + b1 | Z1 starts with 0.5 |
| Activate | np.maximum(0, Z1) | -0.1 becomes 0.0 |
| Output scores | H @ W2 + b2 | -0.42, 1.17, 0.29 |
| Softmax | e / e.sum(axis=1, keepdims=True) | 0.13, 0.62, 0.26 |
| Count parameters | weights + biases | 17 (digit network 101,770) |
Try it yourself
Set b1 to [0.0, 0.0] and run the cells again. Which hidden values change, and do the probabilities still add up to one?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Why Neural Networks: Pixels, One Neuron and Layers
Next →Loss and Backpropagation: How Wrong, and Who Is to Blame
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.
Your First Neural Network with Keras: MNIST Digits at 97.7%
Build the 784-128-10 digit network in Keras in five steps: load and scale, Sequential with Flatten and Dense, compile, fit for ten epochs, and test once. It reads handwritten digits with 97.72% test accuracy.