Neural networks

Lecture 5 · Machine Learning for ICE · University of Klagenfurt, 2023

Nunzio Alexandro Letizia

This lecture

Lecture 5 of 8

  1. Why deep learning
  2. Neural networks from scratch: forward pass, cost, gradient descent
  3. Back-propagation
  4. Activations and losses

From Machine Learning for ICE at the University of Klagenfurt, first taught in 2022: this is the 2023 edition, so some of it may be a little dated. All lectures.

Why deep learning

01

AI, machine learning, deep learning

  • Artificial intelligence: programs able to solve tasks like humans.
  • Machine learning: algorithms able to learn without being explicitly programmed.
  • Deep learning: the subset of machine learning in which artificial neural networks adapt and learn from vast amounts of data.

Three nested circles: deep learning inside machine learning inside artificial intelligence.

What is it? Extracting useful patterns from data.

How? Neural networks, Python, ML and DL frameworks.

Challenges? Good data, good questions, good architectures.

Why now? Huge amounts of data, hardware, open-source code, investments and communities.

Why deep learning

  • Deep learning is a scalable version of machine learning: performance keeps growing with data, where classic methods plateau.
  • Deep learning is also representation learning (feature learning): the network finds the features itself, instead of an engineer designing them. And representation matters a lot.

Performance against amount of data: classic machine learning flattens out, deep learning keeps growing.

It now runs handwriting recognition, object recognition and image classification, speech recognition, face identification, game playing, medical diagnosis, finance, social networks, web search, content generation, protein folding, geospatial analysis, weather forecasting, and more.

Neural networks from scratch

02

Artificial neural networks

An artificial neural network is a network of simple elements, the artificial neurons. Each one combines its inputs with weights, adds a bias, and passes the result through an activation function f:

A neuron: three inputs multiplied by weights, summed with a bias and passed through the activation function.

The network connecting inputs and outputs is a weighted graph. Learning means changing the weights.

The forward pass

Layer by layer, the activation of neuron j in layer l is

a_j^l=f\Big(\sum_kw_{jk}^l\,a_k^{l-1}+b_j^l\Big)

or compactly, with \mathbf{w}^l the matrix of the weights w_{jk}^l from neuron k in layer l-1 to neuron j in layer l,

\mathbf{a}^l=f\big(\mathbf{w}^l\mathbf{a}^{l-1}+\mathbf{b}^l\big)=f(\mathbf{z}^l)

A fully connected network with an input layer, two hidden layers and an output layer; one weight between the hidden layers is highlighted.

Universal approximation. A network with a single hidden layer, enough neurons and a non-linear activation can approximate any continuous function (on a compact set) as closely as we like.

The cost

Input data Neural network Prediction Measure of error Adjust to reduce the error

forward pass, then backward pass

The cost C(\cdot) measures how far a solution is from the optimal one: non-negative, close to 0 for accurate predictions, large for large errors.

For example, find weights and biases such that the network output \mathbf{a}^L approximates \mathbf{y}_i for every input \mathbf{x}_i, by minimizing the mean squared error

C(\mathbf{w},\mathbf{b})=\frac{1}{2N}\sum_{i=1}^N\big\lVert\mathbf{y}_i-\mathbf{a}^L(\mathbf{x}_i)\big\rVert^2

where \mathbf{a}^L depends both on the input and on the parameters of the network.

Gradient descent

From calculus (ignoring the bias),

\Delta C\approx\nabla_{\mathbf{w}}C\cdot\Delta\mathbf{w}

and choosing the step \Delta\mathbf{w}=-\eta\,\nabla_{\mathbf{w}}C guarantees at each iteration

\Delta C\approx-\eta\,\lVert\nabla_{\mathbf{w}}C\rVert^2\le0

so the error decreases. With mini-batches of m samples, the updates are

w_k'=w_k-\eta\frac{\partial C}{\partial w_k}\approx w_k-\frac{\eta}{m}\sum_j\frac{\partial C_{\mathbf{x}_j}}{\partial w_k},\qquad b_l'=b_l-\eta\frac{\partial C}{\partial b_l}\approx b_l-\frac{\eta}{m}\sum_j\frac{\partial C_{\mathbf{x}_j}}{\partial b_l}

\eta is the learning rate: too small and training crawls, too large and it overshoots and oscillates, as in the zig-zag on the right.

Contour lines of a cost and the zig-zag path of gradient descent towards the minimum.

Back-propagation

03

The output error

We need \dfrac{\partial C}{\partial w_{jk}^l} and \dfrac{\partial C}{\partial b_j^l} for every weight and bias. Back-propagation computes all of them in one sweep. Write

a_j^l=\sigma(z_j^l),\qquad z_j^l=\sum_kw_{jk}^la_k^{l-1}+b_j^l

and define the error of neuron j in the output layer L as \delta_j^L=\dfrac{\partial C}{\partial z_j^L}. By the chain rule,

\delta_j^L=\sum_k\frac{\partial C}{\partial a_k^L}\frac{\partial a_k^L}{\partial z_j^L}=\frac{\partial C}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}=\frac{\partial C}{\partial a_j^L}\,\sigma'(z_j^L)

since a_k^L only depends on z_k^L. In vector form,

\boldsymbol\delta^L=\nabla_{\mathbf{a}}C\odot\sigma'(\mathbf{z}^L)

The error, backwards

Define the error in any layer, \delta_j^l=\dfrac{\partial C}{\partial z_j^l}. The idea is to express \delta^l through \delta^{l+1}:

