Guide to AI and Data Courses · Lecture Notes

Chapter 4: Artificial Neural Networks

Every day a postal service has to read thousands of handwritten digits on envelopes, yet nobody can write a rule that describes every way people draw a "four". Neural networks approach the job differently: they connect many small units, each taking a weighted sum and passing it through a simple function, in layers, and they learn the weights from examples. This course explains what a single unit does, why units must be stacked in layers, and how the error is distributed back to the weights. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.

Learning outcomes

The artificial neuron
Compute a neuron's weighted sum and activation output; apply the perceptron learning rule by hand on a small data set.
Linear separability
Explain why a single-layer perceptron cannot learn XOR and show how a hidden layer solves it.
Forward pass
Compute the prediction of a small multilayer network layer by layer and count its parameters.
Backpropagation
Compute the gradient of a weight with the chain rule, check it against a numerical derivative, and carry out a gradient descent step.
Place of the course
State what separates neural networks from machine learning, deep learning, optimization and neuroevolution.

4.1What question does the course ask?

How do networks of simple units learn by adjusting their weights?

Artificial neural networks are models built by connecting, in layers, simple units that take a weighted sum and pass it through an activation function. Learning means adjusting the weights so as to reduce a loss function; the main tools for this are backpropagation and gradient descent.

In machine learning a model is a function learned from examples. The neural networks course fixes the shape of that function: it is built by connecting simple units, all of the same kind, in layers. One unit does very little, but with enough units and a nonlinear activation function a network can learn complicated boundaries and relationships. The first question of the course is therefore "what can a single unit compute, and what can it not?"

The second question is about training: if a network has thousands of weights, how do we find out how much each one contributed to the error? The answer is backpropagation. It is not a new learning method; it is an efficient way of computing the gradient of the loss with the chain rule. The weights are then updated by the gradient descent we already know from Machine Learning.

4.1.1What does the course assume?

The chain rule and partial derivatives are the language of this course, and matrix-vector multiplication lets us write a whole layer in one line. In these notes every calculation is small enough to do by hand: networks with two or three weights. In real networks the calculation is the same; there is just much more of it.

4.1.2At a glance

CriterionArtificial Neural Networks
Approachnetwork of simple weighted units
Inputnumeric feature vector
Outputclass or numeric prediction
Success measureloss and accuracy
Math loadmedium-high: derivatives, matrices
Data needsmoderate

4.2A short history

YearMilestone
1943McCulloch and Pitts propose the first artificial neuron model with threshold logic units.
1949Hebb suggests that connections between neurons that fire together grow stronger: the Hebbian rule.
1957Rosenblatt introduces the perceptron; its weights are tuned from examples.
1969Minsky and Papert show that a single-layer perceptron cannot solve problems such as XOR.
1982Hopfield publishes a recurrent network that recalls memories by minimizing energy.
1986Rumelhart, Hinton and Williams popularize backpropagation; multilayer networks become trainable.

4.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
Artificial neuronWeighted sum of inputs, a bias and an output.
ActivationSigmoid, tanh, ReLU: adds nonlinearity to the network.
PerceptronSingle-layer network that separates linearly separable classes.
Multilayer networkHidden layers learn nonlinear boundaries.
Forward passComputing the prediction layer by layer from input to output.
BackpropagationFinding the gradient of every weight with the chain rule.
Gradient descentMoves the weights in small steps where the loss decreases.
RegularizationWeight penalties and early stopping prevent overfitting.

4.4The artificial neuron and the perceptron

An artificial neuron multiplies its inputs by weights, adds them up, adds a bias and passes the result through an activation function. The weights say how important each input is; the bias says how easily the unit "fires".

Definition 4.1 (Artificial neuron)

z = w1x1 + … + wnxn + b is the weighted sum and y = f(z) is the output. In a perceptron f is a step function: y = 1 if z ≥ 0, otherwise y = 0.

The perceptron learning rule is very simple. On each example the prediction y is compared with the target t; if they agree nothing happens, otherwise the weights are corrected according to the error: wi ← wi + η(t − y)xi, b ← b + η(t − y). Here η is the learning rate.

Example 4.1: Learning the OR function

