Part IV — Modeling · Chapter 7

Neural Networks

~42 min read6 interactive widgets4 plates

In this chapter

  1. The model, at the heart of the pipeline
  2. The artificial neuron
  3. Boolean functions and the XOR problem
  4. Artificial Neural Networks: layers and topologies
  5. Activation functions
  6. Universal approximation, and why depth
  7. Deep learning and the loss function
  8. Softmax and cross entropy
  9. Gradient descent, SGD and Adam
  10. Batch, iterations, epoch
  11. Delta rule and backpropagation
  12. Learning curves and the MLP in scikit-learn
  13. Developing AI systems: ML vs DL, and hardware
  14. Check your understanding

1. The model, at the heart of the pipeline

The deck opens by redrawing the pipeline of Chapter 5 and pointing at the last box: we now focus on the model, the "heart" of the AI in our system.

The lecturer also lists the interactive demos worth playing with: Playground TensorFlow, Convnetjs, LLM architectures, Transformers, and an interactive gradient descent visualisation. And a disclaimer: neural networks are mathematically intensive.

2. The artificial neuron

Neural Networks (NN): the key idea is to imitate, as far as possible, the neurons of the human brainnetworks because neurons are connected to each other. The biological picture the deck starts from:

The first scheme about the neuron was introduced by McCulloch and Pitts (1943); the first Artificial Neuron (AN) was introduced by Rosenblatt in 1957. Its four design decisions:

  1. Inputs are digital numbers, not analog signals.
  2. Inputs are weighted: signals are not all equally important.
  3. Inputs are merged with a sum function, plus a bias.
  4. An activation function generates the final output — the brain also filters inputs, since it is impossible to always take everything into account.

A working example

Will I pass the Machine Learning exam?

y' = 1   if  0.3 * x1 + 0.8 * x2 + 0.5 * x3 >= 3
     0   otherwise
THE ARTIFICIAL NEURON (ROSENBLATT, 1957) x1 x2 x3 inputs (digital numbers) w1 = 0.3 w2 = 0.8 w3 = 0.5 weights: not all signals matter equally sum + bias b activation function (a switch: fires past a threshold) y′ y′ = 1 if 0.3·x1 + 0.8·x2 + 0.5·x3 ≥ 3, else 0 the threshold 3 is the bias, moved to the other side of the inequality
Plate 7.1 — The artificial neuron with the exam example wired in. Weights scale the inputs, the sum collects them, the bias sets where the switch trips, and the activation function decides what comes out.

3. Boolean functions and the XOR problem

The deck asks how to implement not, and, or with a single artificial neuron — all three are shown to work — and then asks the decisive question: what about xor?

x1 / x201x1 / x201
and 000or 001
and 101or 111
xor 001not: x1 = 0 → 1, x1 = 1 → 0
xor 110

The answer, stated flatly on the slide: a single AN can solve only linear problems. The solution is to use more ANs organized on different layers → the Multi-Layer Perceptron (MLP). It is not so easy, since this introduces several mathematical problems, and it greatly increases the computational load.

WHY ONE NEURON IS NOT ENOUGH AND linearly separable OR linearly separable XOR NOT linearly separable no single line puts the two filled dots on one side filled dot = output 1, hollow dot = output 0. A single neuron draws exactly one straight boundary. Hence: more neurons, organized on different layers - the Multi-Layer Perceptron.
Plate 7.2 — The historical wall. A single artificial neuron computes a weighted sum and thresholds it, which draws one straight boundary in the input space: enough for AND and OR, never enough for XOR.

Widget — the perceptron playground

Set the two weights and the threshold, and try to reproduce each Boolean function. XOR will resist.

4. Artificial Neural Networks: layers and topologies

Neural networks are groups of artificial neurons organized in different layers:

Each neuron is fully connected to those of the next level. Again, this imitates the hierarchical nature of our neurons: we have "only" about ten levels between the retina and the actuator muscles — otherwise we would be too slow to react to stimuli.

