A4.3.8 Inside an artificial neural network
HL onlyCommand terms: Outline, Sketch1. Inside a single perceptron
A perceptron is one artificial neuron. It multiplies each input by a weight, adds them up with a bias, and passes the total through an activation function to give an output. Change the inputs and weights. Can you make it behave like an AND gate?
2. How a perceptron learns
Instead of setting the weights by hand, let the perceptron learn them from labelled examples. For each example, if the output is wrong, nudge each weight: w ← w + learning rate × (target − output) × input. The weights above update as it trains.
3. Build a multi-layer perceptron (MLP)
Connecting many neurons in layers lets a network model complex patterns. Design a network and watch data flow through it.
4. Why hidden layers matter: solving XOR
No single perceptron can do XOR: you can't separate its 1s from its 0s with one straight line. A tiny MLP with one hidden layer of 2 neurons can. Toggle the inputs:
5. Label the sketch
Exam questions may ask you to sketch a perceptron. Identify each labelled part. Score: 0 /
In this lab you practise a perceptron's weights, bias and step activation, the perceptron learning rule, why XOR needs hidden layers, and training an MLP with backpropagation. Work through the sections in order: run it, read it, change it, then extend it.
1. Set up in PyCharm
- Open PyCharm and choose New Project (a pure Python project; any recent Python 3 works). Name it
shelfwise_ai. - Right-click the project folder → New → Python File, and give it the file name shown below.
- Press Copy code below and paste it into the empty file (or press Download .py and drag the file into the project).
- Right-click inside the editor and choose Run (Windows Shift+F10, Mac Ctrl+R). The output appears in the Run window at the bottom.
- No extra libraries are needed: the lab uses only Python's built-in modules, so you can see exactly how the algorithm works.
2. Copy and run the program
# ShelfWise AI - Lab A4.3.8: from a single perceptron to a multi-layer network
import random, math
LEARNING_RATE = 0.1
EPOCHS = 20 # perceptron training passes
HIDDEN = 3 # neurons in the hidden layer of the MLP
MLP_EPOCHS = 5000
random.seed(2)
# Two yes/no inputs: x1 = "member has overdue books", x2 = "member asked to renew"
inputs = [(0, 0), (0, 1), (1, 0), (1, 1)]
targets = {"AND": [0, 0, 0, 1], "OR": [0, 1, 1, 1], "XOR": [0, 1, 1, 0]}
def step(z):
return 1 if z >= 0 else 0
def train_perceptron(t):
w = [0.0, 0.0]
b = 0.0
for _ in range(EPOCHS):
for (x1, x2), target in zip(inputs, t):
out = step(w[0] * x1 + w[1] * x2 + b) # weighted sum + bias -> activation
err = target - out
w[0] += LEARNING_RATE * err * x1 # perceptron learning rule
w[1] += LEARNING_RATE * err * x2
b += LEARNING_RATE * err
outs = [step(w[0] * x1 + w[1] * x2 + b) for x1, x2 in inputs]
return w, b, outs
print("SINGLE PERCEPTRON")
for name, t in targets.items():
w, b, outs = train_perceptron(t)
ok = "learned" if outs == t else "FAILED"
print(f" {name:3}: w1={w[0]:+.2f} w2={w[1]:+.2f} bias={b:+.2f} outputs {outs} target {t} {ok}")
# Multi-layer perceptron: 2 inputs -> HIDDEN sigmoid neurons -> 1 sigmoid output, trained by backpropagation
def sig(z):
return 1 / (1 + math.exp(-z))
w_h = [[random.uniform(-1, 1) for _ in range(2)] for _ in range(HIDDEN)]
b_h = [random.uniform(-1, 1) for _ in range(HIDDEN)]
w_o = [random.uniform(-1, 1) for _ in range(HIDDEN)]
b_o = random.uniform(-1, 1)
t = targets["XOR"]
lr = 0.5
for epoch in range(1, MLP_EPOCHS + 1):
loss = 0
for (x1, x2), target in zip(inputs, t):
h = [sig(w_h[j][0] * x1 + w_h[j][1] * x2 + b_h[j]) for j in range(HIDDEN)] # forward pass
o = sig(sum(w_o[j] * h[j] for j in range(HIDDEN)) + b_o)
loss += (target - o) ** 2
d_o = (o - target) * o * (1 - o) # backward pass
for j in range(HIDDEN):
d_h = d_o * w_o[j] * h[j] * (1 - h[j])
w_o[j] -= lr * d_o * h[j]
w_h[j][0] -= lr * d_h * x1
w_h[j][1] -= lr * d_h * x2
b_h[j] -= lr * d_h
b_o -= lr * d_o
if epoch in (1, 100, 1000, MLP_EPOCHS):
print(("\nMULTI-LAYER PERCEPTRON for XOR (2 -> %d -> 1)" % HIDDEN) if epoch == 1 else "", end="")
print(f"\n epoch {epoch:5}: loss {loss:.4f}", end="")
print()
for (x1, x2), target in zip(inputs, t):
h = [sig(w_h[j][0] * x1 + w_h[j][1] * x2 + b_h[j]) for j in range(HIDDEN)]
o = sig(sum(w_o[j] * h[j] for j in range(HIDDEN)) + b_o)
print(f" input ({x1}, {x2}) -> output {o:.3f} -> class {round(o)} (target {target})")
3. Expected output
The program uses a fixed random seed, so with the same settings you should see exactly this output.
SINGLE PERCEPTRON AND: w1=+0.20 w2=+0.10 bias=-0.20 outputs [0, 0, 0, 1] target [0, 0, 0, 1] learned OR : w1=+0.10 w2=+0.10 bias=-0.10 outputs [0, 1, 1, 1] target [0, 1, 1, 1] learned XOR: w1=-0.10 w2=+0.00 bias=+0.00 outputs [1, 1, 0, 0] target [0, 1, 1, 0] FAILED MULTI-LAYER PERCEPTRON for XOR (2 -> 3 -> 1) epoch 1: loss 1.1009 epoch 100: loss 1.0485 epoch 1000: loss 0.0376 epoch 5000: loss 0.0021 input (0, 0) -> output 0.021 -> class 0 (target 0) input (0, 1) -> output 0.977 -> class 1 (target 1) input (1, 0) -> output 0.977 -> class 1 (target 1) input (1, 1) -> output 0.026 -> class 0 (target 0)
4. Read the output
Answer each question from your own output before you open the answer.
Which logic functions can a single perceptron learn?
In the MLP, what happens to the loss between epoch 1 and epoch 5000?
What do the outputs such as 0.977 mean?
5. Change it and predict
For each change: write down your prediction first, then edit the setting at the top of the program, run it, and compare. Change the setting back before the next task.
Task 1. Change HIDDEN = 3 → HIDDEN = 1
Set HIDDEN = 1. Can one hidden neuron solve XOR?
Check your prediction
No. The loss stays around 0.69 and (0, 0) is classified wrongly. One hidden neuron gives the network only one straight line again; XOR needs at least two hidden neurons.
Output with this change:
SINGLE PERCEPTRON AND: w1=+0.20 w2=+0.10 bias=-0.20 outputs [0, 0, 0, 1] target [0, 0, 0, 1] learned OR : w1=+0.10 w2=+0.10 bias=-0.10 outputs [0, 1, 1, 1] target [0, 1, 1, 1] learned XOR: w1=-0.10 w2=+0.00 bias=+0.00 outputs [1, 1, 0, 0] target [0, 1, 1, 0] FAILED MULTI-LAYER PERCEPTRON for XOR (2 -> 1 -> 1) epoch 1: loss 1.0585 epoch 100: loss 1.0350 epoch 1000: loss 0.7679 epoch 5000: loss 0.6909 input (0, 0) -> output 0.682 -> class 1 (target 0) input (0, 1) -> output 0.677 -> class 1 (target 1) input (1, 0) -> output 0.677 -> class 1 (target 1) input (1, 1) -> output 0.038 -> class 0 (target 0)
Task 2. Change EPOCHS = 20 → EPOCHS = 2
Set EPOCHS = 2. What happens to AND and OR?
Check your prediction
Both now fail: two passes through the data are not enough for the learning rule to find suitable weights. Training needs enough iterations to converge.
Output with this change:
SINGLE PERCEPTRON AND: w1=+0.20 w2=+0.10 bias=-0.10 outputs [0, 1, 1, 1] target [0, 0, 0, 1] FAILED OR : w1=+0.10 w2=+0.10 bias=+0.00 outputs [1, 1, 1, 1] target [0, 1, 1, 1] FAILED XOR: w1=-0.10 w2=+0.00 bias=+0.00 outputs [1, 1, 0, 0] target [0, 1, 1, 0] FAILED MULTI-LAYER PERCEPTRON for XOR (2 -> 3 -> 1) epoch 1: loss 1.1009 epoch 100: loss 1.0485 epoch 1000: loss 0.0376 epoch 5000: loss 0.0021 input (0, 0) -> output 0.021 -> class 0 (target 0) input (0, 1) -> output 0.977 -> class 1 (target 1) input (1, 0) -> output 0.977 -> class 1 (target 1) input (1, 1) -> output 0.026 -> class 0 (target 0)
6. Extended activity: Sketch and build your own network
A longer project for homework or a double lesson. Save it as a new file so you keep the original.
- Sketch the 2 → 3 → 1 network on paper: label inputs, weights, biases, activation functions and the output.
- Change the MLP so it has 3 inputs and learns a 3-input rule of your choice (for example, 'remind if exactly one of three conditions is true'). How many hidden neurons does it need?
- Print the loss every 500 epochs and describe the shape of the learning curve.
- Try learning rates 0.05, 0.5 and 5. Explain what happens with each.
Success criteria
- Your sketch matches your code.
- You find a working number of hidden neurons and explain why.
- You describe the effect of the learning rate with evidence.
7. Level up (optional): the same with scikit-learn
This optional part uses scikit-learn, the library professionals use. Install it once in PyCharm: Settings → Project → Python Interpreter → + → search scikit-learn → Install Package. Or type in PyCharm's Terminal: pip install scikit-learn. If the download is slow in China, use a mirror: pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple. Numbers may differ slightly between library versions.
# Optional: a multi-layer perceptron with scikit-learn (pip install scikit-learn)
from sklearn.neural_network import MLPClassifier
X = [[0, 0], [0, 1], [1, 0], [1, 1]]
y = [0, 1, 1, 0] # XOR
mlp = MLPClassifier(hidden_layer_sizes=(4,), activation="tanh", solver="lbfgs", random_state=1, max_iter=2000)
mlp.fit(X, y)
print("predictions:", mlp.predict(X), " target:", y)
print("weights, input -> hidden:", [[round(float(w), 2) for w in row] for row in mlp.coefs_[0]])
Output on our computer (scikit-learn 1.9):
predictions: [0 1 1 0] target: [0, 1, 1, 0] weights, input -> hidden: [[-1.08, 1.94, -2.6, -3.6], [-2.36, -2.54, -3.24, -2.74]]
Compare this with your from-scratch version: which results match, and why might the library choose slightly different values?
Learning objectives
By the end of this page you should be able to:
- Outline the structure and function of an artificial neural network.
- Sketch a single perceptron, showing inputs, weights, bias, activation function and output.
- Calculate the output of a perceptron for given inputs and weights.
- Sketch a multi-layer perceptron with an input layer, hidden layers and an output layer.
- Outline how multi-layer networks model complex patterns for classification, regression and pattern recognition.
Artificial neural networks
An ANN is a network of simple interconnected processing units (neurons / nodes), loosely inspired by the brain. Each connection has a weight. The network learns by adjusting its weights and biases so that its outputs match the training data. ANNs are used for classification (spam / not spam), regression (predicting a price) and pattern recognition (faces, handwriting, speech).
The perceptron (a single neuron)
| Part | Role |
|---|---|
| Inputs (x₁, x₂, …) | The feature values fed into the neuron. |
| Weights (w₁, w₂, …) | The strength / importance of each input; learned during training. |
| Bias (b) | An extra adjustable value that shifts the threshold, so the neuron can activate even when inputs are 0. |
| Summation (Σ) | Weighted sum: z = w₁x₁ + w₂x₂ + … + b. |
| Activation function (f) | Decides the output from z, e.g. step (1 if z ≥ 0, else 0), sigmoid (0 to 1), ReLU (max(0, z)). Non-linear activations let networks learn complex patterns. |
| Output (y) | y = f(z); passed to the next layer or used as the prediction. |
A single perceptron can only separate data with a straight line (linearly separable problems such as AND, OR). It cannot learn XOR.
Multi-layer perceptron (MLP)
- Input layer: one neuron per feature; passes the data in (no calculation).
- Hidden layer(s): one or more layers between input and output that combine inputs into increasingly useful features. Each neuron is connected to every neuron in the next layer (fully connected).
- Output layer: produces the result: 1 neuron for regression or yes/no; one neuron per class for multi-class classification.
- Forward pass: data flows from input → hidden → output. Training compares the output with the correct answer and adjusts the weights to reduce the error (backpropagation), repeated over many epochs.
- With more hidden layers and neurons, the network can model more complex, non-linear patterns (deep learning = many hidden layers), but it needs more data and computing power and can overfit.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Sketch a single perceptron, labelling its inputs, weights, bias, activation function and output. [4]
2. Sketch a multi-layer perceptron with 3 inputs, one hidden layer of 4 neurons and 2 outputs. Label each layer. [3]
3. A perceptron has inputs x₁ = 1, x₂ = 0, weights w₁ = 0.6, w₂ = 0.4, bias −0.5 and a step activation (output 1 if the sum ≥ 0). Calculate its output. [2]
4. Outline the role of the activation function in a neuron. [2]
5. Explain why multi-layer networks can model more complex patterns than a single perceptron. [3]