Four examples: (0,0)→0, (0,1)→1, (1,0)→1, (1,1)→1. Start with w = (0, 0), b = 0, η = 1; the examples are presented in this order, again and again.

  1. Epoch 1, (0,0): z = 0, y = 1, target 0. Error −1: b = −1. Weights stay (0, 0).
  2. Epoch 1, (0,1): z = −1, y = 0, target 1. Error +1: w = (0, 1), b = 0. The next two examples are correct.
  3. Epoch 2, (0,0): z = 0, y = 1, target 0: b = −1.
  4. Epoch 2, (1,0): z = −1, y = 0, target 1: w = (1, 1), b = 0. (1,1) is correct.
  5. Epoch 3, (0,0): z = 0, y = 1, target 0: b = −1. The other three are correct.
  6. Epoch 4: no errors on any of the four examples; training stops.

The result is w = (1, 1), b = −1: the neuron outputs 1 when x1 + x2 − 1 ≥ 0. Check: (0,0)→−1→0, (0,1)→0→1, (1,0)→0→1, (1,1)→1→1. Five corrections were enough to find the right rule.

The perceptron comes with a guarantee: if the classes can be separated by a line (a hyperplane in higher dimensions), that is, if they are linearly separable, the rule finds correct weights in a finite number of steps. OR is a linearly separable function, but the guarantee ends there.

Common mistake

Forgetting the bias. A neuron without a bias always has a decision boundary through the origin. In the example above, without b the value z for the example (0,0) would always be 0, and that example, whose output must be 0, could not be classified correctly.

4.5Multilayer networks and XOR

The decision boundary of a single neuron is a line. In 1969 Minsky and Papert showed that a single-layer perceptron cannot learn XOR ((0,0)→0, (0,1)→1, (1,0)→1, (1,1)→0). A short proof shows why: for (0,0) to output 0 we need b < 0. For (0,1) and (1,0) we need w2 + b ≥ 0 and w1 + b ≥ 0. Adding the two gives w1 + w2 + 2b ≥ 0, so w1 + w2 + b ≥ −b > 0; but for (1,1) we needed w1 + w2 + b < 0. This is a contradiction: no such line exists.

The fix is to put a hidden layer between input and output. The hidden units move the inputs into a new space, and the output unit solves the problem linearly in that new space.

Example 4.2: Solving XOR with two hidden units

The weights are chosen by hand, not learned. All units use a step function (output 1 if z ≥ 0).

  • Hidden unit h1 (like OR): z = x1 + x2 − 0.5.
  • Hidden unit h2 (like AND): z = x1 + x2 − 1.5.
  • Output: z = h1 − h2 − 0.5.
(x1, x2)h1h2output zoutput
(0, 0)0 (z = −0.5)0 (z = −1.5)−0.50
(0, 1)1 (z = 0.5)0 (z = −0.5)0.51
(1, 0)1 (z = 0.5)0 (z = −0.5)0.51
(1, 1)1 (z = 1.5)1 (z = 0.5)−0.50

All four outputs match XOR. The hidden layer moved the points into the (h1, h2) space: (0,0)→(0,0), (0,1) and (1,0)→(1,0), (1,1)→(1,1). There the two classes are separated by the line h1 − h2 = 0.5.

4.5.1Activation functions

For the hidden layer to be useful, the activation function must be nonlinear. The step function is not differentiable, so networks trained by gradients use smooth functions. Some values of three common choices:

zSigmoid 1/(1 + e−z)tanh(z)ReLU max(0, z)
−20.1192−0.96400
00.500
20.88080.96402
Common mistake

Building the hidden layer with a linear activation. Without an activation, two layers collapse into one: W2(W1x) = (W2W1)x. For example W1 = [[1, 2], [0, 1]] and W2 = [[2, 0], [1, 1]] multiply to [[2, 4], [1, 3]]; however deep the network, it is a single linear map and still cannot learn XOR.

4.6Backpropagation

A network computes its prediction from input to output (the forward pass). In training the loss of that prediction is measured and we need ∂L/∂w for every weight. Because the network is made of nested functions, these derivatives are found with the chain rule: the error at the output is carried backward through the network layer by layer, and each weight receives its share. Since the same intermediate results are reused, all gradients together cost about as much as one forward pass.