TopologyDefinitionSuitable for
Feed forwardThe connections connect the neurons of one level with the neurons of the next level. Backward connections or connections to the same level are not allowed.The only kind used in this course
RecurrentFeedback connections are expected — generally towards neurons of the same level, but also backward.Sequences, because they have a (short-term) memory effect
FEED FORWARD (USED IN THIS COURSE) input hidden output fully connected, one direction only RECURRENT feedback: same level, and backward gives a short-term memory effect, which makes it suitable for sequences
Plate 7.3 — The two topologies. In a feed-forward network the signal only moves right; a recurrent network re-injects it, and that loop is what gives it memory of what came before.

5. Activation functions

Activation functions define the output of the neuron given an input or set of inputs:

The three shown in the deck are ReLU, Sigmoid and Linear.

Widget — draw the activation

6. Universal approximation, and why depth

For the exam — Universal Approximation Theorem

A NN with at least 1 hidden layer can approximate any continuous function to any desired degree of accuracy, given sufficient neurons in that hidden layer, the right weights and biases, and a non-polynomial activation function.

And immediately, its four limitations — which are the interesting half:

Håstad's switching lemma

Håstad's switching lemma (Hastad 1986): certain functions, while easily represented by deep networks with a modest number of neurons, require an exponentially larger number of neurons to represent accurately if constrained to a single hidden layer. "Global" functions are harder to approximate, for instance:

This lemma provides a theoretical foundation for using depth in both circuit complexity and neural networks: it justifies the need for a layered structure when working with complex, globally-dependent functions.

Universal approximation for deep narrow networks

Kidger and Lyons (2020): let n be the number of input neurons, m the number of output neurons, and let ρ be any nonaffine continuous function with a continuous, nonzero derivative at some point. The class of neural networks of arbitrary depth, width n + m + 2, and activation function ρ, is dense in C(K; Rm) for K ⊆ Rn compact. This covers any activation function, including polynomial ones.

The deck draws the conclusion in one line: this is why deep neural networks work.

Key idea

Read the three results as one argument. The classical theorem says width is enough in principle; Håstad says width can cost exponentially more than depth; Kidger and Lyons say depth is enough too, with a fixed narrow width. Together they explain the shape of modern networks — deep rather than merely wide — and, importantly, none of the three tells you how to find the weights. That question is answered by gradient descent and backpropagation, further down this page.

7. Deep learning and the loss function

General considerations about neural network architectures: a greater number of hidden layers (therefore neurons) means better performance, but also the need for more training data and a greater computational load. Training a neural network is complicated, but specific frameworks exist — TensorFlow and PyTorch — exactly as scikit-learn plays that role in classical machine learning.

Deep Learning is a branch of ML that avoids the problematic phase of feature extraction (also) with high-dimensional inputs. Feature extraction requires human intervention — and often, this is the weak link in the chain.

Training a NN means tuning the weights to optimize the prediction accuracy, by minimizing a loss/cost function. The visual guide given on the slide, point by point:

  1. The surface is the solution space of the loss function: low values mean low error.
  2. The starting point is the output of the NN with initial (random) weights.
  3. The global minimum is the desired goal point.
  4. The learning procedure is performed in an iterative manner: following the gradient, the optimizers look for the (global) minimum.
  5. Each step is proportional to the learning rate adopted.
  6. There are local minima: the loss function of DL models usually has many of them, and the solution obtained by the final iteration may only locally minimize the loss.

The cost function is a mathematical formulation of the learning goal: it measures the error between the prediction and the ground truth (label), and presents the performance (or error) in the form of a single real number.

8. Softmax and cross entropy

Cross Entropy is the distance between what the model believes the output distribution should be and what the original distribution is. To use the Cross Entropy loss, the output layer must output probabilities.

Binary Cross Entropy (BCE)
  Loss = -yi * log(y_hat_i) - (1 - yi) * log(1 - y_hat_i)

Categorical Cross Entropy (CCE)
  Loss = - SUM over i of  yi * log(y_hat_i)

Softmax

The softmax layer transforms an n-dimensional vector of real numbers into a vector of real numbers in [0, 1] which adds up to 1. The softmax activation function determines the final probability value of each class:

p_i = e^(a_i) / SUM over k = 1..n of e^(a_k)

Softmax is a continuously differentiable function — which is not a detail, because the whole training procedure requires differentiability.