\delta_j^l=\frac{\partial C}{\partial z_j^l}=\sum_k\frac{\partial C}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^l}=\sum_k\frac{\partial z_k^{l+1}}{\partial z_j^l}\,\delta_k^{l+1}

By definition

z_k^{l+1}=\sum_jw_{kj}^{l+1}a_j^l+b_k^{l+1}=\sum_jw_{kj}^{l+1}\sigma(z_j^l)+b_k^{l+1}

and differentiating, \dfrac{\partial z_k^{l+1}}{\partial z_j^l}=w_{kj}^{l+1}\sigma'(z_j^l), so

\delta_j^l=\sum_kw_{kj}^{l+1}\,\delta_k^{l+1}\,\sigma'(z_j^l)

The four equations

From the errors, the gradients come for free:

\frac{\partial C}{\partial w_{jk}^l}=\frac{\partial C}{\partial z_j^l}\frac{\partial z_j^l}{\partial w_{jk}^l}=a_k^{l-1}\delta_j^l,\qquad\frac{\partial C}{\partial b_j^l}=\frac{\partial C}{\partial z_j^l}\frac{\partial z_j^l}{\partial b_j^l}=\delta_j^l

Back-propagation. \begin{aligned} \boldsymbol\delta^L&=\nabla_{\mathbf{a}}C\odot\sigma'(\mathbf{z}^L)&\qquad\frac{\partial C}{\partial b_j^l}&=\delta_j^l\\[0.3em] \boldsymbol\delta^l&=\big((\mathbf{w}^{l+1})^T\boldsymbol\delta^{l+1}\big)\odot\sigma'(\mathbf{z}^l)&\qquad\frac{\partial C}{\partial w_{jk}^l}&=a_k^{l-1}\delta_j^l \end{aligned}

Then update weights and biases by gradient descent.

Notation after M. Nielsen, Neural Networks and Deep Learning, chapter 2.

Activations and losses

04

Activation functions

The activation \sigma(\cdot) matters a lot during training: it enters every error, starting from \boldsymbol\delta^L=\nabla_{\mathbf{a}}C\odot\sigma'(\mathbf{z}^L). Activations differ by their range and their derivative.

Activation \sigma(z) Range
Linear z (-\infty,+\infty)
Sigmoid \dfrac{1}{1+e^{-z}} (0,1)
Hyperbolic tangent \dfrac{e^z-e^{-z}}{e^z+e^{-z}} (-1,1)
ReLU \max(0,z) [0,+\infty)
Softmax \dfrac{e^{z_j}}{\sum_ke^{z_k}} (0,1), with \sum_k\sigma(z_k)=1

Activations, in a picture

Plots of the linear, sigmoid, hyperbolic tangent and ReLU activation functions.

The sigmoid and tanh saturate: for large \lvert z\rvert their derivative vanishes, and so does \boldsymbol\delta, which slows deep networks down. The ReLU does not saturate for z>0, which is a big part of why it became the default in hidden layers.

Loss functions

The loss C(\cdot) depends on the task.

Regression: predict real values y_i. A last linear layer, and the mean squared error

C(\mathbf{w},\mathbf{b})=\frac{1}{2N}\sum_{i=1}^N\big\lVert\mathbf{y}_i-\mathbf{a}^L(\mathbf{x}_i)\big\rVert^2\approx\frac12\,\mathbb{E}\big[\lVert\mathbf{y}-\mathbf{a}^L(\mathbf{x})\rVert^2\big]

Classification: predict one of M classes. The true class of \mathbf{x}_i is a one-hot vector \mathbf{p}(\mathbf{x}_i)=[0,\dots,0,1,0,\dots,0], with the 1 at the position of the class y_i. The network models the probabilities \mathbf{q}(\mathbf{x}_i) with M output neurons and a softmax, and is trained by minimizing the cross-entropy

C(\mathbf{w},\mathbf{b})=-\frac1N\sum_{i=1}^N\sum_{j=1}^Mp_j(\mathbf{x}_i)\log q_j(\mathbf{x}_i)

A neural decoder

Let X\in\{-1,1\} be the samples transmitted over the non-linear Gaussian channel of lectures 3 and 4,

Y=X+4\epsilon\cdot\mathbb{1}(-X)+N,\qquad\epsilon\sim\mathrm{Bernoulli}(0.5),\quad N\sim\mathcal{N}(0,\sigma^2)

Train a feed-forward neural network classifier that learns to decode Y by minimizing the cross-entropy. Show the accuracy of the model and the decision boundaries.

Activity 6: the outcome

# sigma = 0.4, the non-linear channel (linear_flag = 0)
model = Sequential()
model.add(Dense(100, input_dim=1, activation='relu'))
model.add(Dense(2, activation='softmax'))
# ...
self.combined.compile(loss='categorical_crossentropy',
                      optimizer=Adam(0.005, 0.5))

for epoch in range(epochs):    # 100 steps, batches of 32
    batch = np.random.randint(7500, size=(batch_size, 1))
    y_cat = to_categorical(y_train[batch, 0], num_classes=2)
    d_loss = self.combined.train_on_batch(X_train[batch, 0], y_cat)
The accuracy of the classifier is: 0.9924

One hidden layer of 100 neurons decodes 99.2% of the test samples: it learns that +1 lives between the two humps of -1. The notebook’s own plot of the posterior is scrambled, because it sorts y but not the probabilities: plot probs[idx] against X_test[idx], with idx = np.argsort(X_test[:, 0]).

Cross-entropy training loss falling over 100 epochs.

the cross-entropy over the 100 training steps

The exact posterior probabilities of the two symbols against the received sample: plus one wins between about zero and two, minus one outside.

what the network approximates: the exact posterior, by Bayes