Example 4.3: Gradient in a network with two weights

Input x = 1, target t = 1. The network is h = σ(w1x), ŷ = σ(w2h) with loss L = ½(ŷ − t)2; σ is the sigmoid function. Start with w1 = 0.5, w2 = −0.4.

  1. Forward pass. h = σ(0.5) ≈ 0.6225; z2 = −0.4 · 0.6225 ≈ −0.2490; ŷ = σ(−0.2490) ≈ 0.4381; L ≈ 0.1579.
  2. Error at the output. ∂L/∂ŷ = ŷ − t ≈ −0.5619. The sigmoid derivative is σ'(z) = σ(z)(1 − σ(z)), so σ'(z2) = 0.4381 · 0.5619 ≈ 0.2462. Hence δ2 = ∂L/∂z2 ≈ −0.5619 · 0.2462 ≈ −0.1383.
  3. Second weight. ∂L/∂w2 = δ2 · h ≈ −0.1383 · 0.6225 ≈ −0.0861.
  4. Carry the error back. ∂L/∂h = δ2 · w2 ≈ −0.1383 · (−0.4) ≈ 0.0553; σ'(z1) = 0.6225 · 0.3775 ≈ 0.2350; δ1 ≈ 0.0553 · 0.2350 ≈ 0.0130.
  5. First weight. ∂L/∂w1 = δ1 · x ≈ 0.0130.
  6. Numerical check. With ε = 10−6, (L(w1 + ε) − L(w1 − ε)) / 2ε is about 0.0130; for w2 it is about −0.0861. The backpropagation results are correct.
  7. Gradient descent. With η = 1: w1 ← 0.5 − 0.0130 ≈ 0.4870, w2 ← −0.4 + 0.0861 ≈ −0.3139. The new loss is L ≈ 0.1504, smaller than 0.1579.

Look at the signs: the gradient for w2 is negative, so w2 grew and the output moved a little closer to the target. Notice also that δ1 ≈ 0.013 is about a tenth of δ2 ≈ −0.138: the error carried backward is multiplied by at most 0.25 at every sigmoid layer, so it shrinks. In deep networks this is the vanishing gradient problem, and it is one reason activations such as ReLU became common.

The workflow in this example is the same for every network: store the intermediate values during the forward pass, start from the output and find each layer's δ, write the gradient of a weight as "its own input × its own δ", then update by gradient descent. Checking the gradient against a numerical derivative is the most reliable way to test a backpropagation routine you wrote yourself.

Common mistake

Initializing all weights with the same value (for example zero). Units in the same layer see the same inputs with the same weights, so they produce the same output and receive the same gradient. After the update they are still copies of each other, and the layer behaves like a single unit however many units it has. Small random initial values break the symmetry.

4.7How is the course taught?

4.7.1A typical workflow

Initializeweightssmall randomvaluesForwardpasscomputepredictionMeasurelosserror,cross-entropyBack-propagategradientsUpdatelearning rate,epoch by epoch
Figure 4.1: A typical workflow in Artificial Neural Networks

A small network that reads handwritten digits takes a 28×28-pixel image as 784 inputs, passes it through a hidden layer and outputs probabilities for 10 classes. A wrong guess means a large loss; backpropagation computes each weight's share and gradient descent corrects the weights a little.

4.7.2Topics over the semester

  1. Biological and artificial neurons; McCulloch-Pitts
  2. Hebbian learning and the perceptron algorithm
  3. Adaline, least mean squares and the delta rule
  4. Linear separability and the XOR problem
  5. Multilayer networks and activation functions
  6. Backpropagation: computational graphs, chain rule
  7. Loss functions: squared error, cross-entropy
  8. Gradient descent, learning rate and momentum
  9. Weight initialization and vanishing gradients
  10. Generalization: regularization, early stopping
  11. Radial basis function networks
  12. Hopfield networks and self-organizing maps (SOM)

This is a typical semester; the order and coverage vary between universities.

4.7.3Skills you will gain

  • writing a network from scratch in NumPy
  • deriving backpropagation by hand
  • numerical gradient checking
  • training networks in PyTorch and Keras
  • reading learning curves

4.7.4Try it yourself