Cross entropy + softmax, on an image classifier

The deck follows one image through training: at first the network assigns a moderate probability to the correct class and the loss is 0.3677; after some training iterations the probability of the correct class is higher and the loss is 0.0923. The loss function has decreased.

Editor's note — reading the two numbers

The text extracted from the slide prints CCE = −log2 0.755 = 0.3677 and CCE = −log2 0.0938 = 0.0923. Neither line is arithmetically consistent as written, but the intended values are recoverable: 2^(−0.3677) = 0.775 and 2^(−0.0923) = 0.938. So the story is: the probability assigned to the correct class rises from about 0.775 to about 0.938, and the loss correspondingly falls from 0.3677 to 0.0923. Use the widget below to check the relationship yourself — that is what the slide is teaching, and it holds regardless of the typography.

Widget — softmax and cross entropy

9. Gradient descent, SGD and Adam

How to minimize the loss? Adjusting (changing) the weights and the bias of every neuron.

Gradient descent is a method for unconstrained mathematical optimization: a first-order iterative algorithm for minimizing a differentiable multivariate function F(x). It takes repeated steps in the opposite direction of the gradient of F(x) at the current point — the direction of steepest descent. Conversely, stepping in the direction of the gradient leads to a trajectory that maximizes the function (gradient ascent).

If F(x) is defined and differentiable in a neighborhood of a point a, then F(x) decreases fastest in the direction of the negative gradient of F at a, that is −∇F(a). It follows that if

a(n+1) = a(n) - eta * grad F( a(n) )

then for a small enough step size or learning rate η ∈ R+, we have F(an) ≥ F(an+1).

GRADIENT DESCENT loss weight space (the solution space of the loss) start: random weights local minimum each step ~ learning rate global minimum LEARNING CURVES epochs loss training validation start of the overfitting the loss drops rapidly at first low loss values are good: this is an error, not a score
Plate 7.4 — Left: the descent, its step size, and the local minimum that a real loss surface is full of. Right: the diagnostic plot — while the training loss keeps falling, the validation loss turning upwards marks the beginning of overfitting.
  1. Start with random initial values for parameters (weights and biases).
  2. Use the current parameters to compute predictions on the training data.
  3. Compute the cost function.
  4. Calculate the gradient of the cost function with respect to each parameter, grad J(Theta).
  5. Adjust each parameter in the opposite direction of the gradient: Theta = Theta - eta * grad J(Theta).
  6. Repeat steps 2–5 for each epoch (iteration over the entire dataset) until the cost function converges to a minimum or reaches a predefined number of epochs.

Smooth convergence, but not recommended for huge training datasets: it is a slow and computationally expensive algorithm.

  1. Start with random values for parameters.
  2. Split the dataset into multiple small batches of a predefined size.
  3. For each mini-batch B: make predictions with the current parameters for each sample in B; calculate the cost or error for the mini-batch; compute the gradient of the cost function with respect to each parameter; adjust each parameter, Theta = Theta - eta * grad J(Theta; B).
  4. Go through all mini-batches until every sample in the dataset has been used once (one epoch), then shuffle the dataset and repeat for the next epoch.

Advantages: faster training — more frequent parameter updates than batch gradient descent, leading to faster convergence; efficient GPU/CPU utilization — mini-batches enable parallel processing.

Drawbacks: selecting an optimal batch size requires experimentation, as it affects both the speed and the stability of convergence; mini-batch gradient descent is less stable than full-batch gradient descent, especially for small batch sizes.

Adam (Adaptive Moment Estimation) is a stochastic gradient descent method with fewer parameters than SGD. It is based on two principles:

  • Momentum: an exponentially decaying average of past gradients to smooth out the gradients over multiple steps. This helps the optimizer move faster in the direction of the overall gradient, improving convergence speed.
  • Adaptive learning rates: a moving average tracks the squared gradients, adjusting the learning rate based on the variability of the gradient. Parameters with large (small) gradient changes get smaller (larger) learning rates.

It is the default solver of scikit-learn's MLPClassifier.

Widget — descend the loss

Set the learning rate and step. Too small and you crawl; too large and you overshoot the minimum entirely.

10. Batch, iterations, epoch