The Try It: Tangerine or Lemon? slide in the presentation lets you solve a typical problem of this course yourself: A camera on the sorting belt measures the weight and color hue of each fruit. A single artificial neuron (a perceptron) learns to separate the two kinds: train it, or click a fruit to flip its label.

4.8Are you ready for this course?

4.8.1Prerequisites

CourseWhy it is needed
Machine Learningparametric model, loss function, gradient descent
Linear Algebraweight matrices, vectorized computation
Optimizationgradient descent, learning rate
Calculusderivatives, partial derivatives and the chain rule: the math of backpropagation
Programmingarrays, loops and functions in Python

4.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you differentiate a composite function with the chain rule?Derivatives and the chain rule from calculus
Can you multiply a matrix by a vector and state the result's shape?Linear Algebra
Can you do vectorized operations on NumPy arrays without loops?An intro programming course, then a short NumPy tutorial
Can you explain the difference between training and test error?Machine Learning

4.9Neighboring courses

Machine LearningDeep LearningLinear AlgebraOptimizationEvolutionary OptimizationNeural Networks
subfieldbuilds onshares methodsapplication
Figure 4.2: Neighbors of Artificial Neural Networks and the kind of relation

4.9.1Where it overlaps

RelationCourseShared ground
subfieldThis course is a subfield of Machine Learningparametric model, loss function, gradient descent
subfieldDeep Learning is a subfield of this coursemultilayer networks, backpropagation, activation functions
builds onThis course builds on Linear Algebraweight matrices, vectorized computation
builds onThis course builds on Optimizationgradient descent, learning rate
shares methodsShares methods with Evolutionary and Metaheuristic Optimizationneuroevolution, hyperparameter search

4.9.2Where it differs

  • Machine Learning: ML covers many model families from decision trees to SVMs; this course focuses only on networks built from neurons.
  • Deep Learning: Deep learning moves on to convolutional, recurrent and transformer architectures; this course builds the basic network and training they rest on.
  • Optimization: Optimization studies gradient methods in general; this course uses them to learn weights.
  • Evolutionary and Metaheuristic Optimization: Neuroevolution searches weights or architectures by evolution; this course learns weights by gradients and backpropagation.

4.10In practice

4.10.1Applications

AreaWhat is done
Digit recognitionHandwritten digits on ZIP codes and checks.
Tabular dataClassification tasks such as credit risk or churn.
Function approximationLearning nonlinear relations from measurements.
ControlSimple robot and process controllers.
Signal classificationDetecting faults or motion from sensor data.
Associative memoryCompleting a corrupted pattern with a Hopfield network.

4.10.2Risks and ethics

RiskExplanation
Memorization and overfittingA large network on a small dataset drives training error to zero and then fails on new examples; without a validation set you never see it.
Shortcut learningA network may learn traces of data collection instead of the real feature: a ruler in the photo, the background or a scanner tag.
Unstable trainingPoor initialization or a large learning rate makes the loss blow up; a result from a single random seed may not reproduce.
Decisions without reasonsWeights do not read as rules; that is a serious problem where a justification is required, as in credit or medical decisions.

These issues are discussed in depth in Explainable AI and AI Ethics.

4.10.3Tools and datasets

Tools: NumPy, PyTorch, Keras, scikit-learn (MLPClassifier), TensorFlow Playground, MATLAB Deep Learning Toolbox.

Well-known datasets: XOR problem, Iris, MNIST, Fashion-MNIST, Two spirals, CIFAR-10.

In this course, writing a network by hand in NumPy first is the best way to see what backpropagation really does.

4.11Common misconceptions

Common mistake

Neural networks imitate the brain.

Biology is the inspiration, but the artificial neuron is a very crude model and its learning rule differs from the brain's.

Common mistake

More neurons are always better.

A large network can memorize the training data; size is chosen with a validation set.

Common mistake

Backpropagation is a separate learning method.

Backpropagation only computes the gradient; gradient descent updates the weights.

Common mistake

Training gives the same result every time.

Random initialization and shuffling can lead to different local minima.