TermDefinition
Batch (size)The hyperparameter of gradient descent that controls the number of training samples to work through before the model's internal parameters are updated
#IterationsThe size of the training set divided by the batch size
EpochThe learning procedure is applied to the entire training dataset: one epoch means that each sample in the training set has had an opportunity to update the weights

The practical notes on batch size:

And on epochs: an epoch is comprised of one or more batches (or iterations), and the number of epochs is traditionally large (10, 100, 1000, …).

11. Delta rule and backpropagation

The delta rule

We can apply the Widrow-Hoff (delta) rule on the perceptron — a simple gradient descent technique. For a neuron j with activation function g(x), the delta rule for neuron j's i-th weight wji is:

delta w_ij = eta * (yi - y_hat_i) * g'(h_j) * xi

Backpropagation

Backpropagation — backward propagation of errors — propagates the error to the input of an ANN.

The introduction of backpropagation has been fundamental in training DNNs, and the delta rule is a special case of the more general backpropagation algorithm.

The four steps:

  1. Forward pass: the network takes input data, computes outputs layer by layer, and calculates a final prediction — y_hat = f^L(W^L f^(L-1)(W^(L-1) ... f^1(W^1 x) ...)).
  2. Loss calculation: the loss function quantifies the difference between the predicted output and the true output; given an input–output pair (x, y) it is C(y, f^L(W^L f^(L-1)(W^(L-1) ... f^2(W^2 f^1(W^1 x)) ...))).
  3. Backward pass: gradients are computed by propagating the error backward to each layer, using the chain rule.
  4. Parameter update: using gradient descent, each parameter (weight and bias) is updated to reduce the error.

The chain rule is used to differentiate composite functions: given f() and g() with y = f(g(x)), then dy/dx = dy/dg * dg/dx. The worked example on the slide:

y = sin(x^2)

  dy/dg = cos(g)  ;   dg/dx = 2x   ;   finally   dy/dx = cos(x^2) * 2x

In a DNN the same rule is chained through every hidden layer — where x is the input, zl is the weighted input of hidden layer l and al is its output — producing the long product of partial derivatives from the loss all the way back to the input.

For the exam — the whole training loop in six lines
  1. Loss function → the desired goal of the NN.
  2. Minimize the loss function → moving close to the goal.
  3. In practice this means adjusting weights (and bias) of the NN.
  4. Through gradient descent → optimizers, with parameters such as the learning rate and the batch size.
  5. Based on backpropagation + the chain rule.
  6. Therefore: the loss function must be differentiable.

And the practical warning attached to it: the choice of the right value of the learning rate is important.

12. Learning curves and the MLP in scikit-learn

It is common to create line plots that show epochs along the x-axis and the loss value of the model on the y-axis. These plots are called learning curves:

The MLP in scikit-learn

Every argument in that constructor is a concept from this chapter: the architecture, the activation function, the optimizer, the batch size, the learning rate schedule, the number of epochs, and the shuffling that mini-batch SGD requires.

13. Developing AI systems: ML vs DL, and hardware

It is not just important how well a particular classifier works. The main steps of an AI project are known — data collection, data processing (and feature extraction), model training, prediction analysis through metrics — but other considerations remain: when to address a problem through ML? when through DL? what hardware and software resources are needed?

ElementMachine LearningDeep Learning
DataLarge data (~ hundreds)Huge data (~ thousands)
AccuracyHigh accuracyBest accuracy (high-dimensional data)
Training time~ minutes~ hours, days
HardwareCPUGPU
FeaturesManualLearned
InterpretabilityGoodLow

Hardware for deep learning

The training of NNs, especially deep ones, requires specialized hardware: before starting a project with DL, you need to ask if the company or lab has the necessary hardware. Having one or more GPUs is today a fundamental factor — GPUs are essential for parallelizing (and therefore speeding up) calculations, and the deeper a network is, the more computational load is introduced. To date Nvidia dominates the market: parallelization is made possible by the CUDA libraries (Compute Unified Device Architecture, the true core business of Nvidia), and Google has started a competition by introducing the TPU (Tensor Processor Unit).