4.12Summary

  • An artificial neuron takes a weighted sum of its inputs, adds a bias and passes the result through an activation function; the perceptron rule changes the weights by η(t − y)x only on a wrong prediction.
  • A single-layer perceptron learns only linearly separable classes; XOR is the classic counterexample.
  • A hidden layer with a nonlinear activation moves the inputs into a new space where the classes can be separated; without an activation the layers collapse into one linear map.
  • Backpropagation computes all gradients with the chain rule at about the cost of one forward pass; gradient descent updates the weights. Gradients can be checked with a numerical derivative.
  • In sigmoid layers the derivative is at most 0.25, so the gradient shrinks going backward; initialization, ReLU and regularization matter for stable training and generalization.

4.13Test Yourself

  1. A neuron has weights w = (2, −1), bias b = 0.5 and input x = (1, 3). What is its output with a sigmoid activation?

    Answer

    z = 2·1 + (−1)·3 + 0.5 = −0.5. σ(−0.5) = 1/(1 + e0.5) ≈ 0.3775.

  2. A perceptron has w = (0, 1), b = −1, η = 1. The example is x = (1, 0) with target t = 1 (step: output 1 if z ≥ 0). What are the weights after the update?

    Answer

    z = 0·1 + 1·0 − 1 = −1, y = 0, error t − y = 1. w = (0 + 1·1, 1 + 1·0) = (1, 1), b = −1 + 1 = 0. The new z is 1, so the example is now correct.

  3. How many parameters does a fully connected network with 784 inputs, 30 hidden units and 10 outputs have (with a bias in each layer)?

    Answer

    First layer 784·30 + 30 = 23,550; second layer 30·10 + 10 = 310. Total 23,550 + 310 = 23,860.

  4. Take W1 = [[1, 2], [0, 1]], W2 = [[2, 0], [1, 1]] and a two-layer network without activations. Compute the output for x = (1, 1) in two ways. Can the network be reduced to one layer?

    Answer

    W1x = (3, 1), W2(3, 1) = (6, 4). The product is W2W1 = [[2, 4], [1, 3]] and [[2, 4], [1, 3]](1, 1) = (6, 4). Yes: two linear layers are equivalent to one linear layer, which is why the hidden activation must be nonlinear.

  5. In the backpropagation example, ∂L/∂w2 ≈ −0.0861 and w2 = −0.4. After one gradient descent step with η = 0.5, what is w2, and does the loss go up or down?

    Answer

    w2 ← −0.4 − 0.5 · (−0.0861) ≈ −0.357. Because the gradient is negative, w2 increases; for a small step the loss decreases (the direction opposite to the gradient is the direction in which the loss falls). If the step is too large, this guarantee no longer holds.

  6. A network's training loss falls every epoch, but its validation loss starts to rise after epoch 12. What does this show and what can be done?

    Answer

    Overfitting: the network has started to learn details specific to the training data. One can stop at epoch 12 (early stopping), add a weight penalty, shrink the network or use more data. The choice is made with the validation set, not the test set.

4.14After this course

This course is the gateway to deep learning: convolutional networks, recurrent networks and transformers are built on the ideas of neuron, loss and backpropagation introduced here. It also reinforces optimization and linear algebra.

Courses that build on or extend this one: Deep Learning.

Related careers: Machine learning engineer, Deep learning engineer, Researcher, Embedded AI developer.

4.15Further reading

  • M. Nielsen, Neural Networks and Deep Learning (2015, online): derives backpropagation step by step with a small network and a handwritten-digit example.
  • S. Haykin, Neural Networks and Learning Machines (3rd ed., 2009): a textbook treatment of all topics of the course, from the perceptron to radial basis function networks and the Hopfield network.
  • I. Goodfellow, Y. Bengio and A. Courville, Deep Learning (2016): presents the forward pass and backpropagation as the mathematical foundation of deep learning.

4.16References

  1. Haykin, Neural Networks and Learning Machines, 3rd ed., Pearson, 2009.
  2. Bishop, Neural Networks for Pattern Recognition, Oxford University Press, 1995.
  3. Nielsen, Neural Networks and Deep Learning, Determination Press, 2015 (online book).
  4. Rumelhart, Hinton and Williams, "Learning representations by back-propagating errors", Nature 323, 1986.

Related pages: Slides · Slides (PDF) · Course page