In-house solutionExternal solution (PaaS / cloud)
What it isThe company buys the necessary hardware and is the direct ownerThe hardware is rented through the PaaS paradigm
ProsExtreme freedom of use of hardware; in the long run it tends to have lower costsHardware maintenance is not required; no investment over time for upgrades; dedicated server rooms are not required and energy consumption is not borne by the company
ConsHardware maintenance requires specialized technicians; hardware ages quickly; for large numbers of GPUs you need server rooms with temperature and access control, and high energy consumption (a latest-generation GPU draws ~450 W); the GPU market is expensive and volatile — very few companies are involved in production (TSMC), semiconductor shortages, and external factors such as mining and warsIn the long run it tends to have higher costs; plus the classic cloud problems: vendor lock-in, who really owns the data, and privacy issues

The deck points at cost calculators (Google Cloud, LeaderGPU, Colab Pro, AWS) and closes the economic argument with two references: the piece "Saying 'Thank You' to ChatGPT Is Costly. But Maybe It's Worth the Price", and Cottier et al. (2024) on the rising costs of training frontier AI models. The very last slide returns to where Chapter 1 started: classic programming on one side, deep learning on the other.

Check your understanding

Describe the artificial neuron and its four design decisions.

The first scheme of the neuron is by McCulloch and Pitts (1943); the first Artificial Neuron by Rosenblatt in 1957. Its inputs are digital numbers (not analog signals); they are weighted, because signals are not all equally important; they are merged with a sum function plus a bias; and an activation function generates the final output — like the brain, which filters inputs because it is impossible to always take everything into account. The example given: y' = 1 if 0.3·x1 + 0.8·x2 + 0.5·x3 ≥ 3, else 0.

Why can a single artificial neuron not compute XOR?

Because a single AN can solve only linear problems: it computes a weighted sum and thresholds it, which draws a single straight boundary in the input space. AND and OR are linearly separable, XOR is not — no single line puts the two 1-outputs on one side. The solution is to use more ANs organized on different layers, the Multi-Layer Perceptron; this is not easy, since it introduces several mathematical problems and greatly increases the computational load.

What are the layers of an ANN, and what is the difference between feed-forward and recurrent?

An input layer, an output layer and one or more hidden layers, with each neuron fully connected to those of the next level. Feed forward: connections go from one level to the next, and backward connections or connections to the same level are not allowed. Recurrent: feedback connections are expected, generally towards neurons of the same level but also backward, which gives a short-term memory effect and makes them suitable for sequences. This course uses only feed-forward networks.

What is an activation function?

It defines the output of the neuron given an input or set of inputs: it outputs a small value for small inputs and a larger value if the inputs exceed a threshold. It is a sort of switch of the artificial neuron. The three shown are ReLU, Sigmoid and Linear.

State the Universal Approximation Theorem and its four limitations.

A NN with at least 1 hidden layer can approximate any continuous function to any desired degree of accuracy, given sufficient neurons in that hidden layer, the right weights and biases, and a non-polynomial activation function. Limitations: it applies to feedforward networks with n inputs, a single hidden layer and 1 output; a close approximation may need an impractically large number of neurons, making the network hard to train; it assumes the right weights and biases exist but does not say how to find them; and it is not applicable to discontinuous functions.

What does Håstad's switching lemma add, and what are parity and majority?

It says that certain functions, easily represented by deep networks with a modest number of neurons, require an exponentially larger number of neurons if constrained to a single hidden layer; "global" functions are harder to approximate. The parity function determines whether the number of 1s in a binary input string is odd or even; the majority function outputs 1 if more than half of the input bits are 1. The lemma is the theoretical foundation for using depth, in circuit complexity and in neural networks alike.

What is deep learning, in the definition given?

A branch of ML that avoids the problematic phase of feature extraction, also with high-dimensional inputs. Feature extraction requires human intervention, and this is often the weak link in the chain. The trade-off appears in the comparison table: more data (~thousands vs ~hundreds), best accuracy on high-dimensional data, training in hours or days rather than minutes, GPU rather than CPU, features learned rather than manual, and low interpretability instead of good.

Define cross entropy and write BCE and CCE.

Cross entropy is the distance between what the model believes the output distribution should be and what the original distribution is; to use it, the output layer must output probabilities. BCE: Loss = −yi·log(y_hat_i) − (1 − yi)·log(1 − y_hat_i), where the first term cancels out if the target is 0 and the second if the target is 1. CCE: Loss = − SUM_i yi·log(y_hat_i).

What does the softmax layer do?

It transforms an n-dimensional vector of real numbers into a vector of real numbers in [0, 1] which adds up to 1, determining the final probability value of each class: p_i = e^(a_i) / SUM_k e^(a_k). It is continuously differentiable, which matters because the whole training procedure requires differentiability.

Write the gradient descent update and explain the role of eta.

a(n+1) = a(n) − eta · grad F(a(n)). Gradient descent is a first-order iterative algorithm for minimizing a differentiable multivariate function, taking repeated steps in the opposite direction of the gradient — the direction of steepest descent. For a small enough step size or learning rate eta > 0, F(an) ≥ F(an+1): each step is proportional to the learning rate, and choosing it well is important — too small and convergence crawls, too large and the steps overshoot.

Compare vanilla gradient descent, mini-batch SGD and Adam.

Vanilla: compute the cost and gradient over the entire dataset, then update once per epoch — smooth convergence, but slow and computationally expensive, not recommended for huge datasets. Mini-batch SGD: split into small batches and update once per batch, shuffling after each epoch — faster training and efficient GPU/CPU utilization, at the cost of needing experimentation for the batch size and being less stable, especially for small batches. Adam: an SGD method with fewer parameters, combining momentum (an exponentially decaying average of past gradients, smoothing them) and adaptive learning rates (a moving average of squared gradients; parameters with large gradient changes get smaller learning rates and vice versa).

Define batch size, iterations and epoch.

Batch size: the hyperparameter controlling the number of training samples to work through before the model's internal parameters are updated; typically a multiple of a power of two (16, 32, 64), too small compromises stability, larger uses more video memory, and empirically it may be at least equal to the number of classes. #Iterations = size of the training set / batch size. Epoch: the learning procedure applied to the entire training dataset — each sample has had an opportunity to update the weights; an epoch comprises one or more batches, and the number of epochs is traditionally large (10, 100, 1000).

Write the delta rule and explain each symbol.

delta w_ij = eta (yi − y_hat_i) g'(h_j) xi, the Widrow-Hoff rule, a simple gradient descent technique for the perceptron. xi is the i-th input; h_j = SUM_i xi·w_ji is the weighted sum of inputs; g'() is the derivative of the activation function; y_hat_i is the actual output and yi the target; eta is the learning rate. The delta rule is a special case of backpropagation.

Explain backpropagation in four steps, and say why the chain rule is needed.

(1) Forward pass: compute outputs layer by layer up to a prediction. (2) Loss calculation: quantify the difference between prediction and true output. (3) Backward pass: compute gradients by propagating the error backward to each layer, using the chain rule. (4) Parameter update: adjust each weight and bias by gradient descent. The chain rule is needed because we cannot directly compute the derivative of the loss with respect to the network outputs, and because backpropagation is a local process — neurons are completely unaware of the complete topology. Example: y = sin(x²) gives dy/dx = cos(x²)·2x.

What are learning curves and what do they diagnose?

Line plots with epochs on the x-axis and the loss value on the y-axis, usually two overlapped — one for training, one for validation. Since these are loss values, low is good. They help diagnose whether the model has over-learned (overfitting), under-learned (underfitting), or suitably fits the training set. Typically the loss drops rapidly at the beginning; the point where the validation curve stops improving while the training curve keeps falling marks the start of overfitting.

In-house or cloud GPUs? Give the trade-off.

In-house: extreme freedom of use and lower costs in the long run, but hardware maintenance requiring specialized technicians, quick ageing and repeated investment, and — with many GPUs — server rooms with temperature and access control plus high energy consumption (a latest-generation GPU draws about 450 W); the GPU market is expensive and volatile, with very few producers (TSMC), semiconductor shortages, and external factors such as mining and wars. External / PaaS: no maintenance, no upgrade investment, no server room or energy bill, but higher costs in the long run plus the classic cloud issues — vendor lock-in, data ownership, and privacy.