From 57a03deeefbde44d65492e92b5350d27d7019911 Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Sat, 19 Oct 2024 09:10:40 +0200 Subject: [PATCH] update week 43 --- doc/pub/week43/html/week43-bs.html | 4283 +++++++-------- doc/pub/week43/html/week43-reveal.html | 4347 +++++++-------- doc/pub/week43/html/week43-solarized.html | 4218 +++++++-------- doc/pub/week43/html/week43.html | 4218 +++++++-------- doc/pub/week43/ipynb/ipynb-week43-src.tar.gz | Bin 192 -> 192 bytes doc/pub/week43/ipynb/week43.ipynb | 5102 +++++++++--------- doc/src/week43/week43.do.txt | 3261 ++++++----- 7 files changed, 12063 insertions(+), 13366 deletions(-) diff --git a/doc/pub/week43/html/week43-bs.html b/doc/pub/week43/html/week43-bs.html index 8f00c1bfc..f35ec26e7 100644 --- a/doc/pub/week43/html/week43-bs.html +++ b/doc/pub/week43/html/week43-bs.html @@ -37,6 +37,19 @@ doconce format html week43.do.txt --html_style=bootstrap --pygments_html_style=d
  • Plans for week 43
  • +
  • Exercises and lab session week 43
  • +
  • Mathematics of deep learning
  • +
  • Reminder on books with hands-on material and codes
  • +
  • Reading recommendations
  • Using Automatic differentiation
  • Back propagation and automatic differentiation
  • -
  • Material for exercises week 43 and week 44
  • -
  • Writing our first neural network code, testing it for the OR and XOR gates
  • -
  • The AND and XOR Gates
  • -
  • Representing the Data Sets
  • -
  • Setting up dimensionalities by hand
  • -
  • Setting up the Neural Network
  • -
  • The Code using Scikit-Learn
  • -
  • Building a neural network code
  • -
  •    Learning rate methods
  • -
  •    Usage of the above learning rate schedulers
  • -
  •    Cost functions
  • -
  •    Activation functions
  • -
  •    The Neural Network
  • -
  •    Multiclass classification
  • -
  • Testing the XOR gate and other gates
  • -
  • Lecture Thursday October 26
  • +
  • Lecture Monday October 21
  • +
  • Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations
  • +
  • Setting up the back propagation algorithm, part 1
  • +
  • Setting up the back propagation algorithm, part 2
  • +
  • Setting up the Back propagation algorithm, part 3
  • +
  • Updating the gradients
  • +
  • Activation functions
  • +
  •    Activation functions, examples
  • +
  • The RELU function family
  • +
  • ELU function
  • +
  • Which activation function should we use?
  • +
  • More on activation functions, output layers
  • +
  • Setting up a Multi-layer perceptron model for classification
  • +
  • Defining the cost function
  • +
  • Example: binary classification problem
  • +
  • The Softmax function
  • Developing a code for doing neural networks with back propagation
  • Collect and pre-process data
  • Train and test datasets
  • @@ -393,20 +389,14 @@ MathJax.Hub.Config({
  • Using Keras
  • Collect and pre-process data
  • The Breast Cancer Data, now with Keras
  • -
  • Fine-tuning neural network hyperparameters
  • -
  • Hidden layers
  • -
  • Which activation function should I use?
  • -
  • Is the Logistic activation function (Sigmoid) our choice?
  • -
  • The derivative of the Logistic funtion
  • -
  • The RELU function family
  • -
  • Which activation function should we use?
  • -
  • More on activation functions, output layers
  • -
  • Batch Normalization
  • -
  • Dropout
  • -
  • Gradient Clipping
  • -
  • A very nice website on Neural Networks
  • -
  • A top-down perspective on Neural networks
  • -
  • Limitations of supervised learning with deep networks
  • +
  • Building a neural network code
  • +
  •    Learning rate methods
  • +
  •    Usage of the above learning rate schedulers
  • +
  •    Cost functions
  • +
  •    Activation functions
  • +
  •    The Neural Network
  • +
  •    Multiclass classification
  • +
  • Testing the XOR gate and other gates
  • Solving ODEs with Deep Learning
  • Ordinary Differential Equations
  • The trial solution
  • @@ -483,7 +473,7 @@ MathJax.Hub.Config({
    -

    Oct 26, 2023

    +

    Oct 19, 2024


    @@ -497,39 +487,62 @@ MathJax.Hub.Config({
    +
    + + + + +

    Exercises and lab session week 43

    +
    +
    + +
      +
    • Exercise on writing your own neural network code
    • The exercises this week will be continued next week as well
    • Discussion of project 2
    • -
    • Video of lab session
    + +

    Mathematics of deep learning

    + +
    + +
    + + + +

    Reminder on books with hands-on material and codes

    -

    I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at http://neuralnetworksanddeeplearning.com/chap4.html.

    + +

    Reading recommendations

    + +
      +
    1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub. See also chapters 12 and 13 on using Pytorch to make a Neural network code.
    2. +
    3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
    4. +

    Using Automatic differentiation

    a @@ -548,172 +561,405 @@ t

  • Slides 12-44 at URL":http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf"
  • -

    Material for exercises week 43 and week 44

    +

    Lecture Monday October 21

    -

    Writing our first neural network code, testing it for the OR and XOR gates

    +

    Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

    +

    This is a reminder from where we ended last week.

    -

    During week 41 we discussed three different types of gates, the -so-called XOR, the OR and the AND gates. In order to develop a code -for neural networks, it can be useful to set up a simpler system with -only two inputs and one output. This can make it easier to debug and -study the feed forward pass and the back propagation part. In the -exercise this and next week, we propose to study this system with just -one hidden layer and two hidden nodes. There is only one output node -and we can choose to use either a simple regression case (fitting a -line) or just a binary classification case with the corss-entropy as -cost function. +

    +
    + +
      +
    1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)
    2. +
    3. Define the number of hidden layers and hidden nodes
    4. +
    5. Define activation functions for hidden layers and output layers
    6. +
    7. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates
    8. +
    9. Define cost function and possible regularization terms with hyperparameters
    10. +
    11. Initialize weights and biases
    12. +
    13. Fix number of iterations for the feed forward part and back propagation part
    14. +
    +
    +
    + + + +

    Setting up the back propagation algorithm, part 1

    + +

    Let us write this out in the form of an algorithm.

    + +

    First, we set up the input data \( \boldsymbol{x} \) and the activations +\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and +the pertinent outputs \( \boldsymbol{a}^1 \).

    -

    Their inputs and outputs can be -summarized using the following tables, first for the OR gate with -inputs \( x_1 \) and \( x_2 \) and outputs \( y \): +

    Secondly, we perform then the feed forward till we reach the output +layer and compute all \( \boldsymbol{z}_l \) of the input layer and compute the +activation function and the pertinent outputs \( \boldsymbol{a}^l \) for +\( l=1,2,3,\dots,L \).

    -
    -
    - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 1
    1 0 1
    1 1 1
    -
    -
    +

    Notation: The first hidden layer has \( l=1 \) as label and the final output layer has \( l=L \).

    -

    The AND and XOR Gates

    +

    Setting up the back propagation algorithm, part 2

    -

    The AND gate is defined as

    +

    Thereafter we compute the ouput error \( \boldsymbol{\delta}^L \) by computing all

    +$$ +\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. +$$ -
    -
    - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 0
    1 0 0
    1 1 1
    -
    -
    +

    Then we compute the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

    +$$ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). +$$ -

    And finally we have the XOR gate

    - -
    -
    - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 1
    1 0 1
    1 1 0
    -
    -
    -

    Representing the Data Sets

    +

    Setting up the Back propagation algorithm, part 3

    -

    Our design matrix is defined by the input values \( x_1 \) and \( x_2 \). Since we have four possible outputs, our design matrix reads

    +

    Finally, we update the weights and the biases using gradient descent +for each \( l=L-1,L-2,\dots,1 \) (the first hidden layer) and update the weights and biases +according to the rules +

    $$ -\boldsymbol{X}=\begin{bmatrix} 0 & 0 \\ - 0 & 1 \\ - 1 & 0 \\ - 1 & 1 \end{bmatrix}, +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, $$ -

    while the vector of outputs is \( \boldsymbol{y}^T=[0,1,1,0] \) for the XOR gate, \( \boldsymbol{y}^T=[0,0,0,1] \) for the AND gate and \( \boldsymbol{y}^T=[0,1,1,1] \) for the OR gate.

    -

    Your tasks here are

    +$$ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +$$ + +

    with \( \eta \) being the learning rate.

    + + +

    Updating the gradients

    + +

    With the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

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

    we update the weights and the biases using gradient descent for each \( l=L-1,L-2,\dots,1 \) and update the weights and biases according to the rules

    +$$ +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, +$$ + + +$$ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +$$ + + + +

    Activation functions

    + +

    A property that characterizes a neural network, other than its +connectivity, is the choice of activation function(s). The following +restrictions are imposed on an activation function for an FFNN to +fulfill the universal approximation theorem +

    + + + +

    Activation functions, examples

    + +

    Typical examples are the logistic Sigmoid

    + +$$ + \sigma(x) = \frac{1}{1 + e^{-x}}, +$$ + +

    and the hyperbolic tangent function

    +$$ + \sigma(x) = \tanh(x) +$$ + + + +

    The RELU function family

    + +

    The ReLU activation function suffers from a problem known as the dying +ReLUs: during training, some neurons effectively die, meaning they +stop outputting anything other than 0. +

    + +

    In some cases, you may find that half of your network’s neurons are +dead, especially if you used a large learning rate. During training, +if a neuron’s weights get updated such that the weighted sum of the +neuron’s inputs is negative, it will start outputting 0. When this +happen, the neuron is unlikely to come back to life since the gradient +of the ReLU function is 0 when its input is negative. +

    + + +

    ELU function

    + +

    To solve this problem, nowadays practitioners use a variant of the +ReLU function, such as the leaky ReLU discussed above or the so-called +exponential linear unit (ELU) function +

    + +$$ +ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. +$$ + + + +

    Which activation function should we use?

    + +

    In general it seems that the ELU activation function is better than +the leaky ReLU function (and its variants), which is better than +ReLU. ReLU performs better than \( \tanh \) which in turn performs better +than the logistic function. +

    + +

    If runtime performance is an issue, then you may opt for the leaky +ReLU function over the ELU function If you don’t want to tweak yet +another hyperparameter, you may just use the default \( \alpha \) of +\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and +computing power, you can use cross-validation or bootstrap to evaluate +other activation functions. +

    + + +

    More on activation functions, output layers

    + +

    In most cases you can use the ReLU activation function in the hidden +layers (or one of its variants). +

    + +

    It is a bit faster to compute than other activation functions, and the +gradient descent optimization does in general not get stuck. +

    + +For the output layer: + + + +

    Setting up a Multi-layer perceptron model for classification

    + +

    We are now gong to develop an example based on the MNIST data +base. This is a classification problem and we need to use our +cross-entropy function we discussed in connection with logistic +regression. The cross-entropy defines our cost function for the +classificaton problems with neural networks. +

    + +

    In binary classification with two classes \( (0, 1) \) we define the +logistic/sigmoid function as the probability that a particular input +is in class \( 0 \) or \( 1 \). This is possible because the logistic +function takes any input from the real numbers and inputs a number +between 0 and 1, and can therefore be interpreted as a probability. It +also has other nice properties, such as a derivative that is simple to +calculate. +

    + +

    For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) +is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) +represents our activation values \( z \). We have +

    +$$ +P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , +$$ + +

    and

    +$$ +P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , +$$ + +

    where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases +of our network. +

    + + + +

    Defining the cost function

    + +

    Our cost function is given as (see the Logistic regression lectures)

    +$$ +\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n +y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . +$$ + +

    This last equality means that we can interpret our cost function as a sum over the loss function +for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). +The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather +than maximizing a negative number. +

    + +

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    + +

    \( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

    + +\( y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) , \) + +

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset (numbers from \( 0 \) to \( 9 \))..

    + +

    If \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th +output vector \( \boldsymbol{y}_i \). +The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: +

    + +$$ +P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} +{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , +$$ + +

    which reduces to the logistic function in the binary case. +The likelihood of this \( C \)-class classifier +is now given as: +

    + +$$ +P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . +$$ + +

    Again we take the negative log-likelihood to define our cost function:

    + +$$ +\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. +$$ + +

    See the logistic regression lectures for a full definition of the cost function.

    + +

    The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!

    + + +

    Example: binary classification problem

    + +

    As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as

    +$$ +\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right), +$$ + +

    where we had defined the logistic (sigmoid) function

    +$$ +p(y_i =1\vert x_i,\boldsymbol{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, +$$ + +

    and

    +$$ +p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). +$$ + +

    The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

    + +

    Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). +We have then +

    +$$ +a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, +$$ + +

    with

    +$$ +z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, +$$ + +

    where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). +Our cost function at the final layer \( l=L \) is now +

    +$$ +\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), +$$ + +

    where we have defined the targets \( t_i \). The derivatives of the cost function with respect to the output \( a_i^L \) are then easily calculated and we get

    +$$ +\frac{\partial \mathcal{C}(\boldsymbol{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. +$$ + +

    In case we use another activation function than the logistic one, we need to evaluate other derivatives.

    + + +

    The Softmax function

    +

    In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need

    +$$ +\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = +\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. +$$ + +

    For the Softmax function we have

    +$$ +f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. +$$ + +

    Its derivative with respect to \( z_j^l \) gives

    +$$ +\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), +$$ + +

    which in case of the simply binary model reduces to having \( i=j \).

    + + +

    Developing a code for doing neural networks with back propagation

    + +

    One can identify a set of key steps when using neural networks to solve supervised learning problems:

      -
    1. Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs.
    2. -
    3. Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function.
    4. -
    5. Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output.
    6. -
    7. Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets.
    8. -
    9. Set up the cost function (cross entropy for classification of binary cases).
    10. -
    11. Calculate the gradients needed for the back propagation part.
    12. -
    13. Use the gradients to train the network in the back propagation part. Think of using automatic differentiation.
    14. -
    15. Train the network and study your results and compare with results obtained either with scikit-learn or TensorFlow.
    16. +
    17. Collect and pre-process data
    18. +
    19. Define model and architecture
    20. +
    21. Choose cost function and optimizer
    22. +
    23. Train the model
    24. +
    25. Evaluate model performance on test data
    26. +
    27. Adjust hyperparameters (if necessary, network architecture)
    -

    Everything you develop here can be used directly into the code for the project.

    - -

    Setting up dimensionalities by hand

    +

    Collect and pre-process data

    -

    It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by

    -$$ -\boldsymbol{W_h}=\begin{bmatrix} 1 & 1 \\ - 1 & 1 \end{bmatrix}, -$$ +

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn +package. You may also find it for example here. +The MNIST (Modified National Institute of Standards and Technology) database is a large database +of handwritten digits that is commonly used for training various image processing systems. +The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. +The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. +

    -

    Multiplying \( \boldsymbol{X} \) and \( \boldsymbol{W} \) gives

    +

    To feed data into a feed-forward neural network we need to represent +the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each +row represents an input, in this case a handwritten digit, and +each column represents a feature, in this case a pixel. The +correct answers, also known as labels or targets are +represented as a 1D array of integers +\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). +

    -$$ -\boldsymbol{X}{W}_h=\begin{bmatrix} 0 & 0 \\ - 1 & 1 \\ - 1 & 1 \\ - 2 & 2 \end{bmatrix}, -$$ +

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from +measurements of height (in m) +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: +

    -

    Assume also that the bias vector for the hidden layer is

    -$$ -\boldsymbol{b}_h=\begin{bmatrix} 0 \\ - -1\end{bmatrix}, -$$ +

    $$ X = \begin{bmatrix} +1.85 & 81\\ +1.71 & 65\\ +1.95 & 103\\ +1.55 & 42\\ +1.63 & 56 +\end{bmatrix} ,$$ +

    -

    Adding it gives us the input to the activation function of the hidden layer

    -$$ -\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h=\begin{bmatrix} 0 & -1 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, -$$ +

    and the targets would be:

    -

    Let us then assume that our activation function is the RELU function, which simply means that we take the max of \( 0 \) and the elements of the input argument \( \boldsymbol{z}_h \), that is we have

    -$$ -\boldsymbol{a}_h=\mathrm{RELU}(\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h)=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, -$$ +

    $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

    -

    Assume also that the bias of the output layer is zero and that the weights of the output layer are

    -$$ -\boldsymbol{w}_o=\begin{bmatrix} 1 \\ - -2\end{bmatrix}, -$$ - -

    and multiplying with \( \boldsymbol{a}_h \) gives the output

    -$$ -\boldsymbol{a}_o=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}\begin{bmatrix} 1 \\ - -2\end{bmatrix}=\begin{bmatrix} 0 \\ 1 \\ 1 \\0\end{bmatrix}, -$$ - -

    the wanted result. Pay attention to the dimensionalities as well.

    - - -

    Setting up the Neural Network

    - -

    We define first our design matrix and the various output vectors for the different gates.

    +

    Since each input image is a 2D matrix, we need to flatten the image +(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a +design/feature matrix. This means we lose all spatial information in the +image, such as locality and translational invariance. More complicated +architectures such as Convolutional Neural Networks can take advantage +of such information, and are most commonly applied when analyzing +images. +

    @@ -722,63 +968,48 @@ $$
    -
    """
    -Simple code that tests XOR, OR and AND gates with linear regression
    -"""
    -
    -# import necessary packages
    +  
    # import necessary packages
     import numpy as np
     import matplotlib.pyplot as plt
     from sklearn import datasets
     
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    probabilities = sigmoid(z_o)
    -    return probabilities
    -
     
     # ensure the same random numbers appear every time
     np.random.seed(0)
     
    -# Design matrix
    -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
     
    -# The XOR gate
    -yXOR = np.array( [ 0, 1 ,1, 0])
    -# The OR gate
    -yOR = np.array( [ 0, 1 ,1, 1])
    -# The AND gate
    -yAND = np.array( [ 0, 0 ,0, 1])
     
    -# Defining the neural network
    -n_inputs, n_features = X.shape
    -n_hidden_neurons = 2
    -n_categories = 1
    -n_features = 2
    +# download MNIST dataset
    +digits = datasets.load_digits()
     
    -# we make the weights normally distributed using numpy.random.randn
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
     
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
     
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
     
    -probabilities = feed_forward(X)
    -print(probabilities)
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
     
    @@ -794,10 +1025,1117 @@ probabilities = feed_forward(X)
    -

    Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above.

    -

    The Code using Scikit-Learn

    +

    Train and test datasets

    + +

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    + +

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    + +

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure +no bias in the sampling. +Say you are taking measurements of weather data to predict the weather in the coming 5 days. +You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data +collected from 12.00 to 24.00. +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.model_selection import train_test_split
    +
    +# one-liner from scikit-learn library
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +# equivalently in numpy
    +def train_test_split_numpy(inputs, labels, train_size, test_size):
    +    n_inputs = len(inputs)
    +    inputs_shuffled = inputs.copy()
    +    labels_shuffled = labels.copy()
    +    
    +    np.random.shuffle(inputs_shuffled)
    +    np.random.shuffle(labels_shuffled)
    +    
    +    train_end = int(n_inputs*train_size)
    +    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    +    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    +    
    +    return X_train, X_test, Y_train, Y_test
    +
    +#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    +
    +print("Number of training images: " + str(len(X_train)))
    +print("Number of test images: " + str(len(X_test)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Define model and architecture

    + +

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    + +

    $$ z = \sum_{i=1}^n w_i a_i ,$$

    + +

    $$ y = f(z) ,$$

    + +

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer +and \( w_i \) is the weight to input \( i \). +The activation of the neurons in the input layer is just the features (e.g. a pixel value). +

    + +

    The simplest activation function for a neuron is the Heaviside function:

    + +

    $$ f(z) = +\begin{cases} +1, & z > 0\\ +0, & \text{otherwise} +\end{cases} +$$ +

    + +

    A feed-forward neural network with this activation is known as a perceptron. +For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. +This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), +and we call these architectures multiclass perceptrons. +

    + +

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and +Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. +

    + +

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). +We will be using the sigmoid function \( \sigma(x) \): +

    + +

    $$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$

    + +

    which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

    + + +

    Layers

    + + +

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    + + +

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. +Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. +

    + + +

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, +which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. +

    + +

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    + +

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    + +

    $$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} +{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ +

    + +

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. +The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. +The exponent is just the weighted sum of inputs as before: +

    + +

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

    + +

    Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 +weights to the output layer. +

    + + +

    Weights and biases

    + +

    Typically weights are initialized with small values distributed around zero, drawn from a uniform +or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. +

    + +

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range +of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): +

    + +

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

    + +

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    + + +
    +
    +
    +
    +
    +
    # building our neural network
    +
    +n_inputs, n_features = X_train.shape
    +n_hidden_neurons = 50
    +n_categories = 10
    +
    +# we make the weights normally distributed using numpy.random.randn
    +
    +# weights and bias in the hidden layer
    +hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    +hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    +
    +# weights and bias in the output layer
    +output_weights = np.random.randn(n_hidden_neurons, n_categories)
    +output_bias = np.zeros(n_categories) + 0.01
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Feed-forward pass

    + +

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. +For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): +

    + +

    $$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

    + +

    this is then passed through our activation function

    + +

    $$ a_{j}^{l} = f(z_{j}^{l}) .$$

    + +

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    + +

    $$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

    + +

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    + +

    $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} +{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ +

    + + +

    Matrix multiplications

    + +

    Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden +layer have the dimensions +\( W_{hidden} = (n_{features}, n_{hidden}) \), +we can easily feed the network all our training data in one go by taking the matrix product +

    + +

    $$ X W^{h} = (n_{inputs}, n_{hidden}),$$

    + +

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer +for each input image and each hidden neuron. +We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): +

    + +

    $$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

    + +

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. +This is then passed through the activation: +

    + +

    $$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

    + +

    This is fed to the output layer:

    + +

    $$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

    + +

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    + +

    $$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

    + + + +
    +
    +
    +
    +
    +
    # setup the feed-forward pass, subscript h = hidden layer
    +
    +def sigmoid(x):
    +    return 1/(1 + np.exp(-x))
    +
    +def feed_forward(X):
    +    # weighted sum of inputs to the hidden layer
    +    z_h = np.matmul(X, hidden_weights) + hidden_bias
    +    # activation in the hidden layer
    +    a_h = sigmoid(z_h)
    +    
    +    # weighted sum of inputs to the output layer
    +    z_o = np.matmul(a_h, output_weights) + output_bias
    +    # softmax output
    +    # axis 0 holds each input and axis 1 the probabilities of each category
    +    exp_term = np.exp(z_o)
    +    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +    
    +    return probabilities
    +
    +probabilities = feed_forward(X_train)
    +print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    +print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    +print("probabilities sum up to: " + str(probabilities[0].sum()))
    +print()
    +
    +# we obtain a prediction by taking the class with the highest likelihood
    +def predict(X):
    +    probabilities = feed_forward(X)
    +    return np.argmax(probabilities, axis=1)
    +
    +predictions = predict(X_train)
    +print("predictions = (n_inputs) = " + str(predictions.shape))
    +print("prediction for image 0: " + str(predictions[0]))
    +print("correct label for image 0: " + str(Y_train[0]))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Choose cost function and optimizer

    + +

    To measure how well our neural network is doing we need to introduce a cost function. +We will call the function that gives the error of a single sample output the loss function, and the function +that gives the total error of our network across all samples the cost function. +A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. +

    + +

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    + +

    $$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

    + +

    $$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$

    + +

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

    + +

    Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. +We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. +

    + +

    In the one-hot representation only one of the terms in the loss function is non-zero, namely the +probability of the correct category \( c' \) +(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong +you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. +

    + + + +

    Optimizing the cost function

    + +

    The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent +is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. +Each parameter \( \theta \) is iteratively adjusted according to the rule +

    + +

    $$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

    + +

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. +This update can be repeated for any number of iterations, or until we are satisfied with the result. +

    + +

    A simple and effective improvement is a variant called Batch Gradient Descent. +Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient +on a subset of the data called a minibatch. +If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches +is \( N/M \). +We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: +

    + +

    $$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ +

    + +

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    + +

    This has two important benefits:

    +
      +
    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. +
    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. +
    +

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    + + +

    Regularization

    + +

    It is common to add an extra term to the cost function, proportional +to the size of the weights. This is equivalent to constraining the +size of the weights, so that they do not grow out of control. +Constraining the size of the weights means that the weights cannot +grow arbitrarily large to fit the training data, and in this way +reduces overfitting. +

    + +

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    + +

    $$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ +

    + +

    i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

    + +

    In order to train the model, we need to calculate the derivative of +the cost function with respect to every bias and weight in the +network. In total our network has \( (64 + 1)\times 50=3250 \) weights in +the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output +layer (\( +1 \) for the bias), and the gradient must be calculated for +every parameter. We use the backpropagation algorithm discussed +above. This is a clever use of the chain rule that allows us to +calculate the gradient efficently. +

    + + +

    Matrix multiplication

    + +

    To more efficently train our network these equations are implemented using matrix operations. +The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, +

    + +

    $$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

    + +

    The gradient for the output weights is calculated as

    + +

    $$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

    + +

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. +Since we are going backwards we have to transpose the activation matrix. +

    + +

    The gradient with respect to the output bias is then

    + +

    $$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

    + +

    The error in the hidden layer is

    + +

    $$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

    + +

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean +that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes +the Hadamard product, meaning element-wise multiplication. +

    + +

    This again gives us the gradients in the hidden layer:

    + +

    $$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

    + +

    $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

    + + + +
    +
    +
    +
    +
    +
    # to categorical turns our integer vector into a onehot representation
    +from sklearn.metrics import accuracy_score
    +
    +# one-hot in numpy
    +def to_categorical_numpy(integer_vector):
    +    n_inputs = len(integer_vector)
    +    n_categories = np.max(integer_vector) + 1
    +    onehot_vector = np.zeros((n_inputs, n_categories))
    +    onehot_vector[range(n_inputs), integer_vector] = 1
    +    
    +    return onehot_vector
    +
    +#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    +Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    +
    +def feed_forward_train(X):
    +    # weighted sum of inputs to the hidden layer
    +    z_h = np.matmul(X, hidden_weights) + hidden_bias
    +    # activation in the hidden layer
    +    a_h = sigmoid(z_h)
    +    
    +    # weighted sum of inputs to the output layer
    +    z_o = np.matmul(a_h, output_weights) + output_bias
    +    # softmax output
    +    # axis 0 holds each input and axis 1 the probabilities of each category
    +    exp_term = np.exp(z_o)
    +    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +    
    +    # for backpropagation need activations in hidden and output layers
    +    return a_h, probabilities
    +
    +def backpropagation(X, Y):
    +    a_h, probabilities = feed_forward_train(X)
    +    
    +    # error in the output layer
    +    error_output = probabilities - Y
    +    # error in the hidden layer
    +    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    +    
    +    # gradients for the output layer
    +    output_weights_gradient = np.matmul(a_h.T, error_output)
    +    output_bias_gradient = np.sum(error_output, axis=0)
    +    
    +    # gradient for the hidden layer
    +    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    +    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    +
    +    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    +
    +print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    +
    +eta = 0.01
    +lmbd = 0.01
    +for i in range(1000):
    +    # calculate gradients
    +    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    +    
    +    # regularization term gradients
    +    dWo += lmbd * output_weights
    +    dWh += lmbd * hidden_weights
    +    
    +    # update weights and biases
    +    output_weights -= eta * dWo
    +    output_bias -= eta * dBo
    +    hidden_weights -= eta * dWh
    +    hidden_bias -= eta * dBh
    +
    +print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Improving performance

    + +

    As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. +In order to obtain a network that does something useful, we will have to do a bit more work. +

    + +

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    + +

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period +going through the entire dataset (\( n/M \) batches) an epoch. +

    + +

    If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. +Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. +

    + + +

    Full object-oriented implementation

    + +

    It is very natural to think of the network as an object, with specific instances of the network +being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. +

    + + + +
    +
    +
    +
    +
    +
    class NeuralNetwork:
    +    def __init__(
    +            self,
    +            X_data,
    +            Y_data,
    +            n_hidden_neurons=50,
    +            n_categories=10,
    +            epochs=10,
    +            batch_size=100,
    +            eta=0.1,
    +            lmbd=0.0):
    +
    +        self.X_data_full = X_data
    +        self.Y_data_full = Y_data
    +
    +        self.n_inputs = X_data.shape[0]
    +        self.n_features = X_data.shape[1]
    +        self.n_hidden_neurons = n_hidden_neurons
    +        self.n_categories = n_categories
    +
    +        self.epochs = epochs
    +        self.batch_size = batch_size
    +        self.iterations = self.n_inputs // self.batch_size
    +        self.eta = eta
    +        self.lmbd = lmbd
    +
    +        self.create_biases_and_weights()
    +
    +    def create_biases_and_weights(self):
    +        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    +        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    +
    +        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    +        self.output_bias = np.zeros(self.n_categories) + 0.01
    +
    +    def feed_forward(self):
    +        # feed-forward for training
    +        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    +        self.a_h = sigmoid(self.z_h)
    +
    +        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    +
    +        exp_term = np.exp(self.z_o)
    +        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +
    +    def feed_forward_out(self, X):
    +        # feed-forward for output
    +        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    +        a_h = sigmoid(z_h)
    +
    +        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    +        
    +        exp_term = np.exp(z_o)
    +        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +        return probabilities
    +
    +    def backpropagation(self):
    +        error_output = self.probabilities - self.Y_data
    +        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    +
    +        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    +        self.output_bias_gradient = np.sum(error_output, axis=0)
    +
    +        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    +        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    +
    +        if self.lmbd > 0.0:
    +            self.output_weights_gradient += self.lmbd * self.output_weights
    +            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    +
    +        self.output_weights -= self.eta * self.output_weights_gradient
    +        self.output_bias -= self.eta * self.output_bias_gradient
    +        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    +        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    +
    +    def predict(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return np.argmax(probabilities, axis=1)
    +
    +    def predict_probabilities(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return probabilities
    +
    +    def train(self):
    +        data_indices = np.arange(self.n_inputs)
    +
    +        for i in range(self.epochs):
    +            for j in range(self.iterations):
    +                # pick datapoints with replacement
    +                chosen_datapoints = np.random.choice(
    +                    data_indices, size=self.batch_size, replace=False
    +                )
    +
    +                # minibatch training data
    +                self.X_data = self.X_data_full[chosen_datapoints]
    +                self.Y_data = self.Y_data_full[chosen_datapoints]
    +
    +                self.feed_forward()
    +                self.backpropagation()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Evaluate model performance on test data

    + +

    To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. +We measure the performance of the network using the accuracy score. +The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). +

    + +

    $$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

    + +

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    + + + +
    +
    +
    +
    +
    +
    epochs = 100
    +batch_size = 100
    +
    +dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +dnn.train()
    +test_predict = dnn.predict(X_test)
    +
    +# accuracy score from scikit library
    +print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +
    +# equivalent in numpy
    +def accuracy_score_numpy(Y_test, Y_pred):
    +    return np.sum(Y_test == Y_pred) / len(Y_test)
    +
    +#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Adjust hyperparameters

    + +

    We now perform a grid search to find the optimal hyperparameters for the network. +Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). +

    + + + +
    +
    +
    +
    +
    +
    eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +# store the models for later use
    +DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +
    +# grid search
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +        dnn.train()
    +        
    +        DNN_numpy[i][j] = dnn
    +        
    +        test_predict = dnn.predict(X_test)
    +        
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Visualization

    + + + +
    +
    +
    +
    +
    +
    # visual representation of grid search
    +# uses seaborn heatmap, you can also do this with matplotlib imshow
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_numpy[i][j]
    +        
    +        train_pred = dnn.predict(X_train) 
    +        test_pred = dnn.predict(X_test)
    +
    +        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    +        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    scikit-learn implementation

    + +

    scikit-learn focuses more +on traditional machine learning methods, such as regression, +clustering, decision trees, etc. As such, it has only two types of +neural networks: Multi Layer Perceptron outputting continuous values, +MPLRegressor, and Multi Layer Perceptron outputting labels, +MLPClassifier. We will see how simple it is to use these classes. +

    + +

    scikit-learn implements a few improvements from our neural network, +such as early stopping, a varying learning rate, different +optimization methods, etc. We would therefore expect a better +performance overall. +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.neural_network import MLPClassifier
    +# store models for later use
    +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    +                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    +        dnn.fit(X_train, Y_train)
    +        
    +        DNN_scikit[i][j] = dnn
    +        
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Visualization

    + + +
    +
    +
    +
    +
    +
    # optional
    +# visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_scikit[i][j]
    +        
    +        train_pred = dnn.predict(X_train) 
    +        test_pred = dnn.predict(X_test)
    +
    +        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    +        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Building neural networks in Tensorflow and Keras

    + +

    Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. +

    + +

    In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. +

    + + +

    Tensorflow

    + +

    Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. +

    + +

    Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. +

    + +

    Tensorflow uses so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow graph +to represent your model, and then create a Tensorflow session to run the graph. +

    + +

    In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. +

    + +

    To install tensorflow on Unix/Linux systems, use pip as

    + + +
    +
    +
    +
    +
    +
    pip3 install tensorflow
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    and/or if you use anaconda, just write (or install from the graphical user interface) +(current release of CPU-only TensorFlow) +

    + + +
    +
    +
    +
    +
    +
    conda create -n tf tensorflow
    +conda activate tf
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    To install the current release of GPU TensorFlow

    + + +
    +
    +
    +
    +
    +
    conda create -n tf-gpu tensorflow-gpu
    +conda activate tf-gpu
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Using Keras

    + +

    Keras is a high level neural network +that supports Tensorflow, CTNK and Theano as backends. +If you have Anaconda installed you may run the following command +

    + + +
    +
    +
    +
    +
    +
    conda install keras
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    You can look up the instructions here for more information.

    + +

    We will to a large extent use keras in this course.

    + + +

    Collect and pre-process data

    + +

    Let us look again at the MINST data set.

    @@ -809,50 +2147,195 @@ probabilities = feed_forward(X)
    # import necessary packages
     import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.neural_network import MLPClassifier
    -from sklearn.metrics import accuracy_score
    -import seaborn as sns
    +import tensorflow as tf
    +from sklearn import datasets
    +
     
     # ensure the same random numbers appear every time
     np.random.seed(0)
     
    -# Design matrix
    -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
     
    -# The XOR gate
    -yXOR = np.array( [ 0, 1 ,1, 0])
    -# The OR gate
    -yOR = np.array( [ 0, 1 ,1, 1])
    -# The AND gate
    -yAND = np.array( [ 0, 0 ,0, 1])
     
    -# Defining the neural network
    -n_hidden_neurons = 2
    +# download MNIST dataset
    +digits = datasets.load_digits()
     
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
    +
    + + + + +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +
    +from sklearn.model_selection import train_test_split
    +
    +# one-hot representation of labels
    +labels = to_categorical(labels)
    +
    +# split into train and test data
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    epochs = 100
    +batch_size = 100
    +n_neurons_layer1 = 100
    +n_neurons_layer2 = 50
    +n_categories = 10
     eta_vals = np.logspace(-5, 1, 7)
     lmbd_vals = np.logspace(-5, 1, 7)
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -epochs = 100
    -
    +def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
    +    model = Sequential()
    +    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_categories, activation='softmax'))
    +    
    +    sgd = optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    +    
    +    return model
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +        
     for i, eta in enumerate(eta_vals):
         for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X, yXOR)
    -        DNN_scikit[i][j] = dnn
    -        print("Learning rate  = ", eta)
    +        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
    +                                         eta=eta, lmbd=lmbd)
    +        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    +        scores = DNN.evaluate(X_test, Y_test)
    +        
    +        DNN_keras[i][j] = DNN
    +        
    +        print("Learning rate = ", eta)
             print("Lambda = ", lmbd)
    -        print("Accuracy score on data set: ", dnn.score(X, yXOR))
    +        print("Test accuracy: %.3f" % scores[1])
             print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    # optional
    +# visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
     
     sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
     test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
     for i in range(len(eta_vals)):
         for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    -        test_pred = dnn.predict(X)
    -        test_accuracy[i][j] = accuracy_score(yXOR, test_pred)
    +        DNN = DNN_keras[i][j]
    +
    +        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
    +        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
     
     fig, ax = plt.subplots(figsize = (10, 10))
     sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    @@ -876,6 +2359,197 @@ plt.show()
     
    + +

    The Breast Cancer Data, now with Keras

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +import numpy as np
    +import matplotlib.pyplot as plt
    +import seaborn as sns
    +from sklearn.model_selection import train_test_split as splitter
    +from sklearn.datasets import load_breast_cancer
    +import pickle
    +import os 
    +
    +
    +"""Load breast cancer dataset"""
    +
    +np.random.seed(0)        #create same seed for random number every time
    +
    +cancer=load_breast_cancer()      #Download breast cancer dataset
    +
    +inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    +outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    +labels=cancer.feature_names[0:30]
    +
    +print('The content of the breast cancer dataset is:')      #Print information about the datasets
    +print(labels)
    +print('-------------------------')
    +print("inputs =  " + str(inputs.shape))
    +print("outputs =  " + str(outputs.shape))
    +print("labels =  "+ str(labels.shape))
    +
    +x=inputs      #Reassign the Feature and Label matrices to other variables
    +y=outputs
    +
    +#%% 
    +
    +# Visualisation of dataset (for correlation analysis)
    +
    +plt.figure()
    +plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean radius',fontweight='bold')
    +plt.ylabel('Mean perimeter',fontweight='bold')
    +plt.show()
    +
    +plt.figure()
    +plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    +plt.xlabel('Mean compactness',fontweight='bold')
    +plt.ylabel('Mean concavity',fontweight='bold')
    +plt.show()
    +
    +
    +plt.figure()
    +plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean radius',fontweight='bold')
    +plt.ylabel('Mean texture',fontweight='bold')
    +plt.show()
    +
    +plt.figure()
    +plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean perimeter',fontweight='bold')
    +plt.ylabel('Mean compactness',fontweight='bold')
    +plt.show()
    +
    +
    +# Generate training and testing datasets
    +
    +#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    +#and add to input matrix
    +
    +temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    +temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    +X=np.hstack((temp1,temp2))      
    +temp=np.reshape(x[:,5],(len(x[:,5]),1))
    +X=np.hstack((X,temp))       
    +temp=np.reshape(x[:,8],(len(x[:,8]),1))
    +X=np.hstack((X,temp))       
    +
    +X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    +
    +y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    +y_test=to_categorical(y_test)
    +
    +del temp1,temp2,temp
    +
    +# %%
    +
    +# Define tunable parameters"
    +
    +eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    +lamda=0.01                                  #Define hyperparameter
    +n_layers=2                                  #Define number of hidden layers in the model
    +n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    +epochs=100                                   #Number of reiterations over the input data
    +batch_size=100                              #Number of samples per gradient update
    +
    +# %%
    +
    +"""Define function to return Deep Neural Network model"""
    +
    +def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    +    model=Sequential()      
    +    for i in range(n_layers):       #Run loop to add hidden layers to the model
    +        if (i==0):                  #First layer requires input dimensions
    +            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    +        else:                       #Subsequent layers are capable of automatic shape inferencing
    +            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    +    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    +    sgd=optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    +    return model
    +
    +    
    +Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    +Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    +
    +for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    +    for j in range(len(eta)):      #accuracy scores 
    +        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    +        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    +        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    +        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    +               
    +
    +def plot_data(x,y,data,title=None):
    +
    +    # plot results
    +    fontsize=16
    +
    +
    +    fig = plt.figure()
    +    ax = fig.add_subplot(111)
    +    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    +    
    +    cbar=fig.colorbar(cax)
    +    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    +    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    +    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    +
    +    # put text on matrix elements
    +    for i, x_val in enumerate(np.arange(len(x))):
    +        for j, y_val in enumerate(np.arange(len(y))):
    +            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    +            ax.text(x_val, y_val, c, va='center', ha='center')
    +
    +    # convert axis vaues to to string labels
    +    x=[str(i) for i in x]
    +    y=[str(i) for i in y]
    +
    +
    +    ax.set_xticklabels(['']+x)
    +    ax.set_yticklabels(['']+y)
    +
    +    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    +    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    +    if title is not None:
    +        ax.set_title(title)
    +
    +    plt.tight_layout()
    +
    +    plt.show()
    +    
    +plot_data(eta,n_neuron,Train_accuracy, 'training')
    +plot_data(eta,n_neuron,Test_accuracy, 'testing')
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Building a neural network code

    @@ -2226,1963 +3900,6 @@ scores = logistic_regressionLecture Thursday October 26 - - -

    Developing a code for doing neural networks with back propagation

    - -

    We repeat some of the elements discussed last week. The first part of -the material for Thursday was contained in the slides for last -week as well. We will repeat some of the topics here before we move into -applications to differential equations and other examples. -

    - -

    One can identify a set of key steps when using neural networks to solve supervised learning problems:

    - -
      -
    1. Collect and pre-process data
    2. -
    3. Define model and architecture
    4. -
    5. Choose cost function and optimizer
    6. -
    7. Train the model
    8. -
    9. Evaluate model performance on test data
    10. -
    11. Adjust hyperparameters (if necessary, network architecture)
    12. -
    - -

    Collect and pre-process data

    - -

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

    - -

    To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

    - -

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

    - -

    $$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

    - -

    and the targets would be:

    - -

    $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

    - -

    Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

    - - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Train and test datasets

    - -

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    - -

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    - -

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -
    -# one-liner from scikit-learn library
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -# equivalently in numpy
    -def train_test_split_numpy(inputs, labels, train_size, test_size):
    -    n_inputs = len(inputs)
    -    inputs_shuffled = inputs.copy()
    -    labels_shuffled = labels.copy()
    -    
    -    np.random.shuffle(inputs_shuffled)
    -    np.random.shuffle(labels_shuffled)
    -    
    -    train_end = int(n_inputs*train_size)
    -    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    -    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    -    
    -    return X_train, X_test, Y_train, Y_test
    -
    -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    -
    -print("Number of training images: " + str(len(X_train)))
    -print("Number of test images: " + str(len(X_test)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Define model and architecture

    - -

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    - -

    $$ z = \sum_{i=1}^n w_i a_i ,$$

    - -

    $$ y = f(z) ,$$

    - -

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

    - -

    The simplest activation function for a neuron is the Heaviside function:

    - -

    $$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

    - -

    A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

    - -

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

    - -

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

    - -

    $$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$

    - -

    which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

    - - -

    Layers

    - -
      -
    • Input
    • -
    -

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    - -
      -
    • Hidden layer
    • -
    -

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

    - -
      -
    • Output
    • -
    -

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

    - -

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    - -

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    - -

    $$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

    - -

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

    - -

    Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. -

    - - -

    Weights and biases

    - -

    Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. -

    - -

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

    - -

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    - - -
    -
    -
    -
    -
    -
    # building our neural network
    -
    -n_inputs, n_features = X_train.shape
    -n_hidden_neurons = 50
    -n_categories = 10
    -
    -# we make the weights normally distributed using numpy.random.randn
    -
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    -
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Feed-forward pass

    - -

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

    - -

    $$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

    - -

    this is then passed through our activation function

    - -

    $$ a_{j}^{l} = f(z_{j}^{l}) .$$

    - -

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    - -

    $$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

    - -

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    - -

    $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

    - - -

    Matrix multiplications

    - -

    Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden -layer have the dimensions -\( W_{hidden} = (n_{features}, n_{hidden}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

    - -

    $$ X W^{h} = (n_{inputs}, n_{hidden}),$$

    - -

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

    - -

    $$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

    - -

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

    - -

    $$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

    - -

    This is fed to the output layer:

    - -

    $$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

    - -

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    - -

    $$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

    - - - -
    -
    -
    -
    -
    -
    # setup the feed-forward pass, subscript h = hidden layer
    -
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    return probabilities
    -
    -probabilities = feed_forward(X_train)
    -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    -print("probabilities sum up to: " + str(probabilities[0].sum()))
    -print()
    -
    -# we obtain a prediction by taking the class with the highest likelihood
    -def predict(X):
    -    probabilities = feed_forward(X)
    -    return np.argmax(probabilities, axis=1)
    -
    -predictions = predict(X_train)
    -print("predictions = (n_inputs) = " + str(predictions.shape))
    -print("prediction for image 0: " + str(predictions[0]))
    -print("correct label for image 0: " + str(Y_train[0]))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Choose cost function and optimizer

    - -

    To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

    $$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

    - -

    $$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$

    - -

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

    - -

    Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

    - -

    In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category \( c' \) -(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. -

    - - - -

    Optimizing the cost function

    - -

    The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

    - -

    $$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

    - -

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

    - -

    A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

    - -

    $$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

    - -

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    - -

    This has two important benefits:

    -
      -
    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. -
    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. -
    -

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    - - -

    Regularization

    - -

    It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

    - -

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    - -

    $$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

    - -

    i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

    - -

    In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has \( (64 + 1)\times 50=3250 \) weights in -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -layer (\( +1 \) for the bias), and the gradient must be calculated for -every parameter. We use the backpropagation algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. -

    - - -

    Matrix multiplication

    - -

    To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

    - -

    $$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

    - -

    The gradient for the output weights is calculated as

    - -

    $$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

    - -

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

    - -

    The gradient with respect to the output bias is then

    - -

    $$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

    - -

    The error in the hidden layer is

    - -

    $$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

    - -

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

    - -

    This again gives us the gradients in the hidden layer:

    - -

    $$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

    - -

    $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

    - - - -
    -
    -
    -
    -
    -
    # to categorical turns our integer vector into a onehot representation
    -from sklearn.metrics import accuracy_score
    -
    -# one-hot in numpy
    -def to_categorical_numpy(integer_vector):
    -    n_inputs = len(integer_vector)
    -    n_categories = np.max(integer_vector) + 1
    -    onehot_vector = np.zeros((n_inputs, n_categories))
    -    onehot_vector[range(n_inputs), integer_vector] = 1
    -    
    -    return onehot_vector
    -
    -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    -
    -def feed_forward_train(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    # for backpropagation need activations in hidden and output layers
    -    return a_h, probabilities
    -
    -def backpropagation(X, Y):
    -    a_h, probabilities = feed_forward_train(X)
    -    
    -    # error in the output layer
    -    error_output = probabilities - Y
    -    # error in the hidden layer
    -    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    -    
    -    # gradients for the output layer
    -    output_weights_gradient = np.matmul(a_h.T, error_output)
    -    output_bias_gradient = np.sum(error_output, axis=0)
    -    
    -    # gradient for the hidden layer
    -    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    -    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    -
    -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -eta = 0.01
    -lmbd = 0.01
    -for i in range(1000):
    -    # calculate gradients
    -    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    -    
    -    # regularization term gradients
    -    dWo += lmbd * output_weights
    -    dWh += lmbd * hidden_weights
    -    
    -    # update weights and biases
    -    output_weights -= eta * dWo
    -    output_bias -= eta * dBo
    -    hidden_weights -= eta * dWh
    -    hidden_bias -= eta * dBh
    -
    -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Improving performance

    - -

    As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. -

    - -

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    - -

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

    - -

    If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. -

    - - -

    Full object-oriented implementation

    - -

    It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. -

    - - - -
    -
    -
    -
    -
    -
    class NeuralNetwork:
    -    def __init__(
    -            self,
    -            X_data,
    -            Y_data,
    -            n_hidden_neurons=50,
    -            n_categories=10,
    -            epochs=10,
    -            batch_size=100,
    -            eta=0.1,
    -            lmbd=0.0):
    -
    -        self.X_data_full = X_data
    -        self.Y_data_full = Y_data
    -
    -        self.n_inputs = X_data.shape[0]
    -        self.n_features = X_data.shape[1]
    -        self.n_hidden_neurons = n_hidden_neurons
    -        self.n_categories = n_categories
    -
    -        self.epochs = epochs
    -        self.batch_size = batch_size
    -        self.iterations = self.n_inputs // self.batch_size
    -        self.eta = eta
    -        self.lmbd = lmbd
    -
    -        self.create_biases_and_weights()
    -
    -    def create_biases_and_weights(self):
    -        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    -        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    -
    -        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    -        self.output_bias = np.zeros(self.n_categories) + 0.01
    -
    -    def feed_forward(self):
    -        # feed-forward for training
    -        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    -        self.a_h = sigmoid(self.z_h)
    -
    -        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    -
    -        exp_term = np.exp(self.z_o)
    -        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -
    -    def feed_forward_out(self, X):
    -        # feed-forward for output
    -        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    -        a_h = sigmoid(z_h)
    -
    -        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    -        
    -        exp_term = np.exp(z_o)
    -        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -        return probabilities
    -
    -    def backpropagation(self):
    -        error_output = self.probabilities - self.Y_data
    -        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    -
    -        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    -        self.output_bias_gradient = np.sum(error_output, axis=0)
    -
    -        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    -        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -        if self.lmbd > 0.0:
    -            self.output_weights_gradient += self.lmbd * self.output_weights
    -            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    -
    -        self.output_weights -= self.eta * self.output_weights_gradient
    -        self.output_bias -= self.eta * self.output_bias_gradient
    -        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    -        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    -
    -    def predict(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return np.argmax(probabilities, axis=1)
    -
    -    def predict_probabilities(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return probabilities
    -
    -    def train(self):
    -        data_indices = np.arange(self.n_inputs)
    -
    -        for i in range(self.epochs):
    -            for j in range(self.iterations):
    -                # pick datapoints with replacement
    -                chosen_datapoints = np.random.choice(
    -                    data_indices, size=self.batch_size, replace=False
    -                )
    -
    -                # minibatch training data
    -                self.X_data = self.X_data_full[chosen_datapoints]
    -                self.Y_data = self.Y_data_full[chosen_datapoints]
    -
    -                self.feed_forward()
    -                self.backpropagation()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Evaluate model performance on test data

    - -

    To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the accuracy score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). -

    - -

    $$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

    - -

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    - - - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -
    -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -dnn.train()
    -test_predict = dnn.predict(X_test)
    -
    -# accuracy score from scikit library
    -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -
    -# equivalent in numpy
    -def accuracy_score_numpy(Y_test, Y_pred):
    -    return np.sum(Y_test == Y_pred) / len(Y_test)
    -
    -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Adjust hyperparameters

    - -

    We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

    - - - -
    -
    -
    -
    -
    -
    eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -# store the models for later use
    -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -# grid search
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -        dnn.train()
    -        
    -        DNN_numpy[i][j] = dnn
    -        
    -        test_predict = dnn.predict(X_test)
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, you can also do this with matplotlib imshow
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_numpy[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    scikit-learn implementation

    - -

    scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

    - -

    scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.neural_network import MLPClassifier
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X_train, Y_train)
    -        
    -        DNN_scikit[i][j] = dnn
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Visualization

    - - -
    -
    -
    -
    -
    -
    # optional
    -# visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Building neural networks in Tensorflow and Keras

    - -

    Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. -

    - -

    In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. -

    - - -

    Tensorflow

    - -

    Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. -

    - -

    Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. -

    - -

    Tensorflow uses so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow graph -to represent your model, and then create a Tensorflow session to run the graph. -

    - -

    In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. -

    - -

    To install tensorflow on Unix/Linux systems, use pip as

    - - -
    -
    -
    -
    -
    -
    pip3 install tensorflow
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    and/or if you use anaconda, just write (or install from the graphical user interface) -(current release of CPU-only TensorFlow) -

    - - -
    -
    -
    -
    -
    -
    conda create -n tf tensorflow
    -conda activate tf
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    To install the current release of GPU TensorFlow

    - - -
    -
    -
    -
    -
    -
    conda create -n tf-gpu tensorflow-gpu
    -conda activate tf-gpu
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Using Keras

    - -

    Keras is a high level neural network -that supports Tensorflow, CTNK and Theano as backends. -If you have Anaconda installed you may run the following command -

    - - -
    -
    -
    -
    -
    -
    conda install keras
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    You can look up the instructions here for more information.

    - -

    We will to a large extent use keras in our examples..

    - - -

    Collect and pre-process data

    - -

    Let us look again at the MINST data set.

    - - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import tensorflow as tf
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -
    -from sklearn.model_selection import train_test_split
    -
    -# one-hot representation of labels
    -labels = to_categorical(labels)
    -
    -# split into train and test data
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -n_neurons_layer1 = 100
    -n_neurons_layer2 = 50
    -n_categories = 10
    -eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
    -    model = Sequential()
    -    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(Dense(n_categories, activation='softmax'))
    -    
    -    sgd = optimizers.SGD(lr=eta)
    -    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    -    
    -    return model
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -        
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
    -                                         eta=eta, lmbd=lmbd)
    -        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    -        scores = DNN.evaluate(X_test, Y_test)
    -        
    -        DNN_keras[i][j] = DNN
    -        
    -        print("Learning rate = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Test accuracy: %.3f" % scores[1])
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    # optional
    -# visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        DNN = DNN_keras[i][j]
    -
    -        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
    -        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    The Breast Cancer Data, now with Keras

    - - - -
    -
    -
    -
    -
    -
    import tensorflow as tf
    -from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import seaborn as sns
    -from sklearn.model_selection import train_test_split as splitter
    -from sklearn.datasets import load_breast_cancer
    -import pickle
    -import os 
    -
    -
    -"""Load breast cancer dataset"""
    -
    -np.random.seed(0)        #create same seed for random number every time
    -
    -cancer=load_breast_cancer()      #Download breast cancer dataset
    -
    -inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    -outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    -labels=cancer.feature_names[0:30]
    -
    -print('The content of the breast cancer dataset is:')      #Print information about the datasets
    -print(labels)
    -print('-------------------------')
    -print("inputs =  " + str(inputs.shape))
    -print("outputs =  " + str(outputs.shape))
    -print("labels =  "+ str(labels.shape))
    -
    -x=inputs      #Reassign the Feature and Label matrices to other variables
    -y=outputs
    -
    -#%% 
    -
    -# Visualisation of dataset (for correlation analysis)
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean perimeter',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    -plt.xlabel('Mean compactness',fontweight='bold')
    -plt.ylabel('Mean concavity',fontweight='bold')
    -plt.show()
    -
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean texture',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean perimeter',fontweight='bold')
    -plt.ylabel('Mean compactness',fontweight='bold')
    -plt.show()
    -
    -
    -# Generate training and testing datasets
    -
    -#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    -#and add to input matrix
    -
    -temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    -temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    -X=np.hstack((temp1,temp2))      
    -temp=np.reshape(x[:,5],(len(x[:,5]),1))
    -X=np.hstack((X,temp))       
    -temp=np.reshape(x[:,8],(len(x[:,8]),1))
    -X=np.hstack((X,temp))       
    -
    -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    -
    -y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    -y_test=to_categorical(y_test)
    -
    -del temp1,temp2,temp
    -
    -# %%
    -
    -# Define tunable parameters"
    -
    -eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    -lamda=0.01                                  #Define hyperparameter
    -n_layers=2                                  #Define number of hidden layers in the model
    -n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    -epochs=100                                   #Number of reiterations over the input data
    -batch_size=100                              #Number of samples per gradient update
    -
    -# %%
    -
    -"""Define function to return Deep Neural Network model"""
    -
    -def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    -    model=Sequential()      
    -    for i in range(n_layers):       #Run loop to add hidden layers to the model
    -        if (i==0):                  #First layer requires input dimensions
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    -        else:                       #Subsequent layers are capable of automatic shape inferencing
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    -    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    -    sgd=optimizers.SGD(lr=eta)
    -    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    -    return model
    -
    -    
    -Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    -Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    -
    -for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    -    for j in range(len(eta)):      #accuracy scores 
    -        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    -        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    -        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    -        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    -               
    -
    -def plot_data(x,y,data,title=None):
    -
    -    # plot results
    -    fontsize=16
    -
    -
    -    fig = plt.figure()
    -    ax = fig.add_subplot(111)
    -    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    -    
    -    cbar=fig.colorbar(cax)
    -    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    -    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    -    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    -
    -    # put text on matrix elements
    -    for i, x_val in enumerate(np.arange(len(x))):
    -        for j, y_val in enumerate(np.arange(len(y))):
    -            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    -            ax.text(x_val, y_val, c, va='center', ha='center')
    -
    -    # convert axis vaues to to string labels
    -    x=[str(i) for i in x]
    -    y=[str(i) for i in y]
    -
    -
    -    ax.set_xticklabels(['']+x)
    -    ax.set_yticklabels(['']+y)
    -
    -    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    -    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    -    if title is not None:
    -        ax.set_title(title)
    -
    -    plt.tight_layout()
    -
    -    plt.show()
    -    
    -plot_data(eta,n_neuron,Train_accuracy, 'training')
    -plot_data(eta,n_neuron,Test_accuracy, 'testing')
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Fine-tuning neural network hyperparameters

    - -

    The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are interconnected), -but even in a simple FFNN you can change the number of layers, the -number of neurons per layer, the type of activation function to use in -each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you -know what combination of hyperparameters is the best for your task? -

    - -
      -
    • You can use grid search with cross-validation to find the right hyperparameters.
    • -
    -

    However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. -

    - -
      -
    • You can use randomized search.
    • -
    • Or use tools like Oscar, which implements more complex algorithms to help you find a good set of hyperparameters quickly.
    • -
    - -

    Hidden layers

    - -

    For many problems you can start with just one or two hidden layers and it will work just fine. -For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a -few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of -neurons, in roughly the same amount of training time. -

    - -

    For more complex problems, you can gradually -ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such -as large image classification or speech recognition, typically require networks with dozens of layers -and they need a huge amount -of training data. However, you will rarely have to train such networks from scratch: it is much more -common to reuse parts of a pretrained state-of-the-art network that performs a similar task. -

    - - -

    Which activation function should I use?

    - -

    The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. -

    - -

    Unfortunately for us, the gradients often get smaller and smaller as the -algorithm progresses down to the first hidden layers. As a result, the -GD update leaves the lower layer connection weights -virtually unchanged, and training never converges to a good -solution. This is known in the literature as -the vanishing gradients problem. -

    - -

    In other cases, the opposite can happen, namely the the gradients can grow bigger and -bigger. The result is that many of the layers get large updates of the -weights the -algorithm diverges. This is the exploding gradients problem, which is -mostly encountered in recurrent neural networks. More generally, deep -neural networks suffer from unstable gradients, different layers may -learn at widely different speeds -

    - - -

    Is the Logistic activation function (Sigmoid) our choice?

    - -

    Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. -

    - -

    A paper titled Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -

    - -

    They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -

    - - -

    The derivative of the Logistic funtion

    - -

    Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. -

    - -

    In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -

    - -

    One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -

    - - -

    The RELU function family

    - -

    The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. -

    - -

    In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. -

    - -

    To solve this problem, nowadays practitioners use a variant of the ReLU -function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function -

    - -$$ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -$$ - - - -

    Which activation function should we use?

    - -

    In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than \( \tanh \) which in turn performs better -than the logistic function. -

    - -

    If runtime -performance is an issue, then you may opt for the leaky ReLU function over the -ELU function If you don’t -want to tweak yet another hyperparameter, you may just use the default -\( \alpha \) of \( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have -spare time and computing power, you can use cross-validation or -bootstrap to evaluate other activation functions. -

    - - -

    More on activation functions, output layers

    - -

    In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).

    - -

    It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck.

    - -For the output layer: - -
      -
    • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
    • -
    • For regression tasks, you can simply use no activation function at all.
    • -
    - -

    Batch Normalization

    - -

    Batch Normalization -aims to address the vanishing/exploding gradients problems, and more generally the problem that the -distribution of each layer’s inputs changes during training, as the parameters of the previous layers change. -

    - -

    The technique consists of adding an operation in the model just before the activation function of each -layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new -parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model -learn the optimal scale and mean of the inputs for each layer. -In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and -standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current -mini-batch, from this the name batch normalization. -

    - - -

    Dropout

    - -

    It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but -excluding the output neurons) has a probability \( p \) of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active during the next step. -

    - -

    The -hyperparameter \( p \) is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore. - It is viewed as one of the most popular regularization techniques. -

    - - -

    Gradient Clipping

    - -

    A popular technique to lessen the exploding gradients problem is to simply clip the gradients during -backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural -networks). -

    - -

    This technique is called Gradient Clipping.

    - -

    In general however, Batch -Normalization is preferred. -

    - - -

    A very nice website on Neural Networks

    - -

    You may find this website very useful.

    - - -

    A top-down perspective on Neural networks

    - -

    The first thing we would like to do is divide the data into two or three -parts. A training set, a validation or dev (development) set, and a -test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: -

    - -
      -
    • Estimate optimal error rate
    • -
    • Minimize underfitting (bias) on training data set.
    • -
    • Make sure you are not overfitting.
    • -
    -

    If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. -

    - -

    However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -

    - - -

    Limitations of supervised learning with deep networks

    - -

    Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). -

    - -

    Here we list some of the important limitations of supervised neural network based models.

    - -
      -
    • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
    • -
    • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
    • -
    • Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
    • -
    • Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
    • -
    -

    Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.

    -

    Solving ODEs with Deep Learning

    @@ -6854,7 +6571,7 @@ $$ -->
    - © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/week43/html/week43-reveal.html b/doc/pub/week43/html/week43-reveal.html index f120544f5..e5533676d 100644 --- a/doc/pub/week43/html/week43-reveal.html +++ b/doc/pub/week43/html/week43-reveal.html @@ -184,13 +184,13 @@ MathJax.Hub.Config({
    -

    Oct 26, 2023

    +

    Oct 19, 2024


    - © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    @@ -198,58 +198,68 @@ MathJax.Hub.Config({

    Plans for week 43

    -Material for the active learning sessions on Tuesday and Wednesday +Material for the lecture on Monday October 21, 2024

      -

    • Exercise on writing your own neural network code, application to the OR and XOR gates
    • +

    • Building our own Feed-forward Neural Network with intro to Tensorflow
    • + +

    • Solving differential equations with Neural Networks + +
    • +
    +
    + + +
    +

    Exercises and lab session week 43

    +
    +Lab sessions on Tuesday and Wednesday +

    +

      + +

    • Exercise on writing your own neural network code
    • The exercises this week will be continued next week as well
    • Discussion of project 2
    • - -

    • Video of lab session
    - +
    + +
    +

    Mathematics of deep learning

    -Material for the lecture on Thursday October 26, 2023 +Two recent books online

    -

    -

    -

    I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at http://neuralnetworksanddeeplearning.com/chap4.html.

    +
      +

    1. The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen, published as Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022
    2. +

    3. Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger
    4. +
    +
    +

    Reminder on books with hands-on material and codes

    + +
    + +
    +

    Reading recommendations

    + +
      +

    1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub. See also chapters 12 and 13 on using Pytorch to make a Neural network code.
    2. +

    3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
    4. +
    +
    +

    Using Automatic differentiation

    a @@ -271,182 +281,481 @@ t

    -

    Material for exercises week 43 and week 44

    +

    Lecture Monday October 21

    -

    Writing our first neural network code, testing it for the OR and XOR gates

    +

    Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

    +

    This is a reminder from where we ended last week.

    -

    During week 41 we discussed three different types of gates, the -so-called XOR, the OR and the AND gates. In order to develop a code -for neural networks, it can be useful to set up a simpler system with -only two inputs and one output. This can make it easier to debug and -study the feed forward pass and the back propagation part. In the -exercise this and next week, we propose to study this system with just -one hidden layer and two hidden nodes. There is only one output node -and we can choose to use either a simple regression case (fitting a -line) or just a binary classification case with the corss-entropy as -cost function. +

    +The architecture (our model) +

    +

      +

    1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)
    2. +

    3. Define the number of hidden layers and hidden nodes
    4. +

    5. Define activation functions for hidden layers and output layers
    6. +

    7. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates
    8. +

    9. Define cost function and possible regularization terms with hyperparameters
    10. +

    11. Initialize weights and biases
    12. +

    13. Fix number of iterations for the feed forward part and back propagation part
    14. +
    +
    +
    + +
    +

    Setting up the back propagation algorithm, part 1

    + +

    Let us write this out in the form of an algorithm.

    + +

    First, we set up the input data \( \boldsymbol{x} \) and the activations +\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and +the pertinent outputs \( \boldsymbol{a}^1 \).

    -

    Their inputs and outputs can be -summarized using the following tables, first for the OR gate with -inputs \( x_1 \) and \( x_2 \) and outputs \( y \): +

    Secondly, we perform then the feed forward till we reach the output +layer and compute all \( \boldsymbol{z}_l \) of the input layer and compute the +activation function and the pertinent outputs \( \boldsymbol{a}^l \) for +\( l=1,2,3,\dots,L \).

    - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 1
    1 0 1
    1 1 1
    +

    Notation: The first hidden layer has \( l=1 \) as label and the final output layer has \( l=L \).

    -

    The AND and XOR Gates

    - -

    The AND gate is defined as

    - - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 0
    1 0 0
    1 1 1
    - -

    And finally we have the XOR gate

    - - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 1
    1 0 1
    1 1 0
    -
    - -
    -

    Representing the Data Sets

    - -

    Our design matrix is defined by the input values \( x_1 \) and \( x_2 \). Since we have four possible outputs, our design matrix reads

    +

    Setting up the back propagation algorithm, part 2

    +

    Thereafter we compute the ouput error \( \boldsymbol{\delta}^L \) by computing all

     
    $$ -\boldsymbol{X}=\begin{bmatrix} 0 & 0 \\ - 0 & 1 \\ - 1 & 0 \\ - 1 & 1 \end{bmatrix}, +\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. $$

     
    -

    while the vector of outputs is \( \boldsymbol{y}^T=[0,1,1,0] \) for the XOR gate, \( \boldsymbol{y}^T=[0,0,0,1] \) for the AND gate and \( \boldsymbol{y}^T=[0,1,1,1] \) for the OR gate.

    +

    Then we compute the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

    +

     
    +$$ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). +$$ +

     
    +

    -

    Your tasks here are

    +
    +

    Setting up the Back propagation algorithm, part 3

    + +

    Finally, we update the weights and the biases using gradient descent +for each \( l=L-1,L-2,\dots,1 \) (the first hidden layer) and update the weights and biases +according to the rules +

    + +

     
    +$$ +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, +$$ +

     
    + +

     
    +$$ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +$$ +

     
    + +

    with \( \eta \) being the learning rate.

    +
    + +
    +

    Updating the gradients

    + +

    With the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

    +

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

     
    + +

    we update the weights and the biases using gradient descent for each \( l=L-1,L-2,\dots,1 \) and update the weights and biases according to the rules

    +

     
    +$$ +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, +$$ +

     
    + +

     
    +$$ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +$$ +

     
    +

    + +
    +

    Activation functions

    + +

    A property that characterizes a neural network, other than its +connectivity, is the choice of activation function(s). The following +restrictions are imposed on an activation function for an FFNN to +fulfill the universal approximation theorem +

    + +
      + +

    • Non-constant
    • + +

    • Bounded
    • + +

    • Monotonically-increasing
    • + +

    • Continuous
    • +
    +
    + +
    +

    Activation functions, examples

    + +

    Typical examples are the logistic Sigmoid

    + +

     
    +$$ + \sigma(x) = \frac{1}{1 + e^{-x}}, +$$ +

     
    + +

    and the hyperbolic tangent function

    +

     
    +$$ + \sigma(x) = \tanh(x) +$$ +

     
    +

    + +
    +

    The RELU function family

    + +

    The ReLU activation function suffers from a problem known as the dying +ReLUs: during training, some neurons effectively die, meaning they +stop outputting anything other than 0. +

    + +

    In some cases, you may find that half of your network’s neurons are +dead, especially if you used a large learning rate. During training, +if a neuron’s weights get updated such that the weighted sum of the +neuron’s inputs is negative, it will start outputting 0. When this +happen, the neuron is unlikely to come back to life since the gradient +of the ReLU function is 0 when its input is negative. +

    +
    + +
    +

    ELU function

    + +

    To solve this problem, nowadays practitioners use a variant of the +ReLU function, such as the leaky ReLU discussed above or the so-called +exponential linear unit (ELU) function +

    + +

     
    +$$ +ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. +$$ +

     
    +

    + +
    +

    Which activation function should we use?

    + +

    In general it seems that the ELU activation function is better than +the leaky ReLU function (and its variants), which is better than +ReLU. ReLU performs better than \( \tanh \) which in turn performs better +than the logistic function. +

    + +

    If runtime performance is an issue, then you may opt for the leaky +ReLU function over the ELU function If you don’t want to tweak yet +another hyperparameter, you may just use the default \( \alpha \) of +\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and +computing power, you can use cross-validation or bootstrap to evaluate +other activation functions. +

    +
    + +
    +

    More on activation functions, output layers

    + +

    In most cases you can use the ReLU activation function in the hidden +layers (or one of its variants). +

    + +

    It is a bit faster to compute than other activation functions, and the +gradient descent optimization does in general not get stuck. +

    + +For the output layer: + +
      +

    • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
    • +

    • For regression tasks, you can simply use no activation function at all.
    • +
    +
    + +
    +

    Setting up a Multi-layer perceptron model for classification

    + +

    We are now gong to develop an example based on the MNIST data +base. This is a classification problem and we need to use our +cross-entropy function we discussed in connection with logistic +regression. The cross-entropy defines our cost function for the +classificaton problems with neural networks. +

    + +

    In binary classification with two classes \( (0, 1) \) we define the +logistic/sigmoid function as the probability that a particular input +is in class \( 0 \) or \( 1 \). This is possible because the logistic +function takes any input from the real numbers and inputs a number +between 0 and 1, and can therefore be interpreted as a probability. It +also has other nice properties, such as a derivative that is simple to +calculate. +

    + +

    For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) +is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) +represents our activation values \( z \). We have +

    +

     
    +$$ +P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , +$$ +

     
    + +

    and

    +

     
    +$$ +P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , +$$ +

     
    + +

    where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases +of our network. +

    +
    + +
    +

    Defining the cost function

    + +

    Our cost function is given as (see the Logistic regression lectures)

    +

     
    +$$ +\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n +y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . +$$ +

     
    + +

    This last equality means that we can interpret our cost function as a sum over the loss function +for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). +The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather +than maximizing a negative number. +

    + +

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    + +

    \( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

    + +\( y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) , \) + +

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset (numbers from \( 0 \) to \( 9 \))..

    + +

    If \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th +output vector \( \boldsymbol{y}_i \). +The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: +

    + +

     
    +$$ +P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} +{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , +$$ +

     
    + +

    which reduces to the logistic function in the binary case. +The likelihood of this \( C \)-class classifier +is now given as: +

    + +

     
    +$$ +P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . +$$ +

     
    + +

    Again we take the negative log-likelihood to define our cost function:

    + +

     
    +$$ +\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. +$$ +

     
    + +

    See the logistic regression lectures for a full definition of the cost function.

    + +

    The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!

    +
    + +
    +

    Example: binary classification problem

    + +

    As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as

    +

     
    +$$ +\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right), +$$ +

     
    + +

    where we had defined the logistic (sigmoid) function

    +

     
    +$$ +p(y_i =1\vert x_i,\boldsymbol{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, +$$ +

     
    + +

    and

    +

     
    +$$ +p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). +$$ +

     
    + +

    The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

    + +

    Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). +We have then +

    +

     
    +$$ +a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, +$$ +

     
    + +

    with

    +

     
    +$$ +z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, +$$ +

     
    + +

    where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). +Our cost function at the final layer \( l=L \) is now +

    +

     
    +$$ +\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), +$$ +

     
    + +

    where we have defined the targets \( t_i \). The derivatives of the cost function with respect to the output \( a_i^L \) are then easily calculated and we get

    +

     
    +$$ +\frac{\partial \mathcal{C}(\boldsymbol{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. +$$ +

     
    + +

    In case we use another activation function than the logistic one, we need to evaluate other derivatives.

    +
    + +
    +

    The Softmax function

    +

    In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need

    +

     
    +$$ +\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = +\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. +$$ +

     
    + +

    For the Softmax function we have

    +

     
    +$$ +f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. +$$ +

     
    + +

    Its derivative with respect to \( z_j^l \) gives

    +

     
    +$$ +\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), +$$ +

     
    + +

    which in case of the simply binary model reduces to having \( i=j \).

    +
    + +
    +

    Developing a code for doing neural networks with back propagation

    + +

    One can identify a set of key steps when using neural networks to solve supervised learning problems:

      -

    1. Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs.
    2. -

    3. Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function.
    4. -

    5. Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output.
    6. -

    7. Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets.
    8. -

    9. Set up the cost function (cross entropy for classification of binary cases).
    10. -

    11. Calculate the gradients needed for the back propagation part.
    12. -

    13. Use the gradients to train the network in the back propagation part. Think of using automatic differentiation.
    14. -

    15. Train the network and study your results and compare with results obtained either with scikit-learn or TensorFlow.
    16. +

    17. Collect and pre-process data
    18. + +

    19. Define model and architecture
    20. + +

    21. Choose cost function and optimizer
    22. + +

    23. Train the model
    24. + +

    25. Evaluate model performance on test data
    26. + +

    27. Adjust hyperparameters (if necessary, network architecture)
    -

    -

    Everything you develop here can be used directly into the code for the project.

    -

    Setting up dimensionalities by hand

    +

    Collect and pre-process data

    -

    It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by

    -

     
    -$$ -\boldsymbol{W_h}=\begin{bmatrix} 1 & 1 \\ - 1 & 1 \end{bmatrix}, -$$ -

     
    +

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn +package. You may also find it for example here. +The MNIST (Modified National Institute of Standards and Technology) database is a large database +of handwritten digits that is commonly used for training various image processing systems. +The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. +The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. +

    -

    Multiplying \( \boldsymbol{X} \) and \( \boldsymbol{W} \) gives

    +

    To feed data into a feed-forward neural network we need to represent +the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each +row represents an input, in this case a handwritten digit, and +each column represents a feature, in this case a pixel. The +correct answers, also known as labels or targets are +represented as a 1D array of integers +\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). +

    -

     
    -$$ -\boldsymbol{X}{W}_h=\begin{bmatrix} 0 & 0 \\ - 1 & 1 \\ - 1 & 1 \\ - 2 & 2 \end{bmatrix}, -$$ -

     
    +

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from +measurements of height (in m) +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: +

    -

    Assume also that the bias vector for the hidden layer is

    -

     
    -$$ -\boldsymbol{b}_h=\begin{bmatrix} 0 \\ - -1\end{bmatrix}, -$$ -

     
    +

     
    +$$ X = \begin{bmatrix} +1.85 & 81\\ +1.71 & 65\\ +1.95 & 103\\ +1.55 & 42\\ +1.63 & 56 +\end{bmatrix} ,$$ +

     
    +

    -

    Adding it gives us the input to the activation function of the hidden layer

    -

     
    -$$ -\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h=\begin{bmatrix} 0 & -1 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, -$$ -

     
    +

    and the targets would be:

    -

    Let us then assume that our activation function is the RELU function, which simply means that we take the max of \( 0 \) and the elements of the input argument \( \boldsymbol{z}_h \), that is we have

    -

     
    -$$ -\boldsymbol{a}_h=\mathrm{RELU}(\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h)=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, -$$ -

     
    +

     
    +$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ +

     

    -

    Assume also that the bias of the output layer is zero and that the weights of the output layer are

    -

     
    -$$ -\boldsymbol{w}_o=\begin{bmatrix} 1 \\ - -2\end{bmatrix}, -$$ -

     
    - -

    and multiplying with \( \boldsymbol{a}_h \) gives the output

    -

     
    -$$ -\boldsymbol{a}_o=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}\begin{bmatrix} 1 \\ - -2\end{bmatrix}=\begin{bmatrix} 0 \\ 1 \\ 1 \\0\end{bmatrix}, -$$ -

     
    - -

    the wanted result. Pay attention to the dimensionalities as well.

    -
    - -
    -

    Setting up the Neural Network

    - -

    We define first our design matrix and the various output vectors for the different gates.

    +

    Since each input image is a 2D matrix, we need to flatten the image +(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a +design/feature matrix. This means we lose all spatial information in the +image, such as locality and translational invariance. More complicated +architectures such as Convolutional Neural Networks can take advantage +of such information, and are most commonly applied when analyzing +images. +

    @@ -455,15 +764,365 @@ $$
    -
    """
    -Simple code that tests XOR, OR and AND gates with linear regression
    -"""
    -
    -# import necessary packages
    +  
    # import necessary packages
     import numpy as np
     import matplotlib.pyplot as plt
     from sklearn import datasets
     
    +
    +# ensure the same random numbers appear every time
    +np.random.seed(0)
    +
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
    +
    +
    +# download MNIST dataset
    +digits = datasets.load_digits()
    +
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +
    +

    Train and test datasets

    + +

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    + +

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    + +

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure +no bias in the sampling. +Say you are taking measurements of weather data to predict the weather in the coming 5 days. +You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data +collected from 12.00 to 24.00. +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.model_selection import train_test_split
    +
    +# one-liner from scikit-learn library
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +# equivalently in numpy
    +def train_test_split_numpy(inputs, labels, train_size, test_size):
    +    n_inputs = len(inputs)
    +    inputs_shuffled = inputs.copy()
    +    labels_shuffled = labels.copy()
    +    
    +    np.random.shuffle(inputs_shuffled)
    +    np.random.shuffle(labels_shuffled)
    +    
    +    train_end = int(n_inputs*train_size)
    +    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    +    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    +    
    +    return X_train, X_test, Y_train, Y_test
    +
    +#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    +
    +print("Number of training images: " + str(len(X_train)))
    +print("Number of test images: " + str(len(X_test)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Define model and architecture

    + +

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    + +

     
    +$$ z = \sum_{i=1}^n w_i a_i ,$$ +

     

    + +

     
    +$$ y = f(z) ,$$ +

     

    + +

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer +and \( w_i \) is the weight to input \( i \). +The activation of the neurons in the input layer is just the features (e.g. a pixel value). +

    + +

    The simplest activation function for a neuron is the Heaviside function:

    + +

     
    +$$ f(z) = +\begin{cases} +1, & z > 0\\ +0, & \text{otherwise} +\end{cases} +$$ +

     
    +

    + +

    A feed-forward neural network with this activation is known as a perceptron. +For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. +This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), +and we call these architectures multiclass perceptrons. +

    + +

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and +Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. +

    + +

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). +We will be using the sigmoid function \( \sigma(x) \): +

    + +

     
    +$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$ +

     

    + +

    which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

    +
    + +
    +

    Layers

    + +
      +

    • Input
    • +
    +

    +

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    + +
      +

    • Hidden layer
    • +
    +

    +

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. +Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. +

    + +
      +

    • Output
    • +
    +

    +

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, +which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. +

    + +

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    + +

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    + +

     
    +$$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} +{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ +

     
    +

    + +

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. +The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. +The exponent is just the weighted sum of inputs as before: +

    + +

     
    +$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ +

     

    + +

    Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 +weights to the output layer. +

    +
    + +
    +

    Weights and biases

    + +

    Typically weights are initialized with small values distributed around zero, drawn from a uniform +or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. +

    + +

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range +of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): +

    + +

     
    +$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ +

     

    + +

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    + + +
    +
    +
    +
    +
    +
    # building our neural network
    +
    +n_inputs, n_features = X_train.shape
    +n_hidden_neurons = 50
    +n_categories = 10
    +
    +# we make the weights normally distributed using numpy.random.randn
    +
    +# weights and bias in the hidden layer
    +hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    +hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    +
    +# weights and bias in the output layer
    +output_weights = np.random.randn(n_hidden_neurons, n_categories)
    +output_bias = np.zeros(n_categories) + 0.01
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Feed-forward pass

    + +

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. +For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): +

    + +

     
    +$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ +

     

    + +

    this is then passed through our activation function

    + +

     
    +$$ a_{j}^{l} = f(z_{j}^{l}) .$$ +

     

    + +

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    + +

     
    +$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ +

     

    + +

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    + +

     
    +$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} +{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ +

     
    +

    +
    + +
    +

    Matrix multiplications

    + +

    Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden +layer have the dimensions +\( W_{hidden} = (n_{features}, n_{hidden}) \), +we can easily feed the network all our training data in one go by taking the matrix product +

    + +

     
    +$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ +

     

    + +

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer +for each input image and each hidden neuron. +We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): +

    + +

     
    +$$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$ +

     

    + +

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. +This is then passed through the activation: +

    + +

     
    +$$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$ +

     

    + +

    This is fed to the output layer:

    + +

     
    +$$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$ +

     

    + +

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    + +

     
    +$$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$ +

     

    + + + +
    +
    +
    +
    +
    +
    # setup the feed-forward pass, subscript h = hidden layer
    +
     def sigmoid(x):
         return 1/(1 + np.exp(-x))
     
    @@ -477,41 +1136,764 @@ $$
         z_o = np.matmul(a_h, output_weights) + output_bias
         # softmax output
         # axis 0 holds each input and axis 1 the probabilities of each category
    -    probabilities = sigmoid(z_o)
    +    exp_term = np.exp(z_o)
    +    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +    
         return probabilities
     
    +probabilities = feed_forward(X_train)
    +print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    +print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    +print("probabilities sum up to: " + str(probabilities[0].sum()))
    +print()
     
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    +# we obtain a prediction by taking the class with the highest likelihood
    +def predict(X):
    +    probabilities = feed_forward(X)
    +    return np.argmax(probabilities, axis=1)
     
    -# Design matrix
    -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    +predictions = predict(X_train)
    +print("predictions = (n_inputs) = " + str(predictions.shape))
    +print("prediction for image 0: " + str(predictions[0]))
    +print("correct label for image 0: " + str(Y_train[0]))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -# The XOR gate -yXOR = np.array( [ 0, 1 ,1, 0]) -# The OR gate -yOR = np.array( [ 0, 1 ,1, 1]) -# The AND gate -yAND = np.array( [ 0, 0 ,0, 1]) +
    +

    Choose cost function and optimizer

    -# Defining the neural network -n_inputs, n_features = X.shape -n_hidden_neurons = 2 -n_categories = 1 -n_features = 2 +

    To measure how well our neural network is doing we need to introduce a cost function. +We will call the function that gives the error of a single sample output the loss function, and the function +that gives the total error of our network across all samples the cost function. +A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. +

    -# we make the weights normally distributed using numpy.random.randn +

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    -# weights and bias in the hidden layer -hidden_weights = np.random.randn(n_features, n_hidden_neurons) -hidden_bias = np.zeros(n_hidden_neurons) + 0.01 +

     
    +$$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ +

     

    -# weights and bias in the output layer -output_weights = np.random.randn(n_hidden_neurons, n_categories) -output_bias = np.zeros(n_categories) + 0.01 +

     
    +$$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ +

     

    -probabilities = feed_forward(X) -print(probabilities) +

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

    + +

    Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. +We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. +

    + +

    In the one-hot representation only one of the terms in the loss function is non-zero, namely the +probability of the correct category \( c' \) +(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong +you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. +

    +
    + +
    +

    Optimizing the cost function

    + +

    The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent +is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. +Each parameter \( \theta \) is iteratively adjusted according to the rule +

    + +

     
    +$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ +

     

    + +

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. +This update can be repeated for any number of iterations, or until we are satisfied with the result. +

    + +

    A simple and effective improvement is a variant called Batch Gradient Descent. +Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient +on a subset of the data called a minibatch. +If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches +is \( N/M \). +We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: +

    + +

     
    +$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ +

     
    +

    + +

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    + +

    This has two important benefits:

    +
      +

    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. + +

    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. +
    +

    +

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    +
    + +
    +

    Regularization

    + +

    It is common to add an extra term to the cost function, proportional +to the size of the weights. This is equivalent to constraining the +size of the weights, so that they do not grow out of control. +Constraining the size of the weights means that the weights cannot +grow arbitrarily large to fit the training data, and in this way +reduces overfitting. +

    + +

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    + +

     
    +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ +

     
    +

    + +

    i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

    + +

    In order to train the model, we need to calculate the derivative of +the cost function with respect to every bias and weight in the +network. In total our network has \( (64 + 1)\times 50=3250 \) weights in +the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output +layer (\( +1 \) for the bias), and the gradient must be calculated for +every parameter. We use the backpropagation algorithm discussed +above. This is a clever use of the chain rule that allows us to +calculate the gradient efficently. +

    +
    + +
    +

    Matrix multiplication

    + +

    To more efficently train our network these equations are implemented using matrix operations. +The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, +

    + +

     
    +$$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ +

     

    + +

    The gradient for the output weights is calculated as

    + +

     
    +$$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ +

     

    + +

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. +Since we are going backwards we have to transpose the activation matrix. +

    + +

    The gradient with respect to the output bias is then

    + +

     
    +$$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ +

     

    + +

    The error in the hidden layer is

    + +

     
    +$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ +

     

    + +

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean +that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes +the Hadamard product, meaning element-wise multiplication. +

    + +

    This again gives us the gradients in the hidden layer:

    + +

     
    +$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ +

     

    + +

     
    +$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ +

     

    + + + +
    +
    +
    +
    +
    +
    # to categorical turns our integer vector into a onehot representation
    +from sklearn.metrics import accuracy_score
    +
    +# one-hot in numpy
    +def to_categorical_numpy(integer_vector):
    +    n_inputs = len(integer_vector)
    +    n_categories = np.max(integer_vector) + 1
    +    onehot_vector = np.zeros((n_inputs, n_categories))
    +    onehot_vector[range(n_inputs), integer_vector] = 1
    +    
    +    return onehot_vector
    +
    +#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    +Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    +
    +def feed_forward_train(X):
    +    # weighted sum of inputs to the hidden layer
    +    z_h = np.matmul(X, hidden_weights) + hidden_bias
    +    # activation in the hidden layer
    +    a_h = sigmoid(z_h)
    +    
    +    # weighted sum of inputs to the output layer
    +    z_o = np.matmul(a_h, output_weights) + output_bias
    +    # softmax output
    +    # axis 0 holds each input and axis 1 the probabilities of each category
    +    exp_term = np.exp(z_o)
    +    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +    
    +    # for backpropagation need activations in hidden and output layers
    +    return a_h, probabilities
    +
    +def backpropagation(X, Y):
    +    a_h, probabilities = feed_forward_train(X)
    +    
    +    # error in the output layer
    +    error_output = probabilities - Y
    +    # error in the hidden layer
    +    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    +    
    +    # gradients for the output layer
    +    output_weights_gradient = np.matmul(a_h.T, error_output)
    +    output_bias_gradient = np.sum(error_output, axis=0)
    +    
    +    # gradient for the hidden layer
    +    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    +    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    +
    +    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    +
    +print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    +
    +eta = 0.01
    +lmbd = 0.01
    +for i in range(1000):
    +    # calculate gradients
    +    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    +    
    +    # regularization term gradients
    +    dWo += lmbd * output_weights
    +    dWh += lmbd * hidden_weights
    +    
    +    # update weights and biases
    +    output_weights -= eta * dWo
    +    output_bias -= eta * dBo
    +    hidden_weights -= eta * dWh
    +    hidden_bias -= eta * dBh
    +
    +print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Improving performance

    + +

    As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. +In order to obtain a network that does something useful, we will have to do a bit more work. +

    + +

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    + +

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period +going through the entire dataset (\( n/M \) batches) an epoch. +

    + +

    If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. +Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. +

    +
    + +
    +

    Full object-oriented implementation

    + +

    It is very natural to think of the network as an object, with specific instances of the network +being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. +

    + + + +
    +
    +
    +
    +
    +
    class NeuralNetwork:
    +    def __init__(
    +            self,
    +            X_data,
    +            Y_data,
    +            n_hidden_neurons=50,
    +            n_categories=10,
    +            epochs=10,
    +            batch_size=100,
    +            eta=0.1,
    +            lmbd=0.0):
    +
    +        self.X_data_full = X_data
    +        self.Y_data_full = Y_data
    +
    +        self.n_inputs = X_data.shape[0]
    +        self.n_features = X_data.shape[1]
    +        self.n_hidden_neurons = n_hidden_neurons
    +        self.n_categories = n_categories
    +
    +        self.epochs = epochs
    +        self.batch_size = batch_size
    +        self.iterations = self.n_inputs // self.batch_size
    +        self.eta = eta
    +        self.lmbd = lmbd
    +
    +        self.create_biases_and_weights()
    +
    +    def create_biases_and_weights(self):
    +        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    +        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    +
    +        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    +        self.output_bias = np.zeros(self.n_categories) + 0.01
    +
    +    def feed_forward(self):
    +        # feed-forward for training
    +        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    +        self.a_h = sigmoid(self.z_h)
    +
    +        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    +
    +        exp_term = np.exp(self.z_o)
    +        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +
    +    def feed_forward_out(self, X):
    +        # feed-forward for output
    +        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    +        a_h = sigmoid(z_h)
    +
    +        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    +        
    +        exp_term = np.exp(z_o)
    +        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +        return probabilities
    +
    +    def backpropagation(self):
    +        error_output = self.probabilities - self.Y_data
    +        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    +
    +        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    +        self.output_bias_gradient = np.sum(error_output, axis=0)
    +
    +        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    +        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    +
    +        if self.lmbd > 0.0:
    +            self.output_weights_gradient += self.lmbd * self.output_weights
    +            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    +
    +        self.output_weights -= self.eta * self.output_weights_gradient
    +        self.output_bias -= self.eta * self.output_bias_gradient
    +        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    +        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    +
    +    def predict(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return np.argmax(probabilities, axis=1)
    +
    +    def predict_probabilities(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return probabilities
    +
    +    def train(self):
    +        data_indices = np.arange(self.n_inputs)
    +
    +        for i in range(self.epochs):
    +            for j in range(self.iterations):
    +                # pick datapoints with replacement
    +                chosen_datapoints = np.random.choice(
    +                    data_indices, size=self.batch_size, replace=False
    +                )
    +
    +                # minibatch training data
    +                self.X_data = self.X_data_full[chosen_datapoints]
    +                self.Y_data = self.Y_data_full[chosen_datapoints]
    +
    +                self.feed_forward()
    +                self.backpropagation()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Evaluate model performance on test data

    + +

    To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. +We measure the performance of the network using the accuracy score. +The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). +

    + +

     
    +$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ +

     

    + +

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    + + + +
    +
    +
    +
    +
    +
    epochs = 100
    +batch_size = 100
    +
    +dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +dnn.train()
    +test_predict = dnn.predict(X_test)
    +
    +# accuracy score from scikit library
    +print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +
    +# equivalent in numpy
    +def accuracy_score_numpy(Y_test, Y_pred):
    +    return np.sum(Y_test == Y_pred) / len(Y_test)
    +
    +#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Adjust hyperparameters

    + +

    We now perform a grid search to find the optimal hyperparameters for the network. +Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). +

    + + + +
    +
    +
    +
    +
    +
    eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +# store the models for later use
    +DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +
    +# grid search
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +        dnn.train()
    +        
    +        DNN_numpy[i][j] = dnn
    +        
    +        test_predict = dnn.predict(X_test)
    +        
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Visualization

    + + + +
    +
    +
    +
    +
    +
    # visual representation of grid search
    +# uses seaborn heatmap, you can also do this with matplotlib imshow
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_numpy[i][j]
    +        
    +        train_pred = dnn.predict(X_train) 
    +        test_pred = dnn.predict(X_test)
    +
    +        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    +        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    scikit-learn implementation

    + +

    scikit-learn focuses more +on traditional machine learning methods, such as regression, +clustering, decision trees, etc. As such, it has only two types of +neural networks: Multi Layer Perceptron outputting continuous values, +MPLRegressor, and Multi Layer Perceptron outputting labels, +MLPClassifier. We will see how simple it is to use these classes. +

    + +

    scikit-learn implements a few improvements from our neural network, +such as early stopping, a varying learning rate, different +optimization methods, etc. We would therefore expect a better +performance overall. +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.neural_network import MLPClassifier
    +# store models for later use
    +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    +                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    +        dnn.fit(X_train, Y_train)
    +        
    +        DNN_scikit[i][j] = dnn
    +        
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Visualization

    + + +
    +
    +
    +
    +
    +
    # optional
    +# visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_scikit[i][j]
    +        
    +        train_pred = dnn.predict(X_train) 
    +        test_pred = dnn.predict(X_test)
    +
    +        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    +        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Building neural networks in Tensorflow and Keras

    + +

    Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. +

    + +

    In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. +

    +
    + +
    +

    Tensorflow

    + +

    Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. +

    + +

    Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. +

    + +

    Tensorflow uses so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow graph +to represent your model, and then create a Tensorflow session to run the graph. +

    + +

    In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. +

    + +

    To install tensorflow on Unix/Linux systems, use pip as

    + + +
    +
    +
    +
    +
    +
    pip3 install tensorflow
     
    @@ -527,11 +1909,98 @@ probabilities = feed_forward(X)
    -

    Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above.

    +

    and/or if you use anaconda, just write (or install from the graphical user interface) +(current release of CPU-only TensorFlow) +

    + + +
    +
    +
    +
    +
    +
    conda create -n tf tensorflow
    +conda activate tf
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    To install the current release of GPU TensorFlow

    + + +
    +
    +
    +
    +
    +
    conda create -n tf-gpu tensorflow-gpu
    +conda activate tf-gpu
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    The Code using Scikit-Learn

    +

    Using Keras

    + +

    Keras is a high level neural network +that supports Tensorflow, CTNK and Theano as backends. +If you have Anaconda installed you may run the following command +

    + + +
    +
    +
    +
    +
    +
    conda install keras
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    You can look up the instructions here for more information.

    + +

    We will to a large extent use keras in this course.

    +
    + +
    +

    Collect and pre-process data

    + +

    Let us look again at the MINST data set.

    @@ -543,50 +2012,195 @@ probabilities = feed_forward(X)
    # import necessary packages
     import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.neural_network import MLPClassifier
    -from sklearn.metrics import accuracy_score
    -import seaborn as sns
    +import tensorflow as tf
    +from sklearn import datasets
    +
     
     # ensure the same random numbers appear every time
     np.random.seed(0)
     
    -# Design matrix
    -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
     
    -# The XOR gate
    -yXOR = np.array( [ 0, 1 ,1, 0])
    -# The OR gate
    -yOR = np.array( [ 0, 1 ,1, 1])
    -# The AND gate
    -yAND = np.array( [ 0, 0 ,0, 1])
     
    -# Defining the neural network
    -n_hidden_neurons = 2
    +# download MNIST dataset
    +digits = datasets.load_digits()
     
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +
    +from sklearn.model_selection import train_test_split
    +
    +# one-hot representation of labels
    +labels = to_categorical(labels)
    +
    +# split into train and test data
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    epochs = 100
    +batch_size = 100
    +n_neurons_layer1 = 100
    +n_neurons_layer2 = 50
    +n_categories = 10
     eta_vals = np.logspace(-5, 1, 7)
     lmbd_vals = np.logspace(-5, 1, 7)
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -epochs = 100
    -
    +def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
    +    model = Sequential()
    +    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_categories, activation='softmax'))
    +    
    +    sgd = optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    +    
    +    return model
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +        
     for i, eta in enumerate(eta_vals):
         for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X, yXOR)
    -        DNN_scikit[i][j] = dnn
    -        print("Learning rate  = ", eta)
    +        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
    +                                         eta=eta, lmbd=lmbd)
    +        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    +        scores = DNN.evaluate(X_test, Y_test)
    +        
    +        DNN_keras[i][j] = DNN
    +        
    +        print("Learning rate = ", eta)
             print("Lambda = ", lmbd)
    -        print("Accuracy score on data set: ", dnn.score(X, yXOR))
    +        print("Test accuracy: %.3f" % scores[1])
             print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    # optional
    +# visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
     
     sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
     test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
     for i in range(len(eta_vals)):
         for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    -        test_pred = dnn.predict(X)
    -        test_accuracy[i][j] = accuracy_score(yXOR, test_pred)
    +        DNN = DNN_keras[i][j]
    +
    +        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
    +        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
     
     fig, ax = plt.subplots(figsize = (10, 10))
     sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    @@ -610,6 +2224,197 @@ plt.show()
     
    +
    +

    The Breast Cancer Data, now with Keras

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +import numpy as np
    +import matplotlib.pyplot as plt
    +import seaborn as sns
    +from sklearn.model_selection import train_test_split as splitter
    +from sklearn.datasets import load_breast_cancer
    +import pickle
    +import os 
    +
    +
    +"""Load breast cancer dataset"""
    +
    +np.random.seed(0)        #create same seed for random number every time
    +
    +cancer=load_breast_cancer()      #Download breast cancer dataset
    +
    +inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    +outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    +labels=cancer.feature_names[0:30]
    +
    +print('The content of the breast cancer dataset is:')      #Print information about the datasets
    +print(labels)
    +print('-------------------------')
    +print("inputs =  " + str(inputs.shape))
    +print("outputs =  " + str(outputs.shape))
    +print("labels =  "+ str(labels.shape))
    +
    +x=inputs      #Reassign the Feature and Label matrices to other variables
    +y=outputs
    +
    +#%% 
    +
    +# Visualisation of dataset (for correlation analysis)
    +
    +plt.figure()
    +plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean radius',fontweight='bold')
    +plt.ylabel('Mean perimeter',fontweight='bold')
    +plt.show()
    +
    +plt.figure()
    +plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    +plt.xlabel('Mean compactness',fontweight='bold')
    +plt.ylabel('Mean concavity',fontweight='bold')
    +plt.show()
    +
    +
    +plt.figure()
    +plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean radius',fontweight='bold')
    +plt.ylabel('Mean texture',fontweight='bold')
    +plt.show()
    +
    +plt.figure()
    +plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean perimeter',fontweight='bold')
    +plt.ylabel('Mean compactness',fontweight='bold')
    +plt.show()
    +
    +
    +# Generate training and testing datasets
    +
    +#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    +#and add to input matrix
    +
    +temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    +temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    +X=np.hstack((temp1,temp2))      
    +temp=np.reshape(x[:,5],(len(x[:,5]),1))
    +X=np.hstack((X,temp))       
    +temp=np.reshape(x[:,8],(len(x[:,8]),1))
    +X=np.hstack((X,temp))       
    +
    +X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    +
    +y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    +y_test=to_categorical(y_test)
    +
    +del temp1,temp2,temp
    +
    +# %%
    +
    +# Define tunable parameters"
    +
    +eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    +lamda=0.01                                  #Define hyperparameter
    +n_layers=2                                  #Define number of hidden layers in the model
    +n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    +epochs=100                                   #Number of reiterations over the input data
    +batch_size=100                              #Number of samples per gradient update
    +
    +# %%
    +
    +"""Define function to return Deep Neural Network model"""
    +
    +def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    +    model=Sequential()      
    +    for i in range(n_layers):       #Run loop to add hidden layers to the model
    +        if (i==0):                  #First layer requires input dimensions
    +            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    +        else:                       #Subsequent layers are capable of automatic shape inferencing
    +            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    +    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    +    sgd=optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    +    return model
    +
    +    
    +Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    +Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    +
    +for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    +    for j in range(len(eta)):      #accuracy scores 
    +        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    +        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    +        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    +        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    +               
    +
    +def plot_data(x,y,data,title=None):
    +
    +    # plot results
    +    fontsize=16
    +
    +
    +    fig = plt.figure()
    +    ax = fig.add_subplot(111)
    +    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    +    
    +    cbar=fig.colorbar(cax)
    +    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    +    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    +    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    +
    +    # put text on matrix elements
    +    for i, x_val in enumerate(np.arange(len(x))):
    +        for j, y_val in enumerate(np.arange(len(y))):
    +            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    +            ax.text(x_val, y_val, c, va='center', ha='center')
    +
    +    # convert axis vaues to to string labels
    +    x=[str(i) for i in x]
    +    y=[str(i) for i in y]
    +
    +
    +    ax.set_xticklabels(['']+x)
    +    ax.set_yticklabels(['']+y)
    +
    +    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    +    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    +    if title is not None:
    +        ax.set_title(title)
    +
    +    plt.tight_layout()
    +
    +    plt.show()
    +    
    +plot_data(eta,n_neuron,Train_accuracy, 'training')
    +plot_data(eta,n_neuron,Test_accuracy, 'testing')
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Building a neural network code

    @@ -1961,2064 +3766,6 @@ scores = logistic_regression.fit(X, yXOR, scheduler, epochs=Lecture Thursday October 26 -
    - -
    -

    Developing a code for doing neural networks with back propagation

    - -

    We repeat some of the elements discussed last week. The first part of -the material for Thursday was contained in the slides for last -week as well. We will repeat some of the topics here before we move into -applications to differential equations and other examples. -

    - -

    One can identify a set of key steps when using neural networks to solve supervised learning problems:

    - -
      -

    1. Collect and pre-process data
    2. - -

    3. Define model and architecture
    4. - -

    5. Choose cost function and optimizer
    6. - -

    7. Train the model
    8. - -

    9. Evaluate model performance on test data
    10. - -

    11. Adjust hyperparameters (if necessary, network architecture)
    12. -
    -
    - -
    -

    Collect and pre-process data

    - -

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

    - -

    To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

    - -

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

    - -

     
    -$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

     
    -

    - -

    and the targets would be:

    - -

     
    -$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ -

     

    - -

    Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

    - - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Train and test datasets

    - -

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    - -

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    - -

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -
    -# one-liner from scikit-learn library
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -# equivalently in numpy
    -def train_test_split_numpy(inputs, labels, train_size, test_size):
    -    n_inputs = len(inputs)
    -    inputs_shuffled = inputs.copy()
    -    labels_shuffled = labels.copy()
    -    
    -    np.random.shuffle(inputs_shuffled)
    -    np.random.shuffle(labels_shuffled)
    -    
    -    train_end = int(n_inputs*train_size)
    -    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    -    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    -    
    -    return X_train, X_test, Y_train, Y_test
    -
    -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    -
    -print("Number of training images: " + str(len(X_train)))
    -print("Number of test images: " + str(len(X_test)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Define model and architecture

    - -

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    - -

     
    -$$ z = \sum_{i=1}^n w_i a_i ,$$ -

     

    - -

     
    -$$ y = f(z) ,$$ -

     

    - -

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

    - -

    The simplest activation function for a neuron is the Heaviside function:

    - -

     
    -$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

     
    -

    - -

    A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

    - -

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

    - -

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

    - -

     
    -$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$ -

     

    - -

    which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

    -
    - -
    -

    Layers

    - -
      -

    • Input
    • -
    -

    -

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    - -
      -

    • Hidden layer
    • -
    -

    -

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

    - -
      -

    • Output
    • -
    -

    -

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

    - -

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    - -

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    - -

     
    -$$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

     
    -

    - -

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

    - -

     
    -$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ -

     

    - -

    Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. -

    -
    - -
    -

    Weights and biases

    - -

    Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. -

    - -

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

    - -

     
    -$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ -

     

    - -

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    - - -
    -
    -
    -
    -
    -
    # building our neural network
    -
    -n_inputs, n_features = X_train.shape
    -n_hidden_neurons = 50
    -n_categories = 10
    -
    -# we make the weights normally distributed using numpy.random.randn
    -
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    -
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Feed-forward pass

    - -

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

    - -

     
    -$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ -

     

    - -

    this is then passed through our activation function

    - -

     
    -$$ a_{j}^{l} = f(z_{j}^{l}) .$$ -

     

    - -

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    - -

     
    -$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ -

     

    - -

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    - -

     
    -$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

     
    -

    -
    - -
    -

    Matrix multiplications

    - -

    Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden -layer have the dimensions -\( W_{hidden} = (n_{features}, n_{hidden}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

    - -

     
    -$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ -

     

    - -

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

    - -

     
    -$$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$ -

     

    - -

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

    - -

     
    -$$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$ -

     

    - -

    This is fed to the output layer:

    - -

     
    -$$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$ -

     

    - -

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    - -

     
    -$$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$ -

     

    - - - -
    -
    -
    -
    -
    -
    # setup the feed-forward pass, subscript h = hidden layer
    -
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    return probabilities
    -
    -probabilities = feed_forward(X_train)
    -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    -print("probabilities sum up to: " + str(probabilities[0].sum()))
    -print()
    -
    -# we obtain a prediction by taking the class with the highest likelihood
    -def predict(X):
    -    probabilities = feed_forward(X)
    -    return np.argmax(probabilities, axis=1)
    -
    -predictions = predict(X_train)
    -print("predictions = (n_inputs) = " + str(predictions.shape))
    -print("prediction for image 0: " + str(predictions[0]))
    -print("correct label for image 0: " + str(Y_train[0]))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Choose cost function and optimizer

    - -

    To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

     
    -$$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ -

     

    - -

     
    -$$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ -

     

    - -

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

    - -

    Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

    - -

    In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category \( c' \) -(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. -

    -
    - -
    -

    Optimizing the cost function

    - -

    The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

    - -

     
    -$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ -

     

    - -

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

    - -

    A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

    - -

     
    -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

     
    -

    - -

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    - -

    This has two important benefits:

    -
      -

    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. - -

    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. -
    -

    -

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    -
    - -
    -

    Regularization

    - -

    It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

    - -

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    - -

     
    -$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

     
    -

    - -

    i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

    - -

    In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has \( (64 + 1)\times 50=3250 \) weights in -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -layer (\( +1 \) for the bias), and the gradient must be calculated for -every parameter. We use the backpropagation algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. -

    -
    - -
    -

    Matrix multiplication

    - -

    To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

    - -

     
    -$$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ -

     

    - -

    The gradient for the output weights is calculated as

    - -

     
    -$$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ -

     

    - -

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

    - -

    The gradient with respect to the output bias is then

    - -

     
    -$$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ -

     

    - -

    The error in the hidden layer is

    - -

     
    -$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ -

     

    - -

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

    - -

    This again gives us the gradients in the hidden layer:

    - -

     
    -$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ -

     

    - -

     
    -$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ -

     

    - - - -
    -
    -
    -
    -
    -
    # to categorical turns our integer vector into a onehot representation
    -from sklearn.metrics import accuracy_score
    -
    -# one-hot in numpy
    -def to_categorical_numpy(integer_vector):
    -    n_inputs = len(integer_vector)
    -    n_categories = np.max(integer_vector) + 1
    -    onehot_vector = np.zeros((n_inputs, n_categories))
    -    onehot_vector[range(n_inputs), integer_vector] = 1
    -    
    -    return onehot_vector
    -
    -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    -
    -def feed_forward_train(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    # for backpropagation need activations in hidden and output layers
    -    return a_h, probabilities
    -
    -def backpropagation(X, Y):
    -    a_h, probabilities = feed_forward_train(X)
    -    
    -    # error in the output layer
    -    error_output = probabilities - Y
    -    # error in the hidden layer
    -    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    -    
    -    # gradients for the output layer
    -    output_weights_gradient = np.matmul(a_h.T, error_output)
    -    output_bias_gradient = np.sum(error_output, axis=0)
    -    
    -    # gradient for the hidden layer
    -    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    -    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    -
    -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -eta = 0.01
    -lmbd = 0.01
    -for i in range(1000):
    -    # calculate gradients
    -    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    -    
    -    # regularization term gradients
    -    dWo += lmbd * output_weights
    -    dWh += lmbd * hidden_weights
    -    
    -    # update weights and biases
    -    output_weights -= eta * dWo
    -    output_bias -= eta * dBo
    -    hidden_weights -= eta * dWh
    -    hidden_bias -= eta * dBh
    -
    -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Improving performance

    - -

    As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. -

    - -

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    - -

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

    - -

    If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. -

    -
    - -
    -

    Full object-oriented implementation

    - -

    It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. -

    - - - -
    -
    -
    -
    -
    -
    class NeuralNetwork:
    -    def __init__(
    -            self,
    -            X_data,
    -            Y_data,
    -            n_hidden_neurons=50,
    -            n_categories=10,
    -            epochs=10,
    -            batch_size=100,
    -            eta=0.1,
    -            lmbd=0.0):
    -
    -        self.X_data_full = X_data
    -        self.Y_data_full = Y_data
    -
    -        self.n_inputs = X_data.shape[0]
    -        self.n_features = X_data.shape[1]
    -        self.n_hidden_neurons = n_hidden_neurons
    -        self.n_categories = n_categories
    -
    -        self.epochs = epochs
    -        self.batch_size = batch_size
    -        self.iterations = self.n_inputs // self.batch_size
    -        self.eta = eta
    -        self.lmbd = lmbd
    -
    -        self.create_biases_and_weights()
    -
    -    def create_biases_and_weights(self):
    -        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    -        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    -
    -        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    -        self.output_bias = np.zeros(self.n_categories) + 0.01
    -
    -    def feed_forward(self):
    -        # feed-forward for training
    -        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    -        self.a_h = sigmoid(self.z_h)
    -
    -        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    -
    -        exp_term = np.exp(self.z_o)
    -        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -
    -    def feed_forward_out(self, X):
    -        # feed-forward for output
    -        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    -        a_h = sigmoid(z_h)
    -
    -        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    -        
    -        exp_term = np.exp(z_o)
    -        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -        return probabilities
    -
    -    def backpropagation(self):
    -        error_output = self.probabilities - self.Y_data
    -        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    -
    -        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    -        self.output_bias_gradient = np.sum(error_output, axis=0)
    -
    -        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    -        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -        if self.lmbd > 0.0:
    -            self.output_weights_gradient += self.lmbd * self.output_weights
    -            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    -
    -        self.output_weights -= self.eta * self.output_weights_gradient
    -        self.output_bias -= self.eta * self.output_bias_gradient
    -        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    -        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    -
    -    def predict(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return np.argmax(probabilities, axis=1)
    -
    -    def predict_probabilities(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return probabilities
    -
    -    def train(self):
    -        data_indices = np.arange(self.n_inputs)
    -
    -        for i in range(self.epochs):
    -            for j in range(self.iterations):
    -                # pick datapoints with replacement
    -                chosen_datapoints = np.random.choice(
    -                    data_indices, size=self.batch_size, replace=False
    -                )
    -
    -                # minibatch training data
    -                self.X_data = self.X_data_full[chosen_datapoints]
    -                self.Y_data = self.Y_data_full[chosen_datapoints]
    -
    -                self.feed_forward()
    -                self.backpropagation()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Evaluate model performance on test data

    - -

    To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the accuracy score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). -

    - -

     
    -$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ -

     

    - -

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    - - - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -
    -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -dnn.train()
    -test_predict = dnn.predict(X_test)
    -
    -# accuracy score from scikit library
    -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -
    -# equivalent in numpy
    -def accuracy_score_numpy(Y_test, Y_pred):
    -    return np.sum(Y_test == Y_pred) / len(Y_test)
    -
    -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Adjust hyperparameters

    - -

    We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

    - - - -
    -
    -
    -
    -
    -
    eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -# store the models for later use
    -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -# grid search
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -        dnn.train()
    -        
    -        DNN_numpy[i][j] = dnn
    -        
    -        test_predict = dnn.predict(X_test)
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, you can also do this with matplotlib imshow
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_numpy[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    scikit-learn implementation

    - -

    scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

    - -

    scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.neural_network import MLPClassifier
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X_train, Y_train)
    -        
    -        DNN_scikit[i][j] = dnn
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Visualization

    - - -
    -
    -
    -
    -
    -
    # optional
    -# visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Building neural networks in Tensorflow and Keras

    - -

    Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. -

    - -

    In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. -

    -
    - -
    -

    Tensorflow

    - -

    Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. -

    - -

    Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. -

    - -

    Tensorflow uses so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow graph -to represent your model, and then create a Tensorflow session to run the graph. -

    - -

    In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. -

    - -

    To install tensorflow on Unix/Linux systems, use pip as

    - - -
    -
    -
    -
    -
    -
    pip3 install tensorflow
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    and/or if you use anaconda, just write (or install from the graphical user interface) -(current release of CPU-only TensorFlow) -

    - - -
    -
    -
    -
    -
    -
    conda create -n tf tensorflow
    -conda activate tf
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    To install the current release of GPU TensorFlow

    - - -
    -
    -
    -
    -
    -
    conda create -n tf-gpu tensorflow-gpu
    -conda activate tf-gpu
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Using Keras

    - -

    Keras is a high level neural network -that supports Tensorflow, CTNK and Theano as backends. -If you have Anaconda installed you may run the following command -

    - - -
    -
    -
    -
    -
    -
    conda install keras
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    You can look up the instructions here for more information.

    - -

    We will to a large extent use keras in our examples..

    -
    - -
    -

    Collect and pre-process data

    - -

    Let us look again at the MINST data set.

    - - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import tensorflow as tf
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -
    -from sklearn.model_selection import train_test_split
    -
    -# one-hot representation of labels
    -labels = to_categorical(labels)
    -
    -# split into train and test data
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -n_neurons_layer1 = 100
    -n_neurons_layer2 = 50
    -n_categories = 10
    -eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
    -    model = Sequential()
    -    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(Dense(n_categories, activation='softmax'))
    -    
    -    sgd = optimizers.SGD(lr=eta)
    -    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    -    
    -    return model
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -        
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
    -                                         eta=eta, lmbd=lmbd)
    -        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    -        scores = DNN.evaluate(X_test, Y_test)
    -        
    -        DNN_keras[i][j] = DNN
    -        
    -        print("Learning rate = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Test accuracy: %.3f" % scores[1])
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    # optional
    -# visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        DNN = DNN_keras[i][j]
    -
    -        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
    -        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    The Breast Cancer Data, now with Keras

    - - - -
    -
    -
    -
    -
    -
    import tensorflow as tf
    -from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import seaborn as sns
    -from sklearn.model_selection import train_test_split as splitter
    -from sklearn.datasets import load_breast_cancer
    -import pickle
    -import os 
    -
    -
    -"""Load breast cancer dataset"""
    -
    -np.random.seed(0)        #create same seed for random number every time
    -
    -cancer=load_breast_cancer()      #Download breast cancer dataset
    -
    -inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    -outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    -labels=cancer.feature_names[0:30]
    -
    -print('The content of the breast cancer dataset is:')      #Print information about the datasets
    -print(labels)
    -print('-------------------------')
    -print("inputs =  " + str(inputs.shape))
    -print("outputs =  " + str(outputs.shape))
    -print("labels =  "+ str(labels.shape))
    -
    -x=inputs      #Reassign the Feature and Label matrices to other variables
    -y=outputs
    -
    -#%% 
    -
    -# Visualisation of dataset (for correlation analysis)
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean perimeter',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    -plt.xlabel('Mean compactness',fontweight='bold')
    -plt.ylabel('Mean concavity',fontweight='bold')
    -plt.show()
    -
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean texture',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean perimeter',fontweight='bold')
    -plt.ylabel('Mean compactness',fontweight='bold')
    -plt.show()
    -
    -
    -# Generate training and testing datasets
    -
    -#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    -#and add to input matrix
    -
    -temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    -temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    -X=np.hstack((temp1,temp2))      
    -temp=np.reshape(x[:,5],(len(x[:,5]),1))
    -X=np.hstack((X,temp))       
    -temp=np.reshape(x[:,8],(len(x[:,8]),1))
    -X=np.hstack((X,temp))       
    -
    -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    -
    -y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    -y_test=to_categorical(y_test)
    -
    -del temp1,temp2,temp
    -
    -# %%
    -
    -# Define tunable parameters"
    -
    -eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    -lamda=0.01                                  #Define hyperparameter
    -n_layers=2                                  #Define number of hidden layers in the model
    -n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    -epochs=100                                   #Number of reiterations over the input data
    -batch_size=100                              #Number of samples per gradient update
    -
    -# %%
    -
    -"""Define function to return Deep Neural Network model"""
    -
    -def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    -    model=Sequential()      
    -    for i in range(n_layers):       #Run loop to add hidden layers to the model
    -        if (i==0):                  #First layer requires input dimensions
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    -        else:                       #Subsequent layers are capable of automatic shape inferencing
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    -    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    -    sgd=optimizers.SGD(lr=eta)
    -    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    -    return model
    -
    -    
    -Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    -Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    -
    -for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    -    for j in range(len(eta)):      #accuracy scores 
    -        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    -        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    -        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    -        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    -               
    -
    -def plot_data(x,y,data,title=None):
    -
    -    # plot results
    -    fontsize=16
    -
    -
    -    fig = plt.figure()
    -    ax = fig.add_subplot(111)
    -    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    -    
    -    cbar=fig.colorbar(cax)
    -    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    -    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    -    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    -
    -    # put text on matrix elements
    -    for i, x_val in enumerate(np.arange(len(x))):
    -        for j, y_val in enumerate(np.arange(len(y))):
    -            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    -            ax.text(x_val, y_val, c, va='center', ha='center')
    -
    -    # convert axis vaues to to string labels
    -    x=[str(i) for i in x]
    -    y=[str(i) for i in y]
    -
    -
    -    ax.set_xticklabels(['']+x)
    -    ax.set_yticklabels(['']+y)
    -
    -    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    -    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    -    if title is not None:
    -        ax.set_title(title)
    -
    -    plt.tight_layout()
    -
    -    plt.show()
    -    
    -plot_data(eta,n_neuron,Train_accuracy, 'training')
    -plot_data(eta,n_neuron,Test_accuracy, 'testing')
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Fine-tuning neural network hyperparameters

    - -

    The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are interconnected), -but even in a simple FFNN you can change the number of layers, the -number of neurons per layer, the type of activation function to use in -each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you -know what combination of hyperparameters is the best for your task? -

    - -
      -

    • You can use grid search with cross-validation to find the right hyperparameters.
    • -
    -

    -

    However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. -

    - -
      -

    • You can use randomized search.
    • -

    • Or use tools like Oscar, which implements more complex algorithms to help you find a good set of hyperparameters quickly.
    • -
    -
    - -
    -

    Hidden layers

    - -

    For many problems you can start with just one or two hidden layers and it will work just fine. -For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a -few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of -neurons, in roughly the same amount of training time. -

    - -

    For more complex problems, you can gradually -ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such -as large image classification or speech recognition, typically require networks with dozens of layers -and they need a huge amount -of training data. However, you will rarely have to train such networks from scratch: it is much more -common to reuse parts of a pretrained state-of-the-art network that performs a similar task. -

    -
    - -
    -

    Which activation function should I use?

    - -

    The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. -

    - -

    Unfortunately for us, the gradients often get smaller and smaller as the -algorithm progresses down to the first hidden layers. As a result, the -GD update leaves the lower layer connection weights -virtually unchanged, and training never converges to a good -solution. This is known in the literature as -the vanishing gradients problem. -

    - -

    In other cases, the opposite can happen, namely the the gradients can grow bigger and -bigger. The result is that many of the layers get large updates of the -weights the -algorithm diverges. This is the exploding gradients problem, which is -mostly encountered in recurrent neural networks. More generally, deep -neural networks suffer from unstable gradients, different layers may -learn at widely different speeds -

    -
    - -
    -

    Is the Logistic activation function (Sigmoid) our choice?

    - -

    Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. -

    - -

    A paper titled Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -

    - -

    They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -

    -
    - -
    -

    The derivative of the Logistic funtion

    - -

    Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. -

    - -

    In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -

    - -

    One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -

    -
    - -
    -

    The RELU function family

    - -

    The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. -

    - -

    In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. -

    - -

    To solve this problem, nowadays practitioners use a variant of the ReLU -function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function -

    - -

     
    -$$ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -$$ -

     
    -

    - -
    -

    Which activation function should we use?

    - -

    In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than \( \tanh \) which in turn performs better -than the logistic function. -

    - -

    If runtime -performance is an issue, then you may opt for the leaky ReLU function over the -ELU function If you don’t -want to tweak yet another hyperparameter, you may just use the default -\( \alpha \) of \( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have -spare time and computing power, you can use cross-validation or -bootstrap to evaluate other activation functions. -

    -
    - -
    -

    More on activation functions, output layers

    - -

    In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).

    - -

    It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck.

    - -For the output layer: - -
      -

    • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
    • -

    • For regression tasks, you can simply use no activation function at all.
    • -
    -
    - -
    -

    Batch Normalization

    - -

    Batch Normalization -aims to address the vanishing/exploding gradients problems, and more generally the problem that the -distribution of each layer’s inputs changes during training, as the parameters of the previous layers change. -

    - -

    The technique consists of adding an operation in the model just before the activation function of each -layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new -parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model -learn the optimal scale and mean of the inputs for each layer. -In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and -standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current -mini-batch, from this the name batch normalization. -

    -
    - -
    -

    Dropout

    - -

    It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but -excluding the output neurons) has a probability \( p \) of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active during the next step. -

    - -

    The -hyperparameter \( p \) is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore. - It is viewed as one of the most popular regularization techniques. -

    -
    - -
    -

    Gradient Clipping

    - -

    A popular technique to lessen the exploding gradients problem is to simply clip the gradients during -backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural -networks). -

    - -

    This technique is called Gradient Clipping.

    - -

    In general however, Batch -Normalization is preferred. -

    -
    - -
    -

    A very nice website on Neural Networks

    - -

    You may find this website very useful.

    -
    - -
    -

    A top-down perspective on Neural networks

    - -

    The first thing we would like to do is divide the data into two or three -parts. A training set, a validation or dev (development) set, and a -test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: -

    - -
      -

    • Estimate optimal error rate
    • -

    • Minimize underfitting (bias) on training data set.
    • -

    • Make sure you are not overfitting.
    • -
    -

    -

    If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. -

    - -

    However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -

    -
    - -
    -

    Limitations of supervised learning with deep networks

    - -

    Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). -

    - -

    Here we list some of the important limitations of supervised neural network based models.

    - -
      -

    • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
    • -

    • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
    • -

    • Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
    • -

    • Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
    • -
    -

    -

    Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.

    -
    -

    Solving ODEs with Deep Learning

    diff --git a/doc/pub/week43/html/week43-solarized.html b/doc/pub/week43/html/week43-solarized.html index 5f10c8219..b12aa532f 100644 --- a/doc/pub/week43/html/week43-solarized.html +++ b/doc/pub/week43/html/week43-solarized.html @@ -64,6 +64,19 @@ div.toc p,a {
    @@ -388,40 +380,61 @@ MathJax.Hub.Config({

    Plans for week 43

    -Material for the active learning sessions on Tuesday and Wednesday +Material for the lecture on Monday October 21, 2024

      -
    • Exercise on writing your own neural network code, application to the OR and XOR gates
    • +
    • Building our own Feed-forward Neural Network with intro to Tensorflow
    • +
    • Solving differential equations with Neural Networks + +
    • +
    +
    + + +









    +

    Exercises and lab session week 43

    +
    +Lab sessions on Tuesday and Wednesday +

    +

      +
    • Exercise on writing your own neural network code
    • The exercises this week will be continued next week as well
    • Discussion of project 2
    • -
    • Video of lab session
    +









    +

    Mathematics of deep learning

    +
    -Material for the lecture on Thursday October 26, 2023 +Two recent books online

    -

    -

    I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at http://neuralnetworksanddeeplearning.com/chap4.html.

    +
      +
    1. The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen, published as Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022
    2. +
    3. Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger
    4. +
    +









    +

    Reminder on books with hands-on material and codes

    + + + +









    +

    Reading recommendations

    + +
      +
    1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub. See also chapters 12 and 13 on using Pytorch to make a Neural network code.
    2. +
    3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
    4. +










    Using Automatic differentiation

    a @@ -440,160 +453,404 @@ t

  • Slides 12-44 at URL":http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf"










  • -

    Material for exercises week 43 and week 44

    +

    Lecture Monday October 21











    -

    Writing our first neural network code, testing it for the OR and XOR gates

    +

    Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

    +

    This is a reminder from where we ended last week.

    -

    During week 41 we discussed three different types of gates, the -so-called XOR, the OR and the AND gates. In order to develop a code -for neural networks, it can be useful to set up a simpler system with -only two inputs and one output. This can make it easier to debug and -study the feed forward pass and the back propagation part. In the -exercise this and next week, we propose to study this system with just -one hidden layer and two hidden nodes. There is only one output node -and we can choose to use either a simple regression case (fitting a -line) or just a binary classification case with the corss-entropy as -cost function. +

    +The architecture (our model) +

    +

      +
    1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)
    2. +
    3. Define the number of hidden layers and hidden nodes
    4. +
    5. Define activation functions for hidden layers and output layers
    6. +
    7. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates
    8. +
    9. Define cost function and possible regularization terms with hyperparameters
    10. +
    11. Initialize weights and biases
    12. +
    13. Fix number of iterations for the feed forward part and back propagation part
    14. +
    +
    + + +









    +

    Setting up the back propagation algorithm, part 1

    + +

    Let us write this out in the form of an algorithm.

    + +

    First, we set up the input data \( \boldsymbol{x} \) and the activations +\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and +the pertinent outputs \( \boldsymbol{a}^1 \).

    -

    Their inputs and outputs can be -summarized using the following tables, first for the OR gate with -inputs \( x_1 \) and \( x_2 \) and outputs \( y \): +

    Secondly, we perform then the feed forward till we reach the output +layer and compute all \( \boldsymbol{z}_l \) of the input layer and compute the +activation function and the pertinent outputs \( \boldsymbol{a}^l \) for +\( l=1,2,3,\dots,L \).

    - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 1
    1 0 1
    1 1 1
    +

    Notation: The first hidden layer has \( l=1 \) as label and the final output layer has \( l=L \).











    -

    The AND and XOR Gates

    +

    Setting up the back propagation algorithm, part 2

    -

    The AND gate is defined as

    +

    Thereafter we compute the ouput error \( \boldsymbol{\delta}^L \) by computing all

    +$$ +\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. +$$ - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 0
    1 0 0
    1 1 1
    +

    Then we compute the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

    +$$ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). +$$ -

    And finally we have the XOR gate

    - - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 1
    1 0 1
    1 1 0










    -

    Representing the Data Sets

    +

    Setting up the Back propagation algorithm, part 3

    -

    Our design matrix is defined by the input values \( x_1 \) and \( x_2 \). Since we have four possible outputs, our design matrix reads

    +

    Finally, we update the weights and the biases using gradient descent +for each \( l=L-1,L-2,\dots,1 \) (the first hidden layer) and update the weights and biases +according to the rules +

    $$ -\boldsymbol{X}=\begin{bmatrix} 0 & 0 \\ - 0 & 1 \\ - 1 & 0 \\ - 1 & 1 \end{bmatrix}, +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, $$ -

    while the vector of outputs is \( \boldsymbol{y}^T=[0,1,1,0] \) for the XOR gate, \( \boldsymbol{y}^T=[0,0,0,1] \) for the AND gate and \( \boldsymbol{y}^T=[0,1,1,1] \) for the OR gate.

    -

    Your tasks here are

    +$$ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +$$ + +

    with \( \eta \) being the learning rate.

    + +









    +

    Updating the gradients

    + +

    With the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

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

    we update the weights and the biases using gradient descent for each \( l=L-1,L-2,\dots,1 \) and update the weights and biases according to the rules

    +$$ +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, +$$ + + +$$ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +$$ + + +









    +

    Activation functions

    + +

    A property that characterizes a neural network, other than its +connectivity, is the choice of activation function(s). The following +restrictions are imposed on an activation function for an FFNN to +fulfill the universal approximation theorem +

    + +
      +
    • Non-constant
    • +
    • Bounded
    • +
    • Monotonically-increasing
    • +
    • Continuous
    • +
    +









    +

    Activation functions, examples

    + +

    Typical examples are the logistic Sigmoid

    + +$$ + \sigma(x) = \frac{1}{1 + e^{-x}}, +$$ + +

    and the hyperbolic tangent function

    +$$ + \sigma(x) = \tanh(x) +$$ + + +









    +

    The RELU function family

    + +

    The ReLU activation function suffers from a problem known as the dying +ReLUs: during training, some neurons effectively die, meaning they +stop outputting anything other than 0. +

    + +

    In some cases, you may find that half of your network’s neurons are +dead, especially if you used a large learning rate. During training, +if a neuron’s weights get updated such that the weighted sum of the +neuron’s inputs is negative, it will start outputting 0. When this +happen, the neuron is unlikely to come back to life since the gradient +of the ReLU function is 0 when its input is negative. +

    + +









    +

    ELU function

    + +

    To solve this problem, nowadays practitioners use a variant of the +ReLU function, such as the leaky ReLU discussed above or the so-called +exponential linear unit (ELU) function +

    + +$$ +ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. +$$ + + +









    +

    Which activation function should we use?

    + +

    In general it seems that the ELU activation function is better than +the leaky ReLU function (and its variants), which is better than +ReLU. ReLU performs better than \( \tanh \) which in turn performs better +than the logistic function. +

    + +

    If runtime performance is an issue, then you may opt for the leaky +ReLU function over the ELU function If you don’t want to tweak yet +another hyperparameter, you may just use the default \( \alpha \) of +\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and +computing power, you can use cross-validation or bootstrap to evaluate +other activation functions. +

    + +









    +

    More on activation functions, output layers

    + +

    In most cases you can use the ReLU activation function in the hidden +layers (or one of its variants). +

    + +

    It is a bit faster to compute than other activation functions, and the +gradient descent optimization does in general not get stuck. +

    + +For the output layer: + +
      +
    • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
    • +
    • For regression tasks, you can simply use no activation function at all.
    • +
    + +

    Setting up a Multi-layer perceptron model for classification

    + +

    We are now gong to develop an example based on the MNIST data +base. This is a classification problem and we need to use our +cross-entropy function we discussed in connection with logistic +regression. The cross-entropy defines our cost function for the +classificaton problems with neural networks. +

    + +

    In binary classification with two classes \( (0, 1) \) we define the +logistic/sigmoid function as the probability that a particular input +is in class \( 0 \) or \( 1 \). This is possible because the logistic +function takes any input from the real numbers and inputs a number +between 0 and 1, and can therefore be interpreted as a probability. It +also has other nice properties, such as a derivative that is simple to +calculate. +

    + +

    For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) +is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) +represents our activation values \( z \). We have +

    +$$ +P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , +$$ + +

    and

    +$$ +P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , +$$ + +

    where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases +of our network. +

    + + +









    +

    Defining the cost function

    + +

    Our cost function is given as (see the Logistic regression lectures)

    +$$ +\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n +y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . +$$ + +

    This last equality means that we can interpret our cost function as a sum over the loss function +for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). +The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather +than maximizing a negative number. +

    + +

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    + +

    \( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

    + +\( y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) , \) + +

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset (numbers from \( 0 \) to \( 9 \))..

    + +

    If \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th +output vector \( \boldsymbol{y}_i \). +The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: +

    + +$$ +P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} +{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , +$$ + +

    which reduces to the logistic function in the binary case. +The likelihood of this \( C \)-class classifier +is now given as: +

    + +$$ +P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . +$$ + +

    Again we take the negative log-likelihood to define our cost function:

    + +$$ +\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. +$$ + +

    See the logistic regression lectures for a full definition of the cost function.

    + +

    The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!

    + +









    +

    Example: binary classification problem

    + +

    As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as

    +$$ +\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right), +$$ + +

    where we had defined the logistic (sigmoid) function

    +$$ +p(y_i =1\vert x_i,\boldsymbol{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, +$$ + +

    and

    +$$ +p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). +$$ + +

    The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

    + +

    Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). +We have then +

    +$$ +a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, +$$ + +

    with

    +$$ +z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, +$$ + +

    where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). +Our cost function at the final layer \( l=L \) is now +

    +$$ +\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), +$$ + +

    where we have defined the targets \( t_i \). The derivatives of the cost function with respect to the output \( a_i^L \) are then easily calculated and we get

    +$$ +\frac{\partial \mathcal{C}(\boldsymbol{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. +$$ + +

    In case we use another activation function than the logistic one, we need to evaluate other derivatives.

    + +









    +

    The Softmax function

    +

    In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need

    +$$ +\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = +\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. +$$ + +

    For the Softmax function we have

    +$$ +f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. +$$ + +

    Its derivative with respect to \( z_j^l \) gives

    +$$ +\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), +$$ + +

    which in case of the simply binary model reduces to having \( i=j \).

    + + +

    Developing a code for doing neural networks with back propagation

    + +

    One can identify a set of key steps when using neural networks to solve supervised learning problems:

      -
    1. Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs.
    2. -
    3. Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function.
    4. -
    5. Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output.
    6. -
    7. Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets.
    8. -
    9. Set up the cost function (cross entropy for classification of binary cases).
    10. -
    11. Calculate the gradients needed for the back propagation part.
    12. -
    13. Use the gradients to train the network in the back propagation part. Think of using automatic differentiation.
    14. -
    15. Train the network and study your results and compare with results obtained either with scikit-learn or TensorFlow.
    16. +
    17. Collect and pre-process data
    18. +
    19. Define model and architecture
    20. +
    21. Choose cost function and optimizer
    22. +
    23. Train the model
    24. +
    25. Evaluate model performance on test data
    26. +
    27. Adjust hyperparameters (if necessary, network architecture)
    -

    Everything you develop here can be used directly into the code for the project.

    -









    -

    Setting up dimensionalities by hand

    +

    Collect and pre-process data

    -

    It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by

    -$$ -\boldsymbol{W_h}=\begin{bmatrix} 1 & 1 \\ - 1 & 1 \end{bmatrix}, -$$ +

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn +package. You may also find it for example here. +The MNIST (Modified National Institute of Standards and Technology) database is a large database +of handwritten digits that is commonly used for training various image processing systems. +The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. +The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. +

    -

    Multiplying \( \boldsymbol{X} \) and \( \boldsymbol{W} \) gives

    +

    To feed data into a feed-forward neural network we need to represent +the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each +row represents an input, in this case a handwritten digit, and +each column represents a feature, in this case a pixel. The +correct answers, also known as labels or targets are +represented as a 1D array of integers +\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). +

    -$$ -\boldsymbol{X}{W}_h=\begin{bmatrix} 0 & 0 \\ - 1 & 1 \\ - 1 & 1 \\ - 2 & 2 \end{bmatrix}, -$$ +

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from +measurements of height (in m) +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: +

    -

    Assume also that the bias vector for the hidden layer is

    -$$ -\boldsymbol{b}_h=\begin{bmatrix} 0 \\ - -1\end{bmatrix}, -$$ +

    $$ X = \begin{bmatrix} +1.85 & 81\\ +1.71 & 65\\ +1.95 & 103\\ +1.55 & 42\\ +1.63 & 56 +\end{bmatrix} ,$$ +

    -

    Adding it gives us the input to the activation function of the hidden layer

    -$$ -\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h=\begin{bmatrix} 0 & -1 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, -$$ +

    and the targets would be:

    -

    Let us then assume that our activation function is the RELU function, which simply means that we take the max of \( 0 \) and the elements of the input argument \( \boldsymbol{z}_h \), that is we have

    -$$ -\boldsymbol{a}_h=\mathrm{RELU}(\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h)=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, -$$ +

    $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

    -

    Assume also that the bias of the output layer is zero and that the weights of the output layer are

    -$$ -\boldsymbol{w}_o=\begin{bmatrix} 1 \\ - -2\end{bmatrix}, -$$ - -

    and multiplying with \( \boldsymbol{a}_h \) gives the output

    -$$ -\boldsymbol{a}_o=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}\begin{bmatrix} 1 \\ - -2\end{bmatrix}=\begin{bmatrix} 0 \\ 1 \\ 1 \\0\end{bmatrix}, -$$ - -

    the wanted result. Pay attention to the dimensionalities as well.

    - -









    -

    Setting up the Neural Network

    - -

    We define first our design matrix and the various output vectors for the different gates.

    +

    Since each input image is a 2D matrix, we need to flatten the image +(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a +design/feature matrix. This means we lose all spatial information in the +image, such as locality and translational invariance. More complicated +architectures such as Convolutional Neural Networks can take advantage +of such information, and are most commonly applied when analyzing +images. +

    @@ -602,63 +859,48 @@ $$
    -
    """
    -Simple code that tests XOR, OR and AND gates with linear regression
    -"""
    -
    -# import necessary packages
    +  
    # import necessary packages
     import numpy as np
     import matplotlib.pyplot as plt
     from sklearn import datasets
     
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    probabilities = sigmoid(z_o)
    -    return probabilities
    -
     
     # ensure the same random numbers appear every time
     np.random.seed(0)
     
    -# Design matrix
    -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
     
    -# The XOR gate
    -yXOR = np.array( [ 0, 1 ,1, 0])
    -# The OR gate
    -yOR = np.array( [ 0, 1 ,1, 1])
    -# The AND gate
    -yAND = np.array( [ 0, 0 ,0, 1])
     
    -# Defining the neural network
    -n_inputs, n_features = X.shape
    -n_hidden_neurons = 2
    -n_categories = 1
    -n_features = 2
    +# download MNIST dataset
    +digits = datasets.load_digits()
     
    -# we make the weights normally distributed using numpy.random.randn
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
     
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
     
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
     
    -probabilities = feed_forward(X)
    -print(probabilities)
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
     
    @@ -674,10 +916,1117 @@ probabilities = feed_forward(X)
    -

    Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above.











    -

    The Code using Scikit-Learn

    +

    Train and test datasets

    + +

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    + +

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    + +

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure +no bias in the sampling. +Say you are taking measurements of weather data to predict the weather in the coming 5 days. +You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data +collected from 12.00 to 24.00. +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.model_selection import train_test_split
    +
    +# one-liner from scikit-learn library
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +# equivalently in numpy
    +def train_test_split_numpy(inputs, labels, train_size, test_size):
    +    n_inputs = len(inputs)
    +    inputs_shuffled = inputs.copy()
    +    labels_shuffled = labels.copy()
    +    
    +    np.random.shuffle(inputs_shuffled)
    +    np.random.shuffle(labels_shuffled)
    +    
    +    train_end = int(n_inputs*train_size)
    +    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    +    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    +    
    +    return X_train, X_test, Y_train, Y_test
    +
    +#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    +
    +print("Number of training images: " + str(len(X_train)))
    +print("Number of test images: " + str(len(X_test)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Define model and architecture

    + +

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    + +

    $$ z = \sum_{i=1}^n w_i a_i ,$$

    + +

    $$ y = f(z) ,$$

    + +

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer +and \( w_i \) is the weight to input \( i \). +The activation of the neurons in the input layer is just the features (e.g. a pixel value). +

    + +

    The simplest activation function for a neuron is the Heaviside function:

    + +

    $$ f(z) = +\begin{cases} +1, & z > 0\\ +0, & \text{otherwise} +\end{cases} +$$ +

    + +

    A feed-forward neural network with this activation is known as a perceptron. +For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. +This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), +and we call these architectures multiclass perceptrons. +

    + +

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and +Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. +

    + +

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). +We will be using the sigmoid function \( \sigma(x) \): +

    + +

    $$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$

    + +

    which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

    + + +

    Layers

    + +
      +
    • Input
    • +
    +

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    + +
      +
    • Hidden layer
    • +
    +

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. +Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. +

    + +
      +
    • Output
    • +
    +

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, +which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. +

    + +

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    + +

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    + +

    $$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} +{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ +

    + +

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. +The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. +The exponent is just the weighted sum of inputs as before: +

    + +

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

    + +

    Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 +weights to the output layer. +

    + + +

    Weights and biases

    + +

    Typically weights are initialized with small values distributed around zero, drawn from a uniform +or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. +

    + +

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range +of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): +

    + +

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

    + +

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    + + +
    +
    +
    +
    +
    +
    # building our neural network
    +
    +n_inputs, n_features = X_train.shape
    +n_hidden_neurons = 50
    +n_categories = 10
    +
    +# we make the weights normally distributed using numpy.random.randn
    +
    +# weights and bias in the hidden layer
    +hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    +hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    +
    +# weights and bias in the output layer
    +output_weights = np.random.randn(n_hidden_neurons, n_categories)
    +output_bias = np.zeros(n_categories) + 0.01
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Feed-forward pass

    + +

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. +For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): +

    + +

    $$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

    + +

    this is then passed through our activation function

    + +

    $$ a_{j}^{l} = f(z_{j}^{l}) .$$

    + +

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    + +

    $$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

    + +

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    + +

    $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} +{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ +

    + + +

    Matrix multiplications

    + +

    Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden +layer have the dimensions +\( W_{hidden} = (n_{features}, n_{hidden}) \), +we can easily feed the network all our training data in one go by taking the matrix product +

    + +

    $$ X W^{h} = (n_{inputs}, n_{hidden}),$$

    + +

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer +for each input image and each hidden neuron. +We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): +

    + +

    $$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

    + +

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. +This is then passed through the activation: +

    + +

    $$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

    + +

    This is fed to the output layer:

    + +

    $$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

    + +

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    + +

    $$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

    + + + +
    +
    +
    +
    +
    +
    # setup the feed-forward pass, subscript h = hidden layer
    +
    +def sigmoid(x):
    +    return 1/(1 + np.exp(-x))
    +
    +def feed_forward(X):
    +    # weighted sum of inputs to the hidden layer
    +    z_h = np.matmul(X, hidden_weights) + hidden_bias
    +    # activation in the hidden layer
    +    a_h = sigmoid(z_h)
    +    
    +    # weighted sum of inputs to the output layer
    +    z_o = np.matmul(a_h, output_weights) + output_bias
    +    # softmax output
    +    # axis 0 holds each input and axis 1 the probabilities of each category
    +    exp_term = np.exp(z_o)
    +    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +    
    +    return probabilities
    +
    +probabilities = feed_forward(X_train)
    +print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    +print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    +print("probabilities sum up to: " + str(probabilities[0].sum()))
    +print()
    +
    +# we obtain a prediction by taking the class with the highest likelihood
    +def predict(X):
    +    probabilities = feed_forward(X)
    +    return np.argmax(probabilities, axis=1)
    +
    +predictions = predict(X_train)
    +print("predictions = (n_inputs) = " + str(predictions.shape))
    +print("prediction for image 0: " + str(predictions[0]))
    +print("correct label for image 0: " + str(Y_train[0]))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Choose cost function and optimizer

    + +

    To measure how well our neural network is doing we need to introduce a cost function. +We will call the function that gives the error of a single sample output the loss function, and the function +that gives the total error of our network across all samples the cost function. +A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. +

    + +

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    + +

    $$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

    + +

    $$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$

    + +

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

    + +

    Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. +We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. +

    + +

    In the one-hot representation only one of the terms in the loss function is non-zero, namely the +probability of the correct category \( c' \) +(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong +you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. +

    + + +









    +

    Optimizing the cost function

    + +

    The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent +is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. +Each parameter \( \theta \) is iteratively adjusted according to the rule +

    + +

    $$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

    + +

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. +This update can be repeated for any number of iterations, or until we are satisfied with the result. +

    + +

    A simple and effective improvement is a variant called Batch Gradient Descent. +Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient +on a subset of the data called a minibatch. +If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches +is \( N/M \). +We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: +

    + +

    $$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ +

    + +

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    + +

    This has two important benefits:

    +
      +
    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. +
    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. +
    +

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    + + +

    Regularization

    + +

    It is common to add an extra term to the cost function, proportional +to the size of the weights. This is equivalent to constraining the +size of the weights, so that they do not grow out of control. +Constraining the size of the weights means that the weights cannot +grow arbitrarily large to fit the training data, and in this way +reduces overfitting. +

    + +

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    + +

    $$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ +

    + +

    i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

    + +

    In order to train the model, we need to calculate the derivative of +the cost function with respect to every bias and weight in the +network. In total our network has \( (64 + 1)\times 50=3250 \) weights in +the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output +layer (\( +1 \) for the bias), and the gradient must be calculated for +every parameter. We use the backpropagation algorithm discussed +above. This is a clever use of the chain rule that allows us to +calculate the gradient efficently. +

    + +









    +

    Matrix multiplication

    + +

    To more efficently train our network these equations are implemented using matrix operations. +The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, +

    + +

    $$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

    + +

    The gradient for the output weights is calculated as

    + +

    $$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

    + +

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. +Since we are going backwards we have to transpose the activation matrix. +

    + +

    The gradient with respect to the output bias is then

    + +

    $$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

    + +

    The error in the hidden layer is

    + +

    $$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

    + +

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean +that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes +the Hadamard product, meaning element-wise multiplication. +

    + +

    This again gives us the gradients in the hidden layer:

    + +

    $$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

    + +

    $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

    + + + +
    +
    +
    +
    +
    +
    # to categorical turns our integer vector into a onehot representation
    +from sklearn.metrics import accuracy_score
    +
    +# one-hot in numpy
    +def to_categorical_numpy(integer_vector):
    +    n_inputs = len(integer_vector)
    +    n_categories = np.max(integer_vector) + 1
    +    onehot_vector = np.zeros((n_inputs, n_categories))
    +    onehot_vector[range(n_inputs), integer_vector] = 1
    +    
    +    return onehot_vector
    +
    +#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    +Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    +
    +def feed_forward_train(X):
    +    # weighted sum of inputs to the hidden layer
    +    z_h = np.matmul(X, hidden_weights) + hidden_bias
    +    # activation in the hidden layer
    +    a_h = sigmoid(z_h)
    +    
    +    # weighted sum of inputs to the output layer
    +    z_o = np.matmul(a_h, output_weights) + output_bias
    +    # softmax output
    +    # axis 0 holds each input and axis 1 the probabilities of each category
    +    exp_term = np.exp(z_o)
    +    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +    
    +    # for backpropagation need activations in hidden and output layers
    +    return a_h, probabilities
    +
    +def backpropagation(X, Y):
    +    a_h, probabilities = feed_forward_train(X)
    +    
    +    # error in the output layer
    +    error_output = probabilities - Y
    +    # error in the hidden layer
    +    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    +    
    +    # gradients for the output layer
    +    output_weights_gradient = np.matmul(a_h.T, error_output)
    +    output_bias_gradient = np.sum(error_output, axis=0)
    +    
    +    # gradient for the hidden layer
    +    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    +    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    +
    +    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    +
    +print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    +
    +eta = 0.01
    +lmbd = 0.01
    +for i in range(1000):
    +    # calculate gradients
    +    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    +    
    +    # regularization term gradients
    +    dWo += lmbd * output_weights
    +    dWh += lmbd * hidden_weights
    +    
    +    # update weights and biases
    +    output_weights -= eta * dWo
    +    output_bias -= eta * dBo
    +    hidden_weights -= eta * dWh
    +    hidden_bias -= eta * dBh
    +
    +print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Improving performance

    + +

    As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. +In order to obtain a network that does something useful, we will have to do a bit more work. +

    + +

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    + +

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period +going through the entire dataset (\( n/M \) batches) an epoch. +

    + +

    If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. +Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. +

    + +









    +

    Full object-oriented implementation

    + +

    It is very natural to think of the network as an object, with specific instances of the network +being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. +

    + + + +
    +
    +
    +
    +
    +
    class NeuralNetwork:
    +    def __init__(
    +            self,
    +            X_data,
    +            Y_data,
    +            n_hidden_neurons=50,
    +            n_categories=10,
    +            epochs=10,
    +            batch_size=100,
    +            eta=0.1,
    +            lmbd=0.0):
    +
    +        self.X_data_full = X_data
    +        self.Y_data_full = Y_data
    +
    +        self.n_inputs = X_data.shape[0]
    +        self.n_features = X_data.shape[1]
    +        self.n_hidden_neurons = n_hidden_neurons
    +        self.n_categories = n_categories
    +
    +        self.epochs = epochs
    +        self.batch_size = batch_size
    +        self.iterations = self.n_inputs // self.batch_size
    +        self.eta = eta
    +        self.lmbd = lmbd
    +
    +        self.create_biases_and_weights()
    +
    +    def create_biases_and_weights(self):
    +        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    +        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    +
    +        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    +        self.output_bias = np.zeros(self.n_categories) + 0.01
    +
    +    def feed_forward(self):
    +        # feed-forward for training
    +        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    +        self.a_h = sigmoid(self.z_h)
    +
    +        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    +
    +        exp_term = np.exp(self.z_o)
    +        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +
    +    def feed_forward_out(self, X):
    +        # feed-forward for output
    +        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    +        a_h = sigmoid(z_h)
    +
    +        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    +        
    +        exp_term = np.exp(z_o)
    +        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +        return probabilities
    +
    +    def backpropagation(self):
    +        error_output = self.probabilities - self.Y_data
    +        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    +
    +        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    +        self.output_bias_gradient = np.sum(error_output, axis=0)
    +
    +        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    +        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    +
    +        if self.lmbd > 0.0:
    +            self.output_weights_gradient += self.lmbd * self.output_weights
    +            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    +
    +        self.output_weights -= self.eta * self.output_weights_gradient
    +        self.output_bias -= self.eta * self.output_bias_gradient
    +        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    +        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    +
    +    def predict(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return np.argmax(probabilities, axis=1)
    +
    +    def predict_probabilities(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return probabilities
    +
    +    def train(self):
    +        data_indices = np.arange(self.n_inputs)
    +
    +        for i in range(self.epochs):
    +            for j in range(self.iterations):
    +                # pick datapoints with replacement
    +                chosen_datapoints = np.random.choice(
    +                    data_indices, size=self.batch_size, replace=False
    +                )
    +
    +                # minibatch training data
    +                self.X_data = self.X_data_full[chosen_datapoints]
    +                self.Y_data = self.Y_data_full[chosen_datapoints]
    +
    +                self.feed_forward()
    +                self.backpropagation()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Evaluate model performance on test data

    + +

    To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. +We measure the performance of the network using the accuracy score. +The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). +

    + +

    $$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

    + +

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    + + + +
    +
    +
    +
    +
    +
    epochs = 100
    +batch_size = 100
    +
    +dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +dnn.train()
    +test_predict = dnn.predict(X_test)
    +
    +# accuracy score from scikit library
    +print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +
    +# equivalent in numpy
    +def accuracy_score_numpy(Y_test, Y_pred):
    +    return np.sum(Y_test == Y_pred) / len(Y_test)
    +
    +#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Adjust hyperparameters

    + +

    We now perform a grid search to find the optimal hyperparameters for the network. +Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). +

    + + + +
    +
    +
    +
    +
    +
    eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +# store the models for later use
    +DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +
    +# grid search
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +        dnn.train()
    +        
    +        DNN_numpy[i][j] = dnn
    +        
    +        test_predict = dnn.predict(X_test)
    +        
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Visualization

    + + + +
    +
    +
    +
    +
    +
    # visual representation of grid search
    +# uses seaborn heatmap, you can also do this with matplotlib imshow
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_numpy[i][j]
    +        
    +        train_pred = dnn.predict(X_train) 
    +        test_pred = dnn.predict(X_test)
    +
    +        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    +        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    scikit-learn implementation

    + +

    scikit-learn focuses more +on traditional machine learning methods, such as regression, +clustering, decision trees, etc. As such, it has only two types of +neural networks: Multi Layer Perceptron outputting continuous values, +MPLRegressor, and Multi Layer Perceptron outputting labels, +MLPClassifier. We will see how simple it is to use these classes. +

    + +

    scikit-learn implements a few improvements from our neural network, +such as early stopping, a varying learning rate, different +optimization methods, etc. We would therefore expect a better +performance overall. +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.neural_network import MLPClassifier
    +# store models for later use
    +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    +                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    +        dnn.fit(X_train, Y_train)
    +        
    +        DNN_scikit[i][j] = dnn
    +        
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Visualization

    + + +
    +
    +
    +
    +
    +
    # optional
    +# visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_scikit[i][j]
    +        
    +        train_pred = dnn.predict(X_train) 
    +        test_pred = dnn.predict(X_test)
    +
    +        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    +        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Building neural networks in Tensorflow and Keras

    + +

    Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. +

    + +

    In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. +

    + +









    +

    Tensorflow

    + +

    Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. +

    + +

    Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. +

    + +

    Tensorflow uses so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow graph +to represent your model, and then create a Tensorflow session to run the graph. +

    + +

    In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. +

    + +

    To install tensorflow on Unix/Linux systems, use pip as

    + + +
    +
    +
    +
    +
    +
    pip3 install tensorflow
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    and/or if you use anaconda, just write (or install from the graphical user interface) +(current release of CPU-only TensorFlow) +

    + + +
    +
    +
    +
    +
    +
    conda create -n tf tensorflow
    +conda activate tf
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    To install the current release of GPU TensorFlow

    + + +
    +
    +
    +
    +
    +
    conda create -n tf-gpu tensorflow-gpu
    +conda activate tf-gpu
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Using Keras

    + +

    Keras is a high level neural network +that supports Tensorflow, CTNK and Theano as backends. +If you have Anaconda installed you may run the following command +

    + + +
    +
    +
    +
    +
    +
    conda install keras
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    You can look up the instructions here for more information.

    + +

    We will to a large extent use keras in this course.

    + +









    +

    Collect and pre-process data

    + +

    Let us look again at the MINST data set.

    @@ -689,50 +2038,195 @@ probabilities = feed_forward(X)
    # import necessary packages
     import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.neural_network import MLPClassifier
    -from sklearn.metrics import accuracy_score
    -import seaborn as sns
    +import tensorflow as tf
    +from sklearn import datasets
    +
     
     # ensure the same random numbers appear every time
     np.random.seed(0)
     
    -# Design matrix
    -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
     
    -# The XOR gate
    -yXOR = np.array( [ 0, 1 ,1, 0])
    -# The OR gate
    -yOR = np.array( [ 0, 1 ,1, 1])
    -# The AND gate
    -yAND = np.array( [ 0, 0 ,0, 1])
     
    -# Defining the neural network
    -n_hidden_neurons = 2
    +# download MNIST dataset
    +digits = datasets.load_digits()
     
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +
    +from sklearn.model_selection import train_test_split
    +
    +# one-hot representation of labels
    +labels = to_categorical(labels)
    +
    +# split into train and test data
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    epochs = 100
    +batch_size = 100
    +n_neurons_layer1 = 100
    +n_neurons_layer2 = 50
    +n_categories = 10
     eta_vals = np.logspace(-5, 1, 7)
     lmbd_vals = np.logspace(-5, 1, 7)
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -epochs = 100
    -
    +def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
    +    model = Sequential()
    +    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_categories, activation='softmax'))
    +    
    +    sgd = optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    +    
    +    return model
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +        
     for i, eta in enumerate(eta_vals):
         for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X, yXOR)
    -        DNN_scikit[i][j] = dnn
    -        print("Learning rate  = ", eta)
    +        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
    +                                         eta=eta, lmbd=lmbd)
    +        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    +        scores = DNN.evaluate(X_test, Y_test)
    +        
    +        DNN_keras[i][j] = DNN
    +        
    +        print("Learning rate = ", eta)
             print("Lambda = ", lmbd)
    -        print("Accuracy score on data set: ", dnn.score(X, yXOR))
    +        print("Test accuracy: %.3f" % scores[1])
             print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    # optional
    +# visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
     
     sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
     test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
     for i in range(len(eta_vals)):
         for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    -        test_pred = dnn.predict(X)
    -        test_accuracy[i][j] = accuracy_score(yXOR, test_pred)
    +        DNN = DNN_keras[i][j]
    +
    +        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
    +        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
     
     fig, ax = plt.subplots(figsize = (10, 10))
     sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    @@ -756,6 +2250,197 @@ plt.show()
     
    +









    +

    The Breast Cancer Data, now with Keras

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +import numpy as np
    +import matplotlib.pyplot as plt
    +import seaborn as sns
    +from sklearn.model_selection import train_test_split as splitter
    +from sklearn.datasets import load_breast_cancer
    +import pickle
    +import os 
    +
    +
    +"""Load breast cancer dataset"""
    +
    +np.random.seed(0)        #create same seed for random number every time
    +
    +cancer=load_breast_cancer()      #Download breast cancer dataset
    +
    +inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    +outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    +labels=cancer.feature_names[0:30]
    +
    +print('The content of the breast cancer dataset is:')      #Print information about the datasets
    +print(labels)
    +print('-------------------------')
    +print("inputs =  " + str(inputs.shape))
    +print("outputs =  " + str(outputs.shape))
    +print("labels =  "+ str(labels.shape))
    +
    +x=inputs      #Reassign the Feature and Label matrices to other variables
    +y=outputs
    +
    +#%% 
    +
    +# Visualisation of dataset (for correlation analysis)
    +
    +plt.figure()
    +plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean radius',fontweight='bold')
    +plt.ylabel('Mean perimeter',fontweight='bold')
    +plt.show()
    +
    +plt.figure()
    +plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    +plt.xlabel('Mean compactness',fontweight='bold')
    +plt.ylabel('Mean concavity',fontweight='bold')
    +plt.show()
    +
    +
    +plt.figure()
    +plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean radius',fontweight='bold')
    +plt.ylabel('Mean texture',fontweight='bold')
    +plt.show()
    +
    +plt.figure()
    +plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean perimeter',fontweight='bold')
    +plt.ylabel('Mean compactness',fontweight='bold')
    +plt.show()
    +
    +
    +# Generate training and testing datasets
    +
    +#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    +#and add to input matrix
    +
    +temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    +temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    +X=np.hstack((temp1,temp2))      
    +temp=np.reshape(x[:,5],(len(x[:,5]),1))
    +X=np.hstack((X,temp))       
    +temp=np.reshape(x[:,8],(len(x[:,8]),1))
    +X=np.hstack((X,temp))       
    +
    +X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    +
    +y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    +y_test=to_categorical(y_test)
    +
    +del temp1,temp2,temp
    +
    +# %%
    +
    +# Define tunable parameters"
    +
    +eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    +lamda=0.01                                  #Define hyperparameter
    +n_layers=2                                  #Define number of hidden layers in the model
    +n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    +epochs=100                                   #Number of reiterations over the input data
    +batch_size=100                              #Number of samples per gradient update
    +
    +# %%
    +
    +"""Define function to return Deep Neural Network model"""
    +
    +def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    +    model=Sequential()      
    +    for i in range(n_layers):       #Run loop to add hidden layers to the model
    +        if (i==0):                  #First layer requires input dimensions
    +            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    +        else:                       #Subsequent layers are capable of automatic shape inferencing
    +            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    +    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    +    sgd=optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    +    return model
    +
    +    
    +Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    +Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    +
    +for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    +    for j in range(len(eta)):      #accuracy scores 
    +        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    +        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    +        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    +        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    +               
    +
    +def plot_data(x,y,data,title=None):
    +
    +    # plot results
    +    fontsize=16
    +
    +
    +    fig = plt.figure()
    +    ax = fig.add_subplot(111)
    +    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    +    
    +    cbar=fig.colorbar(cax)
    +    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    +    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    +    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    +
    +    # put text on matrix elements
    +    for i, x_val in enumerate(np.arange(len(x))):
    +        for j, y_val in enumerate(np.arange(len(y))):
    +            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    +            ax.text(x_val, y_val, c, va='center', ha='center')
    +
    +    # convert axis vaues to to string labels
    +    x=[str(i) for i in x]
    +    y=[str(i) for i in y]
    +
    +
    +    ax.set_xticklabels(['']+x)
    +    ax.set_yticklabels(['']+y)
    +
    +    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    +    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    +    if title is not None:
    +        ax.set_title(title)
    +
    +    plt.tight_layout()
    +
    +    plt.show()
    +    
    +plot_data(eta,n_neuron,Train_accuracy, 'training')
    +plot_data(eta,n_neuron,Test_accuracy, 'testing')
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +









    Building a neural network code

    @@ -2106,1963 +3791,6 @@ scores = logistic_regression.fit(X, yXOR, scheduler, epochs=Lecture Thursday October 26 - - -

    Developing a code for doing neural networks with back propagation

    - -

    We repeat some of the elements discussed last week. The first part of -the material for Thursday was contained in the slides for last -week as well. We will repeat some of the topics here before we move into -applications to differential equations and other examples. -

    - -

    One can identify a set of key steps when using neural networks to solve supervised learning problems:

    - -
      -
    1. Collect and pre-process data
    2. -
    3. Define model and architecture
    4. -
    5. Choose cost function and optimizer
    6. -
    7. Train the model
    8. -
    9. Evaluate model performance on test data
    10. -
    11. Adjust hyperparameters (if necessary, network architecture)
    12. -
    -









    -

    Collect and pre-process data

    - -

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

    - -

    To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

    - -

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

    - -

    $$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

    - -

    and the targets would be:

    - -

    $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

    - -

    Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

    - - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Train and test datasets

    - -

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    - -

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    - -

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -
    -# one-liner from scikit-learn library
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -# equivalently in numpy
    -def train_test_split_numpy(inputs, labels, train_size, test_size):
    -    n_inputs = len(inputs)
    -    inputs_shuffled = inputs.copy()
    -    labels_shuffled = labels.copy()
    -    
    -    np.random.shuffle(inputs_shuffled)
    -    np.random.shuffle(labels_shuffled)
    -    
    -    train_end = int(n_inputs*train_size)
    -    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    -    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    -    
    -    return X_train, X_test, Y_train, Y_test
    -
    -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    -
    -print("Number of training images: " + str(len(X_train)))
    -print("Number of test images: " + str(len(X_test)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Define model and architecture

    - -

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    - -

    $$ z = \sum_{i=1}^n w_i a_i ,$$

    - -

    $$ y = f(z) ,$$

    - -

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

    - -

    The simplest activation function for a neuron is the Heaviside function:

    - -

    $$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

    - -

    A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

    - -

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

    - -

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

    - -

    $$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$

    - -

    which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

    - - -

    Layers

    - -
      -
    • Input
    • -
    -

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    - -
      -
    • Hidden layer
    • -
    -

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

    - -
      -
    • Output
    • -
    -

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

    - -

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    - -

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    - -

    $$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

    - -

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

    - -

    Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. -

    - - -

    Weights and biases

    - -

    Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. -

    - -

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

    - -

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    - - -
    -
    -
    -
    -
    -
    # building our neural network
    -
    -n_inputs, n_features = X_train.shape
    -n_hidden_neurons = 50
    -n_categories = 10
    -
    -# we make the weights normally distributed using numpy.random.randn
    -
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    -
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Feed-forward pass

    - -

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

    - -

    $$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

    - -

    this is then passed through our activation function

    - -

    $$ a_{j}^{l} = f(z_{j}^{l}) .$$

    - -

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    - -

    $$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

    - -

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    - -

    $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

    - - -

    Matrix multiplications

    - -

    Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden -layer have the dimensions -\( W_{hidden} = (n_{features}, n_{hidden}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

    - -

    $$ X W^{h} = (n_{inputs}, n_{hidden}),$$

    - -

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

    - -

    $$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

    - -

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

    - -

    $$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

    - -

    This is fed to the output layer:

    - -

    $$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

    - -

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    - -

    $$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

    - - - -
    -
    -
    -
    -
    -
    # setup the feed-forward pass, subscript h = hidden layer
    -
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    return probabilities
    -
    -probabilities = feed_forward(X_train)
    -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    -print("probabilities sum up to: " + str(probabilities[0].sum()))
    -print()
    -
    -# we obtain a prediction by taking the class with the highest likelihood
    -def predict(X):
    -    probabilities = feed_forward(X)
    -    return np.argmax(probabilities, axis=1)
    -
    -predictions = predict(X_train)
    -print("predictions = (n_inputs) = " + str(predictions.shape))
    -print("prediction for image 0: " + str(predictions[0]))
    -print("correct label for image 0: " + str(Y_train[0]))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Choose cost function and optimizer

    - -

    To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

    $$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

    - -

    $$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$

    - -

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

    - -

    Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

    - -

    In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category \( c' \) -(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. -

    - - -









    -

    Optimizing the cost function

    - -

    The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

    - -

    $$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

    - -

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

    - -

    A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

    - -

    $$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

    - -

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    - -

    This has two important benefits:

    -
      -
    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. -
    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. -
    -

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    - - -

    Regularization

    - -

    It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

    - -

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    - -

    $$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

    - -

    i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

    - -

    In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has \( (64 + 1)\times 50=3250 \) weights in -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -layer (\( +1 \) for the bias), and the gradient must be calculated for -every parameter. We use the backpropagation algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. -

    - -









    -

    Matrix multiplication

    - -

    To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

    - -

    $$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

    - -

    The gradient for the output weights is calculated as

    - -

    $$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

    - -

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

    - -

    The gradient with respect to the output bias is then

    - -

    $$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

    - -

    The error in the hidden layer is

    - -

    $$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

    - -

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

    - -

    This again gives us the gradients in the hidden layer:

    - -

    $$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

    - -

    $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

    - - - -
    -
    -
    -
    -
    -
    # to categorical turns our integer vector into a onehot representation
    -from sklearn.metrics import accuracy_score
    -
    -# one-hot in numpy
    -def to_categorical_numpy(integer_vector):
    -    n_inputs = len(integer_vector)
    -    n_categories = np.max(integer_vector) + 1
    -    onehot_vector = np.zeros((n_inputs, n_categories))
    -    onehot_vector[range(n_inputs), integer_vector] = 1
    -    
    -    return onehot_vector
    -
    -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    -
    -def feed_forward_train(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    # for backpropagation need activations in hidden and output layers
    -    return a_h, probabilities
    -
    -def backpropagation(X, Y):
    -    a_h, probabilities = feed_forward_train(X)
    -    
    -    # error in the output layer
    -    error_output = probabilities - Y
    -    # error in the hidden layer
    -    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    -    
    -    # gradients for the output layer
    -    output_weights_gradient = np.matmul(a_h.T, error_output)
    -    output_bias_gradient = np.sum(error_output, axis=0)
    -    
    -    # gradient for the hidden layer
    -    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    -    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    -
    -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -eta = 0.01
    -lmbd = 0.01
    -for i in range(1000):
    -    # calculate gradients
    -    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    -    
    -    # regularization term gradients
    -    dWo += lmbd * output_weights
    -    dWh += lmbd * hidden_weights
    -    
    -    # update weights and biases
    -    output_weights -= eta * dWo
    -    output_bias -= eta * dBo
    -    hidden_weights -= eta * dWh
    -    hidden_bias -= eta * dBh
    -
    -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Improving performance

    - -

    As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. -

    - -

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    - -

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

    - -

    If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. -

    - -









    -

    Full object-oriented implementation

    - -

    It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. -

    - - - -
    -
    -
    -
    -
    -
    class NeuralNetwork:
    -    def __init__(
    -            self,
    -            X_data,
    -            Y_data,
    -            n_hidden_neurons=50,
    -            n_categories=10,
    -            epochs=10,
    -            batch_size=100,
    -            eta=0.1,
    -            lmbd=0.0):
    -
    -        self.X_data_full = X_data
    -        self.Y_data_full = Y_data
    -
    -        self.n_inputs = X_data.shape[0]
    -        self.n_features = X_data.shape[1]
    -        self.n_hidden_neurons = n_hidden_neurons
    -        self.n_categories = n_categories
    -
    -        self.epochs = epochs
    -        self.batch_size = batch_size
    -        self.iterations = self.n_inputs // self.batch_size
    -        self.eta = eta
    -        self.lmbd = lmbd
    -
    -        self.create_biases_and_weights()
    -
    -    def create_biases_and_weights(self):
    -        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    -        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    -
    -        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    -        self.output_bias = np.zeros(self.n_categories) + 0.01
    -
    -    def feed_forward(self):
    -        # feed-forward for training
    -        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    -        self.a_h = sigmoid(self.z_h)
    -
    -        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    -
    -        exp_term = np.exp(self.z_o)
    -        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -
    -    def feed_forward_out(self, X):
    -        # feed-forward for output
    -        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    -        a_h = sigmoid(z_h)
    -
    -        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    -        
    -        exp_term = np.exp(z_o)
    -        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -        return probabilities
    -
    -    def backpropagation(self):
    -        error_output = self.probabilities - self.Y_data
    -        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    -
    -        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    -        self.output_bias_gradient = np.sum(error_output, axis=0)
    -
    -        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    -        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -        if self.lmbd > 0.0:
    -            self.output_weights_gradient += self.lmbd * self.output_weights
    -            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    -
    -        self.output_weights -= self.eta * self.output_weights_gradient
    -        self.output_bias -= self.eta * self.output_bias_gradient
    -        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    -        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    -
    -    def predict(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return np.argmax(probabilities, axis=1)
    -
    -    def predict_probabilities(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return probabilities
    -
    -    def train(self):
    -        data_indices = np.arange(self.n_inputs)
    -
    -        for i in range(self.epochs):
    -            for j in range(self.iterations):
    -                # pick datapoints with replacement
    -                chosen_datapoints = np.random.choice(
    -                    data_indices, size=self.batch_size, replace=False
    -                )
    -
    -                # minibatch training data
    -                self.X_data = self.X_data_full[chosen_datapoints]
    -                self.Y_data = self.Y_data_full[chosen_datapoints]
    -
    -                self.feed_forward()
    -                self.backpropagation()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Evaluate model performance on test data

    - -

    To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the accuracy score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). -

    - -

    $$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

    - -

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    - - - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -
    -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -dnn.train()
    -test_predict = dnn.predict(X_test)
    -
    -# accuracy score from scikit library
    -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -
    -# equivalent in numpy
    -def accuracy_score_numpy(Y_test, Y_pred):
    -    return np.sum(Y_test == Y_pred) / len(Y_test)
    -
    -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Adjust hyperparameters

    - -

    We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

    - - - -
    -
    -
    -
    -
    -
    eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -# store the models for later use
    -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -# grid search
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -        dnn.train()
    -        
    -        DNN_numpy[i][j] = dnn
    -        
    -        test_predict = dnn.predict(X_test)
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, you can also do this with matplotlib imshow
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_numpy[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    scikit-learn implementation

    - -

    scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

    - -

    scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.neural_network import MLPClassifier
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X_train, Y_train)
    -        
    -        DNN_scikit[i][j] = dnn
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualization

    - - -
    -
    -
    -
    -
    -
    # optional
    -# visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Building neural networks in Tensorflow and Keras

    - -

    Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. -

    - -

    In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. -

    - -









    -

    Tensorflow

    - -

    Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. -

    - -

    Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. -

    - -

    Tensorflow uses so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow graph -to represent your model, and then create a Tensorflow session to run the graph. -

    - -

    In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. -

    - -

    To install tensorflow on Unix/Linux systems, use pip as

    - - -
    -
    -
    -
    -
    -
    pip3 install tensorflow
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    and/or if you use anaconda, just write (or install from the graphical user interface) -(current release of CPU-only TensorFlow) -

    - - -
    -
    -
    -
    -
    -
    conda create -n tf tensorflow
    -conda activate tf
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    To install the current release of GPU TensorFlow

    - - -
    -
    -
    -
    -
    -
    conda create -n tf-gpu tensorflow-gpu
    -conda activate tf-gpu
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Using Keras

    - -

    Keras is a high level neural network -that supports Tensorflow, CTNK and Theano as backends. -If you have Anaconda installed you may run the following command -

    - - -
    -
    -
    -
    -
    -
    conda install keras
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    You can look up the instructions here for more information.

    - -

    We will to a large extent use keras in our examples..

    - -









    -

    Collect and pre-process data

    - -

    Let us look again at the MINST data set.

    - - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import tensorflow as tf
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -
    -from sklearn.model_selection import train_test_split
    -
    -# one-hot representation of labels
    -labels = to_categorical(labels)
    -
    -# split into train and test data
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -n_neurons_layer1 = 100
    -n_neurons_layer2 = 50
    -n_categories = 10
    -eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
    -    model = Sequential()
    -    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(Dense(n_categories, activation='softmax'))
    -    
    -    sgd = optimizers.SGD(lr=eta)
    -    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    -    
    -    return model
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -        
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
    -                                         eta=eta, lmbd=lmbd)
    -        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    -        scores = DNN.evaluate(X_test, Y_test)
    -        
    -        DNN_keras[i][j] = DNN
    -        
    -        print("Learning rate = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Test accuracy: %.3f" % scores[1])
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    # optional
    -# visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        DNN = DNN_keras[i][j]
    -
    -        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
    -        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    The Breast Cancer Data, now with Keras

    - - - -
    -
    -
    -
    -
    -
    import tensorflow as tf
    -from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import seaborn as sns
    -from sklearn.model_selection import train_test_split as splitter
    -from sklearn.datasets import load_breast_cancer
    -import pickle
    -import os 
    -
    -
    -"""Load breast cancer dataset"""
    -
    -np.random.seed(0)        #create same seed for random number every time
    -
    -cancer=load_breast_cancer()      #Download breast cancer dataset
    -
    -inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    -outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    -labels=cancer.feature_names[0:30]
    -
    -print('The content of the breast cancer dataset is:')      #Print information about the datasets
    -print(labels)
    -print('-------------------------')
    -print("inputs =  " + str(inputs.shape))
    -print("outputs =  " + str(outputs.shape))
    -print("labels =  "+ str(labels.shape))
    -
    -x=inputs      #Reassign the Feature and Label matrices to other variables
    -y=outputs
    -
    -#%% 
    -
    -# Visualisation of dataset (for correlation analysis)
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean perimeter',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    -plt.xlabel('Mean compactness',fontweight='bold')
    -plt.ylabel('Mean concavity',fontweight='bold')
    -plt.show()
    -
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean texture',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean perimeter',fontweight='bold')
    -plt.ylabel('Mean compactness',fontweight='bold')
    -plt.show()
    -
    -
    -# Generate training and testing datasets
    -
    -#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    -#and add to input matrix
    -
    -temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    -temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    -X=np.hstack((temp1,temp2))      
    -temp=np.reshape(x[:,5],(len(x[:,5]),1))
    -X=np.hstack((X,temp))       
    -temp=np.reshape(x[:,8],(len(x[:,8]),1))
    -X=np.hstack((X,temp))       
    -
    -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    -
    -y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    -y_test=to_categorical(y_test)
    -
    -del temp1,temp2,temp
    -
    -# %%
    -
    -# Define tunable parameters"
    -
    -eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    -lamda=0.01                                  #Define hyperparameter
    -n_layers=2                                  #Define number of hidden layers in the model
    -n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    -epochs=100                                   #Number of reiterations over the input data
    -batch_size=100                              #Number of samples per gradient update
    -
    -# %%
    -
    -"""Define function to return Deep Neural Network model"""
    -
    -def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    -    model=Sequential()      
    -    for i in range(n_layers):       #Run loop to add hidden layers to the model
    -        if (i==0):                  #First layer requires input dimensions
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    -        else:                       #Subsequent layers are capable of automatic shape inferencing
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    -    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    -    sgd=optimizers.SGD(lr=eta)
    -    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    -    return model
    -
    -    
    -Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    -Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    -
    -for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    -    for j in range(len(eta)):      #accuracy scores 
    -        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    -        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    -        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    -        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    -               
    -
    -def plot_data(x,y,data,title=None):
    -
    -    # plot results
    -    fontsize=16
    -
    -
    -    fig = plt.figure()
    -    ax = fig.add_subplot(111)
    -    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    -    
    -    cbar=fig.colorbar(cax)
    -    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    -    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    -    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    -
    -    # put text on matrix elements
    -    for i, x_val in enumerate(np.arange(len(x))):
    -        for j, y_val in enumerate(np.arange(len(y))):
    -            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    -            ax.text(x_val, y_val, c, va='center', ha='center')
    -
    -    # convert axis vaues to to string labels
    -    x=[str(i) for i in x]
    -    y=[str(i) for i in y]
    -
    -
    -    ax.set_xticklabels(['']+x)
    -    ax.set_yticklabels(['']+y)
    -
    -    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    -    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    -    if title is not None:
    -        ax.set_title(title)
    -
    -    plt.tight_layout()
    -
    -    plt.show()
    -    
    -plot_data(eta,n_neuron,Train_accuracy, 'training')
    -plot_data(eta,n_neuron,Test_accuracy, 'testing')
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Fine-tuning neural network hyperparameters

    - -

    The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are interconnected), -but even in a simple FFNN you can change the number of layers, the -number of neurons per layer, the type of activation function to use in -each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you -know what combination of hyperparameters is the best for your task? -

    - -
      -
    • You can use grid search with cross-validation to find the right hyperparameters.
    • -
    -

    However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. -

    - -
      -
    • You can use randomized search.
    • -
    • Or use tools like Oscar, which implements more complex algorithms to help you find a good set of hyperparameters quickly.
    • -
    -









    -

    Hidden layers

    - -

    For many problems you can start with just one or two hidden layers and it will work just fine. -For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a -few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of -neurons, in roughly the same amount of training time. -

    - -

    For more complex problems, you can gradually -ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such -as large image classification or speech recognition, typically require networks with dozens of layers -and they need a huge amount -of training data. However, you will rarely have to train such networks from scratch: it is much more -common to reuse parts of a pretrained state-of-the-art network that performs a similar task. -

    - - -

    Which activation function should I use?

    - -

    The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. -

    - -

    Unfortunately for us, the gradients often get smaller and smaller as the -algorithm progresses down to the first hidden layers. As a result, the -GD update leaves the lower layer connection weights -virtually unchanged, and training never converges to a good -solution. This is known in the literature as -the vanishing gradients problem. -

    - -

    In other cases, the opposite can happen, namely the the gradients can grow bigger and -bigger. The result is that many of the layers get large updates of the -weights the -algorithm diverges. This is the exploding gradients problem, which is -mostly encountered in recurrent neural networks. More generally, deep -neural networks suffer from unstable gradients, different layers may -learn at widely different speeds -

    - - -

    Is the Logistic activation function (Sigmoid) our choice?

    - -

    Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. -

    - -

    A paper titled Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -

    - -

    They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -

    - -









    -

    The derivative of the Logistic funtion

    - -

    Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. -

    - -

    In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -

    - -

    One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -

    - -









    -

    The RELU function family

    - -

    The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. -

    - -

    In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. -

    - -

    To solve this problem, nowadays practitioners use a variant of the ReLU -function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function -

    - -$$ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -$$ - - -









    -

    Which activation function should we use?

    - -

    In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than \( \tanh \) which in turn performs better -than the logistic function. -

    - -

    If runtime -performance is an issue, then you may opt for the leaky ReLU function over the -ELU function If you don’t -want to tweak yet another hyperparameter, you may just use the default -\( \alpha \) of \( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have -spare time and computing power, you can use cross-validation or -bootstrap to evaluate other activation functions. -

    - -









    -

    More on activation functions, output layers

    - -

    In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).

    - -

    It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck.

    - -For the output layer: - -
      -
    • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
    • -
    • For regression tasks, you can simply use no activation function at all.
    • -
    -









    -

    Batch Normalization

    - -

    Batch Normalization -aims to address the vanishing/exploding gradients problems, and more generally the problem that the -distribution of each layer’s inputs changes during training, as the parameters of the previous layers change. -

    - -

    The technique consists of adding an operation in the model just before the activation function of each -layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new -parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model -learn the optimal scale and mean of the inputs for each layer. -In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and -standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current -mini-batch, from this the name batch normalization. -

    - -









    -

    Dropout

    - -

    It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but -excluding the output neurons) has a probability \( p \) of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active during the next step. -

    - -

    The -hyperparameter \( p \) is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore. - It is viewed as one of the most popular regularization techniques. -

    - -









    -

    Gradient Clipping

    - -

    A popular technique to lessen the exploding gradients problem is to simply clip the gradients during -backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural -networks). -

    - -

    This technique is called Gradient Clipping.

    - -

    In general however, Batch -Normalization is preferred. -

    - -









    -

    A very nice website on Neural Networks

    - -

    You may find this website very useful.

    - - -

    A top-down perspective on Neural networks

    - -

    The first thing we would like to do is divide the data into two or three -parts. A training set, a validation or dev (development) set, and a -test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: -

    - -
      -
    • Estimate optimal error rate
    • -
    • Minimize underfitting (bias) on training data set.
    • -
    • Make sure you are not overfitting.
    • -
    -

    If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. -

    - -

    However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -

    - -









    -

    Limitations of supervised learning with deep networks

    - -

    Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). -

    - -

    Here we list some of the important limitations of supervised neural network based models.

    - -
      -
    • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
    • -
    • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
    • -
    • Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
    • -
    • Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
    • -
    -

    Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.

    -









    Solving ODEs with Deep Learning

    @@ -6721,7 +6449,7 @@ $$
    - © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/week43/html/week43.html b/doc/pub/week43/html/week43.html index ab90a39f9..6a8e7d251 100644 --- a/doc/pub/week43/html/week43.html +++ b/doc/pub/week43/html/week43.html @@ -141,6 +141,19 @@ div.toc p,a {
    @@ -465,40 +457,61 @@ MathJax.Hub.Config({

    Plans for week 43

    -Material for the active learning sessions on Tuesday and Wednesday +Material for the lecture on Monday October 21, 2024

      -
    • Exercise on writing your own neural network code, application to the OR and XOR gates
    • +
    • Building our own Feed-forward Neural Network with intro to Tensorflow
    • +
    • Solving differential equations with Neural Networks + +
    • +
    +
    + + +









    +

    Exercises and lab session week 43

    +
    +Lab sessions on Tuesday and Wednesday +

    +

      +
    • Exercise on writing your own neural network code
    • The exercises this week will be continued next week as well
    • Discussion of project 2
    • -
    • Video of lab session
    +









    +

    Mathematics of deep learning

    +
    -Material for the lecture on Thursday October 26, 2023 +Two recent books online

    -

    -

    I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at http://neuralnetworksanddeeplearning.com/chap4.html.

    +
      +
    1. The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen, published as Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022
    2. +
    3. Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger
    4. +
    +









    +

    Reminder on books with hands-on material and codes

    + + + +









    +

    Reading recommendations

    + +
      +
    1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub. See also chapters 12 and 13 on using Pytorch to make a Neural network code.
    2. +
    3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
    4. +










    Using Automatic differentiation

    a @@ -517,160 +530,404 @@ t

  • Slides 12-44 at URL":http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf"










  • -

    Material for exercises week 43 and week 44

    +

    Lecture Monday October 21











    -

    Writing our first neural network code, testing it for the OR and XOR gates

    +

    Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

    +

    This is a reminder from where we ended last week.

    -

    During week 41 we discussed three different types of gates, the -so-called XOR, the OR and the AND gates. In order to develop a code -for neural networks, it can be useful to set up a simpler system with -only two inputs and one output. This can make it easier to debug and -study the feed forward pass and the back propagation part. In the -exercise this and next week, we propose to study this system with just -one hidden layer and two hidden nodes. There is only one output node -and we can choose to use either a simple regression case (fitting a -line) or just a binary classification case with the corss-entropy as -cost function. +

    +The architecture (our model) +

    +

      +
    1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)
    2. +
    3. Define the number of hidden layers and hidden nodes
    4. +
    5. Define activation functions for hidden layers and output layers
    6. +
    7. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates
    8. +
    9. Define cost function and possible regularization terms with hyperparameters
    10. +
    11. Initialize weights and biases
    12. +
    13. Fix number of iterations for the feed forward part and back propagation part
    14. +
    +
    + + +









    +

    Setting up the back propagation algorithm, part 1

    + +

    Let us write this out in the form of an algorithm.

    + +

    First, we set up the input data \( \boldsymbol{x} \) and the activations +\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and +the pertinent outputs \( \boldsymbol{a}^1 \).

    -

    Their inputs and outputs can be -summarized using the following tables, first for the OR gate with -inputs \( x_1 \) and \( x_2 \) and outputs \( y \): +

    Secondly, we perform then the feed forward till we reach the output +layer and compute all \( \boldsymbol{z}_l \) of the input layer and compute the +activation function and the pertinent outputs \( \boldsymbol{a}^l \) for +\( l=1,2,3,\dots,L \).

    - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 1
    1 0 1
    1 1 1
    +

    Notation: The first hidden layer has \( l=1 \) as label and the final output layer has \( l=L \).











    -

    The AND and XOR Gates

    +

    Setting up the back propagation algorithm, part 2

    -

    The AND gate is defined as

    +

    Thereafter we compute the ouput error \( \boldsymbol{\delta}^L \) by computing all

    +$$ +\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. +$$ - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 0
    1 0 0
    1 1 1
    +

    Then we compute the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

    +$$ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). +$$ -

    And finally we have the XOR gate

    - - - - - - - - - - - -
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 1
    1 0 1
    1 1 0










    -

    Representing the Data Sets

    +

    Setting up the Back propagation algorithm, part 3

    -

    Our design matrix is defined by the input values \( x_1 \) and \( x_2 \). Since we have four possible outputs, our design matrix reads

    +

    Finally, we update the weights and the biases using gradient descent +for each \( l=L-1,L-2,\dots,1 \) (the first hidden layer) and update the weights and biases +according to the rules +

    $$ -\boldsymbol{X}=\begin{bmatrix} 0 & 0 \\ - 0 & 1 \\ - 1 & 0 \\ - 1 & 1 \end{bmatrix}, +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, $$ -

    while the vector of outputs is \( \boldsymbol{y}^T=[0,1,1,0] \) for the XOR gate, \( \boldsymbol{y}^T=[0,0,0,1] \) for the AND gate and \( \boldsymbol{y}^T=[0,1,1,1] \) for the OR gate.

    -

    Your tasks here are

    +$$ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +$$ + +

    with \( \eta \) being the learning rate.

    + +









    +

    Updating the gradients

    + +

    With the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

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

    we update the weights and the biases using gradient descent for each \( l=L-1,L-2,\dots,1 \) and update the weights and biases according to the rules

    +$$ +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, +$$ + + +$$ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +$$ + + +









    +

    Activation functions

    + +

    A property that characterizes a neural network, other than its +connectivity, is the choice of activation function(s). The following +restrictions are imposed on an activation function for an FFNN to +fulfill the universal approximation theorem +

    + +
      +
    • Non-constant
    • +
    • Bounded
    • +
    • Monotonically-increasing
    • +
    • Continuous
    • +
    +









    +

    Activation functions, examples

    + +

    Typical examples are the logistic Sigmoid

    + +$$ + \sigma(x) = \frac{1}{1 + e^{-x}}, +$$ + +

    and the hyperbolic tangent function

    +$$ + \sigma(x) = \tanh(x) +$$ + + +









    +

    The RELU function family

    + +

    The ReLU activation function suffers from a problem known as the dying +ReLUs: during training, some neurons effectively die, meaning they +stop outputting anything other than 0. +

    + +

    In some cases, you may find that half of your network’s neurons are +dead, especially if you used a large learning rate. During training, +if a neuron’s weights get updated such that the weighted sum of the +neuron’s inputs is negative, it will start outputting 0. When this +happen, the neuron is unlikely to come back to life since the gradient +of the ReLU function is 0 when its input is negative. +

    + +









    +

    ELU function

    + +

    To solve this problem, nowadays practitioners use a variant of the +ReLU function, such as the leaky ReLU discussed above or the so-called +exponential linear unit (ELU) function +

    + +$$ +ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. +$$ + + +









    +

    Which activation function should we use?

    + +

    In general it seems that the ELU activation function is better than +the leaky ReLU function (and its variants), which is better than +ReLU. ReLU performs better than \( \tanh \) which in turn performs better +than the logistic function. +

    + +

    If runtime performance is an issue, then you may opt for the leaky +ReLU function over the ELU function If you don’t want to tweak yet +another hyperparameter, you may just use the default \( \alpha \) of +\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and +computing power, you can use cross-validation or bootstrap to evaluate +other activation functions. +

    + +









    +

    More on activation functions, output layers

    + +

    In most cases you can use the ReLU activation function in the hidden +layers (or one of its variants). +

    + +

    It is a bit faster to compute than other activation functions, and the +gradient descent optimization does in general not get stuck. +

    + +For the output layer: + +
      +
    • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
    • +
    • For regression tasks, you can simply use no activation function at all.
    • +
    + +

    Setting up a Multi-layer perceptron model for classification

    + +

    We are now gong to develop an example based on the MNIST data +base. This is a classification problem and we need to use our +cross-entropy function we discussed in connection with logistic +regression. The cross-entropy defines our cost function for the +classificaton problems with neural networks. +

    + +

    In binary classification with two classes \( (0, 1) \) we define the +logistic/sigmoid function as the probability that a particular input +is in class \( 0 \) or \( 1 \). This is possible because the logistic +function takes any input from the real numbers and inputs a number +between 0 and 1, and can therefore be interpreted as a probability. It +also has other nice properties, such as a derivative that is simple to +calculate. +

    + +

    For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) +is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) +represents our activation values \( z \). We have +

    +$$ +P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , +$$ + +

    and

    +$$ +P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , +$$ + +

    where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases +of our network. +

    + + +









    +

    Defining the cost function

    + +

    Our cost function is given as (see the Logistic regression lectures)

    +$$ +\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n +y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . +$$ + +

    This last equality means that we can interpret our cost function as a sum over the loss function +for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). +The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather +than maximizing a negative number. +

    + +

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    + +

    \( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

    + +\( y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) , \) + +

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset (numbers from \( 0 \) to \( 9 \))..

    + +

    If \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th +output vector \( \boldsymbol{y}_i \). +The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: +

    + +$$ +P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} +{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , +$$ + +

    which reduces to the logistic function in the binary case. +The likelihood of this \( C \)-class classifier +is now given as: +

    + +$$ +P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . +$$ + +

    Again we take the negative log-likelihood to define our cost function:

    + +$$ +\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. +$$ + +

    See the logistic regression lectures for a full definition of the cost function.

    + +

    The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!

    + +









    +

    Example: binary classification problem

    + +

    As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as

    +$$ +\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right), +$$ + +

    where we had defined the logistic (sigmoid) function

    +$$ +p(y_i =1\vert x_i,\boldsymbol{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, +$$ + +

    and

    +$$ +p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). +$$ + +

    The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

    + +

    Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). +We have then +

    +$$ +a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, +$$ + +

    with

    +$$ +z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, +$$ + +

    where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). +Our cost function at the final layer \( l=L \) is now +

    +$$ +\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), +$$ + +

    where we have defined the targets \( t_i \). The derivatives of the cost function with respect to the output \( a_i^L \) are then easily calculated and we get

    +$$ +\frac{\partial \mathcal{C}(\boldsymbol{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. +$$ + +

    In case we use another activation function than the logistic one, we need to evaluate other derivatives.

    + +









    +

    The Softmax function

    +

    In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need

    +$$ +\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = +\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. +$$ + +

    For the Softmax function we have

    +$$ +f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. +$$ + +

    Its derivative with respect to \( z_j^l \) gives

    +$$ +\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), +$$ + +

    which in case of the simply binary model reduces to having \( i=j \).

    + + +

    Developing a code for doing neural networks with back propagation

    + +

    One can identify a set of key steps when using neural networks to solve supervised learning problems:

      -
    1. Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs.
    2. -
    3. Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function.
    4. -
    5. Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output.
    6. -
    7. Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets.
    8. -
    9. Set up the cost function (cross entropy for classification of binary cases).
    10. -
    11. Calculate the gradients needed for the back propagation part.
    12. -
    13. Use the gradients to train the network in the back propagation part. Think of using automatic differentiation.
    14. -
    15. Train the network and study your results and compare with results obtained either with scikit-learn or TensorFlow.
    16. +
    17. Collect and pre-process data
    18. +
    19. Define model and architecture
    20. +
    21. Choose cost function and optimizer
    22. +
    23. Train the model
    24. +
    25. Evaluate model performance on test data
    26. +
    27. Adjust hyperparameters (if necessary, network architecture)
    -

    Everything you develop here can be used directly into the code for the project.

    -









    -

    Setting up dimensionalities by hand

    +

    Collect and pre-process data

    -

    It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by

    -$$ -\boldsymbol{W_h}=\begin{bmatrix} 1 & 1 \\ - 1 & 1 \end{bmatrix}, -$$ +

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn +package. You may also find it for example here. +The MNIST (Modified National Institute of Standards and Technology) database is a large database +of handwritten digits that is commonly used for training various image processing systems. +The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. +The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. +

    -

    Multiplying \( \boldsymbol{X} \) and \( \boldsymbol{W} \) gives

    +

    To feed data into a feed-forward neural network we need to represent +the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each +row represents an input, in this case a handwritten digit, and +each column represents a feature, in this case a pixel. The +correct answers, also known as labels or targets are +represented as a 1D array of integers +\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). +

    -$$ -\boldsymbol{X}{W}_h=\begin{bmatrix} 0 & 0 \\ - 1 & 1 \\ - 1 & 1 \\ - 2 & 2 \end{bmatrix}, -$$ +

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from +measurements of height (in m) +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: +

    -

    Assume also that the bias vector for the hidden layer is

    -$$ -\boldsymbol{b}_h=\begin{bmatrix} 0 \\ - -1\end{bmatrix}, -$$ +

    $$ X = \begin{bmatrix} +1.85 & 81\\ +1.71 & 65\\ +1.95 & 103\\ +1.55 & 42\\ +1.63 & 56 +\end{bmatrix} ,$$ +

    -

    Adding it gives us the input to the activation function of the hidden layer

    -$$ -\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h=\begin{bmatrix} 0 & -1 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, -$$ +

    and the targets would be:

    -

    Let us then assume that our activation function is the RELU function, which simply means that we take the max of \( 0 \) and the elements of the input argument \( \boldsymbol{z}_h \), that is we have

    -$$ -\boldsymbol{a}_h=\mathrm{RELU}(\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h)=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, -$$ +

    $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

    -

    Assume also that the bias of the output layer is zero and that the weights of the output layer are

    -$$ -\boldsymbol{w}_o=\begin{bmatrix} 1 \\ - -2\end{bmatrix}, -$$ - -

    and multiplying with \( \boldsymbol{a}_h \) gives the output

    -$$ -\boldsymbol{a}_o=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}\begin{bmatrix} 1 \\ - -2\end{bmatrix}=\begin{bmatrix} 0 \\ 1 \\ 1 \\0\end{bmatrix}, -$$ - -

    the wanted result. Pay attention to the dimensionalities as well.

    - -









    -

    Setting up the Neural Network

    - -

    We define first our design matrix and the various output vectors for the different gates.

    +

    Since each input image is a 2D matrix, we need to flatten the image +(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a +design/feature matrix. This means we lose all spatial information in the +image, such as locality and translational invariance. More complicated +architectures such as Convolutional Neural Networks can take advantage +of such information, and are most commonly applied when analyzing +images. +

    @@ -679,63 +936,48 @@ $$
    -
    """
    -Simple code that tests XOR, OR and AND gates with linear regression
    -"""
    -
    -# import necessary packages
    +  
    # import necessary packages
     import numpy as np
     import matplotlib.pyplot as plt
     from sklearn import datasets
     
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    probabilities = sigmoid(z_o)
    -    return probabilities
    -
     
     # ensure the same random numbers appear every time
     np.random.seed(0)
     
    -# Design matrix
    -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
     
    -# The XOR gate
    -yXOR = np.array( [ 0, 1 ,1, 0])
    -# The OR gate
    -yOR = np.array( [ 0, 1 ,1, 1])
    -# The AND gate
    -yAND = np.array( [ 0, 0 ,0, 1])
     
    -# Defining the neural network
    -n_inputs, n_features = X.shape
    -n_hidden_neurons = 2
    -n_categories = 1
    -n_features = 2
    +# download MNIST dataset
    +digits = datasets.load_digits()
     
    -# we make the weights normally distributed using numpy.random.randn
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
     
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
     
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
     
    -probabilities = feed_forward(X)
    -print(probabilities)
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
     
    @@ -751,10 +993,1117 @@ probabilities = feed_forward(X)
    -

    Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above.











    -

    The Code using Scikit-Learn

    +

    Train and test datasets

    + +

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    + +

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    + +

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure +no bias in the sampling. +Say you are taking measurements of weather data to predict the weather in the coming 5 days. +You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data +collected from 12.00 to 24.00. +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.model_selection import train_test_split
    +
    +# one-liner from scikit-learn library
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +# equivalently in numpy
    +def train_test_split_numpy(inputs, labels, train_size, test_size):
    +    n_inputs = len(inputs)
    +    inputs_shuffled = inputs.copy()
    +    labels_shuffled = labels.copy()
    +    
    +    np.random.shuffle(inputs_shuffled)
    +    np.random.shuffle(labels_shuffled)
    +    
    +    train_end = int(n_inputs*train_size)
    +    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    +    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    +    
    +    return X_train, X_test, Y_train, Y_test
    +
    +#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    +
    +print("Number of training images: " + str(len(X_train)))
    +print("Number of test images: " + str(len(X_test)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Define model and architecture

    + +

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    + +

    $$ z = \sum_{i=1}^n w_i a_i ,$$

    + +

    $$ y = f(z) ,$$

    + +

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer +and \( w_i \) is the weight to input \( i \). +The activation of the neurons in the input layer is just the features (e.g. a pixel value). +

    + +

    The simplest activation function for a neuron is the Heaviside function:

    + +

    $$ f(z) = +\begin{cases} +1, & z > 0\\ +0, & \text{otherwise} +\end{cases} +$$ +

    + +

    A feed-forward neural network with this activation is known as a perceptron. +For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. +This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), +and we call these architectures multiclass perceptrons. +

    + +

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and +Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. +

    + +

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). +We will be using the sigmoid function \( \sigma(x) \): +

    + +

    $$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$

    + +

    which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

    + + +

    Layers

    + +
      +
    • Input
    • +
    +

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    + +
      +
    • Hidden layer
    • +
    +

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. +Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. +

    + +
      +
    • Output
    • +
    +

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, +which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. +

    + +

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    + +

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    + +

    $$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} +{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ +

    + +

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. +The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. +The exponent is just the weighted sum of inputs as before: +

    + +

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

    + +

    Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 +weights to the output layer. +

    + + +

    Weights and biases

    + +

    Typically weights are initialized with small values distributed around zero, drawn from a uniform +or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. +

    + +

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range +of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): +

    + +

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

    + +

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    + + +
    +
    +
    +
    +
    +
    # building our neural network
    +
    +n_inputs, n_features = X_train.shape
    +n_hidden_neurons = 50
    +n_categories = 10
    +
    +# we make the weights normally distributed using numpy.random.randn
    +
    +# weights and bias in the hidden layer
    +hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    +hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    +
    +# weights and bias in the output layer
    +output_weights = np.random.randn(n_hidden_neurons, n_categories)
    +output_bias = np.zeros(n_categories) + 0.01
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Feed-forward pass

    + +

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. +For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): +

    + +

    $$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

    + +

    this is then passed through our activation function

    + +

    $$ a_{j}^{l} = f(z_{j}^{l}) .$$

    + +

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    + +

    $$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

    + +

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    + +

    $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} +{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ +

    + + +

    Matrix multiplications

    + +

    Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden +layer have the dimensions +\( W_{hidden} = (n_{features}, n_{hidden}) \), +we can easily feed the network all our training data in one go by taking the matrix product +

    + +

    $$ X W^{h} = (n_{inputs}, n_{hidden}),$$

    + +

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer +for each input image and each hidden neuron. +We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): +

    + +

    $$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

    + +

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. +This is then passed through the activation: +

    + +

    $$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

    + +

    This is fed to the output layer:

    + +

    $$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

    + +

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    + +

    $$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

    + + + +
    +
    +
    +
    +
    +
    # setup the feed-forward pass, subscript h = hidden layer
    +
    +def sigmoid(x):
    +    return 1/(1 + np.exp(-x))
    +
    +def feed_forward(X):
    +    # weighted sum of inputs to the hidden layer
    +    z_h = np.matmul(X, hidden_weights) + hidden_bias
    +    # activation in the hidden layer
    +    a_h = sigmoid(z_h)
    +    
    +    # weighted sum of inputs to the output layer
    +    z_o = np.matmul(a_h, output_weights) + output_bias
    +    # softmax output
    +    # axis 0 holds each input and axis 1 the probabilities of each category
    +    exp_term = np.exp(z_o)
    +    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +    
    +    return probabilities
    +
    +probabilities = feed_forward(X_train)
    +print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    +print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    +print("probabilities sum up to: " + str(probabilities[0].sum()))
    +print()
    +
    +# we obtain a prediction by taking the class with the highest likelihood
    +def predict(X):
    +    probabilities = feed_forward(X)
    +    return np.argmax(probabilities, axis=1)
    +
    +predictions = predict(X_train)
    +print("predictions = (n_inputs) = " + str(predictions.shape))
    +print("prediction for image 0: " + str(predictions[0]))
    +print("correct label for image 0: " + str(Y_train[0]))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Choose cost function and optimizer

    + +

    To measure how well our neural network is doing we need to introduce a cost function. +We will call the function that gives the error of a single sample output the loss function, and the function +that gives the total error of our network across all samples the cost function. +A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. +

    + +

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    + +

    $$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

    + +

    $$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$

    + +

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

    + +

    Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. +We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. +

    + +

    In the one-hot representation only one of the terms in the loss function is non-zero, namely the +probability of the correct category \( c' \) +(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong +you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. +

    + + +









    +

    Optimizing the cost function

    + +

    The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent +is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. +Each parameter \( \theta \) is iteratively adjusted according to the rule +

    + +

    $$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

    + +

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. +This update can be repeated for any number of iterations, or until we are satisfied with the result. +

    + +

    A simple and effective improvement is a variant called Batch Gradient Descent. +Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient +on a subset of the data called a minibatch. +If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches +is \( N/M \). +We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: +

    + +

    $$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ +

    + +

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    + +

    This has two important benefits:

    +
      +
    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. +
    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. +
    +

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    + + +

    Regularization

    + +

    It is common to add an extra term to the cost function, proportional +to the size of the weights. This is equivalent to constraining the +size of the weights, so that they do not grow out of control. +Constraining the size of the weights means that the weights cannot +grow arbitrarily large to fit the training data, and in this way +reduces overfitting. +

    + +

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    + +

    $$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ +

    + +

    i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

    + +

    In order to train the model, we need to calculate the derivative of +the cost function with respect to every bias and weight in the +network. In total our network has \( (64 + 1)\times 50=3250 \) weights in +the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output +layer (\( +1 \) for the bias), and the gradient must be calculated for +every parameter. We use the backpropagation algorithm discussed +above. This is a clever use of the chain rule that allows us to +calculate the gradient efficently. +

    + +









    +

    Matrix multiplication

    + +

    To more efficently train our network these equations are implemented using matrix operations. +The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, +

    + +

    $$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

    + +

    The gradient for the output weights is calculated as

    + +

    $$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

    + +

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. +Since we are going backwards we have to transpose the activation matrix. +

    + +

    The gradient with respect to the output bias is then

    + +

    $$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

    + +

    The error in the hidden layer is

    + +

    $$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

    + +

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean +that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes +the Hadamard product, meaning element-wise multiplication. +

    + +

    This again gives us the gradients in the hidden layer:

    + +

    $$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

    + +

    $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

    + + + +
    +
    +
    +
    +
    +
    # to categorical turns our integer vector into a onehot representation
    +from sklearn.metrics import accuracy_score
    +
    +# one-hot in numpy
    +def to_categorical_numpy(integer_vector):
    +    n_inputs = len(integer_vector)
    +    n_categories = np.max(integer_vector) + 1
    +    onehot_vector = np.zeros((n_inputs, n_categories))
    +    onehot_vector[range(n_inputs), integer_vector] = 1
    +    
    +    return onehot_vector
    +
    +#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    +Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    +
    +def feed_forward_train(X):
    +    # weighted sum of inputs to the hidden layer
    +    z_h = np.matmul(X, hidden_weights) + hidden_bias
    +    # activation in the hidden layer
    +    a_h = sigmoid(z_h)
    +    
    +    # weighted sum of inputs to the output layer
    +    z_o = np.matmul(a_h, output_weights) + output_bias
    +    # softmax output
    +    # axis 0 holds each input and axis 1 the probabilities of each category
    +    exp_term = np.exp(z_o)
    +    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +    
    +    # for backpropagation need activations in hidden and output layers
    +    return a_h, probabilities
    +
    +def backpropagation(X, Y):
    +    a_h, probabilities = feed_forward_train(X)
    +    
    +    # error in the output layer
    +    error_output = probabilities - Y
    +    # error in the hidden layer
    +    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    +    
    +    # gradients for the output layer
    +    output_weights_gradient = np.matmul(a_h.T, error_output)
    +    output_bias_gradient = np.sum(error_output, axis=0)
    +    
    +    # gradient for the hidden layer
    +    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    +    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    +
    +    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    +
    +print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    +
    +eta = 0.01
    +lmbd = 0.01
    +for i in range(1000):
    +    # calculate gradients
    +    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    +    
    +    # regularization term gradients
    +    dWo += lmbd * output_weights
    +    dWh += lmbd * hidden_weights
    +    
    +    # update weights and biases
    +    output_weights -= eta * dWo
    +    output_bias -= eta * dBo
    +    hidden_weights -= eta * dWh
    +    hidden_bias -= eta * dBh
    +
    +print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Improving performance

    + +

    As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. +In order to obtain a network that does something useful, we will have to do a bit more work. +

    + +

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    + +

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period +going through the entire dataset (\( n/M \) batches) an epoch. +

    + +

    If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. +Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. +

    + +









    +

    Full object-oriented implementation

    + +

    It is very natural to think of the network as an object, with specific instances of the network +being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. +

    + + + +
    +
    +
    +
    +
    +
    class NeuralNetwork:
    +    def __init__(
    +            self,
    +            X_data,
    +            Y_data,
    +            n_hidden_neurons=50,
    +            n_categories=10,
    +            epochs=10,
    +            batch_size=100,
    +            eta=0.1,
    +            lmbd=0.0):
    +
    +        self.X_data_full = X_data
    +        self.Y_data_full = Y_data
    +
    +        self.n_inputs = X_data.shape[0]
    +        self.n_features = X_data.shape[1]
    +        self.n_hidden_neurons = n_hidden_neurons
    +        self.n_categories = n_categories
    +
    +        self.epochs = epochs
    +        self.batch_size = batch_size
    +        self.iterations = self.n_inputs // self.batch_size
    +        self.eta = eta
    +        self.lmbd = lmbd
    +
    +        self.create_biases_and_weights()
    +
    +    def create_biases_and_weights(self):
    +        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    +        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    +
    +        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    +        self.output_bias = np.zeros(self.n_categories) + 0.01
    +
    +    def feed_forward(self):
    +        # feed-forward for training
    +        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    +        self.a_h = sigmoid(self.z_h)
    +
    +        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    +
    +        exp_term = np.exp(self.z_o)
    +        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +
    +    def feed_forward_out(self, X):
    +        # feed-forward for output
    +        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    +        a_h = sigmoid(z_h)
    +
    +        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    +        
    +        exp_term = np.exp(z_o)
    +        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +        return probabilities
    +
    +    def backpropagation(self):
    +        error_output = self.probabilities - self.Y_data
    +        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    +
    +        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    +        self.output_bias_gradient = np.sum(error_output, axis=0)
    +
    +        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    +        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    +
    +        if self.lmbd > 0.0:
    +            self.output_weights_gradient += self.lmbd * self.output_weights
    +            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    +
    +        self.output_weights -= self.eta * self.output_weights_gradient
    +        self.output_bias -= self.eta * self.output_bias_gradient
    +        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    +        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    +
    +    def predict(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return np.argmax(probabilities, axis=1)
    +
    +    def predict_probabilities(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return probabilities
    +
    +    def train(self):
    +        data_indices = np.arange(self.n_inputs)
    +
    +        for i in range(self.epochs):
    +            for j in range(self.iterations):
    +                # pick datapoints with replacement
    +                chosen_datapoints = np.random.choice(
    +                    data_indices, size=self.batch_size, replace=False
    +                )
    +
    +                # minibatch training data
    +                self.X_data = self.X_data_full[chosen_datapoints]
    +                self.Y_data = self.Y_data_full[chosen_datapoints]
    +
    +                self.feed_forward()
    +                self.backpropagation()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Evaluate model performance on test data

    + +

    To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. +We measure the performance of the network using the accuracy score. +The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). +

    + +

    $$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

    + +

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    + + + +
    +
    +
    +
    +
    +
    epochs = 100
    +batch_size = 100
    +
    +dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +dnn.train()
    +test_predict = dnn.predict(X_test)
    +
    +# accuracy score from scikit library
    +print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +
    +# equivalent in numpy
    +def accuracy_score_numpy(Y_test, Y_pred):
    +    return np.sum(Y_test == Y_pred) / len(Y_test)
    +
    +#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Adjust hyperparameters

    + +

    We now perform a grid search to find the optimal hyperparameters for the network. +Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). +

    + + + +
    +
    +
    +
    +
    +
    eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +# store the models for later use
    +DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +
    +# grid search
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +        dnn.train()
    +        
    +        DNN_numpy[i][j] = dnn
    +        
    +        test_predict = dnn.predict(X_test)
    +        
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Visualization

    + + + +
    +
    +
    +
    +
    +
    # visual representation of grid search
    +# uses seaborn heatmap, you can also do this with matplotlib imshow
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_numpy[i][j]
    +        
    +        train_pred = dnn.predict(X_train) 
    +        test_pred = dnn.predict(X_test)
    +
    +        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    +        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    scikit-learn implementation

    + +

    scikit-learn focuses more +on traditional machine learning methods, such as regression, +clustering, decision trees, etc. As such, it has only two types of +neural networks: Multi Layer Perceptron outputting continuous values, +MPLRegressor, and Multi Layer Perceptron outputting labels, +MLPClassifier. We will see how simple it is to use these classes. +

    + +

    scikit-learn implements a few improvements from our neural network, +such as early stopping, a varying learning rate, different +optimization methods, etc. We would therefore expect a better +performance overall. +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.neural_network import MLPClassifier
    +# store models for later use
    +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    +                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    +        dnn.fit(X_train, Y_train)
    +        
    +        DNN_scikit[i][j] = dnn
    +        
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Visualization

    + + +
    +
    +
    +
    +
    +
    # optional
    +# visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_scikit[i][j]
    +        
    +        train_pred = dnn.predict(X_train) 
    +        test_pred = dnn.predict(X_test)
    +
    +        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    +        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Building neural networks in Tensorflow and Keras

    + +

    Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. +

    + +

    In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. +

    + +









    +

    Tensorflow

    + +

    Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. +

    + +

    Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. +

    + +

    Tensorflow uses so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow graph +to represent your model, and then create a Tensorflow session to run the graph. +

    + +

    In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. +

    + +

    To install tensorflow on Unix/Linux systems, use pip as

    + + +
    +
    +
    +
    +
    +
    pip3 install tensorflow
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    and/or if you use anaconda, just write (or install from the graphical user interface) +(current release of CPU-only TensorFlow) +

    + + +
    +
    +
    +
    +
    +
    conda create -n tf tensorflow
    +conda activate tf
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    To install the current release of GPU TensorFlow

    + + +
    +
    +
    +
    +
    +
    conda create -n tf-gpu tensorflow-gpu
    +conda activate tf-gpu
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Using Keras

    + +

    Keras is a high level neural network +that supports Tensorflow, CTNK and Theano as backends. +If you have Anaconda installed you may run the following command +

    + + +
    +
    +
    +
    +
    +
    conda install keras
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    You can look up the instructions here for more information.

    + +

    We will to a large extent use keras in this course.

    + +









    +

    Collect and pre-process data

    + +

    Let us look again at the MINST data set.

    @@ -766,50 +2115,195 @@ probabilities = feed_forward(X)
    # import necessary packages
     import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.neural_network import MLPClassifier
    -from sklearn.metrics import accuracy_score
    -import seaborn as sns
    +import tensorflow as tf
    +from sklearn import datasets
    +
     
     # ensure the same random numbers appear every time
     np.random.seed(0)
     
    -# Design matrix
    -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
     
    -# The XOR gate
    -yXOR = np.array( [ 0, 1 ,1, 0])
    -# The OR gate
    -yOR = np.array( [ 0, 1 ,1, 1])
    -# The AND gate
    -yAND = np.array( [ 0, 0 ,0, 1])
     
    -# Defining the neural network
    -n_hidden_neurons = 2
    +# download MNIST dataset
    +digits = datasets.load_digits()
     
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +
    +from sklearn.model_selection import train_test_split
    +
    +# one-hot representation of labels
    +labels = to_categorical(labels)
    +
    +# split into train and test data
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    epochs = 100
    +batch_size = 100
    +n_neurons_layer1 = 100
    +n_neurons_layer2 = 50
    +n_categories = 10
     eta_vals = np.logspace(-5, 1, 7)
     lmbd_vals = np.logspace(-5, 1, 7)
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -epochs = 100
    -
    +def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
    +    model = Sequential()
    +    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_categories, activation='softmax'))
    +    
    +    sgd = optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    +    
    +    return model
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +        
     for i, eta in enumerate(eta_vals):
         for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X, yXOR)
    -        DNN_scikit[i][j] = dnn
    -        print("Learning rate  = ", eta)
    +        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
    +                                         eta=eta, lmbd=lmbd)
    +        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    +        scores = DNN.evaluate(X_test, Y_test)
    +        
    +        DNN_keras[i][j] = DNN
    +        
    +        print("Learning rate = ", eta)
             print("Lambda = ", lmbd)
    -        print("Accuracy score on data set: ", dnn.score(X, yXOR))
    +        print("Test accuracy: %.3f" % scores[1])
             print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    # optional
    +# visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
     
     sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
     test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
     for i in range(len(eta_vals)):
         for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    -        test_pred = dnn.predict(X)
    -        test_accuracy[i][j] = accuracy_score(yXOR, test_pred)
    +        DNN = DNN_keras[i][j]
    +
    +        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
    +        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
     
     fig, ax = plt.subplots(figsize = (10, 10))
     sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    @@ -833,6 +2327,197 @@ plt.show()
     
    +









    +

    The Breast Cancer Data, now with Keras

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +import numpy as np
    +import matplotlib.pyplot as plt
    +import seaborn as sns
    +from sklearn.model_selection import train_test_split as splitter
    +from sklearn.datasets import load_breast_cancer
    +import pickle
    +import os 
    +
    +
    +"""Load breast cancer dataset"""
    +
    +np.random.seed(0)        #create same seed for random number every time
    +
    +cancer=load_breast_cancer()      #Download breast cancer dataset
    +
    +inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    +outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    +labels=cancer.feature_names[0:30]
    +
    +print('The content of the breast cancer dataset is:')      #Print information about the datasets
    +print(labels)
    +print('-------------------------')
    +print("inputs =  " + str(inputs.shape))
    +print("outputs =  " + str(outputs.shape))
    +print("labels =  "+ str(labels.shape))
    +
    +x=inputs      #Reassign the Feature and Label matrices to other variables
    +y=outputs
    +
    +#%% 
    +
    +# Visualisation of dataset (for correlation analysis)
    +
    +plt.figure()
    +plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean radius',fontweight='bold')
    +plt.ylabel('Mean perimeter',fontweight='bold')
    +plt.show()
    +
    +plt.figure()
    +plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    +plt.xlabel('Mean compactness',fontweight='bold')
    +plt.ylabel('Mean concavity',fontweight='bold')
    +plt.show()
    +
    +
    +plt.figure()
    +plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean radius',fontweight='bold')
    +plt.ylabel('Mean texture',fontweight='bold')
    +plt.show()
    +
    +plt.figure()
    +plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    +plt.xlabel('Mean perimeter',fontweight='bold')
    +plt.ylabel('Mean compactness',fontweight='bold')
    +plt.show()
    +
    +
    +# Generate training and testing datasets
    +
    +#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    +#and add to input matrix
    +
    +temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    +temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    +X=np.hstack((temp1,temp2))      
    +temp=np.reshape(x[:,5],(len(x[:,5]),1))
    +X=np.hstack((X,temp))       
    +temp=np.reshape(x[:,8],(len(x[:,8]),1))
    +X=np.hstack((X,temp))       
    +
    +X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    +
    +y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    +y_test=to_categorical(y_test)
    +
    +del temp1,temp2,temp
    +
    +# %%
    +
    +# Define tunable parameters"
    +
    +eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    +lamda=0.01                                  #Define hyperparameter
    +n_layers=2                                  #Define number of hidden layers in the model
    +n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    +epochs=100                                   #Number of reiterations over the input data
    +batch_size=100                              #Number of samples per gradient update
    +
    +# %%
    +
    +"""Define function to return Deep Neural Network model"""
    +
    +def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    +    model=Sequential()      
    +    for i in range(n_layers):       #Run loop to add hidden layers to the model
    +        if (i==0):                  #First layer requires input dimensions
    +            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    +        else:                       #Subsequent layers are capable of automatic shape inferencing
    +            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    +    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    +    sgd=optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    +    return model
    +
    +    
    +Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    +Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    +
    +for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    +    for j in range(len(eta)):      #accuracy scores 
    +        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    +        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    +        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    +        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    +               
    +
    +def plot_data(x,y,data,title=None):
    +
    +    # plot results
    +    fontsize=16
    +
    +
    +    fig = plt.figure()
    +    ax = fig.add_subplot(111)
    +    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    +    
    +    cbar=fig.colorbar(cax)
    +    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    +    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    +    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    +
    +    # put text on matrix elements
    +    for i, x_val in enumerate(np.arange(len(x))):
    +        for j, y_val in enumerate(np.arange(len(y))):
    +            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    +            ax.text(x_val, y_val, c, va='center', ha='center')
    +
    +    # convert axis vaues to to string labels
    +    x=[str(i) for i in x]
    +    y=[str(i) for i in y]
    +
    +
    +    ax.set_xticklabels(['']+x)
    +    ax.set_yticklabels(['']+y)
    +
    +    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    +    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    +    if title is not None:
    +        ax.set_title(title)
    +
    +    plt.tight_layout()
    +
    +    plt.show()
    +    
    +plot_data(eta,n_neuron,Train_accuracy, 'training')
    +plot_data(eta,n_neuron,Test_accuracy, 'testing')
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +









    Building a neural network code

    @@ -2183,1963 +3868,6 @@ scores = logistic_regressionLecture Thursday October 26 - - -

    Developing a code for doing neural networks with back propagation

    - -

    We repeat some of the elements discussed last week. The first part of -the material for Thursday was contained in the slides for last -week as well. We will repeat some of the topics here before we move into -applications to differential equations and other examples. -

    - -

    One can identify a set of key steps when using neural networks to solve supervised learning problems:

    - -
      -
    1. Collect and pre-process data
    2. -
    3. Define model and architecture
    4. -
    5. Choose cost function and optimizer
    6. -
    7. Train the model
    8. -
    9. Evaluate model performance on test data
    10. -
    11. Adjust hyperparameters (if necessary, network architecture)
    12. -
    -









    -

    Collect and pre-process data

    - -

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

    - -

    To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

    - -

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

    - -

    $$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

    - -

    and the targets would be:

    - -

    $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

    - -

    Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

    - - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Train and test datasets

    - -

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    - -

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    - -

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -
    -# one-liner from scikit-learn library
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -# equivalently in numpy
    -def train_test_split_numpy(inputs, labels, train_size, test_size):
    -    n_inputs = len(inputs)
    -    inputs_shuffled = inputs.copy()
    -    labels_shuffled = labels.copy()
    -    
    -    np.random.shuffle(inputs_shuffled)
    -    np.random.shuffle(labels_shuffled)
    -    
    -    train_end = int(n_inputs*train_size)
    -    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    -    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    -    
    -    return X_train, X_test, Y_train, Y_test
    -
    -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    -
    -print("Number of training images: " + str(len(X_train)))
    -print("Number of test images: " + str(len(X_test)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Define model and architecture

    - -

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    - -

    $$ z = \sum_{i=1}^n w_i a_i ,$$

    - -

    $$ y = f(z) ,$$

    - -

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

    - -

    The simplest activation function for a neuron is the Heaviside function:

    - -

    $$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

    - -

    A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

    - -

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

    - -

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

    - -

    $$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$

    - -

    which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

    - - -

    Layers

    - -
      -
    • Input
    • -
    -

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    - -
      -
    • Hidden layer
    • -
    -

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

    - -
      -
    • Output
    • -
    -

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

    - -

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    - -

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    - -

    $$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

    - -

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

    - -

    Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. -

    - - -

    Weights and biases

    - -

    Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. -

    - -

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

    - -

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    - - -
    -
    -
    -
    -
    -
    # building our neural network
    -
    -n_inputs, n_features = X_train.shape
    -n_hidden_neurons = 50
    -n_categories = 10
    -
    -# we make the weights normally distributed using numpy.random.randn
    -
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    -
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Feed-forward pass

    - -

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

    - -

    $$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

    - -

    this is then passed through our activation function

    - -

    $$ a_{j}^{l} = f(z_{j}^{l}) .$$

    - -

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    - -

    $$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

    - -

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    - -

    $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

    - - -

    Matrix multiplications

    - -

    Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden -layer have the dimensions -\( W_{hidden} = (n_{features}, n_{hidden}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

    - -

    $$ X W^{h} = (n_{inputs}, n_{hidden}),$$

    - -

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

    - -

    $$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

    - -

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

    - -

    $$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

    - -

    This is fed to the output layer:

    - -

    $$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

    - -

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    - -

    $$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

    - - - -
    -
    -
    -
    -
    -
    # setup the feed-forward pass, subscript h = hidden layer
    -
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    return probabilities
    -
    -probabilities = feed_forward(X_train)
    -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    -print("probabilities sum up to: " + str(probabilities[0].sum()))
    -print()
    -
    -# we obtain a prediction by taking the class with the highest likelihood
    -def predict(X):
    -    probabilities = feed_forward(X)
    -    return np.argmax(probabilities, axis=1)
    -
    -predictions = predict(X_train)
    -print("predictions = (n_inputs) = " + str(predictions.shape))
    -print("prediction for image 0: " + str(predictions[0]))
    -print("correct label for image 0: " + str(Y_train[0]))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Choose cost function and optimizer

    - -

    To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

    $$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

    - -

    $$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$

    - -

    i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

    - -

    Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

    - -

    In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category \( c' \) -(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. -

    - - -









    -

    Optimizing the cost function

    - -

    The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

    - -

    $$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

    - -

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

    - -

    A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

    - -

    $$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

    - -

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    - -

    This has two important benefits:

    -
      -
    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. -
    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. -
    -

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    - - -

    Regularization

    - -

    It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

    - -

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    - -

    $$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

    - -

    i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

    - -

    In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has \( (64 + 1)\times 50=3250 \) weights in -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -layer (\( +1 \) for the bias), and the gradient must be calculated for -every parameter. We use the backpropagation algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. -

    - -









    -

    Matrix multiplication

    - -

    To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

    - -

    $$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

    - -

    The gradient for the output weights is calculated as

    - -

    $$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

    - -

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

    - -

    The gradient with respect to the output bias is then

    - -

    $$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

    - -

    The error in the hidden layer is

    - -

    $$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

    - -

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

    - -

    This again gives us the gradients in the hidden layer:

    - -

    $$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

    - -

    $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

    - - - -
    -
    -
    -
    -
    -
    # to categorical turns our integer vector into a onehot representation
    -from sklearn.metrics import accuracy_score
    -
    -# one-hot in numpy
    -def to_categorical_numpy(integer_vector):
    -    n_inputs = len(integer_vector)
    -    n_categories = np.max(integer_vector) + 1
    -    onehot_vector = np.zeros((n_inputs, n_categories))
    -    onehot_vector[range(n_inputs), integer_vector] = 1
    -    
    -    return onehot_vector
    -
    -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    -
    -def feed_forward_train(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    # for backpropagation need activations in hidden and output layers
    -    return a_h, probabilities
    -
    -def backpropagation(X, Y):
    -    a_h, probabilities = feed_forward_train(X)
    -    
    -    # error in the output layer
    -    error_output = probabilities - Y
    -    # error in the hidden layer
    -    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    -    
    -    # gradients for the output layer
    -    output_weights_gradient = np.matmul(a_h.T, error_output)
    -    output_bias_gradient = np.sum(error_output, axis=0)
    -    
    -    # gradient for the hidden layer
    -    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    -    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    -
    -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -eta = 0.01
    -lmbd = 0.01
    -for i in range(1000):
    -    # calculate gradients
    -    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    -    
    -    # regularization term gradients
    -    dWo += lmbd * output_weights
    -    dWh += lmbd * hidden_weights
    -    
    -    # update weights and biases
    -    output_weights -= eta * dWo
    -    output_bias -= eta * dBo
    -    hidden_weights -= eta * dWh
    -    hidden_bias -= eta * dBh
    -
    -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Improving performance

    - -

    As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. -

    - -

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    - -

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

    - -

    If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. -

    - -









    -

    Full object-oriented implementation

    - -

    It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. -

    - - - -
    -
    -
    -
    -
    -
    class NeuralNetwork:
    -    def __init__(
    -            self,
    -            X_data,
    -            Y_data,
    -            n_hidden_neurons=50,
    -            n_categories=10,
    -            epochs=10,
    -            batch_size=100,
    -            eta=0.1,
    -            lmbd=0.0):
    -
    -        self.X_data_full = X_data
    -        self.Y_data_full = Y_data
    -
    -        self.n_inputs = X_data.shape[0]
    -        self.n_features = X_data.shape[1]
    -        self.n_hidden_neurons = n_hidden_neurons
    -        self.n_categories = n_categories
    -
    -        self.epochs = epochs
    -        self.batch_size = batch_size
    -        self.iterations = self.n_inputs // self.batch_size
    -        self.eta = eta
    -        self.lmbd = lmbd
    -
    -        self.create_biases_and_weights()
    -
    -    def create_biases_and_weights(self):
    -        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    -        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    -
    -        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    -        self.output_bias = np.zeros(self.n_categories) + 0.01
    -
    -    def feed_forward(self):
    -        # feed-forward for training
    -        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    -        self.a_h = sigmoid(self.z_h)
    -
    -        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    -
    -        exp_term = np.exp(self.z_o)
    -        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -
    -    def feed_forward_out(self, X):
    -        # feed-forward for output
    -        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    -        a_h = sigmoid(z_h)
    -
    -        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    -        
    -        exp_term = np.exp(z_o)
    -        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -        return probabilities
    -
    -    def backpropagation(self):
    -        error_output = self.probabilities - self.Y_data
    -        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    -
    -        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    -        self.output_bias_gradient = np.sum(error_output, axis=0)
    -
    -        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    -        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -        if self.lmbd > 0.0:
    -            self.output_weights_gradient += self.lmbd * self.output_weights
    -            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    -
    -        self.output_weights -= self.eta * self.output_weights_gradient
    -        self.output_bias -= self.eta * self.output_bias_gradient
    -        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    -        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    -
    -    def predict(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return np.argmax(probabilities, axis=1)
    -
    -    def predict_probabilities(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return probabilities
    -
    -    def train(self):
    -        data_indices = np.arange(self.n_inputs)
    -
    -        for i in range(self.epochs):
    -            for j in range(self.iterations):
    -                # pick datapoints with replacement
    -                chosen_datapoints = np.random.choice(
    -                    data_indices, size=self.batch_size, replace=False
    -                )
    -
    -                # minibatch training data
    -                self.X_data = self.X_data_full[chosen_datapoints]
    -                self.Y_data = self.Y_data_full[chosen_datapoints]
    -
    -                self.feed_forward()
    -                self.backpropagation()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Evaluate model performance on test data

    - -

    To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the accuracy score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). -

    - -

    $$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

    - -

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    - - - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -
    -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -dnn.train()
    -test_predict = dnn.predict(X_test)
    -
    -# accuracy score from scikit library
    -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -
    -# equivalent in numpy
    -def accuracy_score_numpy(Y_test, Y_pred):
    -    return np.sum(Y_test == Y_pred) / len(Y_test)
    -
    -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Adjust hyperparameters

    - -

    We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

    - - - -
    -
    -
    -
    -
    -
    eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -# store the models for later use
    -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -# grid search
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -        dnn.train()
    -        
    -        DNN_numpy[i][j] = dnn
    -        
    -        test_predict = dnn.predict(X_test)
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, you can also do this with matplotlib imshow
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_numpy[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    scikit-learn implementation

    - -

    scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

    - -

    scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.neural_network import MLPClassifier
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X_train, Y_train)
    -        
    -        DNN_scikit[i][j] = dnn
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualization

    - - -
    -
    -
    -
    -
    -
    # optional
    -# visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Building neural networks in Tensorflow and Keras

    - -

    Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. -

    - -

    In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. -

    - -









    -

    Tensorflow

    - -

    Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. -

    - -

    Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. -

    - -

    Tensorflow uses so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow graph -to represent your model, and then create a Tensorflow session to run the graph. -

    - -

    In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. -

    - -

    To install tensorflow on Unix/Linux systems, use pip as

    - - -
    -
    -
    -
    -
    -
    pip3 install tensorflow
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    and/or if you use anaconda, just write (or install from the graphical user interface) -(current release of CPU-only TensorFlow) -

    - - -
    -
    -
    -
    -
    -
    conda create -n tf tensorflow
    -conda activate tf
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    To install the current release of GPU TensorFlow

    - - -
    -
    -
    -
    -
    -
    conda create -n tf-gpu tensorflow-gpu
    -conda activate tf-gpu
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Using Keras

    - -

    Keras is a high level neural network -that supports Tensorflow, CTNK and Theano as backends. -If you have Anaconda installed you may run the following command -

    - - -
    -
    -
    -
    -
    -
    conda install keras
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    You can look up the instructions here for more information.

    - -

    We will to a large extent use keras in our examples..

    - -









    -

    Collect and pre-process data

    - -

    Let us look again at the MINST data set.

    - - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import tensorflow as tf
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -
    -from sklearn.model_selection import train_test_split
    -
    -# one-hot representation of labels
    -labels = to_categorical(labels)
    -
    -# split into train and test data
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -n_neurons_layer1 = 100
    -n_neurons_layer2 = 50
    -n_categories = 10
    -eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
    -    model = Sequential()
    -    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(Dense(n_categories, activation='softmax'))
    -    
    -    sgd = optimizers.SGD(lr=eta)
    -    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    -    
    -    return model
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -        
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
    -                                         eta=eta, lmbd=lmbd)
    -        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    -        scores = DNN.evaluate(X_test, Y_test)
    -        
    -        DNN_keras[i][j] = DNN
    -        
    -        print("Learning rate = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Test accuracy: %.3f" % scores[1])
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    # optional
    -# visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        DNN = DNN_keras[i][j]
    -
    -        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
    -        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    The Breast Cancer Data, now with Keras

    - - - -
    -
    -
    -
    -
    -
    import tensorflow as tf
    -from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import seaborn as sns
    -from sklearn.model_selection import train_test_split as splitter
    -from sklearn.datasets import load_breast_cancer
    -import pickle
    -import os 
    -
    -
    -"""Load breast cancer dataset"""
    -
    -np.random.seed(0)        #create same seed for random number every time
    -
    -cancer=load_breast_cancer()      #Download breast cancer dataset
    -
    -inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    -outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    -labels=cancer.feature_names[0:30]
    -
    -print('The content of the breast cancer dataset is:')      #Print information about the datasets
    -print(labels)
    -print('-------------------------')
    -print("inputs =  " + str(inputs.shape))
    -print("outputs =  " + str(outputs.shape))
    -print("labels =  "+ str(labels.shape))
    -
    -x=inputs      #Reassign the Feature and Label matrices to other variables
    -y=outputs
    -
    -#%% 
    -
    -# Visualisation of dataset (for correlation analysis)
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean perimeter',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    -plt.xlabel('Mean compactness',fontweight='bold')
    -plt.ylabel('Mean concavity',fontweight='bold')
    -plt.show()
    -
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean texture',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean perimeter',fontweight='bold')
    -plt.ylabel('Mean compactness',fontweight='bold')
    -plt.show()
    -
    -
    -# Generate training and testing datasets
    -
    -#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    -#and add to input matrix
    -
    -temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    -temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    -X=np.hstack((temp1,temp2))      
    -temp=np.reshape(x[:,5],(len(x[:,5]),1))
    -X=np.hstack((X,temp))       
    -temp=np.reshape(x[:,8],(len(x[:,8]),1))
    -X=np.hstack((X,temp))       
    -
    -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    -
    -y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    -y_test=to_categorical(y_test)
    -
    -del temp1,temp2,temp
    -
    -# %%
    -
    -# Define tunable parameters"
    -
    -eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    -lamda=0.01                                  #Define hyperparameter
    -n_layers=2                                  #Define number of hidden layers in the model
    -n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    -epochs=100                                   #Number of reiterations over the input data
    -batch_size=100                              #Number of samples per gradient update
    -
    -# %%
    -
    -"""Define function to return Deep Neural Network model"""
    -
    -def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    -    model=Sequential()      
    -    for i in range(n_layers):       #Run loop to add hidden layers to the model
    -        if (i==0):                  #First layer requires input dimensions
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    -        else:                       #Subsequent layers are capable of automatic shape inferencing
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    -    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    -    sgd=optimizers.SGD(lr=eta)
    -    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    -    return model
    -
    -    
    -Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    -Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    -
    -for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    -    for j in range(len(eta)):      #accuracy scores 
    -        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    -        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    -        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    -        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    -               
    -
    -def plot_data(x,y,data,title=None):
    -
    -    # plot results
    -    fontsize=16
    -
    -
    -    fig = plt.figure()
    -    ax = fig.add_subplot(111)
    -    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    -    
    -    cbar=fig.colorbar(cax)
    -    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    -    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    -    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    -
    -    # put text on matrix elements
    -    for i, x_val in enumerate(np.arange(len(x))):
    -        for j, y_val in enumerate(np.arange(len(y))):
    -            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    -            ax.text(x_val, y_val, c, va='center', ha='center')
    -
    -    # convert axis vaues to to string labels
    -    x=[str(i) for i in x]
    -    y=[str(i) for i in y]
    -
    -
    -    ax.set_xticklabels(['']+x)
    -    ax.set_yticklabels(['']+y)
    -
    -    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    -    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    -    if title is not None:
    -        ax.set_title(title)
    -
    -    plt.tight_layout()
    -
    -    plt.show()
    -    
    -plot_data(eta,n_neuron,Train_accuracy, 'training')
    -plot_data(eta,n_neuron,Test_accuracy, 'testing')
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Fine-tuning neural network hyperparameters

    - -

    The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are interconnected), -but even in a simple FFNN you can change the number of layers, the -number of neurons per layer, the type of activation function to use in -each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you -know what combination of hyperparameters is the best for your task? -

    - -
      -
    • You can use grid search with cross-validation to find the right hyperparameters.
    • -
    -

    However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. -

    - -
      -
    • You can use randomized search.
    • -
    • Or use tools like Oscar, which implements more complex algorithms to help you find a good set of hyperparameters quickly.
    • -
    -









    -

    Hidden layers

    - -

    For many problems you can start with just one or two hidden layers and it will work just fine. -For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a -few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of -neurons, in roughly the same amount of training time. -

    - -

    For more complex problems, you can gradually -ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such -as large image classification or speech recognition, typically require networks with dozens of layers -and they need a huge amount -of training data. However, you will rarely have to train such networks from scratch: it is much more -common to reuse parts of a pretrained state-of-the-art network that performs a similar task. -

    - - -

    Which activation function should I use?

    - -

    The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. -

    - -

    Unfortunately for us, the gradients often get smaller and smaller as the -algorithm progresses down to the first hidden layers. As a result, the -GD update leaves the lower layer connection weights -virtually unchanged, and training never converges to a good -solution. This is known in the literature as -the vanishing gradients problem. -

    - -

    In other cases, the opposite can happen, namely the the gradients can grow bigger and -bigger. The result is that many of the layers get large updates of the -weights the -algorithm diverges. This is the exploding gradients problem, which is -mostly encountered in recurrent neural networks. More generally, deep -neural networks suffer from unstable gradients, different layers may -learn at widely different speeds -

    - - -

    Is the Logistic activation function (Sigmoid) our choice?

    - -

    Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. -

    - -

    A paper titled Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -

    - -

    They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -

    - -









    -

    The derivative of the Logistic funtion

    - -

    Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. -

    - -

    In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -

    - -

    One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -

    - -









    -

    The RELU function family

    - -

    The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. -

    - -

    In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. -

    - -

    To solve this problem, nowadays practitioners use a variant of the ReLU -function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function -

    - -$$ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -$$ - - -









    -

    Which activation function should we use?

    - -

    In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than \( \tanh \) which in turn performs better -than the logistic function. -

    - -

    If runtime -performance is an issue, then you may opt for the leaky ReLU function over the -ELU function If you don’t -want to tweak yet another hyperparameter, you may just use the default -\( \alpha \) of \( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have -spare time and computing power, you can use cross-validation or -bootstrap to evaluate other activation functions. -

    - -









    -

    More on activation functions, output layers

    - -

    In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).

    - -

    It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck.

    - -For the output layer: - -
      -
    • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
    • -
    • For regression tasks, you can simply use no activation function at all.
    • -
    -









    -

    Batch Normalization

    - -

    Batch Normalization -aims to address the vanishing/exploding gradients problems, and more generally the problem that the -distribution of each layer’s inputs changes during training, as the parameters of the previous layers change. -

    - -

    The technique consists of adding an operation in the model just before the activation function of each -layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new -parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model -learn the optimal scale and mean of the inputs for each layer. -In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and -standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current -mini-batch, from this the name batch normalization. -

    - -









    -

    Dropout

    - -

    It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but -excluding the output neurons) has a probability \( p \) of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active during the next step. -

    - -

    The -hyperparameter \( p \) is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore. - It is viewed as one of the most popular regularization techniques. -

    - -









    -

    Gradient Clipping

    - -

    A popular technique to lessen the exploding gradients problem is to simply clip the gradients during -backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural -networks). -

    - -

    This technique is called Gradient Clipping.

    - -

    In general however, Batch -Normalization is preferred. -

    - -









    -

    A very nice website on Neural Networks

    - -

    You may find this website very useful.

    - - -

    A top-down perspective on Neural networks

    - -

    The first thing we would like to do is divide the data into two or three -parts. A training set, a validation or dev (development) set, and a -test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: -

    - -
      -
    • Estimate optimal error rate
    • -
    • Minimize underfitting (bias) on training data set.
    • -
    • Make sure you are not overfitting.
    • -
    -

    If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. -

    - -

    However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -

    - -









    -

    Limitations of supervised learning with deep networks

    - -

    Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). -

    - -

    Here we list some of the important limitations of supervised neural network based models.

    - -
      -
    • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
    • -
    • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
    • -
    • Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
    • -
    • Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
    • -
    -

    Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.

    -









    Solving ODEs with Deep Learning

    @@ -6798,7 +6526,7 @@ $$
    - © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz b/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz index 826cb297297b9446dde7d873502221843123e1a7..617aea4c626865e760df67ae95e4b124fa59bb7e 100644 GIT binary patch delta 124 zcmV-?0E7R)0l)zWABzY8Sz8llkqAv|DPalcJf=Ws%wrw^S?;8l&N^X+Q=00G%A$HV zH;k3#hduKv@XSAPtfYnQzIT;YptQqW>l$u|HH#zJ_9}-$qa9md@Y+d(AXE>cD5R5G eiA&fTeKMl4QTXd;JkRsIuRQ=6Lf|X_2mk_Wl|}V# zZWt@e4}0cU;F*8oSV;@peeWu*Kxv1$)-~J^YZgbc?NttiMmx5^;I)$mL8u-?QAj7X e5|^+w`ea07qwv?yc%J8ZUwZ)hT2ZY42mk." + " * Solving differential equations with Neural Networks\n", + "\n", + "" ] }, { "cell_type": "markdown", - "id": "b84acd9c", + "id": "71e1eeb5", + "metadata": { + "editable": true + }, + "source": [ + "## Exercises and lab session week 43\n", + "**Lab sessions on Tuesday and Wednesday.**\n", + "\n", + " * Exercise on writing your own neural network code\n", + "\n", + " * The exercises this week will be continued next week as well\n", + "\n", + " * Discussion of project 2" + ] + }, + { + "cell_type": "markdown", + "id": "7f7a2fd2", + "metadata": { + "editable": true + }, + "source": [ + "## Mathematics of deep learning\n", + "\n", + "**Two recent books online.**\n", + "\n", + "1. [The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen](https://arxiv.org/abs/2105.04026), published as [Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022](https://doi.org/10.1017/9781009025096.002)\n", + "\n", + "2. [Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger](https://doi.org/10.48550/arXiv.2310.20360)" + ] + }, + { + "cell_type": "markdown", + "id": "cb7cf4c8", + "metadata": { + "editable": true + }, + "source": [ + "## Reminder on books with hands-on material and codes\n", + "* [Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch](https://sebastianraschka.com/blog/2022/ml-pytorch-book.html)" + ] + }, + { + "cell_type": "markdown", + "id": "f1d51dcd", + "metadata": { + "editable": true + }, + "source": [ + "## Reading recommendations\n", + "\n", + "1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from [GitHub](https://github.com/rasbt/machine-learning-book). See also chapters 12 and 13 on using Pytorch to make a Neural network code. \n", + "\n", + "2. Goodfellow et al, chapter 6 and 7 contain most of the neural network background." + ] + }, + { + "cell_type": "markdown", + "id": "564c4073", "metadata": { "editable": true }, @@ -93,7 +119,7 @@ }, { "cell_type": "markdown", - "id": "dc79ff8c", + "id": "2033a900", "metadata": { "editable": true }, @@ -110,344 +136,895 @@ }, { "cell_type": "markdown", - "id": "f4b997dc", + "id": "ba4829f3", "metadata": { "editable": true }, "source": [ - "## Material for exercises week 43 and week 44" + "## Lecture Monday October 21" ] }, { "cell_type": "markdown", - "id": "497f4461", + "id": "98da0749", "metadata": { "editable": true }, "source": [ - "## Writing our first neural network code, testing it for the OR and XOR gates\n", + "## Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations\n", + "This is a reminder from where we ended last week.\n", "\n", - "During week 41 we discussed three different types of gates, the\n", - "so-called XOR, the OR and the AND gates. In order to develop a code\n", - "for neural networks, it can be useful to set up a simpler system with\n", - "only two inputs and one output. This can make it easier to debug and\n", - "study the feed forward pass and the back propagation part. In the\n", - "exercise this and next week, we propose to study this system with just\n", - "one hidden layer and two hidden nodes. There is only one output node\n", - "and we can choose to use either a simple regression case (fitting a\n", - "line) or just a binary classification case with the corss-entropy as\n", - "cost function.\n", + "**The architecture (our model).**\n", "\n", - "Their inputs and outputs can be\n", - "summarized using the following tables, first for the OR gate with\n", - "inputs $x_1$ and $x_2$ and outputs $y$:\n", + "1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)\n", "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
    $x_1$ $x_2$ $y$
    0 0 0
    0 1 1
    1 0 1
    1 1 1
    " + "2. Define the number of hidden layers and hidden nodes\n", + "\n", + "3. Define activation functions for hidden layers and output layers\n", + "\n", + "4. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates\n", + "\n", + "5. Define cost function and possible regularization terms with hyperparameters\n", + "\n", + "6. Initialize weights and biases\n", + "\n", + "7. Fix number of iterations for the feed forward part and back propagation part" ] }, { "cell_type": "markdown", - "id": "31fa283f", + "id": "483e2f2c", "metadata": { "editable": true }, "source": [ - "## The AND and XOR Gates\n", + "## Setting up the back propagation algorithm, part 1\n", "\n", - "The AND gate is defined as\n", + "Let us write this out in the form of an algorithm.\n", "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
    $x_1$ $x_2$ $y$
    0 0 0
    0 1 0
    1 0 0
    1 1 1
    \n", + "**First**, we set up the input data $\\boldsymbol{x}$ and the activations\n", + "$\\boldsymbol{z}_1$ of the input layer and compute the activation function and\n", + "the pertinent outputs $\\boldsymbol{a}^1$.\n", "\n", - "And finally we have the XOR gate\n", + "**Secondly**, we perform then the feed forward till we reach the output\n", + "layer and compute all $\\boldsymbol{z}_l$ of the input layer and compute the\n", + "activation function and the pertinent outputs $\\boldsymbol{a}^l$ for\n", + "$l=1,2,3,\\dots,L$.\n", "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
    $x_1$ $x_2$ $y$
    0 0 0
    0 1 1
    1 0 1
    1 1 0
    " + "**Notation**: The first hidden layer has $l=1$ as label and the final output layer has $l=L$." ] }, { "cell_type": "markdown", - "id": "4dcbdd73", + "id": "b20954e0", "metadata": { "editable": true }, "source": [ - "## Representing the Data Sets\n", + "## Setting up the back propagation algorithm, part 2\n", "\n", - "Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads" + "Thereafter we compute the ouput error $\\boldsymbol{\\delta}^L$ by computing all" ] }, { "cell_type": "markdown", - "id": "c46b2f8b", + "id": "f5a04ade", "metadata": { "editable": true }, "source": [ "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", - " 0 & 1 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 1 & 1 \\end{bmatrix},\n", + "\\delta_j^L = \\sigma'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "b7c5f7d6", + "id": "710634c3", "metadata": { "editable": true }, "source": [ - "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate.\n", - "\n", - "Your tasks here are\n", - "\n", - "1. Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs.\n", - "\n", - "2. Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function.\n", - "\n", - "3. Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output.\n", - "\n", - "4. Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets.\n", - "\n", - "5. Set up the cost function (cross entropy for classification of binary cases).\n", - "\n", - "6. Calculate the gradients needed for the back propagation part.\n", - "\n", - "7. Use the gradients to train the network in the back propagation part. Think of using automatic differentiation.\n", - "\n", - "8. Train the network and study your results and compare with results obtained either with **scikit-learn** or **TensorFlow**.\n", - "\n", - "Everything you develop here can be used directly into the code for the project." + "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,1$ as" ] }, { "cell_type": "markdown", - "id": "f08fc768", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up dimensionalities by hand\n", - "\n", - "It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by" - ] - }, - { - "cell_type": "markdown", - "id": "0fad4a46", + "id": "98263180", "metadata": { "editable": true }, "source": [ "$$\n", - "\\boldsymbol{W_h}=\\begin{bmatrix} 1 & 1 \\\\\n", - " 1 & 1 \\end{bmatrix},\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l).\n", "$$" ] }, { "cell_type": "markdown", - "id": "17c0bcaf", + "id": "c66e293b", "metadata": { "editable": true }, "source": [ - "Multiplying $\\boldsymbol{X}$ and $\\boldsymbol{W}$ gives" - ] - }, - { - "cell_type": "markdown", - "id": "47c99c93", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}{W}_h=\\begin{bmatrix} 0 & 0 \\\\\n", - " 1 & 1 \\\\\n", - "\t\t 1 & 1 \\\\\n", - "\t\t 2 & 2 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "141bf485", - "metadata": { - "editable": true - }, - "source": [ - "Assume also that the bias vector for the hidden layer is" - ] - }, - { - "cell_type": "markdown", - "id": "6463b9b9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{b}_h=\\begin{bmatrix} 0 \\\\\n", - " -1\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5ca8af0c", - "metadata": { - "editable": true - }, - "source": [ - "Adding it gives us the input to the activation function of the hidden layer" - ] - }, - { - "cell_type": "markdown", - "id": "2d909693", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{z}_h=\\boldsymbol{X}\\boldsymbol{W}_h+\\boldsymbol{b}_h=\\begin{bmatrix} 0 & -1 \\\\\n", - " 1 & 0 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 2 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "25cf4c44", - "metadata": { - "editable": true - }, - "source": [ - "Let us then assume that our activation function is the RELU function, which simply means that we take the max of $0$ and the elements of the input argument $\\boldsymbol{z}_h$, that is we have" - ] - }, - { - "cell_type": "markdown", - "id": "95d5d272", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{a}_h=\\mathrm{RELU}(\\boldsymbol{z}_h=\\boldsymbol{X}\\boldsymbol{W}_h+\\boldsymbol{b}_h)=\\begin{bmatrix} 0 & 0 \\\\\n", - " 1 & 0 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 2 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a65ecd62", - "metadata": { - "editable": true - }, - "source": [ - "Assume also that the bias of the output layer is zero and that the weights of the output layer are" - ] - }, - { - "cell_type": "markdown", - "id": "128e6e81", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{w}_o=\\begin{bmatrix} 1 \\\\\n", - " -2\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fca8850c", - "metadata": { - "editable": true - }, - "source": [ - "and multiplying with $\\boldsymbol{a}_h$ gives the output" - ] - }, - { - "cell_type": "markdown", - "id": "cf08153e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{a}_o=\\begin{bmatrix} 0 & 0 \\\\\n", - " 1 & 0 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 2 & 1 \\end{bmatrix}\\begin{bmatrix} 1 \\\\\n", - " -2\\end{bmatrix}=\\begin{bmatrix} 0 \\\\ 1 \\\\ 1 \\\\0\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8d6e69b0", - "metadata": { - "editable": true - }, - "source": [ - "the wanted result. Pay attention to the dimensionalities as well." - ] - }, - { - "cell_type": "markdown", - "id": "83d2a965", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the Neural Network\n", + "## Setting up the Back propagation algorithm, part 3\n", "\n", - "We define first our design matrix and the various output vectors for the different gates." + "Finally, we update the weights and the biases using gradient descent\n", + "for each $l=L-1,L-2,\\dots,1$ (the first hidden layer) and update the weights and biases\n", + "according to the rules" + ] + }, + { + "cell_type": "markdown", + "id": "383b1fae", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "w_{ij}^l\\leftarrow = w_{ij}^l- \\eta \\delta_j^la_i^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "628824b3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1c86d973", + "metadata": { + "editable": true + }, + "source": [ + "with $\\eta$ being the learning rate." + ] + }, + { + "cell_type": "markdown", + "id": "a296124e", + "metadata": { + "editable": true + }, + "source": [ + "## Updating the gradients\n", + "\n", + "With the back propagate error for each $l=L-1,L-2,\\dots,1$ as" + ] + }, + { + "cell_type": "markdown", + "id": "b44a4559", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0a11151c", + "metadata": { + "editable": true + }, + "source": [ + "we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,1$ and update the weights and biases according to the rules" + ] + }, + { + "cell_type": "markdown", + "id": "bf70569b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "w_{ij}^l\\leftarrow = w_{ij}^l- \\eta \\delta_j^la_i^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "731a98b8", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6bf20243", + "metadata": { + "editable": true + }, + "source": [ + "## Activation functions\n", + "\n", + "A property that characterizes a neural network, other than its\n", + "connectivity, is the choice of activation function(s). The following\n", + "restrictions are imposed on an activation function for an FFNN to\n", + "fulfill the universal approximation theorem\n", + "\n", + " * Non-constant\n", + "\n", + " * Bounded\n", + "\n", + " * Monotonically-increasing\n", + "\n", + " * Continuous" + ] + }, + { + "cell_type": "markdown", + "id": "256d376d", + "metadata": { + "editable": true + }, + "source": [ + "### Activation functions, examples\n", + "\n", + "Typical examples are the logistic *Sigmoid*" + ] + }, + { + "cell_type": "markdown", + "id": "75d41dc3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\sigma(x) = \\frac{1}{1 + e^{-x}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6d75fa71", + "metadata": { + "editable": true + }, + "source": [ + "and the *hyperbolic tangent* function" + ] + }, + { + "cell_type": "markdown", + "id": "9215eaeb", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\sigma(x) = \\tanh(x)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "77867e1c", + "metadata": { + "editable": true + }, + "source": [ + "## The RELU function family\n", + "\n", + "The ReLU activation function suffers from a problem known as the dying\n", + "ReLUs: during training, some neurons effectively die, meaning they\n", + "stop outputting anything other than 0.\n", + "\n", + "In some cases, you may find that half of your network’s neurons are\n", + "dead, especially if you used a large learning rate. During training,\n", + "if a neuron’s weights get updated such that the weighted sum of the\n", + "neuron’s inputs is negative, it will start outputting 0. When this\n", + "happen, the neuron is unlikely to come back to life since the gradient\n", + "of the ReLU function is 0 when its input is negative." + ] + }, + { + "cell_type": "markdown", + "id": "6c553b4c", + "metadata": { + "editable": true + }, + "source": [ + "## ELU function\n", + "\n", + "To solve this problem, nowadays practitioners use a variant of the\n", + "ReLU function, such as the leaky ReLU discussed above or the so-called\n", + "exponential linear unit (ELU) function" + ] + }, + { + "cell_type": "markdown", + "id": "5a3ef5f3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "470c6fbf", + "metadata": { + "editable": true + }, + "source": [ + "## Which activation function should we use?\n", + "\n", + "In general it seems that the ELU activation function is better than\n", + "the leaky ReLU function (and its variants), which is better than\n", + "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", + "than the logistic function.\n", + "\n", + "If runtime performance is an issue, then you may opt for the leaky\n", + "ReLU function over the ELU function If you don’t want to tweak yet\n", + "another hyperparameter, you may just use the default $\\alpha$ of\n", + "$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and\n", + "computing power, you can use cross-validation or bootstrap to evaluate\n", + "other activation functions." + ] + }, + { + "cell_type": "markdown", + "id": "08928465", + "metadata": { + "editable": true + }, + "source": [ + "## More on activation functions, output layers\n", + "\n", + "In most cases you can use the ReLU activation function in the hidden\n", + "layers (or one of its variants).\n", + "\n", + "It is a bit faster to compute than other activation functions, and the\n", + "gradient descent optimization does in general not get stuck.\n", + "\n", + "**For the output layer:**\n", + "\n", + "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n", + "\n", + "* For regression tasks, you can simply use no activation function at all." + ] + }, + { + "cell_type": "markdown", + "id": "780b8691", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up a Multi-layer perceptron model for classification\n", + "\n", + "We are now gong to develop an example based on the MNIST data\n", + "base. This is a classification problem and we need to use our\n", + "cross-entropy function we discussed in connection with logistic\n", + "regression. The cross-entropy defines our cost function for the\n", + "classificaton problems with neural networks.\n", + "\n", + "In binary classification with two classes $(0, 1)$ we define the\n", + "logistic/sigmoid function as the probability that a particular input\n", + "is in class $0$ or $1$. This is possible because the logistic\n", + "function takes any input from the real numbers and inputs a number\n", + "between 0 and 1, and can therefore be interpreted as a probability. It\n", + "also has other nice properties, such as a derivative that is simple to\n", + "calculate.\n", + "\n", + "For an input $\\boldsymbol{a}$ from the hidden layer, the probability that the input $\\boldsymbol{x}$\n", + "is in class 0 or 1 is just. We let $\\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$\n", + "represents our activation values $z$. We have" + ] + }, + { + "cell_type": "markdown", + "id": "14286855", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = \\frac{1}{1 + \\exp{(- \\boldsymbol{x}})} ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1817a50c", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "4e4df109", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "P(y = 1 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = 1 - P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4c115b5c", + "metadata": { + "editable": true + }, + "source": [ + "where $y \\in \\{0, 1\\}$ and $\\boldsymbol{\\theta}$ represents the weights and biases\n", + "of our network." + ] + }, + { + "cell_type": "markdown", + "id": "601ad3b6", + "metadata": { + "editable": true + }, + "source": [ + "## Defining the cost function\n", + "\n", + "Our cost function is given as (see the Logistic regression lectures)" + ] + }, + { + "cell_type": "markdown", + "id": "2f49d2d3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = - \\sum_{i=1}^n\n", + "y_i \\ln[P(y_i = 0)] + (1 - y_i) \\ln [1 - P(y_i = 0)] = \\sum_{i=1}^n \\mathcal{L}_i(\\boldsymbol{\\theta}) .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "cf6a1725", + "metadata": { + "editable": true + }, + "source": [ + "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", + "for each point in the dataset $\\mathcal{L}_i(\\boldsymbol{\\theta})$. \n", + "The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather\n", + "than maximizing a negative number. \n", + "\n", + "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", + "\n", + "$y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and\n", + "\n", + "$y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ \n", + "\n", + "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. \n", + "\n", + "If $\\boldsymbol{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th\n", + "output vector $\\boldsymbol{y}_i$. \n", + "The probability of $\\boldsymbol{x}_i$ being in class $c$ will be given by the softmax function:" + ] + }, + { + "cell_type": "markdown", + "id": "20e5a9a6", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "P(y_{ic} = 1 \\mid \\boldsymbol{x}_i, \\boldsymbol{\\theta}) = \\frac{\\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_c)}}\n", + "{\\sum_{c'=0}^{C-1} \\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_{c'})}} ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ded2cd23", + "metadata": { + "editable": true + }, + "source": [ + "which reduces to the logistic function in the binary case. \n", + "The likelihood of this $C$-class classifier\n", + "is now given as:" + ] + }, + { + "cell_type": "markdown", + "id": "999d76ec", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "97807e16", + "metadata": { + "editable": true + }, + "source": [ + "Again we take the negative log-likelihood to define our cost function:" + ] + }, + { + "cell_type": "markdown", + "id": "b2f0403b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\boldsymbol{\\theta})}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a9869137", + "metadata": { + "editable": true + }, + "source": [ + "See the logistic regression lectures for a full definition of the cost function.\n", + "\n", + "The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!" + ] + }, + { + "cell_type": "markdown", + "id": "87f77d1c", + "metadata": { + "editable": true + }, + "source": [ + "## Example: binary classification problem\n", + "\n", + "As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\\beta$ as" + ] + }, + { + "cell_type": "markdown", + "id": "36039872", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathcal{C}(\\boldsymbol{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\boldsymbol{\\beta})}+(1-y_i)\\log{1-p(y_i \\vert x_i,\\boldsymbol{\\beta})}\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7547e347", + "metadata": { + "editable": true + }, + "source": [ + "where we had defined the logistic (sigmoid) function" + ] + }, + { + "cell_type": "markdown", + "id": "83619bba", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "p(y_i =1\\vert x_i,\\boldsymbol{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b2808e9d", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "59c51a30", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "p(y_i =0\\vert x_i,\\boldsymbol{\\beta})=1-p(y_i =1\\vert x_i,\\boldsymbol{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "719a43ce", + "metadata": { + "editable": true + }, + "source": [ + "The parameters $\\boldsymbol{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", + "\n", + "Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. \n", + "We have then" + ] + }, + { + "cell_type": "markdown", + "id": "972a8958", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e7232927", + "metadata": { + "editable": true + }, + "source": [ + "with" + ] + }, + { + "cell_type": "markdown", + "id": "e5152f7e", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "99dc0aff", + "metadata": { + "editable": true + }, + "source": [ + "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", + "Our cost function at the final layer $l=L$ is now" + ] + }, + { + "cell_type": "markdown", + "id": "27d41be2", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathcal{C}(\\boldsymbol{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(1-t_i)\\log{(1-a_i^L)}\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b215905e", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" + ] + }, + { + "cell_type": "markdown", + "id": "94655358", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial \\mathcal{C}(\\boldsymbol{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "549c1791", + "metadata": { + "editable": true + }, + "source": [ + "In case we use another activation function than the logistic one, we need to evaluate other derivatives." + ] + }, + { + "cell_type": "markdown", + "id": "30d6b110", + "metadata": { + "editable": true + }, + "source": [ + "## The Softmax function\n", + "In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need" + ] + }, + { + "cell_type": "markdown", + "id": "2495939b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", + "\\frac{\\partial f(z_i^l)}{\\partial z_j^l} \\frac{\\partial z_j^l}{\\partial w_{jk}^l}= \\frac{\\partial f(z_i^l)}{\\partial z_j^l}a_k^{l-1}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e42b5f4c", + "metadata": { + "editable": true + }, + "source": [ + "For the Softmax function we have" + ] + }, + { + "cell_type": "markdown", + "id": "7fd41ca3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "021ab26d", + "metadata": { + "editable": true + }, + "source": [ + "Its derivative with respect to $z_j^l$ gives" + ] + }, + { + "cell_type": "markdown", + "id": "de6b7497", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "8b63a402", + "metadata": { + "editable": true + }, + "source": [ + "which in case of the simply binary model reduces to having $i=j$." + ] + }, + { + "cell_type": "markdown", + "id": "d3b442de", + "metadata": { + "editable": true + }, + "source": [ + "## Developing a code for doing neural networks with back propagation\n", + "\n", + "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", + "\n", + "1. Collect and pre-process data \n", + "\n", + "2. Define model and architecture \n", + "\n", + "3. Choose cost function and optimizer \n", + "\n", + "4. Train the model \n", + "\n", + "5. Evaluate model performance on test data \n", + "\n", + "6. Adjust hyperparameters (if necessary, network architecture)" + ] + }, + { + "cell_type": "markdown", + "id": "74225f44", + "metadata": { + "editable": true + }, + "source": [ + "## Collect and pre-process data\n", + "\n", + "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", + "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", + "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", + "of handwritten digits that is commonly used for training various image processing systems. \n", + "The MNIST dataset consists of 70 000 images of size $28\\times 28$ pixels, each labeled from 0 to 9. \n", + "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", + "\n", + "To feed data into a feed-forward neural network we need to represent\n", + "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n", + "row represents an *input*, in this case a handwritten digit, and\n", + "each column represents a *feature*, in this case a pixel. The\n", + "correct answers, also known as *labels* or *targets* are\n", + "represented as a 1D array of integers \n", + "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", + "\n", + "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", + "measurements of height (in m) \n", + "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n", + "\n", + "$$ X = \\begin{bmatrix}\n", + "1.85 & 81\\\\\n", + "1.71 & 65\\\\\n", + "1.95 & 103\\\\\n", + "1.55 & 42\\\\\n", + "1.63 & 56\n", + "\\end{bmatrix} ,$$ \n", + "\n", + "and the targets would be: \n", + "\n", + "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", + "\n", + "Since each input image is a 2D matrix, we need to flatten the image\n", + "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", + "design/feature matrix. This means we lose all spatial information in the\n", + "image, such as locality and translational invariance. More complicated\n", + "architectures such as Convolutional Neural Networks can take advantage\n", + "of such information, and are most commonly applied when analyzing\n", + "images." ] }, { "cell_type": "code", "execution_count": 1, - "id": "9cd98d03", + "id": "473de340", "metadata": { "collapsed": false, "editable": true @@ -456,15 +1033,316 @@ "source": [ "%matplotlib inline\n", "\n", - "\"\"\"\n", - "Simple code that tests XOR, OR and AND gates with linear regression\n", - "\"\"\"\n", - "\n", "# import necessary packages\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn import datasets\n", "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# flatten the image\n", + "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", + "n_inputs = len(inputs)\n", + "inputs = inputs.reshape(n_inputs, -1)\n", + "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "6f46d3ac", + "metadata": { + "editable": true + }, + "source": [ + "## Train and test datasets\n", + "\n", + "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", + "\n", + "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", + "\n", + "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", + "no bias in the sampling. \n", + "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", + "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", + "collected from 12.00 to 24.00." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "d0d389a5", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "# one-liner from scikit-learn library\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)\n", + "\n", + "# equivalently in numpy\n", + "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", + " n_inputs = len(inputs)\n", + " inputs_shuffled = inputs.copy()\n", + " labels_shuffled = labels.copy()\n", + " \n", + " np.random.shuffle(inputs_shuffled)\n", + " np.random.shuffle(labels_shuffled)\n", + " \n", + " train_end = int(n_inputs*train_size)\n", + " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", + " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", + " \n", + " return X_train, X_test, Y_train, Y_test\n", + "\n", + "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", + "\n", + "print(\"Number of training images: \" + str(len(X_train)))\n", + "print(\"Number of test images: \" + str(len(X_test)))" + ] + }, + { + "cell_type": "markdown", + "id": "c8a371a8", + "metadata": { + "editable": true + }, + "source": [ + "## Define model and architecture\n", + "\n", + "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", + "\n", + "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", + "\n", + "$$ y = f(z) ,$$\n", + "\n", + "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", + "and $w_i$ is the weight to input $i$. \n", + "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", + "\n", + "The simplest activation function for a neuron is the *Heaviside* function:\n", + "\n", + "$$ f(z) = \n", + "\\begin{cases}\n", + "1, & z > 0\\\\\n", + "0, & \\text{otherwise}\n", + "\\end{cases}\n", + "$$\n", + "\n", + "A feed-forward neural network with this activation is known as a *perceptron*. \n", + "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", + "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", + "and we call these architectures *multiclass perceptrons*. \n", + "\n", + "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", + "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", + "\n", + "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", + "We will be using the sigmoid function $\\sigma(x)$: \n", + "\n", + "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", + "\n", + "which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions." + ] + }, + { + "cell_type": "markdown", + "id": "663e4a73", + "metadata": { + "editable": true + }, + "source": [ + "## Layers\n", + "\n", + "* Input \n", + "\n", + "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", + "\n", + "* Hidden layer\n", + "\n", + "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", + "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", + "\n", + "* Output\n", + "\n", + "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", + "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", + "\n", + "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", + "\n", + "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", + "\n", + "$$ P(\\text{class $j$} \\mid \\text{input $\\boldsymbol{a}$}) = \\frac{\\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_j)}}\n", + "{\\sum_{c=0}^{9} \\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_c)}} ,$$ \n", + "\n", + "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\boldsymbol{a}$, with $\\boldsymbol{w}_j$ the weights of neuron $j$ to the inputs. \n", + "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", + "The exponent is just the weighted sum of inputs as before: \n", + "\n", + "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", + "\n", + "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", + "weights to the output layer." + ] + }, + { + "cell_type": "markdown", + "id": "4bedd90d", + "metadata": { + "editable": true + }, + "source": [ + "## Weights and biases\n", + "\n", + "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", + "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", + "\n", + "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", + "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", + "\n", + "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", + "\n", + "The bias weights $\\boldsymbol{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "f418033e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# building our neural network\n", + "\n", + "n_inputs, n_features = X_train.shape\n", + "n_hidden_neurons = 50\n", + "n_categories = 10\n", + "\n", + "# we make the weights normally distributed using numpy.random.randn\n", + "\n", + "# weights and bias in the hidden layer\n", + "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", + "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", + "\n", + "# weights and bias in the output layer\n", + "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", + "output_bias = np.zeros(n_categories) + 0.01" + ] + }, + { + "cell_type": "markdown", + "id": "81d84610", + "metadata": { + "editable": true + }, + "source": [ + "## Feed-forward pass\n", + "\n", + "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", + "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", + "\n", + "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", + "\n", + "this is then passed through our activation function \n", + "\n", + "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", + "\n", + "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", + "\n", + "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", + "\n", + "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", + "\n", + "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", + "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$" + ] + }, + { + "cell_type": "markdown", + "id": "ef944c56", + "metadata": { + "editable": true + }, + "source": [ + "## Matrix multiplications\n", + "\n", + "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", + "layer have the dimensions \n", + "$W_{hidden} = (n_{features}, n_{hidden})$,\n", + "we can easily feed the network all our training data in one go by taking the matrix product \n", + "\n", + "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", + "\n", + "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", + "for each input image and each hidden neuron. \n", + "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", + "\n", + "$$ \\boldsymbol{z}^{l} = \\boldsymbol{X} \\boldsymbol{W}^{l} + \\boldsymbol{b}^{l} ,$$\n", + "\n", + "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", + "This is then passed through the activation: \n", + "\n", + "$$ \\boldsymbol{a}^{l} = f(\\boldsymbol{z}^l) .$$ \n", + "\n", + "This is fed to the output layer: \n", + "\n", + "$$ \\boldsymbol{z}^{L} = \\boldsymbol{a}^{L} \\boldsymbol{W}^{L} + \\boldsymbol{b}^{L} .$$\n", + "\n", + "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", + "\n", + "$$ output = softmax (\\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "d2eb1ac3", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# setup the feed-forward pass, subscript h = hidden layer\n", + "\n", "def sigmoid(x):\n", " return 1/(1 + np.exp(-x))\n", "\n", @@ -478,120 +1356,533 @@ " z_o = np.matmul(a_h, output_weights) + output_bias\n", " # softmax output\n", " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " probabilities = sigmoid(z_o)\n", + " exp_term = np.exp(z_o)\n", + " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + " \n", " return probabilities\n", "\n", + "probabilities = feed_forward(X_train)\n", + "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", + "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", + "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", + "print()\n", "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", + "# we obtain a prediction by taking the class with the highest likelihood\n", + "def predict(X):\n", + " probabilities = feed_forward(X)\n", + " return np.argmax(probabilities, axis=1)\n", "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_inputs, n_features = X.shape\n", - "n_hidden_neurons = 2\n", - "n_categories = 1\n", - "n_features = 2\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01\n", - "\n", - "probabilities = feed_forward(X)\n", - "print(probabilities)" + "predictions = predict(X_train)\n", + "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", + "print(\"prediction for image 0: \" + str(predictions[0]))\n", + "print(\"correct label for image 0: \" + str(Y_train[0]))" ] }, { "cell_type": "markdown", - "id": "f4c842f0", + "id": "886dd59d", "metadata": { "editable": true }, "source": [ - "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." + "## Choose cost function and optimizer\n", + "\n", + "To measure how well our neural network is doing we need to introduce a cost function. \n", + "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", + "that gives the total error of our network across all samples the *cost* function.\n", + "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", + "\n", + "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", + "\n", + "$$ y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", + "\n", + "$$ y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", + "\n", + "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", + "\n", + "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", + "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\boldsymbol{x}_i$ in the dataset.\n", + "\n", + "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", + "probability of the correct category $c'$ \n", + "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", + "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\boldsymbol{\\theta}$ represents the parameters of our network, i.e. all the weights and biases." ] }, { "cell_type": "markdown", - "id": "39682bf4", + "id": "461e93c0", "metadata": { "editable": true }, "source": [ - "## The Code using Scikit-Learn" + "## Optimizing the cost function\n", + "\n", + "The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent\n", + "is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. \n", + "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", + "\n", + "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", + "\n", + "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", + "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", + "\n", + "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", + "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", + "on a subset of the data called a *minibatch*. \n", + "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", + "is $N/M$. \n", + "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", + "\n", + "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", + "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", + "\n", + "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", + "\n", + "This has two important benefits: \n", + "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", + "\n", + "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", + "\n", + "The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html)." + ] + }, + { + "cell_type": "markdown", + "id": "8015d4d5", + "metadata": { + "editable": true + }, + "source": [ + "## Regularization\n", + "\n", + "It is common to add an extra term to the cost function, proportional\n", + "to the size of the weights. This is equivalent to constraining the\n", + "size of the weights, so that they do not grow out of control.\n", + "Constraining the size of the weights means that the weights cannot\n", + "grow arbitrarily large to fit the training data, and in this way\n", + "reduces *overfitting*.\n", + "\n", + "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", + "\n", + "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", + "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\boldsymbol{w} \\rvert \\rvert_2^2 \n", + "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", + "\n", + "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", + "\n", + "In order to train the model, we need to calculate the derivative of\n", + "the cost function with respect to every bias and weight in the\n", + "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", + "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", + "layer ($+1$ for the bias), and the gradient must be calculated for\n", + "every parameter. We use the *backpropagation* algorithm discussed\n", + "above. This is a clever use of the chain rule that allows us to\n", + "calculate the gradient efficently." + ] + }, + { + "cell_type": "markdown", + "id": "63a32672", + "metadata": { + "editable": true + }, + "source": [ + "## Matrix multiplication\n", + "\n", + "To more efficently train our network these equations are implemented using matrix operations. \n", + "The error in the output layer is calculated simply as, with $\\boldsymbol{t}$ being our targets, \n", + "\n", + "$$ \\delta_L = \\boldsymbol{t} - \\boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ \n", + "\n", + "The gradient for the output weights is calculated as \n", + "\n", + "$$ \\nabla W_{L} = \\boldsymbol{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", + "\n", + "where $\\boldsymbol{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", + "Since we are going backwards we have to transpose the activation matrix. \n", + "\n", + "The gradient with respect to the output bias is then \n", + "\n", + "$$ \\nabla \\boldsymbol{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", + "\n", + "The error in the hidden layer is \n", + "\n", + "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", + "\n", + "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", + "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", + "the *Hadamard product*, meaning element-wise multiplication. \n", + "\n", + "This again gives us the gradients in the hidden layer: \n", + "\n", + "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", + "\n", + "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" ] }, { "cell_type": "code", - "execution_count": 2, - "id": "a3a25dd1", + "execution_count": 5, + "id": "bc6752c7", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.neural_network import MLPClassifier\n", + "# to categorical turns our integer vector into a onehot representation\n", "from sklearn.metrics import accuracy_score\n", - "import seaborn as sns\n", "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", + "# one-hot in numpy\n", + "def to_categorical_numpy(integer_vector):\n", + " n_inputs = len(integer_vector)\n", + " n_categories = np.max(integer_vector) + 1\n", + " onehot_vector = np.zeros((n_inputs, n_categories))\n", + " onehot_vector[range(n_inputs), integer_vector] = 1\n", + " \n", + " return onehot_vector\n", "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", + "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", + "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", + "def feed_forward_train(X):\n", + " # weighted sum of inputs to the hidden layer\n", + " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", + " # activation in the hidden layer\n", + " a_h = sigmoid(z_h)\n", + " \n", + " # weighted sum of inputs to the output layer\n", + " z_o = np.matmul(a_h, output_weights) + output_bias\n", + " # softmax output\n", + " # axis 0 holds each input and axis 1 the probabilities of each category\n", + " exp_term = np.exp(z_o)\n", + " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + " \n", + " # for backpropagation need activations in hidden and output layers\n", + " return a_h, probabilities\n", "\n", - "# Defining the neural network\n", - "n_hidden_neurons = 2\n", + "def backpropagation(X, Y):\n", + " a_h, probabilities = feed_forward_train(X)\n", + " \n", + " # error in the output layer\n", + " error_output = probabilities - Y\n", + " # error in the hidden layer\n", + " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", + " \n", + " # gradients for the output layer\n", + " output_weights_gradient = np.matmul(a_h.T, error_output)\n", + " output_bias_gradient = np.sum(error_output, axis=0)\n", + " \n", + " # gradient for the hidden layer\n", + " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", + " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", "\n", + " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", + "\n", + "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", + "\n", + "eta = 0.01\n", + "lmbd = 0.01\n", + "for i in range(1000):\n", + " # calculate gradients\n", + " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", + " \n", + " # regularization term gradients\n", + " dWo += lmbd * output_weights\n", + " dWh += lmbd * hidden_weights\n", + " \n", + " # update weights and biases\n", + " output_weights -= eta * dWo\n", + " output_bias -= eta * dBo\n", + " hidden_weights -= eta * dWh\n", + " hidden_bias -= eta * dBh\n", + "\n", + "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" + ] + }, + { + "cell_type": "markdown", + "id": "e16e5307", + "metadata": { + "editable": true + }, + "source": [ + "## Improving performance\n", + "\n", + "As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. \n", + "In order to obtain a network that does something useful, we will have to do a bit more work. \n", + "\n", + "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", + "\n", + "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", + "going through the entire dataset ($n/M$ batches) an *epoch*.\n", + "\n", + "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", + "Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/)." + ] + }, + { + "cell_type": "markdown", + "id": "cbbcb7a6", + "metadata": { + "editable": true + }, + "source": [ + "## Full object-oriented implementation\n", + "\n", + "It is very natural to think of the network as an object, with specific instances of the network\n", + "being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "8e880c46", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "class NeuralNetwork:\n", + " def __init__(\n", + " self,\n", + " X_data,\n", + " Y_data,\n", + " n_hidden_neurons=50,\n", + " n_categories=10,\n", + " epochs=10,\n", + " batch_size=100,\n", + " eta=0.1,\n", + " lmbd=0.0):\n", + "\n", + " self.X_data_full = X_data\n", + " self.Y_data_full = Y_data\n", + "\n", + " self.n_inputs = X_data.shape[0]\n", + " self.n_features = X_data.shape[1]\n", + " self.n_hidden_neurons = n_hidden_neurons\n", + " self.n_categories = n_categories\n", + "\n", + " self.epochs = epochs\n", + " self.batch_size = batch_size\n", + " self.iterations = self.n_inputs // self.batch_size\n", + " self.eta = eta\n", + " self.lmbd = lmbd\n", + "\n", + " self.create_biases_and_weights()\n", + "\n", + " def create_biases_and_weights(self):\n", + " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", + " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", + "\n", + " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", + " self.output_bias = np.zeros(self.n_categories) + 0.01\n", + "\n", + " def feed_forward(self):\n", + " # feed-forward for training\n", + " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", + " self.a_h = sigmoid(self.z_h)\n", + "\n", + " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", + "\n", + " exp_term = np.exp(self.z_o)\n", + " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + "\n", + " def feed_forward_out(self, X):\n", + " # feed-forward for output\n", + " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", + " a_h = sigmoid(z_h)\n", + "\n", + " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", + " \n", + " exp_term = np.exp(z_o)\n", + " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + " return probabilities\n", + "\n", + " def backpropagation(self):\n", + " error_output = self.probabilities - self.Y_data\n", + " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", + "\n", + " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", + " self.output_bias_gradient = np.sum(error_output, axis=0)\n", + "\n", + " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", + " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", + "\n", + " if self.lmbd > 0.0:\n", + " self.output_weights_gradient += self.lmbd * self.output_weights\n", + " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", + "\n", + " self.output_weights -= self.eta * self.output_weights_gradient\n", + " self.output_bias -= self.eta * self.output_bias_gradient\n", + " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", + " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", + "\n", + " def predict(self, X):\n", + " probabilities = self.feed_forward_out(X)\n", + " return np.argmax(probabilities, axis=1)\n", + "\n", + " def predict_probabilities(self, X):\n", + " probabilities = self.feed_forward_out(X)\n", + " return probabilities\n", + "\n", + " def train(self):\n", + " data_indices = np.arange(self.n_inputs)\n", + "\n", + " for i in range(self.epochs):\n", + " for j in range(self.iterations):\n", + " # pick datapoints with replacement\n", + " chosen_datapoints = np.random.choice(\n", + " data_indices, size=self.batch_size, replace=False\n", + " )\n", + "\n", + " # minibatch training data\n", + " self.X_data = self.X_data_full[chosen_datapoints]\n", + " self.Y_data = self.Y_data_full[chosen_datapoints]\n", + "\n", + " self.feed_forward()\n", + " self.backpropagation()" + ] + }, + { + "cell_type": "markdown", + "id": "61eb71d7", + "metadata": { + "editable": true + }, + "source": [ + "## Evaluate model performance on test data\n", + "\n", + "To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. \n", + "We measure the performance of the network using the *accuracy* score. \n", + "The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. \n", + "\n", + "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\tilde{y}_i = y_i)}{n} ,$$ \n", + "\n", + "where $I$ is the indicator function, $1$ if $\\tilde{y}_i = y_i$ and $0$ otherwise." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "e6fa8fd8", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "epochs = 100\n", + "batch_size = 100\n", + "\n", + "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", + " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", + "dnn.train()\n", + "test_predict = dnn.predict(X_test)\n", + "\n", + "# accuracy score from scikit library\n", + "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", + "\n", + "# equivalent in numpy\n", + "def accuracy_score_numpy(Y_test, Y_pred):\n", + " return np.sum(Y_test == Y_pred) / len(Y_test)\n", + "\n", + "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" + ] + }, + { + "cell_type": "markdown", + "id": "57bc26b6", + "metadata": { + "editable": true + }, + "source": [ + "## Adjust hyperparameters\n", + "\n", + "We now perform a grid search to find the optimal hyperparameters for the network. \n", + "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "fcefc266", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ "eta_vals = np.logspace(-5, 1, 7)\n", "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "epochs = 100\n", + "# store the models for later use\n", + "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", "\n", + "# grid search\n", "for i, eta in enumerate(eta_vals):\n", " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X, yXOR)\n", - " DNN_scikit[i][j] = dnn\n", + " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", + " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", + " dnn.train()\n", + " \n", + " DNN_numpy[i][j] = dnn\n", + " \n", + " test_predict = dnn.predict(X_test)\n", + " \n", " print(\"Learning rate = \", eta)\n", " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on data set: \", dnn.score(X, yXOR))\n", - " print()\n", + " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "id": "86f335eb", + "metadata": { + "editable": true + }, + "source": [ + "## Visualization" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "12a21061", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# visual representation of grid search\n", + "# uses seaborn heatmap, you can also do this with matplotlib imshow\n", + "import seaborn as sns\n", "\n", "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", "for i in range(len(eta_vals)):\n", " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " test_pred = dnn.predict(X)\n", - " test_accuracy[i][j] = accuracy_score(yXOR, test_pred)\n", + " dnn = DNN_numpy[i][j]\n", + " \n", + " train_pred = dnn.predict(X_train) \n", + " test_pred = dnn.predict(X_test)\n", + "\n", + " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", + " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", "\n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", @@ -603,7 +1894,650 @@ }, { "cell_type": "markdown", - "id": "33661306", + "id": "9f85ce06", + "metadata": { + "editable": true + }, + "source": [ + "## scikit-learn implementation\n", + "\n", + "**scikit-learn** focuses more\n", + "on traditional machine learning methods, such as regression,\n", + "clustering, decision trees, etc. As such, it has only two types of\n", + "neural networks: Multi Layer Perceptron outputting continuous values,\n", + "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", + "*MLPClassifier*. We will see how simple it is to use these classes.\n", + "\n", + "**scikit-learn** implements a few improvements from our neural network,\n", + "such as early stopping, a varying learning rate, different\n", + "optimization methods, etc. We would therefore expect a better\n", + "performance overall." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "dcb3ff4c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from sklearn.neural_network import MLPClassifier\n", + "# store models for later use\n", + "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + "\n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", + " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", + " dnn.fit(X_train, Y_train)\n", + " \n", + " DNN_scikit[i][j] = dnn\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "id": "70c77ae8", + "metadata": { + "editable": true + }, + "source": [ + "## Visualization" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "49fa215e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# optional\n", + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " dnn = DNN_scikit[i][j]\n", + " \n", + " train_pred = dnn.predict(X_train) \n", + " test_pred = dnn.predict(X_test)\n", + "\n", + " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", + " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "539ccef2", + "metadata": { + "editable": true + }, + "source": [ + "## Building neural networks in Tensorflow and Keras\n", + "\n", + "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", + "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", + "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", + "\n", + "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", + "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", + "NumPy arrays." + ] + }, + { + "cell_type": "markdown", + "id": "504a5f1c", + "metadata": { + "editable": true + }, + "source": [ + "## Tensorflow\n", + "\n", + "Tensorflow is an open source library machine learning library\n", + "developed by the Google Brain team for internal use. It was released\n", + "under the Apache 2.0 open source license in November 9, 2015.\n", + "\n", + "Tensorflow is a computational framework that allows you to construct\n", + "machine learning models at different levels of abstraction, from\n", + "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", + "that Tensorflow is built upon. The higher levels of abstraction are\n", + "simpler to use, but less flexible, and our choice of implementation\n", + "should reflect the problems we are trying to solve.\n", + "\n", + "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", + "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", + "to represent your model, and then create a Tensorflow *session* to run the graph.\n", + "\n", + "In this guide we will analyze the same data as we did in our NumPy and\n", + "scikit-learn tutorial, gathered from the MNIST database of images. We\n", + "will give an introduction to the lower level Python Application\n", + "Program Interfaces (APIs), and see how we use them to build our graph.\n", + "Then we will build (effectively) the same graph in Keras, to see just\n", + "how simple solving a machine learning problem can be.\n", + "\n", + "To install tensorflow on Unix/Linux systems, use pip as" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "43434a0f", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "pip3 install tensorflow" + ] + }, + { + "cell_type": "markdown", + "id": "cc322a8c", + "metadata": { + "editable": true + }, + "source": [ + "and/or if you use **anaconda**, just write (or install from the graphical user interface)\n", + "(current release of CPU-only TensorFlow)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "ecd2c04e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "conda create -n tf tensorflow\n", + "conda activate tf" + ] + }, + { + "cell_type": "markdown", + "id": "3d05652f", + "metadata": { + "editable": true + }, + "source": [ + "To install the current release of GPU TensorFlow" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "0e7846a2", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "conda create -n tf-gpu tensorflow-gpu\n", + "conda activate tf-gpu" + ] + }, + { + "cell_type": "markdown", + "id": "010f9361", + "metadata": { + "editable": true + }, + "source": [ + "## Using Keras\n", + "\n", + "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", + "that supports Tensorflow, CTNK and Theano as backends. \n", + "If you have Anaconda installed you may run the following command" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "c2138497", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "conda install keras" + ] + }, + { + "cell_type": "markdown", + "id": "51f1c99f", + "metadata": { + "editable": true + }, + "source": [ + "You can look up the [instructions here](https://keras.io/) for more information.\n", + "\n", + "We will to a large extent use **keras** in this course." + ] + }, + { + "cell_type": "markdown", + "id": "636aba55", + "metadata": { + "editable": true + }, + "source": [ + "## Collect and pre-process data\n", + "\n", + "Let us look again at the MINST data set." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "2754faba", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import tensorflow as tf\n", + "from sklearn import datasets\n", + "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# flatten the image\n", + "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", + "n_inputs = len(inputs)\n", + "inputs = inputs.reshape(n_inputs, -1)\n", + "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "f5ab4f71", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from tensorflow.keras.layers import Input\n", + "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", + "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", + "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", + "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", + "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# one-hot representation of labels\n", + "labels = to_categorical(labels)\n", + "\n", + "# split into train and test data\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "89575223", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "\n", + "epochs = 100\n", + "batch_size = 100\n", + "n_neurons_layer1 = 100\n", + "n_neurons_layer2 = 50\n", + "n_categories = 10\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)\n", + "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", + " model = Sequential()\n", + " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(Dense(n_categories, activation='softmax'))\n", + " \n", + " sgd = optimizers.SGD(lr=eta)\n", + " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", + " \n", + " return model" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "154c52c6", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", + " eta=eta, lmbd=lmbd)\n", + " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", + " scores = DNN.evaluate(X_test, Y_test)\n", + " \n", + " DNN_keras[i][j] = DNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % scores[1])\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "a998f24b", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# optional\n", + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " DNN = DNN_keras[i][j]\n", + "\n", + " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", + " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "d1cb30bd", + "metadata": { + "editable": true + }, + "source": [ + "## The Breast Cancer Data, now with Keras" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "018e25df", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "\n", + "import tensorflow as tf\n", + "from tensorflow.keras.layers import Input\n", + "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", + "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", + "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", + "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", + "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split as splitter\n", + "from sklearn.datasets import load_breast_cancer\n", + "import pickle\n", + "import os \n", + "\n", + "\n", + "\"\"\"Load breast cancer dataset\"\"\"\n", + "\n", + "np.random.seed(0) #create same seed for random number every time\n", + "\n", + "cancer=load_breast_cancer() #Download breast cancer dataset\n", + "\n", + "inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters)\n", + "outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant)\n", + "labels=cancer.feature_names[0:30]\n", + "\n", + "print('The content of the breast cancer dataset is:') #Print information about the datasets\n", + "print(labels)\n", + "print('-------------------------')\n", + "print(\"inputs = \" + str(inputs.shape))\n", + "print(\"outputs = \" + str(outputs.shape))\n", + "print(\"labels = \"+ str(labels.shape))\n", + "\n", + "x=inputs #Reassign the Feature and Label matrices to other variables\n", + "y=outputs\n", + "\n", + "#%% \n", + "\n", + "# Visualisation of dataset (for correlation analysis)\n", + "\n", + "plt.figure()\n", + "plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)\n", + "plt.xlabel('Mean radius',fontweight='bold')\n", + "plt.ylabel('Mean perimeter',fontweight='bold')\n", + "plt.show()\n", + "\n", + "plt.figure()\n", + "plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)\n", + "plt.xlabel('Mean compactness',fontweight='bold')\n", + "plt.ylabel('Mean concavity',fontweight='bold')\n", + "plt.show()\n", + "\n", + "\n", + "plt.figure()\n", + "plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", + "plt.xlabel('Mean radius',fontweight='bold')\n", + "plt.ylabel('Mean texture',fontweight='bold')\n", + "plt.show()\n", + "\n", + "plt.figure()\n", + "plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", + "plt.xlabel('Mean perimeter',fontweight='bold')\n", + "plt.ylabel('Mean compactness',fontweight='bold')\n", + "plt.show()\n", + "\n", + "\n", + "# Generate training and testing datasets\n", + "\n", + "#Select features relevant to classification (texture,perimeter,compactness and symmetery) \n", + "#and add to input matrix\n", + "\n", + "temp1=np.reshape(x[:,1],(len(x[:,1]),1))\n", + "temp2=np.reshape(x[:,2],(len(x[:,2]),1))\n", + "X=np.hstack((temp1,temp2)) \n", + "temp=np.reshape(x[:,5],(len(x[:,5]),1))\n", + "X=np.hstack((X,temp)) \n", + "temp=np.reshape(x[:,8],(len(x[:,8]),1))\n", + "X=np.hstack((X,temp)) \n", + "\n", + "X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing\n", + "\n", + "y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy\n", + "y_test=to_categorical(y_test)\n", + "\n", + "del temp1,temp2,temp\n", + "\n", + "# %%\n", + "\n", + "# Define tunable parameters\"\n", + "\n", + "eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser)\n", + "lamda=0.01 #Define hyperparameter\n", + "n_layers=2 #Define number of hidden layers in the model\n", + "n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer\n", + "epochs=100 #Number of reiterations over the input data\n", + "batch_size=100 #Number of samples per gradient update\n", + "\n", + "# %%\n", + "\n", + "\"\"\"Define function to return Deep Neural Network model\"\"\"\n", + "\n", + "def NN_model(inputsize,n_layers,n_neuron,eta,lamda):\n", + " model=Sequential() \n", + " for i in range(n_layers): #Run loop to add hidden layers to the model\n", + " if (i==0): #First layer requires input dimensions\n", + " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))\n", + " else: #Subsequent layers are capable of automatic shape inferencing\n", + " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))\n", + " model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob)\n", + " sgd=optimizers.SGD(lr=eta)\n", + " model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])\n", + " return model\n", + "\n", + " \n", + "Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function\n", + "Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for \n", + "\n", + "for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate \n", + " for j in range(len(eta)): #accuracy scores \n", + " DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)\n", + " DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)\n", + " Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]\n", + " Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]\n", + " \n", + "\n", + "def plot_data(x,y,data,title=None):\n", + "\n", + " # plot results\n", + " fontsize=16\n", + "\n", + "\n", + " fig = plt.figure()\n", + " ax = fig.add_subplot(111)\n", + " cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)\n", + " \n", + " cbar=fig.colorbar(cax)\n", + " cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)\n", + " cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])\n", + " cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])\n", + "\n", + " # put text on matrix elements\n", + " for i, x_val in enumerate(np.arange(len(x))):\n", + " for j, y_val in enumerate(np.arange(len(y))):\n", + " c = \"${0:.1f}\\\\%$\".format( 100*data[j,i]) \n", + " ax.text(x_val, y_val, c, va='center', ha='center')\n", + "\n", + " # convert axis vaues to to string labels\n", + " x=[str(i) for i in x]\n", + " y=[str(i) for i in y]\n", + "\n", + "\n", + " ax.set_xticklabels(['']+x)\n", + " ax.set_yticklabels(['']+y)\n", + "\n", + " ax.set_xlabel('$\\\\mathrm{learning\\\\ rate}$',fontsize=fontsize)\n", + " ax.set_ylabel('$\\\\mathrm{hidden\\\\ neurons}$',fontsize=fontsize)\n", + " if title is not None:\n", + " ax.set_title(title)\n", + "\n", + " plt.tight_layout()\n", + "\n", + " plt.show()\n", + " \n", + "plot_data(eta,n_neuron,Train_accuracy, 'training')\n", + "plot_data(eta,n_neuron,Test_accuracy, 'testing')" + ] + }, + { + "cell_type": "markdown", + "id": "adb9044f", "metadata": { "editable": true }, @@ -622,7 +2556,7 @@ }, { "cell_type": "markdown", - "id": "bb3d0344", + "id": "c80e2ebf", "metadata": { "editable": true }, @@ -643,8 +2577,8 @@ }, { "cell_type": "code", - "execution_count": 3, - "id": "83719647", + "execution_count": 22, + "id": "e0b55b1d", "metadata": { "collapsed": false, "editable": true @@ -785,7 +2719,7 @@ }, { "cell_type": "markdown", - "id": "27e53de2", + "id": "400de2c8", "metadata": { "editable": true }, @@ -800,8 +2734,8 @@ }, { "cell_type": "code", - "execution_count": 4, - "id": "2be46284", + "execution_count": 23, + "id": "7c3400ff", "metadata": { "collapsed": false, "editable": true @@ -814,7 +2748,7 @@ }, { "cell_type": "markdown", - "id": "70287339", + "id": "afe64cc6", "metadata": { "editable": true }, @@ -825,8 +2759,8 @@ }, { "cell_type": "code", - "execution_count": 5, - "id": "f5b9855b", + "execution_count": 24, + "id": "f73b321f", "metadata": { "collapsed": false, "editable": true @@ -848,7 +2782,7 @@ }, { "cell_type": "markdown", - "id": "84262cf8", + "id": "e0b9195d", "metadata": { "editable": true }, @@ -863,8 +2797,8 @@ }, { "cell_type": "code", - "execution_count": 6, - "id": "f93c1530", + "execution_count": 25, + "id": "4cc0e5c8", "metadata": { "collapsed": false, "editable": true @@ -902,7 +2836,7 @@ }, { "cell_type": "markdown", - "id": "47a93158", + "id": "1e406865", "metadata": { "editable": true }, @@ -914,8 +2848,8 @@ }, { "cell_type": "code", - "execution_count": 7, - "id": "00167a87", + "execution_count": 26, + "id": "7d0109d6", "metadata": { "collapsed": false, "editable": true @@ -936,7 +2870,7 @@ }, { "cell_type": "markdown", - "id": "44f4c8c6", + "id": "63dd2673", "metadata": { "editable": true }, @@ -951,8 +2885,8 @@ }, { "cell_type": "code", - "execution_count": 8, - "id": "53e7cd4d", + "execution_count": 27, + "id": "83238bc7", "metadata": { "collapsed": false, "editable": true @@ -1010,7 +2944,7 @@ }, { "cell_type": "markdown", - "id": "0d1a2531", + "id": "78debb89", "metadata": { "editable": true }, @@ -1024,8 +2958,8 @@ }, { "cell_type": "code", - "execution_count": 9, - "id": "62c49d9e", + "execution_count": 28, + "id": "b865d16e", "metadata": { "collapsed": false, "editable": true @@ -1046,7 +2980,7 @@ }, { "cell_type": "markdown", - "id": "2927902c", + "id": "77f3e01a", "metadata": { "editable": true }, @@ -1069,8 +3003,8 @@ }, { "cell_type": "code", - "execution_count": 10, - "id": "5cca0331", + "execution_count": 29, + "id": "cc9530cf", "metadata": { "collapsed": false, "editable": true @@ -1542,7 +3476,7 @@ }, { "cell_type": "markdown", - "id": "6cc33611", + "id": "aea1989a", "metadata": { "editable": true }, @@ -1553,8 +3487,8 @@ }, { "cell_type": "code", - "execution_count": 11, - "id": "2aee475e", + "execution_count": 30, + "id": "905451de", "metadata": { "collapsed": false, "editable": true @@ -1598,7 +3532,7 @@ }, { "cell_type": "markdown", - "id": "562f2256", + "id": "f62062b8", "metadata": { "editable": true }, @@ -1613,8 +3547,8 @@ }, { "cell_type": "code", - "execution_count": 12, - "id": "9a8267de", + "execution_count": 31, + "id": "5689d08c", "metadata": { "collapsed": false, "editable": true @@ -1629,7 +3563,7 @@ }, { "cell_type": "markdown", - "id": "2b41c8b2", + "id": "67f2c383", "metadata": { "editable": true }, @@ -1639,8 +3573,8 @@ }, { "cell_type": "code", - "execution_count": 13, - "id": "52b76521", + "execution_count": 32, + "id": "879e7827", "metadata": { "collapsed": false, "editable": true @@ -1655,7 +3589,7 @@ }, { "cell_type": "markdown", - "id": "c0abd312", + "id": "619370a1", "metadata": { "editable": true }, @@ -1670,8 +3604,8 @@ }, { "cell_type": "code", - "execution_count": 14, - "id": "97ea9cff", + "execution_count": 33, + "id": "368d91cf", "metadata": { "collapsed": false, "editable": true @@ -1685,7 +3619,7 @@ }, { "cell_type": "markdown", - "id": "8fe07636", + "id": "b2ce0c08", "metadata": { "editable": true }, @@ -1699,8 +3633,8 @@ }, { "cell_type": "code", - "execution_count": 15, - "id": "71b8bbd3", + "execution_count": 34, + "id": "054f27cb", "metadata": { "collapsed": false, "editable": true @@ -1725,8 +3659,8 @@ }, { "cell_type": "code", - "execution_count": 16, - "id": "6ad9b71f", + "execution_count": 35, + "id": "f6339334", "metadata": { "collapsed": false, "editable": true @@ -1741,7 +3675,7 @@ }, { "cell_type": "markdown", - "id": "58241a4b", + "id": "6672f088", "metadata": { "editable": true }, @@ -1751,8 +3685,8 @@ }, { "cell_type": "code", - "execution_count": 17, - "id": "6a835c3d", + "execution_count": 36, + "id": "1c35365a", "metadata": { "collapsed": false, "editable": true @@ -1767,7 +3701,7 @@ }, { "cell_type": "markdown", - "id": "c1cca2a9", + "id": "26c4a96f", "metadata": { "editable": true }, @@ -1777,8 +3711,8 @@ }, { "cell_type": "code", - "execution_count": 18, - "id": "62d47d59", + "execution_count": 37, + "id": "b1486101", "metadata": { "collapsed": false, "editable": true @@ -1797,8 +3731,8 @@ }, { "cell_type": "code", - "execution_count": 19, - "id": "08cb6bfa", + "execution_count": 38, + "id": "e2d14ad1", "metadata": { "collapsed": false, "editable": true @@ -1813,7 +3747,7 @@ }, { "cell_type": "markdown", - "id": "95d33042", + "id": "d11f02d1", "metadata": { "editable": true }, @@ -1827,8 +3761,8 @@ }, { "cell_type": "code", - "execution_count": 20, - "id": "653ada24", + "execution_count": 39, + "id": "bf916774", "metadata": { "collapsed": false, "editable": true @@ -1865,7 +3799,7 @@ }, { "cell_type": "markdown", - "id": "b5914a5b", + "id": "3ef90609", "metadata": { "editable": true }, @@ -1877,8 +3811,8 @@ }, { "cell_type": "code", - "execution_count": 21, - "id": "60d1799b", + "execution_count": 40, + "id": "dbd581c2", "metadata": { "collapsed": false, "editable": true @@ -1901,7 +3835,7 @@ }, { "cell_type": "markdown", - "id": "2738fda7", + "id": "72e62cf6", "metadata": { "editable": true }, @@ -1911,1985 +3845,7 @@ }, { "cell_type": "markdown", - "id": "7a5d9af2", - "metadata": { - "editable": true - }, - "source": [ - "## Lecture Thursday October 26" - ] - }, - { - "cell_type": "markdown", - "id": "80f0d869", - "metadata": { - "editable": true - }, - "source": [ - "## Developing a code for doing neural networks with back propagation\n", - "\n", - "We repeat some of the elements discussed last week. The first part of\n", - "the material for Thursday was contained in the slides for last\n", - "week as well. We will repeat some of the topics here before we move into\n", - "applications to differential equations and other examples.\n", - "\n", - "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", - "\n", - "1. Collect and pre-process data \n", - "\n", - "2. Define model and architecture \n", - "\n", - "3. Choose cost function and optimizer \n", - "\n", - "4. Train the model \n", - "\n", - "5. Evaluate model performance on test data \n", - "\n", - "6. Adjust hyperparameters (if necessary, network architecture)" - ] - }, - { - "cell_type": "markdown", - "id": "b658d988", - "metadata": { - "editable": true - }, - "source": [ - "## Collect and pre-process data\n", - "\n", - "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", - "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", - "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", - "of handwritten digits that is commonly used for training various image processing systems. \n", - "The MNIST dataset consists of 70 000 images of size $28\\times 28$ pixels, each labeled from 0 to 9. \n", - "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", - "\n", - "To feed data into a feed-forward neural network we need to represent\n", - "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n", - "row represents an *input*, in this case a handwritten digit, and\n", - "each column represents a *feature*, in this case a pixel. The\n", - "correct answers, also known as *labels* or *targets* are\n", - "represented as a 1D array of integers \n", - "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", - "\n", - "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", - "measurements of height (in m) \n", - "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n", - "\n", - "$$ X = \\begin{bmatrix}\n", - "1.85 & 81\\\\\n", - "1.71 & 65\\\\\n", - "1.95 & 103\\\\\n", - "1.55 & 42\\\\\n", - "1.63 & 56\n", - "\\end{bmatrix} ,$$ \n", - "\n", - "and the targets would be: \n", - "\n", - "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", - "\n", - "Since each input image is a 2D matrix, we need to flatten the image\n", - "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", - "design/feature matrix. This means we lose all spatial information in the\n", - "image, such as locality and translational invariance. More complicated\n", - "architectures such as Convolutional Neural Networks can take advantage\n", - "of such information, and are most commonly applied when analyzing\n", - "images." - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "9d4fc2a6", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "3d26c1d6", - "metadata": { - "editable": true - }, - "source": [ - "## Train and test datasets\n", - "\n", - "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", - "\n", - "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", - "\n", - "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", - "no bias in the sampling. \n", - "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", - "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", - "collected from 12.00 to 24.00." - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "3fd56b5d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-liner from scikit-learn library\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)\n", - "\n", - "# equivalently in numpy\n", - "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", - " n_inputs = len(inputs)\n", - " inputs_shuffled = inputs.copy()\n", - " labels_shuffled = labels.copy()\n", - " \n", - " np.random.shuffle(inputs_shuffled)\n", - " np.random.shuffle(labels_shuffled)\n", - " \n", - " train_end = int(n_inputs*train_size)\n", - " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", - " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", - " \n", - " return X_train, X_test, Y_train, Y_test\n", - "\n", - "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", - "\n", - "print(\"Number of training images: \" + str(len(X_train)))\n", - "print(\"Number of test images: \" + str(len(X_test)))" - ] - }, - { - "cell_type": "markdown", - "id": "32b14d6e", - "metadata": { - "editable": true - }, - "source": [ - "## Define model and architecture\n", - "\n", - "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", - "\n", - "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", - "\n", - "$$ y = f(z) ,$$\n", - "\n", - "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", - "and $w_i$ is the weight to input $i$. \n", - "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", - "\n", - "The simplest activation function for a neuron is the *Heaviside* function:\n", - "\n", - "$$ f(z) = \n", - "\\begin{cases}\n", - "1, & z > 0\\\\\n", - "0, & \\text{otherwise}\n", - "\\end{cases}\n", - "$$\n", - "\n", - "A feed-forward neural network with this activation is known as a *perceptron*. \n", - "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", - "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", - "and we call these architectures *multiclass perceptrons*. \n", - "\n", - "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", - "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", - "\n", - "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", - "We will be using the sigmoid function $\\sigma(x)$: \n", - "\n", - "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", - "\n", - "which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "6fb7e611", - "metadata": { - "editable": true - }, - "source": [ - "## Layers\n", - "\n", - "* Input \n", - "\n", - "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", - "\n", - "* Hidden layer\n", - "\n", - "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", - "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", - "\n", - "* Output\n", - "\n", - "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", - "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", - "\n", - "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", - "\n", - "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", - "\n", - "$$ P(\\text{class $j$} \\mid \\text{input $\\boldsymbol{a}$}) = \\frac{\\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_j)}}\n", - "{\\sum_{c=0}^{9} \\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_c)}} ,$$ \n", - "\n", - "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\boldsymbol{a}$, with $\\boldsymbol{w}_j$ the weights of neuron $j$ to the inputs. \n", - "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", - "The exponent is just the weighted sum of inputs as before: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", - "\n", - "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", - "weights to the output layer." - ] - }, - { - "cell_type": "markdown", - "id": "a583f502", - "metadata": { - "editable": true - }, - "source": [ - "## Weights and biases\n", - "\n", - "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", - "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", - "\n", - "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", - "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", - "\n", - "The bias weights $\\boldsymbol{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "1fbcf528", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# building our neural network\n", - "\n", - "n_inputs, n_features = X_train.shape\n", - "n_hidden_neurons = 50\n", - "n_categories = 10\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01" - ] - }, - { - "cell_type": "markdown", - "id": "647e5396", - "metadata": { - "editable": true - }, - "source": [ - "## Feed-forward pass\n", - "\n", - "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", - "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", - "\n", - "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", - "\n", - "this is then passed through our activation function \n", - "\n", - "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", - "\n", - "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", - "\n", - "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", - "\n", - "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", - "\n", - "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", - "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$" - ] - }, - { - "cell_type": "markdown", - "id": "4adf55de", - "metadata": { - "editable": true - }, - "source": [ - "## Matrix multiplications\n", - "\n", - "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", - "layer have the dimensions \n", - "$W_{hidden} = (n_{features}, n_{hidden})$,\n", - "we can easily feed the network all our training data in one go by taking the matrix product \n", - "\n", - "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", - "\n", - "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", - "for each input image and each hidden neuron. \n", - "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", - "\n", - "$$ \\boldsymbol{z}^{l} = \\boldsymbol{X} \\boldsymbol{W}^{l} + \\boldsymbol{b}^{l} ,$$\n", - "\n", - "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", - "This is then passed through the activation: \n", - "\n", - "$$ \\boldsymbol{a}^{l} = f(\\boldsymbol{z}^l) .$$ \n", - "\n", - "This is fed to the output layer: \n", - "\n", - "$$ \\boldsymbol{z}^{L} = \\boldsymbol{a}^{L} \\boldsymbol{W}^{L} + \\boldsymbol{b}^{L} .$$\n", - "\n", - "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", - "\n", - "$$ output = softmax (\\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "d9406923", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# setup the feed-forward pass, subscript h = hidden layer\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " return probabilities\n", - "\n", - "probabilities = feed_forward(X_train)\n", - "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", - "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", - "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", - "print()\n", - "\n", - "# we obtain a prediction by taking the class with the highest likelihood\n", - "def predict(X):\n", - " probabilities = feed_forward(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - "predictions = predict(X_train)\n", - "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", - "print(\"prediction for image 0: \" + str(predictions[0]))\n", - "print(\"correct label for image 0: \" + str(Y_train[0]))" - ] - }, - { - "cell_type": "markdown", - "id": "0d1b0eef", - "metadata": { - "editable": true - }, - "source": [ - "## Choose cost function and optimizer\n", - "\n", - "To measure how well our neural network is doing we need to introduce a cost function. \n", - "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", - "that gives the total error of our network across all samples the *cost* function.\n", - "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$$ y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", - "\n", - "$$ y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", - "\n", - "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", - "\n", - "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", - "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\boldsymbol{x}_i$ in the dataset.\n", - "\n", - "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", - "probability of the correct category $c'$ \n", - "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", - "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\boldsymbol{\\theta}$ represents the parameters of our network, i.e. all the weights and biases." - ] - }, - { - "cell_type": "markdown", - "id": "57f59501", - "metadata": { - "editable": true - }, - "source": [ - "## Optimizing the cost function\n", - "\n", - "The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent\n", - "is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. \n", - "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", - "\n", - "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", - "\n", - "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", - "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", - "\n", - "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", - "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", - "on a subset of the data called a *minibatch*. \n", - "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", - "is $N/M$. \n", - "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", - "\n", - "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", - "\n", - "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", - "\n", - "This has two important benefits: \n", - "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", - "\n", - "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", - "\n", - "The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html)." - ] - }, - { - "cell_type": "markdown", - "id": "82a1bb7e", - "metadata": { - "editable": true - }, - "source": [ - "## Regularization\n", - "\n", - "It is common to add an extra term to the cost function, proportional\n", - "to the size of the weights. This is equivalent to constraining the\n", - "size of the weights, so that they do not grow out of control.\n", - "Constraining the size of the weights means that the weights cannot\n", - "grow arbitrarily large to fit the training data, and in this way\n", - "reduces *overfitting*.\n", - "\n", - "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", - "\n", - "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\boldsymbol{w} \\rvert \\rvert_2^2 \n", - "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", - "\n", - "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", - "\n", - "In order to train the model, we need to calculate the derivative of\n", - "the cost function with respect to every bias and weight in the\n", - "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", - "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", - "layer ($+1$ for the bias), and the gradient must be calculated for\n", - "every parameter. We use the *backpropagation* algorithm discussed\n", - "above. This is a clever use of the chain rule that allows us to\n", - "calculate the gradient efficently." - ] - }, - { - "cell_type": "markdown", - "id": "fd11bc91", - "metadata": { - "editable": true - }, - "source": [ - "## Matrix multiplication\n", - "\n", - "To more efficently train our network these equations are implemented using matrix operations. \n", - "The error in the output layer is calculated simply as, with $\\boldsymbol{t}$ being our targets, \n", - "\n", - "$$ \\delta_L = \\boldsymbol{t} - \\boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ \n", - "\n", - "The gradient for the output weights is calculated as \n", - "\n", - "$$ \\nabla W_{L} = \\boldsymbol{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", - "\n", - "where $\\boldsymbol{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", - "Since we are going backwards we have to transpose the activation matrix. \n", - "\n", - "The gradient with respect to the output bias is then \n", - "\n", - "$$ \\nabla \\boldsymbol{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", - "\n", - "The error in the hidden layer is \n", - "\n", - "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", - "\n", - "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", - "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", - "the *Hadamard product*, meaning element-wise multiplication. \n", - "\n", - "This again gives us the gradients in the hidden layer: \n", - "\n", - "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", - "\n", - "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "5b2abd34", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# to categorical turns our integer vector into a onehot representation\n", - "from sklearn.metrics import accuracy_score\n", - "\n", - "# one-hot in numpy\n", - "def to_categorical_numpy(integer_vector):\n", - " n_inputs = len(integer_vector)\n", - " n_categories = np.max(integer_vector) + 1\n", - " onehot_vector = np.zeros((n_inputs, n_categories))\n", - " onehot_vector[range(n_inputs), integer_vector] = 1\n", - " \n", - " return onehot_vector\n", - "\n", - "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", - "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", - "\n", - "def feed_forward_train(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " # for backpropagation need activations in hidden and output layers\n", - " return a_h, probabilities\n", - "\n", - "def backpropagation(X, Y):\n", - " a_h, probabilities = feed_forward_train(X)\n", - " \n", - " # error in the output layer\n", - " error_output = probabilities - Y\n", - " # error in the hidden layer\n", - " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", - " \n", - " # gradients for the output layer\n", - " output_weights_gradient = np.matmul(a_h.T, error_output)\n", - " output_bias_gradient = np.sum(error_output, axis=0)\n", - " \n", - " # gradient for the hidden layer\n", - " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", - " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", - "\n", - "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", - "\n", - "eta = 0.01\n", - "lmbd = 0.01\n", - "for i in range(1000):\n", - " # calculate gradients\n", - " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", - " \n", - " # regularization term gradients\n", - " dWo += lmbd * output_weights\n", - " dWh += lmbd * hidden_weights\n", - " \n", - " # update weights and biases\n", - " output_weights -= eta * dWo\n", - " output_bias -= eta * dBo\n", - " hidden_weights -= eta * dWh\n", - " hidden_bias -= eta * dBh\n", - "\n", - "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" - ] - }, - { - "cell_type": "markdown", - "id": "4828006c", - "metadata": { - "editable": true - }, - "source": [ - "## Improving performance\n", - "\n", - "As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. \n", - "In order to obtain a network that does something useful, we will have to do a bit more work. \n", - "\n", - "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", - "\n", - "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", - "going through the entire dataset ($n/M$ batches) an *epoch*.\n", - "\n", - "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", - "Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/)." - ] - }, - { - "cell_type": "markdown", - "id": "5e71254f", - "metadata": { - "editable": true - }, - "source": [ - "## Full object-oriented implementation\n", - "\n", - "It is very natural to think of the network as an object, with specific instances of the network\n", - "being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "4112a70d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "class NeuralNetwork:\n", - " def __init__(\n", - " self,\n", - " X_data,\n", - " Y_data,\n", - " n_hidden_neurons=50,\n", - " n_categories=10,\n", - " epochs=10,\n", - " batch_size=100,\n", - " eta=0.1,\n", - " lmbd=0.0):\n", - "\n", - " self.X_data_full = X_data\n", - " self.Y_data_full = Y_data\n", - "\n", - " self.n_inputs = X_data.shape[0]\n", - " self.n_features = X_data.shape[1]\n", - " self.n_hidden_neurons = n_hidden_neurons\n", - " self.n_categories = n_categories\n", - "\n", - " self.epochs = epochs\n", - " self.batch_size = batch_size\n", - " self.iterations = self.n_inputs // self.batch_size\n", - " self.eta = eta\n", - " self.lmbd = lmbd\n", - "\n", - " self.create_biases_and_weights()\n", - "\n", - " def create_biases_and_weights(self):\n", - " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", - " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", - "\n", - " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", - " self.output_bias = np.zeros(self.n_categories) + 0.01\n", - "\n", - " def feed_forward(self):\n", - " # feed-forward for training\n", - " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", - " self.a_h = sigmoid(self.z_h)\n", - "\n", - " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", - "\n", - " exp_term = np.exp(self.z_o)\n", - " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - "\n", - " def feed_forward_out(self, X):\n", - " # feed-forward for output\n", - " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", - " a_h = sigmoid(z_h)\n", - "\n", - " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", - " \n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " return probabilities\n", - "\n", - " def backpropagation(self):\n", - " error_output = self.probabilities - self.Y_data\n", - " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", - "\n", - " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", - " self.output_bias_gradient = np.sum(error_output, axis=0)\n", - "\n", - " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", - " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " if self.lmbd > 0.0:\n", - " self.output_weights_gradient += self.lmbd * self.output_weights\n", - " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", - "\n", - " self.output_weights -= self.eta * self.output_weights_gradient\n", - " self.output_bias -= self.eta * self.output_bias_gradient\n", - " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", - " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", - "\n", - " def predict(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - " def predict_probabilities(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return probabilities\n", - "\n", - " def train(self):\n", - " data_indices = np.arange(self.n_inputs)\n", - "\n", - " for i in range(self.epochs):\n", - " for j in range(self.iterations):\n", - " # pick datapoints with replacement\n", - " chosen_datapoints = np.random.choice(\n", - " data_indices, size=self.batch_size, replace=False\n", - " )\n", - "\n", - " # minibatch training data\n", - " self.X_data = self.X_data_full[chosen_datapoints]\n", - " self.Y_data = self.Y_data_full[chosen_datapoints]\n", - "\n", - " self.feed_forward()\n", - " self.backpropagation()" - ] - }, - { - "cell_type": "markdown", - "id": "7a5f2411", - "metadata": { - "editable": true - }, - "source": [ - "## Evaluate model performance on test data\n", - "\n", - "To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. \n", - "We measure the performance of the network using the *accuracy* score. \n", - "The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. \n", - "\n", - "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\tilde{y}_i = y_i)}{n} ,$$ \n", - "\n", - "where $I$ is the indicator function, $1$ if $\\tilde{y}_i = y_i$ and $0$ otherwise." - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "8d874757", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "epochs = 100\n", - "batch_size = 100\n", - "\n", - "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - "dnn.train()\n", - "test_predict = dnn.predict(X_test)\n", - "\n", - "# accuracy score from scikit library\n", - "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - "\n", - "# equivalent in numpy\n", - "def accuracy_score_numpy(Y_test, Y_pred):\n", - " return np.sum(Y_test == Y_pred) / len(Y_test)\n", - "\n", - "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" - ] - }, - { - "cell_type": "markdown", - "id": "2226763c", - "metadata": { - "editable": true - }, - "source": [ - "## Adjust hyperparameters\n", - "\n", - "We now perform a grid search to find the optimal hyperparameters for the network. \n", - "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "5b58b4e7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store the models for later use\n", - "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "# grid search\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - " dnn.train()\n", - " \n", - " DNN_numpy[i][j] = dnn\n", - " \n", - " test_predict = dnn.predict(X_test)\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "9912c227", - "metadata": { - "editable": true - }, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "f151a390", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# visual representation of grid search\n", - "# uses seaborn heatmap, you can also do this with matplotlib imshow\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_numpy[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "e712ce8b", - "metadata": { - "editable": true - }, - "source": [ - "## scikit-learn implementation\n", - "\n", - "**scikit-learn** focuses more\n", - "on traditional machine learning methods, such as regression,\n", - "clustering, decision trees, etc. As such, it has only two types of\n", - "neural networks: Multi Layer Perceptron outputting continuous values,\n", - "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", - "*MLPClassifier*. We will see how simple it is to use these classes.\n", - "\n", - "**scikit-learn** implements a few improvements from our neural network,\n", - "such as early stopping, a varying learning rate, different\n", - "optimization methods, etc. We would therefore expect a better\n", - "performance overall." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "f33cbab4", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.neural_network import MLPClassifier\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X_train, Y_train)\n", - " \n", - " DNN_scikit[i][j] = dnn\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "5ae8aee7", - "metadata": { - "editable": true - }, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "ca90408d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "1f5291fd", - "metadata": { - "editable": true - }, - "source": [ - "## Building neural networks in Tensorflow and Keras\n", - "\n", - "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", - "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", - "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", - "\n", - "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", - "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", - "NumPy arrays." - ] - }, - { - "cell_type": "markdown", - "id": "75724bf0", - "metadata": { - "editable": true - }, - "source": [ - "## Tensorflow\n", - "\n", - "Tensorflow is an open source library machine learning library\n", - "developed by the Google Brain team for internal use. It was released\n", - "under the Apache 2.0 open source license in November 9, 2015.\n", - "\n", - "Tensorflow is a computational framework that allows you to construct\n", - "machine learning models at different levels of abstraction, from\n", - "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", - "that Tensorflow is built upon. The higher levels of abstraction are\n", - "simpler to use, but less flexible, and our choice of implementation\n", - "should reflect the problems we are trying to solve.\n", - "\n", - "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", - "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", - "to represent your model, and then create a Tensorflow *session* to run the graph.\n", - "\n", - "In this guide we will analyze the same data as we did in our NumPy and\n", - "scikit-learn tutorial, gathered from the MNIST database of images. We\n", - "will give an introduction to the lower level Python Application\n", - "Program Interfaces (APIs), and see how we use them to build our graph.\n", - "Then we will build (effectively) the same graph in Keras, to see just\n", - "how simple solving a machine learning problem can be.\n", - "\n", - "To install tensorflow on Unix/Linux systems, use pip as" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "095e4f50", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "pip3 install tensorflow" - ] - }, - { - "cell_type": "markdown", - "id": "f7cee1d2", - "metadata": { - "editable": true - }, - "source": [ - "and/or if you use **anaconda**, just write (or install from the graphical user interface)\n", - "(current release of CPU-only TensorFlow)" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "0090f17b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "conda create -n tf tensorflow\n", - "conda activate tf" - ] - }, - { - "cell_type": "markdown", - "id": "801cbeaf", - "metadata": { - "editable": true - }, - "source": [ - "To install the current release of GPU TensorFlow" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "f3568a04", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "conda create -n tf-gpu tensorflow-gpu\n", - "conda activate tf-gpu" - ] - }, - { - "cell_type": "markdown", - "id": "8ccc7efb", - "metadata": { - "editable": true - }, - "source": [ - "## Using Keras\n", - "\n", - "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", - "that supports Tensorflow, CTNK and Theano as backends. \n", - "If you have Anaconda installed you may run the following command" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "4c10cf23", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "conda install keras" - ] - }, - { - "cell_type": "markdown", - "id": "3765a762", - "metadata": { - "editable": true - }, - "source": [ - "You can look up the [instructions here](https://keras.io/) for more information.\n", - "\n", - "We will to a large extent use **keras** in our examples.." - ] - }, - { - "cell_type": "markdown", - "id": "1b201030", - "metadata": { - "editable": true - }, - "source": [ - "## Collect and pre-process data\n", - "\n", - "Let us look again at the MINST data set." - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "df42be91", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import tensorflow as tf\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "15294871", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", - "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", - "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", - "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", - "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", - "\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-hot representation of labels\n", - "labels = to_categorical(labels)\n", - "\n", - "# split into train and test data\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "7857261b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "epochs = 100\n", - "batch_size = 100\n", - "n_neurons_layer1 = 100\n", - "n_neurons_layer2 = 50\n", - "n_categories = 10\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", - " model = Sequential()\n", - " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(Dense(n_categories, activation='softmax'))\n", - " \n", - " sgd = optimizers.SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", - " \n", - " return model" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "2b3e8444", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - " \n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", - " eta=eta, lmbd=lmbd)\n", - " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", - " scores = DNN.evaluate(X_test, Y_test)\n", - " \n", - " DNN_keras[i][j] = DNN\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Test accuracy: %.3f\" % scores[1])\n", - " print()" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "e11830ca", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " DNN = DNN_keras[i][j]\n", - "\n", - " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", - " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "5240b243", - "metadata": { - "editable": true - }, - "source": [ - "## The Breast Cancer Data, now with Keras" - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "id": "217f2429", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "import tensorflow as tf\n", - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", - "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", - "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", - "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", - "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import seaborn as sns\n", - "from sklearn.model_selection import train_test_split as splitter\n", - "from sklearn.datasets import load_breast_cancer\n", - "import pickle\n", - "import os \n", - "\n", - "\n", - "\"\"\"Load breast cancer dataset\"\"\"\n", - "\n", - "np.random.seed(0) #create same seed for random number every time\n", - "\n", - "cancer=load_breast_cancer() #Download breast cancer dataset\n", - "\n", - "inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters)\n", - "outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant)\n", - "labels=cancer.feature_names[0:30]\n", - "\n", - "print('The content of the breast cancer dataset is:') #Print information about the datasets\n", - "print(labels)\n", - "print('-------------------------')\n", - "print(\"inputs = \" + str(inputs.shape))\n", - "print(\"outputs = \" + str(outputs.shape))\n", - "print(\"labels = \"+ str(labels.shape))\n", - "\n", - "x=inputs #Reassign the Feature and Label matrices to other variables\n", - "y=outputs\n", - "\n", - "#%% \n", - "\n", - "# Visualisation of dataset (for correlation analysis)\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean perimeter',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean compactness',fontweight='bold')\n", - "plt.ylabel('Mean concavity',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean texture',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean perimeter',fontweight='bold')\n", - "plt.ylabel('Mean compactness',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "# Generate training and testing datasets\n", - "\n", - "#Select features relevant to classification (texture,perimeter,compactness and symmetery) \n", - "#and add to input matrix\n", - "\n", - "temp1=np.reshape(x[:,1],(len(x[:,1]),1))\n", - "temp2=np.reshape(x[:,2],(len(x[:,2]),1))\n", - "X=np.hstack((temp1,temp2)) \n", - "temp=np.reshape(x[:,5],(len(x[:,5]),1))\n", - "X=np.hstack((X,temp)) \n", - "temp=np.reshape(x[:,8],(len(x[:,8]),1))\n", - "X=np.hstack((X,temp)) \n", - "\n", - "X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing\n", - "\n", - "y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy\n", - "y_test=to_categorical(y_test)\n", - "\n", - "del temp1,temp2,temp\n", - "\n", - "# %%\n", - "\n", - "# Define tunable parameters\"\n", - "\n", - "eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser)\n", - "lamda=0.01 #Define hyperparameter\n", - "n_layers=2 #Define number of hidden layers in the model\n", - "n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer\n", - "epochs=100 #Number of reiterations over the input data\n", - "batch_size=100 #Number of samples per gradient update\n", - "\n", - "# %%\n", - "\n", - "\"\"\"Define function to return Deep Neural Network model\"\"\"\n", - "\n", - "def NN_model(inputsize,n_layers,n_neuron,eta,lamda):\n", - " model=Sequential() \n", - " for i in range(n_layers): #Run loop to add hidden layers to the model\n", - " if (i==0): #First layer requires input dimensions\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))\n", - " else: #Subsequent layers are capable of automatic shape inferencing\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))\n", - " model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob)\n", - " sgd=optimizers.SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])\n", - " return model\n", - "\n", - " \n", - "Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function\n", - "Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for \n", - "\n", - "for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate \n", - " for j in range(len(eta)): #accuracy scores \n", - " DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)\n", - " DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)\n", - " Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]\n", - " Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]\n", - " \n", - "\n", - "def plot_data(x,y,data,title=None):\n", - "\n", - " # plot results\n", - " fontsize=16\n", - "\n", - "\n", - " fig = plt.figure()\n", - " ax = fig.add_subplot(111)\n", - " cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)\n", - " \n", - " cbar=fig.colorbar(cax)\n", - " cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)\n", - " cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])\n", - " cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])\n", - "\n", - " # put text on matrix elements\n", - " for i, x_val in enumerate(np.arange(len(x))):\n", - " for j, y_val in enumerate(np.arange(len(y))):\n", - " c = \"${0:.1f}\\\\%$\".format( 100*data[j,i]) \n", - " ax.text(x_val, y_val, c, va='center', ha='center')\n", - "\n", - " # convert axis vaues to to string labels\n", - " x=[str(i) for i in x]\n", - " y=[str(i) for i in y]\n", - "\n", - "\n", - " ax.set_xticklabels(['']+x)\n", - " ax.set_yticklabels(['']+y)\n", - "\n", - " ax.set_xlabel('$\\\\mathrm{learning\\\\ rate}$',fontsize=fontsize)\n", - " ax.set_ylabel('$\\\\mathrm{hidden\\\\ neurons}$',fontsize=fontsize)\n", - " if title is not None:\n", - " ax.set_title(title)\n", - "\n", - " plt.tight_layout()\n", - "\n", - " plt.show()\n", - " \n", - "plot_data(eta,n_neuron,Train_accuracy, 'training')\n", - "plot_data(eta,n_neuron,Test_accuracy, 'testing')" - ] - }, - { - "cell_type": "markdown", - "id": "9ff5524f", - "metadata": { - "editable": true - }, - "source": [ - "## Fine-tuning neural network hyperparameters\n", - "\n", - "The flexibility of neural networks is also one of their main\n", - "drawbacks: there are many hyperparameters to tweak. Not only can you\n", - "use any imaginable network topology (how neurons/nodes are interconnected),\n", - "but even in a simple FFNN you can change the number of layers, the\n", - "number of neurons per layer, the type of activation function to use in\n", - "each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you\n", - "know what combination of hyperparameters is the best for your task?\n", - "\n", - "* You can use grid search with cross-validation to find the right hyperparameters.\n", - "\n", - "However,since there are many hyperparameters to tune, and since\n", - "training a neural network on a large dataset takes a lot of time, you\n", - "will only be able to explore a tiny part of the hyperparameter space.\n", - "\n", - "* You can use randomized search.\n", - "\n", - "* Or use tools like [Oscar](http://oscar.calldesk.ai/), which implements more complex algorithms to help you find a good set of hyperparameters quickly." - ] - }, - { - "cell_type": "markdown", - "id": "d511865c", - "metadata": { - "editable": true - }, - "source": [ - "## Hidden layers\n", - "\n", - "For many problems you can start with just one or two hidden layers and it will work just fine.\n", - "For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a\n", - "few hundred neurons.\n", - "You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of\n", - "neurons, in roughly the same amount of training time. \n", - "\n", - "For more complex problems, you can gradually\n", - "ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such\n", - "as large image classification or speech recognition, typically require networks with dozens of layers\n", - "and they need a huge amount\n", - "of training data. However, you will rarely have to train such networks from scratch: it is much more\n", - "common to reuse parts of a pretrained state-of-the-art network that performs a similar task." - ] - }, - { - "cell_type": "markdown", - "id": "75545383", - "metadata": { - "editable": true - }, - "source": [ - "## Which activation function should I use?\n", - "\n", - "The Back propagation algorithm we derived above works by going from\n", - "the output layer to the input layer, propagating the error gradient on\n", - "the way. Once the algorithm has computed the gradient of the cost\n", - "function with regards to each parameter in the network, it uses these\n", - "gradients to update each parameter with a Gradient Descent (GD) step.\n", - "\n", - "Unfortunately for us, the gradients often get smaller and smaller as the\n", - "algorithm progresses down to the first hidden layers. As a result, the\n", - "GD update leaves the lower layer connection weights\n", - "virtually unchanged, and training never converges to a good\n", - "solution. This is known in the literature as \n", - "**the vanishing gradients problem**. \n", - "\n", - "In other cases, the opposite can happen, namely the the gradients can grow bigger and\n", - "bigger. The result is that many of the layers get large updates of the \n", - "weights the\n", - "algorithm diverges. This is the **exploding gradients problem**, which is\n", - "mostly encountered in recurrent neural networks. More generally, deep\n", - "neural networks suffer from unstable gradients, different layers may\n", - "learn at widely different speeds" - ] - }, - { - "cell_type": "markdown", - "id": "77f848ce", - "metadata": { - "editable": true - }, - "source": [ - "## Is the Logistic activation function (Sigmoid) our choice?\n", - "\n", - "Although this unfortunate behavior has been empirically observed for\n", - "quite a while (it was one of the reasons why deep neural networks were\n", - "mostly abandoned for a long time), it is only around 2010 that\n", - "significant progress was made in understanding it.\n", - "\n", - "A paper titled [Understanding the Difficulty of Training Deep\n", - "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n", - "the problems with the popular logistic\n", - "sigmoid activation function and the weight initialization technique\n", - "that was most popular at the time, namely random initialization using\n", - "a normal distribution with a mean of 0 and a standard deviation of\n", - "1. \n", - "\n", - "They showed that with this activation function and this\n", - "initialization scheme, the variance of the outputs of each layer is\n", - "much greater than the variance of its inputs. Going forward in the\n", - "network, the variance keeps increasing after each layer until the\n", - "activation function saturates at the top layers. This is actually made\n", - "worse by the fact that the logistic function has a mean of 0.5, not 0\n", - "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n", - "better than the logistic function in deep networks)." - ] - }, - { - "cell_type": "markdown", - "id": "3a7a82a9", - "metadata": { - "editable": true - }, - "source": [ - "## The derivative of the Logistic funtion\n", - "\n", - "Looking at the logistic activation function, when inputs become large\n", - "(negative or positive), the function saturates at 0 or 1, with a\n", - "derivative extremely close to 0. Thus when backpropagation kicks in,\n", - "it has virtually no gradient to propagate back through the network,\n", - "and what little gradient exists keeps getting diluted as\n", - "backpropagation progresses down through the top layers, so there is\n", - "really nothing left for the lower layers.\n", - "\n", - "In their paper, Glorot and Bengio propose a way to significantly\n", - "alleviate this problem. We need the signal to flow properly in both\n", - "directions: in the forward direction when making predictions, and in\n", - "the reverse direction when backpropagating gradients. We don’t want\n", - "the signal to die out, nor do we want it to explode and saturate. For\n", - "the signal to flow properly, the authors argue that we need the\n", - "variance of the outputs of each layer to be equal to the variance of\n", - "its inputs, and we also need the gradients to have equal variance\n", - "before and after flowing through a layer in the reverse direction.\n", - "\n", - "One of the insights in the 2010 paper by Glorot and Bengio was that\n", - "the vanishing/exploding gradients problems were in part due to a poor\n", - "choice of activation function. Until then most people had assumed that\n", - "if Nature had chosen to use roughly sigmoid activation functions in\n", - "biological neurons, they must be an excellent choice. But it turns out\n", - "that other activation functions behave much better in deep neural\n", - "networks, in particular the ReLU activation function, mostly because\n", - "it does not saturate for positive values (and also because it is quite\n", - "fast to compute)." - ] - }, - { - "cell_type": "markdown", - "id": "b5a2eebb", - "metadata": { - "editable": true - }, - "source": [ - "## The RELU function family\n", - "\n", - "The ReLU activation function suffers from a problem known as the dying\n", - "ReLUs: during training, some neurons effectively die, meaning they\n", - "stop outputting anything other than 0.\n", - "\n", - "In some cases, you may find that half of your network’s neurons are\n", - "dead, especially if you used a large learning rate. During training,\n", - "if a neuron’s weights get updated such that the weighted sum of the\n", - "neuron’s inputs is negative, it will start outputting 0. When this\n", - "happen, the neuron is unlikely to come back to life since the gradient\n", - "of the ReLU function is 0 when its input is negative.\n", - "\n", - "To solve this problem, nowadays practitioners use a variant of the ReLU\n", - "function, such as the leaky ReLU discussed above or the so-called\n", - "exponential linear unit (ELU) function" - ] - }, - { - "cell_type": "markdown", - "id": "70a6d051", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e415600c", - "metadata": { - "editable": true - }, - "source": [ - "## Which activation function should we use?\n", - "\n", - "In general it seems that the ELU activation function is better than\n", - "the leaky ReLU function (and its variants), which is better than\n", - "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", - "than the logistic function. \n", - "\n", - "If runtime\n", - "performance is an issue, then you may opt for the leaky ReLU function over the \n", - "ELU function If you don’t\n", - "want to tweak yet another hyperparameter, you may just use the default\n", - "$\\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have\n", - "spare time and computing power, you can use cross-validation or\n", - "bootstrap to evaluate other activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "857539e6", - "metadata": { - "editable": true - }, - "source": [ - "## More on activation functions, output layers\n", - "\n", - "In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).\n", - "\n", - "It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck.\n", - "\n", - "**For the output layer:**\n", - "\n", - "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n", - "\n", - "* For regression tasks, you can simply use no activation function at all." - ] - }, - { - "cell_type": "markdown", - "id": "a088b34d", - "metadata": { - "editable": true - }, - "source": [ - "## Batch Normalization\n", - "\n", - "Batch Normalization\n", - "aims to address the vanishing/exploding gradients problems, and more generally the problem that the\n", - "distribution of each layer’s inputs changes during training, as the parameters of the previous layers change.\n", - "\n", - "The technique consists of adding an operation in the model just before the activation function of each\n", - "layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new\n", - "parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model\n", - "learn the optimal scale and mean of the inputs for each layer.\n", - "In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and\n", - "standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current\n", - "mini-batch, from this the name batch normalization." - ] - }, - { - "cell_type": "markdown", - "id": "9b6ef868", - "metadata": { - "editable": true - }, - "source": [ - "## Dropout\n", - "\n", - "It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but\n", - "excluding the output neurons) has a probability $p$ of being temporarily dropped out, meaning it will be\n", - "entirely ignored during this training step, but it may be active during the next step.\n", - "\n", - "The\n", - "hyperparameter $p$ is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore.\n", - " It is viewed as one of the most popular regularization techniques." - ] - }, - { - "cell_type": "markdown", - "id": "a28acdc8", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient Clipping\n", - "\n", - "A popular technique to lessen the exploding gradients problem is to simply clip the gradients during\n", - "backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural\n", - "networks).\n", - "\n", - "This technique is called Gradient Clipping.\n", - "\n", - "In general however, Batch\n", - "Normalization is preferred." - ] - }, - { - "cell_type": "markdown", - "id": "7a4056b2", - "metadata": { - "editable": true - }, - "source": [ - "## A very nice website on Neural Networks\n", - "\n", - "You may find this [website](https://playground.tensorflow.org/#activation=tanh&batchSize=10&dataset=circle®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=4,2&seed=0.29243&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false) very useful." - ] - }, - { - "cell_type": "markdown", - "id": "65cfa826", - "metadata": { - "editable": true - }, - "source": [ - "## A top-down perspective on Neural networks\n", - "\n", - "The first thing we would like to do is divide the data into two or three\n", - "parts. A training set, a validation or dev (development) set, and a\n", - "test set. The test set is the data on which we want to make\n", - "predictions. The dev set is a subset of the training data we use to\n", - "check how well we are doing out-of-sample, after training the model on\n", - "the training dataset. We use the validation error as a proxy for the\n", - "test error in order to make tweaks to our model. It is crucial that we\n", - "do not use any of the test data to train the algorithm. This is a\n", - "cardinal sin in ML. Then:\n", - "\n", - "* Estimate optimal error rate\n", - "\n", - "* Minimize underfitting (bias) on training data set.\n", - "\n", - "* Make sure you are not overfitting.\n", - "\n", - "If the validation and test sets are drawn from the same distributions,\n", - "then a good performance on the validation set should lead to similarly\n", - "good performance on the test set. \n", - "\n", - "However, sometimes\n", - "the training data and test data differ in subtle ways because, for\n", - "example, they are collected using slightly different methods, or\n", - "because it is cheaper to collect data in one way versus another. In\n", - "this case, there can be a mismatch between the training and test\n", - "data. This can lead to the neural network overfitting these small\n", - "differences between the test and training sets, and a poor performance\n", - "on the test set despite having a good performance on the validation\n", - "set. To rectify this, Andrew Ng suggests making two validation or dev\n", - "sets, one constructed from the training data and one constructed from\n", - "the test data. The difference between the performance of the algorithm\n", - "on these two validation sets quantifies the train-test mismatch. This\n", - "can serve as another important diagnostic when using DNNs for\n", - "supervised learning." - ] - }, - { - "cell_type": "markdown", - "id": "b43a3bde", - "metadata": { - "editable": true - }, - "source": [ - "## Limitations of supervised learning with deep networks\n", - "\n", - "Like all statistical methods, supervised learning using neural\n", - "networks has important limitations. This is especially important when\n", - "one seeks to apply these methods, especially to physics problems. Like\n", - "all tools, DNNs are not a universal solution. Often, the same or\n", - "better performance on a task can be achieved by using a few\n", - "hand-engineered features (or even a collection of random\n", - "features). \n", - "\n", - "Here we list some of the important limitations of supervised neural network based models. \n", - "\n", - "* **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).\n", - "\n", - "* **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.\n", - "\n", - "* **Homogeneous data.** Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.\n", - "\n", - "* **Many problems are not about prediction.** In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.\n", - "\n", - "Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems." - ] - }, - { - "cell_type": "markdown", - "id": "c9a6d638", + "id": "3a8b831c", "metadata": { "editable": true }, @@ -3916,7 +3872,7 @@ }, { "cell_type": "markdown", - "id": "710647bc", + "id": "5c3c8b51", "metadata": { "editable": true }, @@ -3930,7 +3886,7 @@ }, { "cell_type": "markdown", - "id": "c6e65b5b", + "id": "a765e269", "metadata": { "editable": true }, @@ -3947,7 +3903,7 @@ }, { "cell_type": "markdown", - "id": "92cb46a4", + "id": "5089741f", "metadata": { "editable": true }, @@ -3963,7 +3919,7 @@ }, { "cell_type": "markdown", - "id": "dc07c699", + "id": "4d3d1717", "metadata": { "editable": true }, @@ -3975,7 +3931,7 @@ }, { "cell_type": "markdown", - "id": "bc82d89b", + "id": "10192a31", "metadata": { "editable": true }, @@ -3993,7 +3949,7 @@ }, { "cell_type": "markdown", - "id": "0a6a83d5", + "id": "eef96fda", "metadata": { "editable": true }, @@ -4014,7 +3970,7 @@ }, { "cell_type": "markdown", - "id": "a157be47", + "id": "4569cdf4", "metadata": { "editable": true }, @@ -4031,7 +3987,7 @@ }, { "cell_type": "markdown", - "id": "cf7e4525", + "id": "94442ead", "metadata": { "editable": true }, @@ -4043,7 +3999,7 @@ }, { "cell_type": "markdown", - "id": "071bfae0", + "id": "f4cca2ed", "metadata": { "editable": true }, @@ -4054,7 +4010,7 @@ }, { "cell_type": "markdown", - "id": "278fa742", + "id": "95f9f95f", "metadata": { "editable": true }, @@ -4071,7 +4027,7 @@ }, { "cell_type": "markdown", - "id": "e57267ca", + "id": "9e3814f0", "metadata": { "editable": true }, @@ -4082,7 +4038,7 @@ }, { "cell_type": "markdown", - "id": "edca66d3", + "id": "469fe0b5", "metadata": { "editable": true }, @@ -4098,7 +4054,7 @@ }, { "cell_type": "markdown", - "id": "e6f9452c", + "id": "a50528c5", "metadata": { "editable": true }, @@ -4110,7 +4066,7 @@ }, { "cell_type": "markdown", - "id": "2568aec7", + "id": "5978c5e0", "metadata": { "editable": true }, @@ -4127,7 +4083,7 @@ }, { "cell_type": "markdown", - "id": "caa6477a", + "id": "203b87e8", "metadata": { "editable": true }, @@ -4139,7 +4095,7 @@ }, { "cell_type": "markdown", - "id": "e5576623", + "id": "7a96f79a", "metadata": { "editable": true }, @@ -4157,7 +4113,7 @@ }, { "cell_type": "markdown", - "id": "ebbd3068", + "id": "fe4397bd", "metadata": { "editable": true }, @@ -4167,7 +4123,7 @@ }, { "cell_type": "markdown", - "id": "57c1ee3e", + "id": "aab1298a", "metadata": { "editable": true }, @@ -4179,7 +4135,7 @@ }, { "cell_type": "markdown", - "id": "18f5a350", + "id": "63642bba", "metadata": { "editable": true }, @@ -4196,7 +4152,7 @@ }, { "cell_type": "markdown", - "id": "1e63e810", + "id": "9214a268", "metadata": { "editable": true }, @@ -4208,7 +4164,7 @@ }, { "cell_type": "markdown", - "id": "2347e0ec", + "id": "1d67400a", "metadata": { "editable": true }, @@ -4219,7 +4175,7 @@ }, { "cell_type": "markdown", - "id": "6d4dd997", + "id": "5fbbd6e3", "metadata": { "editable": true }, @@ -4231,7 +4187,7 @@ }, { "cell_type": "markdown", - "id": "ab33f0b1", + "id": "9604e77d", "metadata": { "editable": true }, @@ -4241,7 +4197,7 @@ }, { "cell_type": "markdown", - "id": "fa8477b1", + "id": "9a8194bf", "metadata": { "editable": true }, @@ -4261,7 +4217,7 @@ }, { "cell_type": "markdown", - "id": "5da8446e", + "id": "4de7c416", "metadata": { "editable": true }, @@ -4278,7 +4234,7 @@ }, { "cell_type": "markdown", - "id": "53cff526", + "id": "20582db6", "metadata": { "editable": true }, @@ -4297,7 +4253,7 @@ }, { "cell_type": "markdown", - "id": "20fcb68c", + "id": "0b02d822", "metadata": { "editable": true }, @@ -4309,7 +4265,7 @@ }, { "cell_type": "markdown", - "id": "5827e171", + "id": "b29f4bf8", "metadata": { "editable": true }, @@ -4319,7 +4275,7 @@ }, { "cell_type": "markdown", - "id": "9f808f6d", + "id": "c47afb5e", "metadata": { "editable": true }, @@ -4336,7 +4292,7 @@ }, { "cell_type": "markdown", - "id": "32c67ef2", + "id": "177762e7", "metadata": { "editable": true }, @@ -4346,7 +4302,7 @@ }, { "cell_type": "markdown", - "id": "c0b9a6f5", + "id": "66c0b675", "metadata": { "editable": true }, @@ -4362,7 +4318,7 @@ }, { "cell_type": "markdown", - "id": "65b6d3eb", + "id": "5aca4b55", "metadata": { "editable": true }, @@ -4374,7 +4330,7 @@ }, { "cell_type": "markdown", - "id": "c2955688", + "id": "9466d9ca", "metadata": { "editable": true }, @@ -4386,7 +4342,7 @@ }, { "cell_type": "markdown", - "id": "c32d41b1", + "id": "acf99252", "metadata": { "editable": true }, @@ -4398,7 +4354,7 @@ }, { "cell_type": "markdown", - "id": "a5c6a9c2", + "id": "3d75cdff", "metadata": { "editable": true }, @@ -4408,7 +4364,7 @@ }, { "cell_type": "markdown", - "id": "95993551", + "id": "6fb24959", "metadata": { "editable": true }, @@ -4420,7 +4376,7 @@ }, { "cell_type": "markdown", - "id": "b894d089", + "id": "c688cefb", "metadata": { "editable": true }, @@ -4437,7 +4393,7 @@ }, { "cell_type": "markdown", - "id": "47b9fdf8", + "id": "aa857f39", "metadata": { "editable": true }, @@ -4447,7 +4403,7 @@ }, { "cell_type": "markdown", - "id": "692a34d0", + "id": "0614ff54", "metadata": { "editable": true }, @@ -4459,7 +4415,7 @@ }, { "cell_type": "markdown", - "id": "b7d70fc3", + "id": "7f154a4a", "metadata": { "editable": true }, @@ -4473,7 +4429,7 @@ }, { "cell_type": "markdown", - "id": "f56fda08", + "id": "d11a19d2", "metadata": { "editable": true }, @@ -4489,7 +4445,7 @@ }, { "cell_type": "markdown", - "id": "41c635d7", + "id": "72f3e54f", "metadata": { "editable": true }, @@ -4501,7 +4457,7 @@ }, { "cell_type": "markdown", - "id": "77520b3b", + "id": "c84c0937", "metadata": { "editable": true }, @@ -4523,7 +4479,7 @@ }, { "cell_type": "markdown", - "id": "2dcc09f5", + "id": "c31426a0", "metadata": { "editable": true }, @@ -4535,7 +4491,7 @@ }, { "cell_type": "markdown", - "id": "0b43b4de", + "id": "453814d3", "metadata": { "editable": true }, @@ -4558,7 +4514,7 @@ }, { "cell_type": "markdown", - "id": "099bc7bc", + "id": "ff090abd", "metadata": { "editable": true }, @@ -4574,7 +4530,7 @@ }, { "cell_type": "markdown", - "id": "a3886d10", + "id": "325d5806", "metadata": { "editable": true }, @@ -4586,7 +4542,7 @@ }, { "cell_type": "markdown", - "id": "55b85a23", + "id": "3c9d5d12", "metadata": { "editable": true }, @@ -4610,7 +4566,7 @@ }, { "cell_type": "markdown", - "id": "80e1ade1", + "id": "25d2a4d6", "metadata": { "editable": true }, @@ -4622,7 +4578,7 @@ }, { "cell_type": "markdown", - "id": "7143d6c3", + "id": "ac251537", "metadata": { "editable": true }, @@ -4643,7 +4599,7 @@ }, { "cell_type": "markdown", - "id": "dc144d5f", + "id": "4abf1e4f", "metadata": { "editable": true }, @@ -4655,7 +4611,7 @@ }, { "cell_type": "markdown", - "id": "9110ad54", + "id": "584e53d1", "metadata": { "editable": true }, @@ -4674,7 +4630,7 @@ }, { "cell_type": "markdown", - "id": "f303b115", + "id": "5018e0ac", "metadata": { "editable": true }, @@ -4684,7 +4640,7 @@ }, { "cell_type": "markdown", - "id": "72e2430b", + "id": "2d002209", "metadata": { "editable": true }, @@ -4698,7 +4654,7 @@ }, { "cell_type": "markdown", - "id": "2c36c6d9", + "id": "886f7706", "metadata": { "editable": true }, @@ -4710,7 +4666,7 @@ }, { "cell_type": "markdown", - "id": "b0e23ad3", + "id": "4cf1334c", "metadata": { "editable": true }, @@ -4722,7 +4678,7 @@ }, { "cell_type": "markdown", - "id": "e536c76f", + "id": "cbed4709", "metadata": { "editable": true }, @@ -4739,7 +4695,7 @@ }, { "cell_type": "markdown", - "id": "949d1396", + "id": "cde4ad84", "metadata": { "editable": true }, @@ -4751,7 +4707,7 @@ }, { "cell_type": "markdown", - "id": "0dc96f7c", + "id": "51ba3d32", "metadata": { "editable": true }, @@ -4773,7 +4729,7 @@ }, { "cell_type": "markdown", - "id": "30352389", + "id": "bc990f9d", "metadata": { "editable": true }, @@ -4788,7 +4744,7 @@ }, { "cell_type": "markdown", - "id": "32a6d85d", + "id": "37eeeba2", "metadata": { "editable": true }, @@ -4798,8 +4754,8 @@ }, { "cell_type": "code", - "execution_count": 43, - "id": "9a6ae9a0", + "execution_count": 41, + "id": "e0935387", "metadata": { "collapsed": false, "editable": true @@ -4954,7 +4910,7 @@ }, { "cell_type": "markdown", - "id": "c7bf76ab", + "id": "705831e1", "metadata": { "editable": true }, @@ -4968,8 +4924,8 @@ }, { "cell_type": "code", - "execution_count": 44, - "id": "e548974e", + "execution_count": 42, + "id": "b566606d", "metadata": { "collapsed": false, "editable": true @@ -5138,7 +5094,7 @@ }, { "cell_type": "markdown", - "id": "eb1f08ca", + "id": "9bf1441d", "metadata": { "editable": true }, @@ -5151,7 +5107,7 @@ }, { "cell_type": "markdown", - "id": "2699e6b4", + "id": "449bdc64", "metadata": { "editable": true }, @@ -5168,7 +5124,7 @@ }, { "cell_type": "markdown", - "id": "cc070d3f", + "id": "a6a6e584", "metadata": { "editable": true }, @@ -5184,7 +5140,7 @@ }, { "cell_type": "markdown", - "id": "2eeaf30c", + "id": "d26c95df", "metadata": { "editable": true }, @@ -5197,7 +5153,7 @@ }, { "cell_type": "markdown", - "id": "ab78f889", + "id": "fab08a77", "metadata": { "editable": true }, @@ -5214,7 +5170,7 @@ }, { "cell_type": "markdown", - "id": "47dc3ec7", + "id": "0194be36", "metadata": { "editable": true }, @@ -5226,7 +5182,7 @@ }, { "cell_type": "markdown", - "id": "fb3d01cd", + "id": "be87d802", "metadata": { "editable": true }, @@ -5253,7 +5209,7 @@ }, { "cell_type": "markdown", - "id": "7ab83acd", + "id": "27a2a861", "metadata": { "editable": true }, @@ -5265,8 +5221,8 @@ }, { "cell_type": "code", - "execution_count": 45, - "id": "2b88680d", + "execution_count": 43, + "id": "2901bde5", "metadata": { "collapsed": false, "editable": true @@ -5440,7 +5396,7 @@ }, { "cell_type": "markdown", - "id": "7748a143", + "id": "96571b19", "metadata": { "editable": true }, @@ -5460,7 +5416,7 @@ }, { "cell_type": "markdown", - "id": "5709a433", + "id": "ef982053", "metadata": { "editable": true }, @@ -5475,7 +5431,7 @@ }, { "cell_type": "markdown", - "id": "897eaca0", + "id": "bf36191d", "metadata": { "editable": true }, @@ -5489,7 +5445,7 @@ }, { "cell_type": "markdown", - "id": "44d0a47b", + "id": "a1ab326d", "metadata": { "editable": true }, @@ -5505,7 +5461,7 @@ }, { "cell_type": "markdown", - "id": "ad821520", + "id": "2337ea27", "metadata": { "editable": true }, @@ -5515,7 +5471,7 @@ }, { "cell_type": "markdown", - "id": "2c3329a6", + "id": "7e8ecd2c", "metadata": { "editable": true }, @@ -5537,7 +5493,7 @@ }, { "cell_type": "markdown", - "id": "d142978b", + "id": "62f195f8", "metadata": { "editable": true }, @@ -5550,8 +5506,8 @@ }, { "cell_type": "code", - "execution_count": 46, - "id": "44e060b4", + "execution_count": 44, + "id": "ed7ea5b3", "metadata": { "collapsed": false, "editable": true @@ -5627,7 +5583,7 @@ }, { "cell_type": "markdown", - "id": "d8fc01e3", + "id": "fb91c684", "metadata": { "editable": true }, @@ -5639,7 +5595,7 @@ }, { "cell_type": "markdown", - "id": "0af81d1a", + "id": "ea974758", "metadata": { "editable": true }, @@ -5656,7 +5612,7 @@ }, { "cell_type": "markdown", - "id": "0cd919a7", + "id": "65b1e012", "metadata": { "editable": true }, @@ -5668,7 +5624,7 @@ }, { "cell_type": "markdown", - "id": "670017ba", + "id": "2146d640", "metadata": { "editable": true }, @@ -5683,7 +5639,7 @@ }, { "cell_type": "markdown", - "id": "d78dedae", + "id": "0c2fcb55", "metadata": { "editable": true }, @@ -5695,7 +5651,7 @@ }, { "cell_type": "markdown", - "id": "e847c631", + "id": "4092532c", "metadata": { "editable": true }, @@ -5707,7 +5663,7 @@ }, { "cell_type": "markdown", - "id": "b0d1839c", + "id": "047bcfdf", "metadata": { "editable": true }, @@ -5719,7 +5675,7 @@ }, { "cell_type": "markdown", - "id": "383af9fa", + "id": "ce8fe2b1", "metadata": { "editable": true }, @@ -5729,7 +5685,7 @@ }, { "cell_type": "markdown", - "id": "f0ed39f4", + "id": "018e386c", "metadata": { "editable": true }, @@ -5746,7 +5702,7 @@ }, { "cell_type": "markdown", - "id": "76dcdf88", + "id": "84678ad2", "metadata": { "editable": true }, @@ -5758,7 +5714,7 @@ }, { "cell_type": "markdown", - "id": "73cd9649", + "id": "002987d5", "metadata": { "editable": true }, @@ -5770,7 +5726,7 @@ }, { "cell_type": "markdown", - "id": "f59e0be2", + "id": "862029de", "metadata": { "editable": true }, @@ -5780,7 +5736,7 @@ }, { "cell_type": "markdown", - "id": "40ab528c", + "id": "b85a84f5", "metadata": { "editable": true }, @@ -5792,7 +5748,7 @@ }, { "cell_type": "markdown", - "id": "152bd2bd", + "id": "22ca9f77", "metadata": { "editable": true }, @@ -5802,8 +5758,8 @@ }, { "cell_type": "code", - "execution_count": 47, - "id": "eeff7501", + "execution_count": 45, + "id": "84bf3083", "metadata": { "collapsed": false, "editable": true @@ -5964,7 +5920,7 @@ }, { "cell_type": "markdown", - "id": "15c1d16a", + "id": "04242368", "metadata": { "editable": true }, @@ -5986,7 +5942,7 @@ }, { "cell_type": "markdown", - "id": "93953c79", + "id": "5f23ae18", "metadata": { "editable": true }, @@ -6003,7 +5959,7 @@ }, { "cell_type": "markdown", - "id": "170423f1", + "id": "def24bbf", "metadata": { "editable": true }, @@ -6013,7 +5969,7 @@ }, { "cell_type": "markdown", - "id": "136625b3", + "id": "992d9ea6", "metadata": { "editable": true }, @@ -6028,7 +5984,7 @@ }, { "cell_type": "markdown", - "id": "1d793db3", + "id": "d6cd8183", "metadata": { "editable": true }, @@ -6038,7 +5994,7 @@ }, { "cell_type": "markdown", - "id": "38c0996f", + "id": "2a6c484d", "metadata": { "editable": true }, @@ -6053,7 +6009,7 @@ }, { "cell_type": "markdown", - "id": "3942fb56", + "id": "1755afd0", "metadata": { "editable": true }, @@ -6064,7 +6020,7 @@ }, { "cell_type": "markdown", - "id": "76ba5c9b", + "id": "bf474f28", "metadata": { "editable": true }, @@ -6084,7 +6040,7 @@ }, { "cell_type": "markdown", - "id": "1438da30", + "id": "cf5742d8", "metadata": { "editable": true }, @@ -6096,7 +6052,7 @@ }, { "cell_type": "markdown", - "id": "a3731842", + "id": "8753168d", "metadata": { "editable": true }, @@ -6133,7 +6089,7 @@ }, { "cell_type": "markdown", - "id": "34e781e0", + "id": "93e5f9b1", "metadata": { "editable": true }, @@ -6143,7 +6099,7 @@ }, { "cell_type": "markdown", - "id": "2a2f4871", + "id": "de12d570", "metadata": { "editable": true }, @@ -6155,8 +6111,8 @@ }, { "cell_type": "code", - "execution_count": 48, - "id": "ae8a731a", + "execution_count": 46, + "id": "43222496", "metadata": { "collapsed": false, "editable": true @@ -6357,7 +6313,7 @@ }, { "cell_type": "markdown", - "id": "97c04310", + "id": "a61d7954", "metadata": { "editable": true }, @@ -6374,7 +6330,7 @@ }, { "cell_type": "markdown", - "id": "fa2606dc", + "id": "44d98228", "metadata": { "editable": true }, @@ -6391,7 +6347,7 @@ }, { "cell_type": "markdown", - "id": "cf2cf2a3", + "id": "b188a05d", "metadata": { "editable": true }, @@ -6401,7 +6357,7 @@ }, { "cell_type": "markdown", - "id": "020c23b5", + "id": "d18459ac", "metadata": { "editable": true }, @@ -6416,7 +6372,7 @@ }, { "cell_type": "markdown", - "id": "346a367b", + "id": "d2ffb553", "metadata": { "editable": true }, @@ -6430,7 +6386,7 @@ }, { "cell_type": "markdown", - "id": "abf7c7d7", + "id": "d4fe1100", "metadata": { "editable": true }, @@ -6443,7 +6399,7 @@ }, { "cell_type": "markdown", - "id": "96eef4c2", + "id": "d2eef558", "metadata": { "editable": true }, @@ -6463,7 +6419,7 @@ }, { "cell_type": "markdown", - "id": "0fc76c19", + "id": "15e94e7d", "metadata": { "editable": true }, @@ -6475,7 +6431,7 @@ }, { "cell_type": "markdown", - "id": "8bd11273", + "id": "b1ff57ee", "metadata": { "editable": true }, @@ -6487,7 +6443,7 @@ }, { "cell_type": "markdown", - "id": "f36cb4b9", + "id": "748ca35b", "metadata": { "editable": true }, @@ -6499,7 +6455,7 @@ }, { "cell_type": "markdown", - "id": "a65d4fbb", + "id": "e9436aa6", "metadata": { "editable": true }, @@ -6509,7 +6465,7 @@ }, { "cell_type": "markdown", - "id": "c5fedd1c", + "id": "e5a15029", "metadata": { "editable": true }, @@ -6521,7 +6477,7 @@ }, { "cell_type": "markdown", - "id": "19958832", + "id": "3cc88895", "metadata": { "editable": true }, @@ -6533,7 +6489,7 @@ }, { "cell_type": "markdown", - "id": "40fcacc6", + "id": "a7694445", "metadata": { "editable": true }, @@ -6545,7 +6501,7 @@ }, { "cell_type": "markdown", - "id": "e38354d7", + "id": "d0b02e50", "metadata": { "editable": true }, @@ -6555,7 +6511,7 @@ }, { "cell_type": "markdown", - "id": "75de38a3", + "id": "f39cecbb", "metadata": { "editable": true }, @@ -6571,7 +6527,7 @@ }, { "cell_type": "markdown", - "id": "bc7c377f", + "id": "057ea99d", "metadata": { "editable": true }, @@ -6581,7 +6537,7 @@ }, { "cell_type": "markdown", - "id": "2c2f8536", + "id": "30c9bec6", "metadata": { "editable": true }, @@ -6593,7 +6549,7 @@ }, { "cell_type": "markdown", - "id": "2a8a92c1", + "id": "80ac7a5f", "metadata": { "editable": true }, @@ -6610,7 +6566,7 @@ }, { "cell_type": "markdown", - "id": "9a0e8b1e", + "id": "b3bd36b5", "metadata": { "editable": true }, @@ -6620,7 +6576,7 @@ }, { "cell_type": "markdown", - "id": "c2c60587", + "id": "b9a70d98", "metadata": { "editable": true }, @@ -6636,7 +6592,7 @@ }, { "cell_type": "markdown", - "id": "7f5d45d4", + "id": "c1b83cb1", "metadata": { "editable": true }, @@ -6650,7 +6606,7 @@ }, { "cell_type": "markdown", - "id": "f647952c", + "id": "5319976d", "metadata": { "editable": true }, @@ -6668,8 +6624,8 @@ }, { "cell_type": "code", - "execution_count": 49, - "id": "36a602f3", + "execution_count": 47, + "id": "e0ce7303", "metadata": { "collapsed": false, "editable": true @@ -6724,7 +6680,7 @@ }, { "cell_type": "markdown", - "id": "7361cfcb", + "id": "b2d1e5f3", "metadata": { "editable": true }, @@ -6754,7 +6710,7 @@ }, { "cell_type": "markdown", - "id": "26e435ff", + "id": "46371be2", "metadata": { "editable": true }, @@ -6782,8 +6738,8 @@ }, { "cell_type": "code", - "execution_count": 50, - "id": "63e6a3da", + "execution_count": 48, + "id": "376da27e", "metadata": { "collapsed": false, "editable": true @@ -6830,7 +6786,7 @@ }, { "cell_type": "markdown", - "id": "0afa41f0", + "id": "2d56e19d", "metadata": { "editable": true }, @@ -6855,8 +6811,8 @@ }, { "cell_type": "code", - "execution_count": 51, - "id": "206f151c", + "execution_count": 49, + "id": "869a7ce7", "metadata": { "collapsed": false, "editable": true @@ -7090,7 +7046,7 @@ }, { "cell_type": "markdown", - "id": "930d3eea", + "id": "89970852", "metadata": { "editable": true }, @@ -7102,7 +7058,7 @@ }, { "cell_type": "markdown", - "id": "4078dbf3", + "id": "facb0872", "metadata": { "editable": true }, @@ -7114,7 +7070,7 @@ }, { "cell_type": "markdown", - "id": "264233dd", + "id": "581a8a76", "metadata": { "editable": true }, @@ -7126,7 +7082,7 @@ }, { "cell_type": "markdown", - "id": "1351a9c5", + "id": "e6b675e7", "metadata": { "editable": true }, @@ -7143,7 +7099,7 @@ }, { "cell_type": "markdown", - "id": "146bdbf6", + "id": "32e6ecf5", "metadata": { "editable": true }, @@ -7153,7 +7109,7 @@ }, { "cell_type": "markdown", - "id": "9a00d37a", + "id": "5e5d27bf", "metadata": { "editable": true }, @@ -7165,7 +7121,7 @@ }, { "cell_type": "markdown", - "id": "614d55b7", + "id": "25d94470", "metadata": { "editable": true }, @@ -7182,7 +7138,7 @@ }, { "cell_type": "markdown", - "id": "ad60cde3", + "id": "e96a3863", "metadata": { "editable": true }, @@ -7193,7 +7149,7 @@ }, { "cell_type": "markdown", - "id": "1d1ba45a", + "id": "4157c6b3", "metadata": { "editable": true }, @@ -7213,7 +7169,7 @@ }, { "cell_type": "markdown", - "id": "379660b5", + "id": "75306ee4", "metadata": { "editable": true }, @@ -7223,7 +7179,7 @@ }, { "cell_type": "markdown", - "id": "3573c9f9", + "id": "b04f122c", "metadata": { "editable": true }, @@ -7249,7 +7205,7 @@ }, { "cell_type": "markdown", - "id": "7c19c434", + "id": "84137e6f", "metadata": { "editable": true }, @@ -7265,7 +7221,7 @@ }, { "cell_type": "markdown", - "id": "f090a359", + "id": "b48fe5b1", "metadata": { "editable": true }, @@ -7275,8 +7231,8 @@ }, { "cell_type": "code", - "execution_count": 52, - "id": "fc3764f0", + "execution_count": 50, + "id": "3a3e0ae8", "metadata": { "collapsed": false, "editable": true @@ -7507,7 +7463,7 @@ }, { "cell_type": "markdown", - "id": "24f62270", + "id": "f010df37", "metadata": { "editable": true }, diff --git a/doc/src/week43/week43.do.txt b/doc/src/week43/week43.do.txt index 24be2a166..a0b78c634 100644 --- a/doc/src/week43/week43.do.txt +++ b/doc/src/week43/week43.do.txt @@ -5,29 +5,52 @@ DATE: today !split ===== Plans for week 43 ===== -!bblock Material for the active learning sessions on Tuesday and Wednesday - * Exercise on writing your own neural network code, application to the OR and XOR gates +!bblock Material for the lecture on Monday October 21, 2024 + * Building our own Feed-forward Neural Network with intro to Tensorflow + * Solving differential equations with Neural Networks +# * "Video of lecture to be posted asap":"https://youtu.be/" +# * "Whiteboard notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOct21.pdf" +!eblock + + + +!split +===== Exercises and lab session week 43 ===== +!bblock Lab sessions on Tuesday and Wednesday + * Exercise on writing your own neural network code * The exercises this week will be continued next week as well * Discussion of project 2 - * "Video of lab session":"https://youtu.be/Ia6wwDLxqtM" !eblock -!bblock Material for the lecture on Thursday October 26, 2023 - * Building our own Feed-forward Neural Network and discussion of project 2, continuation from last week - * Solving differential equations with Neural Networks and intro to _Tensorflow_ with examples. - * "Video of lecture":"https://youtu.be/_-AwbBh4G-8" - * "Whiteboard notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesOct26.pdf" - * Readings and Videos: - * These lecture notes - * "Aurelien Geron's chapters 10-11":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf" - * For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. - * "Neural Networks demystified":"https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" - * "Building Neural Networks from scratch":"https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex" - * "Video on Neural Networks":"https://www.youtube.com/watch?v=CqOfi41LfDw" - * "Video on the back propagation algorithm":"https://www.youtube.com/watch?v=Ilg3gGewQ5U" -I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at URL:"http://neuralnetworksanddeeplearning.com/chap4.html". + + +!split +===== Mathematics of deep learning ===== + +!bblock Two recent books online +o "The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen":"https://arxiv.org/abs/2105.04026", published as "Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022":"https://doi.org/10.1017/9781009025096.002" + +o "Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger":"https://doi.org/10.48550/arXiv.2310.20360" !eblock + +!split +===== Reminder on books with hands-on material and codes ===== +!bblock +* "Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch":"https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" +!eblock + + +!split +===== Reading recommendations ===== + +o Rashkca et al., chapter 11, jupyter-notebook sent separately, from "GitHub":"https://github.com/rasbt/machine-learning-book". See also chapters 12 and 13 on using Pytorch to make a Neural network code. +o Goodfellow et al, chapter 6 and 7 contain most of the neural network background. + + + + + !split ===== Using Automatic differentiation ===== a @@ -46,161 +69,663 @@ o Slides 12-44 at URL":http://cs231n.stanford.edu/slides/2017/cs231n_2017_lectur !split -===== Material for exercises week 43 and week 44 ===== - -!split -===== Writing our first neural network code, testing it for the OR and XOR gates ===== - -During week 41 we discussed three different types of gates, the -so-called XOR, the OR and the AND gates. In order to develop a code -for neural networks, it can be useful to set up a simpler system with -only two inputs and one output. This can make it easier to debug and -study the feed forward pass and the back propagation part. In the -exercise this and next week, we propose to study this system with just -one hidden layer and two hidden nodes. There is only one output node -and we can choose to use either a simple regression case (fitting a -line) or just a binary classification case with the corss-entropy as -cost function. - - - - -Their inputs and outputs can be -summarized using the following tables, first for the OR gate with -inputs $x_1$ and $x_2$ and outputs $y$: - -|---------------------| -| $x_1$ | $x_2$ | $y$ | -|---------------------| -| 0 | 0 | 0 | -| 0 | 1 | 1 | -| 1 | 0 | 1 | -| 1 | 1 | 1 | -|---------------------| - -!split -===== The AND and XOR Gates ===== - -The AND gate is defined as - -|---------------------| -| $x_1$ | $x_2$ | $y$ | -|---------------------| -| 0 | 0 | 0 | -| 0 | 1 | 0 | -| 1 | 0 | 0 | -| 1 | 1 | 1 | -|---------------------| - -And finally we have the XOR gate - -|---------------------| -| $x_1$ | $x_2$ | $y$ | -|---------------------| -| 0 | 0 | 0 | -| 0 | 1 | 1 | -| 1 | 0 | 1 | -| 1 | 1 | 0 | -|---------------------| - -!split -===== Representing the Data Sets ===== - -Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads - -!bt -\bm{X}=\begin{bmatrix} 0 & 0 \\ - 0 & 1 \\ - 1 & 0 \\ - 1 & 1 \end{bmatrix}, -!et - -while the vector of outputs is $\bm{y}^T=[0,1,1,0]$ for the XOR gate, $\bm{y}^T=[0,0,0,1]$ for the AND gate and $\bm{y}^T=[0,1,1,1]$ for the OR gate. - - - -Your tasks here are - -o Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs. -o Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function. -o Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output. -o Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets. -o Set up the cost function (cross entropy for classification of binary cases). -o Calculate the gradients needed for the back propagation part. -o Use the gradients to train the network in the back propagation part. Think of using automatic differentiation. -o Train the network and study your results and compare with results obtained either with _scikit-learn_ or _TensorFlow_. - -Everything you develop here can be used directly into the code for the project. +===== Lecture Monday October 21 ===== !split -===== Setting up dimensionalities by hand ===== +===== Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations ===== +This is a reminder from where we ended last week. -It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by +!bblock The architecture (our model) +o Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays) +o Define the number of hidden layers and hidden nodes +o Define activation functions for hidden layers and output layers +o Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates +o Define cost function and possible regularization terms with hyperparameters +o Initialize weights and biases +o Fix number of iterations for the feed forward part and back propagation part +!eblock + +!split +===== Setting up the back propagation algorithm, part 1 ===== + +Let us write this out in the form of an algorithm. + +_First_, we set up the input data $\bm{x}$ and the activations +$\bm{z}_1$ of the input layer and compute the activation function and +the pertinent outputs $\bm{a}^1$. + +_Secondly_, we perform then the feed forward till we reach the output +layer and compute all $\bm{z}_l$ of the input layer and compute the +activation function and the pertinent outputs $\bm{a}^l$ for +$l=1,2,3,\dots,L$. + + +_Notation_: The first hidden layer has $l=1$ as label and the final output layer has $l=L$. + +!split +===== Setting up the back propagation algorithm, part 2 ===== + + +Thereafter we compute the ouput error $\bm{\delta}^L$ by computing all !bt -\bm{W_h}=\begin{bmatrix} 1 & 1 \\ - 1 & 1 \end{bmatrix}, +\[ +\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. +\] !et -Multiplying $\bm{X}$ and $\bm{W}$ gives - +Then we compute the back propagate error for each $l=L-1,L-2,\dots,1$ as !bt -\bm{X}{W}_h=\begin{bmatrix} 0 & 0 \\ - 1 & 1 \\ - 1 & 1 \\ - 2 & 2 \end{bmatrix}, -!et -Assume also that the bias vector for the hidden layer is -!bt -\bm{b}_h=\begin{bmatrix} 0 \\ - -1\end{bmatrix}, -!et -Adding it gives us the input to the activation function of the hidden layer -!bt -\bm{z}_h=\bm{X}\bm{W}_h+\bm{b}_h=\begin{bmatrix} 0 & -1 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, +\[ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). +\] !et -Let us then assume that our activation function is the RELU function, which simply means that we take the max of $0$ and the elements of the input argument $\bm{z}_h$, that is we have +!split +===== Setting up the Back propagation algorithm, part 3 ===== + + +Finally, we update the weights and the biases using gradient descent +for each $l=L-1,L-2,\dots,1$ (the first hidden layer) and update the weights and biases +according to the rules + !bt -\bm{a}_h=\mathrm{RELU}(\bm{z}_h=\bm{X}\bm{W}_h+\bm{b}_h)=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, +\[ +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, +\] !et -Assume also that the bias of the output layer is zero and that the weights of the output layer are + !bt -\bm{w}_o=\begin{bmatrix} 1 \\ - -2\end{bmatrix}, +\[ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +\] !et -and multiplying with $\bm{a}_h$ gives the output +with $\eta$ being the learning rate. + +!split +===== Updating the gradients ===== + +With the back propagate error for each $l=L-1,L-2,\dots,1$ as !bt -\bm{a}_o=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}\begin{bmatrix} 1 \\ - -2\end{bmatrix}=\begin{bmatrix} 0 \\ 1 \\ 1 \\0\end{bmatrix}, +\[ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), +\] !et -the wanted result. Pay attention to the dimensionalities as well. +we update the weights and the biases using gradient descent for each $l=L-1,L-2,\dots,1$ and update the weights and biases according to the rules +!bt +\[ +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, +\] +!et + +!bt +\[ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +\] +!et + !split -===== Setting up the Neural Network ===== +===== Activation functions ===== + + +A property that characterizes a neural network, other than its +connectivity, is the choice of activation function(s). The following +restrictions are imposed on an activation function for an FFNN to +fulfill the universal approximation theorem + + * Non-constant + + * Bounded + + * Monotonically-increasing + + * Continuous + +!split +=== Activation functions, examples === + +Typical examples are the logistic *Sigmoid* + +!bt +\[ + \sigma(x) = \frac{1}{1 + e^{-x}}, +\] +!et +and the *hyperbolic tangent* function +!bt +\[ + \sigma(x) = \tanh(x) +\] +!et + + +!split +===== The RELU function family ===== + +The ReLU activation function suffers from a problem known as the dying +ReLUs: during training, some neurons effectively die, meaning they +stop outputting anything other than 0. + +In some cases, you may find that half of your network’s neurons are +dead, especially if you used a large learning rate. During training, +if a neuron’s weights get updated such that the weighted sum of the +neuron’s inputs is negative, it will start outputting 0. When this +happen, the neuron is unlikely to come back to life since the gradient +of the ReLU function is 0 when its input is negative. + +!split +===== ELU function ===== + +To solve this problem, nowadays practitioners use a variant of the +ReLU function, such as the leaky ReLU discussed above or the so-called +exponential linear unit (ELU) function + + +!bt +\[ +ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. +\] +!et + +!split +===== Which activation function should we use? ===== + +In general it seems that the ELU activation function is better than +the leaky ReLU function (and its variants), which is better than +ReLU. ReLU performs better than $\tanh$ which in turn performs better +than the logistic function. + +If runtime performance is an issue, then you may opt for the leaky +ReLU function over the ELU function If you don’t want to tweak yet +another hyperparameter, you may just use the default $\alpha$ of +$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and +computing power, you can use cross-validation or bootstrap to evaluate +other activation functions. + + +!split +===== More on activation functions, output layers ===== + +In most cases you can use the ReLU activation function in the hidden +layers (or one of its variants). + +It is a bit faster to compute than other activation functions, and the +gradient descent optimization does in general not get stuck. + +_For the output layer:_ + +* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive). +* For regression tasks, you can simply use no activation function at all. + + + + +!split +===== Setting up a Multi-layer perceptron model for classification ===== + +We are now gong to develop an example based on the MNIST data +base. This is a classification problem and we need to use our +cross-entropy function we discussed in connection with logistic +regression. The cross-entropy defines our cost function for the +classificaton problems with neural networks. + +In binary classification with two classes $(0, 1)$ we define the +logistic/sigmoid function as the probability that a particular input +is in class $0$ or $1$. This is possible because the logistic +function takes any input from the real numbers and inputs a number +between 0 and 1, and can therefore be interpreted as a probability. It +also has other nice properties, such as a derivative that is simple to +calculate. + +For an input $\boldsymbol{a}$ from the hidden layer, the probability that the input $\boldsymbol{x}$ +is in class 0 or 1 is just. We let $\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$ +represents our activation values $z$. We have +!bt +\[ +P(y = 0 \mid \bm{x}, \bm{\theta}) = \frac{1}{1 + \exp{(- \bm{x}})} , +\] +!et +and +!bt +\[ +P(y = 1 \mid \bm{x}, \bm{\theta}) = 1 - P(y = 0 \mid \bm{x}, \bm{\theta}) , +\] +!et + +where $y \in \{0, 1\}$ and $\bm{\theta}$ represents the weights and biases +of our network. + + +!split +===== Defining the cost function ===== + +Our cost function is given as (see the Logistic regression lectures) +!bt +\[ +\mathcal{C}(\bm{\theta}) = - \ln P(\mathcal{D} \mid \bm{\theta}) = - \sum_{i=1}^n +y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\bm{\theta}) . +\] +!et + +This last equality means that we can interpret our *cost* function as a sum over the *loss* function +for each point in the dataset $\mathcal{L}_i(\bm{\theta})$. +The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather +than maximizing a negative number. + +In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: + +$y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and + + +$y = 1 \quad \rightarrow \quad \bm{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ + + +i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. + +If $\bm{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th +output vector $\bm{y}_i$. +The probability of $\bm{x}_i$ being in class $c$ will be given by the softmax function: + +!bt +\[ +P(y_{ic} = 1 \mid \bm{x}_i, \bm{\theta}) = \frac{\exp{((\bm{a}_i^{hidden})^T \bm{w}_c)}} +{\sum_{c'=0}^{C-1} \exp{((\bm{a}_i^{hidden})^T \bm{w}_{c'})}} , +\] +!et + +which reduces to the logistic function in the binary case. +The likelihood of this $C$-class classifier +is now given as: + +!bt +\[ +P(\mathcal{D} \mid \bm{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . +\] +!et +Again we take the negative log-likelihood to define our cost function: + +!bt +\[ +\mathcal{C}(\bm{\theta}) = - \log{P(\mathcal{D} \mid \bm{\theta})}. +\] +!et +See the logistic regression lectures for a full definition of the cost function. + +The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before! + +!split +===== Example: binary classification problem ===== + +As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\beta$ as +!bt +\[ +\mathcal{C}(\bm{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\bm{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\bm{\beta})}\right), +\] +!et +where we had defined the logistic (sigmoid) function +!bt +\[ +p(y_i =1\vert x_i,\bm{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, +\] +!et +and +!bt +\[ +p(y_i =0\vert x_i,\bm{\beta})=1-p(y_i =1\vert x_i,\bm{\beta}). +\] +!et +The parameters $\bm{\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. + +Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. +We have then +!bt +\[ +a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, +\] +!et +with +!bt +\[ +z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, +\] +!et +where the superscript $l-1$ indicates that these are the outputs from layer $l-1$. +Our cost function at the final layer $l=L$ is now +!bt +\[ +\mathcal{C}(\bm{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), +\] +!et +where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get +!bt +\[ +\frac{\partial \mathcal{C}(\bm{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. +\] +!et +In case we use another activation function than the logistic one, we need to evaluate other derivatives. + + +!split +===== The Softmax function ===== +In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need +!bt +\[ +\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = +\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. +\] +!et +For the Softmax function we have +!bt +\[ +f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. +\] +!et +Its derivative with respect to $z_j^l$ gives +!bt +\[ +\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), +\] +!et +which in case of the simply binary model reduces to having $i=j$. + +!split +===== Developing a code for doing neural networks with back propagation ===== + + +One can identify a set of key steps when using neural networks to solve supervised learning problems: + +o Collect and pre-process data +o Define model and architecture +o Choose cost function and optimizer +o Train the model +o Evaluate model performance on test data +o Adjust hyperparameters (if necessary, network architecture) + +!split +===== Collect and pre-process data ===== + +Here we will be using the MNIST dataset, which is readily available through the _scikit-learn_ +package. You may also find it for example "here":"http://yann.lecun.com/exdb/mnist/". +The *MNIST* (Modified National Institute of Standards and Technology) database is a large database +of handwritten digits that is commonly used for training various image processing systems. +The MNIST dataset consists of 70 000 images of size $28\times 28$ pixels, each labeled from 0 to 9. +The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\times 8$ collected and processed from this database. + +To feed data into a feed-forward neural network we need to represent +the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each +row represents an *input*, in this case a handwritten digit, and +each column represents a *feature*, in this case a pixel. The +correct answers, also known as *labels* or *targets* are +represented as a 1D array of integers +$Y = (n_{inputs}) = (5, 3, 1, 8,...)$. + +As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from +measurements of height (in m) +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: + +$$ X = \begin{bmatrix} +1.85 & 81\\ +1.71 & 65\\ +1.95 & 103\\ +1.55 & 42\\ +1.63 & 56 +\end{bmatrix} ,$$ + +and the targets would be: + +$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ + +Since each input image is a 2D matrix, we need to flatten the image +(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a +design/feature matrix. This means we lose all spatial information in the +image, such as locality and translational invariance. More complicated +architectures such as Convolutional Neural Networks can take advantage +of such information, and are most commonly applied when analyzing +images. -We define first our design matrix and the various output vectors for the different gates. !bc pycod -""" -Simple code that tests XOR, OR and AND gates with linear regression -""" - # import necessary packages import numpy as np import matplotlib.pyplot as plt from sklearn import datasets + +# ensure the same random numbers appear every time +np.random.seed(0) + +# display images in notebook +%matplotlib inline +plt.rcParams['figure.figsize'] = (12,12) + + +# download MNIST dataset +digits = datasets.load_digits() + +# define inputs and labels +inputs = digits.images +labels = digits.target + +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) +print("labels = (n_inputs) = " + str(labels.shape)) + + +# flatten the image +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 +n_inputs = len(inputs) +inputs = inputs.reshape(n_inputs, -1) +print("X = (n_inputs, n_features) = " + str(inputs.shape)) + + +# choose some random images to display +indices = np.arange(n_inputs) +random_indices = np.random.choice(indices, size=5) + +for i, image in enumerate(digits.images[random_indices]): + plt.subplot(1, 5, i+1) + plt.axis('off') + plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') + plt.title("Label: %d" % digits.target[random_indices[i]]) +plt.show() +!ec + +!split +===== Train and test datasets ===== + +Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. + +We will reserve $80 \%$ of our dataset for training and $20 \%$ for testing. + +It is important that the train and test datasets are drawn randomly from our dataset, to ensure +no bias in the sampling. +Say you are taking measurements of weather data to predict the weather in the coming 5 days. +You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data +collected from 12.00 to 24.00. + + +!bc pycod +from sklearn.model_selection import train_test_split + +# one-liner from scikit-learn library +train_size = 0.8 +test_size = 1 - train_size +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, + test_size=test_size) + +# equivalently in numpy +def train_test_split_numpy(inputs, labels, train_size, test_size): + n_inputs = len(inputs) + inputs_shuffled = inputs.copy() + labels_shuffled = labels.copy() + + np.random.shuffle(inputs_shuffled) + np.random.shuffle(labels_shuffled) + + train_end = int(n_inputs*train_size) + X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] + Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] + + return X_train, X_test, Y_train, Y_test + +#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size) + +print("Number of training images: " + str(len(X_train))) +print("Number of test images: " + str(len(X_test))) +!ec + +!split +===== Define model and architecture ===== + +Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have + +$$ z = \sum_{i=1}^n w_i a_i ,$$ + +$$ y = f(z) ,$$ + +where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer +and $w_i$ is the weight to input $i$. +The activation of the neurons in the input layer is just the features (e.g. a pixel value). + +The simplest activation function for a neuron is the *Heaviside* function: + +$$ f(z) = +\begin{cases} +1, & z > 0\\ +0, & \text{otherwise} +\end{cases} +$$ + +A feed-forward neural network with this activation is known as a *perceptron*. +For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. +This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), +and we call these architectures *multiclass perceptrons*. + +However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and +Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. + +Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). +We will be using the sigmoid function $\sigma(x)$: + +$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$ + +which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions. + +!split +===== Layers ===== + +* Input +Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. + +* Hidden layer +We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. +Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. + +* Output +If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, +which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. + +For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. + +Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: + +$$ P(\text{class $j$} \mid \text{input $\bm{a}$}) = \frac{\exp{(\bm{a}^T \bm{w}_j)}} +{\sum_{c=0}^{9} \exp{(\bm{a}^T \bm{w}_c)}} ,$$ + +i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\bm{a}$, with $\bm{w}_j$ the weights of neuron $j$ to the inputs. +The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. +The exponent is just the weighted sum of inputs as before: + +$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ + +Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 +weights to the output layer. + +!split +===== Weights and biases ===== + +Typically weights are initialized with small values distributed around zero, drawn from a uniform +or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. + +Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range +of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: + +$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ + +The bias weights $\bm{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle. +!bc pycod +# building our neural network + +n_inputs, n_features = X_train.shape +n_hidden_neurons = 50 +n_categories = 10 + +# we make the weights normally distributed using numpy.random.randn + +# weights and bias in the hidden layer +hidden_weights = np.random.randn(n_features, n_hidden_neurons) +hidden_bias = np.zeros(n_hidden_neurons) + 0.01 + +# weights and bias in the output layer +output_weights = np.random.randn(n_hidden_neurons, n_categories) +output_bias = np.zeros(n_categories) + 0.01 +!ec + +!split +===== Feed-forward pass ===== + +Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. +For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: + +$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ + +this is then passed through our activation function + +$$ a_{j}^{l} = f(z_{j}^{l}) .$$ + +We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: + +$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ + +Finally we calculate the output of neuron $j$ in the output layer using the softmax function: + +$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} +{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ + +!split +===== Matrix multiplications ===== + +Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden +layer have the dimensions +$W_{hidden} = (n_{features}, n_{hidden})$, +we can easily feed the network all our training data in one go by taking the matrix product + +$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ + +and obtain a matrix that holds the weighted sum of inputs to the hidden layer +for each input image and each hidden neuron. +We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: + +$$ \bm{z}^{l} = \bm{X} \bm{W}^{l} + \bm{b}^{l} ,$$ + +meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. +This is then passed through the activation: + +$$ \bm{a}^{l} = f(\bm{z}^l) .$$ + +This is fed to the output layer: + +$$ \bm{z}^{L} = \bm{a}^{L} \bm{W}^{L} + \bm{b}^{L} .$$ + +Finally we receive our output values for each image and each category by passing it through the softmax function: + +$$ output = softmax (\bm{z}^{L}) = (n_{inputs}, n_{categories}) .$$ + + +!bc pycod +# setup the feed-forward pass, subscript h = hidden layer + def sigmoid(x): return 1/(1 + np.exp(-x)) @@ -214,97 +739,432 @@ def feed_forward(X): z_o = np.matmul(a_h, output_weights) + output_bias # softmax output # axis 0 holds each input and axis 1 the probabilities of each category - probabilities = sigmoid(z_o) + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + return probabilities +probabilities = feed_forward(X_train) +print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape)) +print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0])) +print("probabilities sum up to: " + str(probabilities[0].sum())) +print() -# ensure the same random numbers appear every time -np.random.seed(0) - -# Design matrix -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64) - -# The XOR gate -yXOR = np.array( [ 0, 1 ,1, 0]) -# The OR gate -yOR = np.array( [ 0, 1 ,1, 1]) -# The AND gate -yAND = np.array( [ 0, 0 ,0, 1]) - -# Defining the neural network -n_inputs, n_features = X.shape -n_hidden_neurons = 2 -n_categories = 1 -n_features = 2 - -# we make the weights normally distributed using numpy.random.randn - -# weights and bias in the hidden layer -hidden_weights = np.random.randn(n_features, n_hidden_neurons) -hidden_bias = np.zeros(n_hidden_neurons) + 0.01 - -# weights and bias in the output layer -output_weights = np.random.randn(n_hidden_neurons, n_categories) -output_bias = np.zeros(n_categories) + 0.01 - -probabilities = feed_forward(X) -print(probabilities) +# we obtain a prediction by taking the class with the highest likelihood +def predict(X): + probabilities = feed_forward(X) + return np.argmax(probabilities, axis=1) +predictions = predict(X_train) +print("predictions = (n_inputs) = " + str(predictions.shape)) +print("prediction for image 0: " + str(predictions[0])) +print("correct label for image 0: " + str(Y_train[0])) !ec -Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above. - !split -===== The Code using Scikit-Learn ===== +===== Choose cost function and optimizer ===== + +To measure how well our neural network is doing we need to introduce a cost function. +We will call the function that gives the error of a single sample output the *loss* function, and the function +that gives the total error of our network across all samples the *cost* function. +A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. + +In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: + +$$ y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ + + +$$ y = 1 \quad \rightarrow \quad \bm{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ + + +i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. + +Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. +We define the cost function $\mathcal{C}$ as a sum over the cross-entropy loss for each point $\bm{x}_i$ in the dataset. + +In the one-hot representation only one of the terms in the loss function is non-zero, namely the +probability of the correct category $c'$ +(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong +you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\bm{\theta}$ represents the parameters of our network, i.e. all the weights and biases. + + +!split +===== Optimizing the cost function ===== + +The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent +is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. +Each parameter $\theta$ is iteratively adjusted according to the rule + +$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ + +where $\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. +This update can be repeated for any number of iterations, or until we are satisfied with the result. + +A simple and effective improvement is a variant called *Batch Gradient Descent*. +Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient +on a subset of the data called a *minibatch*. +If there are $N$ data points and we have a minibatch size of $M$, the total number of batches +is $N/M$. +We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: + +$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ + +i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. + +This has two important benefits: +o Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. +o It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. + +The various optmization methods, with codes and algorithms, are discussed in our lectures on "Gradient descent approaches":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". + +!split +===== Regularization ===== + +It is common to add an extra term to the cost function, proportional +to the size of the weights. This is equivalent to constraining the +size of the weights, so that they do not grow out of control. +Constraining the size of the weights means that the weights cannot +grow arbitrarily large to fit the training data, and in this way +reduces *overfitting*. + +We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: + +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \bm{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ + +i.e. we sum up all the weights squared. The factor $\lambda$ is known as a regularization parameter. + + +In order to train the model, we need to calculate the derivative of +the cost function with respect to every bias and weight in the +network. In total our network has $(64 + 1)\times 50=3250$ weights in +the hidden layer and $(50 + 1)\times 10=510$ weights to the output +layer ($+1$ for the bias), and the gradient must be calculated for +every parameter. We use the *backpropagation* algorithm discussed +above. This is a clever use of the chain rule that allows us to +calculate the gradient efficently. + + +!split +===== Matrix multiplication ===== + +To more efficently train our network these equations are implemented using matrix operations. +The error in the output layer is calculated simply as, with $\bm{t}$ being our targets, + +$$ \delta_L = \bm{t} - \bm{y} = (n_{inputs}, n_{categories}) .$$ + +The gradient for the output weights is calculated as + +$$ \nabla W_{L} = \bm{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ + +where $\bm{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. +Since we are going backwards we have to transpose the activation matrix. + +The gradient with respect to the output bias is then + +$$ \nabla \bm{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ + +The error in the hidden layer is + +$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ + +where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean +that we are summing up the products for each neuron in the output layer. The symbol $\circ$ denotes +the *Hadamard product*, meaning element-wise multiplication. + +This again gives us the gradients in the hidden layer: + +$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ + +$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ + !bc pycod -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn.neural_network import MLPClassifier +# to categorical turns our integer vector into a onehot representation from sklearn.metrics import accuracy_score -import seaborn as sns -# ensure the same random numbers appear every time -np.random.seed(0) +# one-hot in numpy +def to_categorical_numpy(integer_vector): + n_inputs = len(integer_vector) + n_categories = np.max(integer_vector) + 1 + onehot_vector = np.zeros((n_inputs, n_categories)) + onehot_vector[range(n_inputs), integer_vector] = 1 + + return onehot_vector -# Design matrix -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64) +#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test) +Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test) -# The XOR gate -yXOR = np.array( [ 0, 1 ,1, 0]) -# The OR gate -yOR = np.array( [ 0, 1 ,1, 1]) -# The AND gate -yAND = np.array( [ 0, 0 ,0, 1]) +def feed_forward_train(X): + # weighted sum of inputs to the hidden layer + z_h = np.matmul(X, hidden_weights) + hidden_bias + # activation in the hidden layer + a_h = sigmoid(z_h) + + # weighted sum of inputs to the output layer + z_o = np.matmul(a_h, output_weights) + output_bias + # softmax output + # axis 0 holds each input and axis 1 the probabilities of each category + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + # for backpropagation need activations in hidden and output layers + return a_h, probabilities -# Defining the neural network -n_hidden_neurons = 2 +def backpropagation(X, Y): + a_h, probabilities = feed_forward_train(X) + + # error in the output layer + error_output = probabilities - Y + # error in the hidden layer + error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h) + + # gradients for the output layer + output_weights_gradient = np.matmul(a_h.T, error_output) + output_bias_gradient = np.sum(error_output, axis=0) + + # gradient for the hidden layer + hidden_weights_gradient = np.matmul(X.T, error_hidden) + hidden_bias_gradient = np.sum(error_hidden, axis=0) + return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient + +print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) + +eta = 0.01 +lmbd = 0.01 +for i in range(1000): + # calculate gradients + dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot) + + # regularization term gradients + dWo += lmbd * output_weights + dWh += lmbd * hidden_weights + + # update weights and biases + output_weights -= eta * dWo + output_bias -= eta * dBo + hidden_weights -= eta * dWh + hidden_bias -= eta * dBh + +print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) +!ec + +!split +===== Improving performance ===== + +As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. +In order to obtain a network that does something useful, we will have to do a bit more work. + +The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\lambda = 10^{-6},...,10^{-0}$. + +Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period +going through the entire dataset ($n/M$ batches) an *epoch*. + +If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. +Andrew Ng goes through some of these considerations in this "video":"https://youtu.be/F1ka6a13S9I". You can find a summary of the video "here":"https://kevinzakka.github.io/2016/09/26/applying-deep-learning/". + +!split +===== Full object-oriented implementation ===== + +It is very natural to think of the network as an object, with specific instances of the network +being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. + + +!bc pycod +class NeuralNetwork: + def __init__( + self, + X_data, + Y_data, + n_hidden_neurons=50, + n_categories=10, + epochs=10, + batch_size=100, + eta=0.1, + lmbd=0.0): + + self.X_data_full = X_data + self.Y_data_full = Y_data + + self.n_inputs = X_data.shape[0] + self.n_features = X_data.shape[1] + self.n_hidden_neurons = n_hidden_neurons + self.n_categories = n_categories + + self.epochs = epochs + self.batch_size = batch_size + self.iterations = self.n_inputs // self.batch_size + self.eta = eta + self.lmbd = lmbd + + self.create_biases_and_weights() + + def create_biases_and_weights(self): + self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons) + self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01 + + self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories) + self.output_bias = np.zeros(self.n_categories) + 0.01 + + def feed_forward(self): + # feed-forward for training + self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias + self.a_h = sigmoid(self.z_h) + + self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias + + exp_term = np.exp(self.z_o) + self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + def feed_forward_out(self, X): + # feed-forward for output + z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias + a_h = sigmoid(z_h) + + z_o = np.matmul(a_h, self.output_weights) + self.output_bias + + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + return probabilities + + def backpropagation(self): + error_output = self.probabilities - self.Y_data + error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h) + + self.output_weights_gradient = np.matmul(self.a_h.T, error_output) + self.output_bias_gradient = np.sum(error_output, axis=0) + + self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden) + self.hidden_bias_gradient = np.sum(error_hidden, axis=0) + + if self.lmbd > 0.0: + self.output_weights_gradient += self.lmbd * self.output_weights + self.hidden_weights_gradient += self.lmbd * self.hidden_weights + + self.output_weights -= self.eta * self.output_weights_gradient + self.output_bias -= self.eta * self.output_bias_gradient + self.hidden_weights -= self.eta * self.hidden_weights_gradient + self.hidden_bias -= self.eta * self.hidden_bias_gradient + + def predict(self, X): + probabilities = self.feed_forward_out(X) + return np.argmax(probabilities, axis=1) + + def predict_probabilities(self, X): + probabilities = self.feed_forward_out(X) + return probabilities + + def train(self): + data_indices = np.arange(self.n_inputs) + + for i in range(self.epochs): + for j in range(self.iterations): + # pick datapoints with replacement + chosen_datapoints = np.random.choice( + data_indices, size=self.batch_size, replace=False + ) + + # minibatch training data + self.X_data = self.X_data_full[chosen_datapoints] + self.Y_data = self.Y_data_full[chosen_datapoints] + + self.feed_forward() + self.backpropagation() +!ec + +!split +===== Evaluate model performance on test data ===== + +To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. +We measure the performance of the network using the *accuracy* score. +The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. + +$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ + +where $I$ is the indicator function, $1$ if $\tilde{y}_i = y_i$ and $0$ otherwise. + + +!bc pycod +epochs = 100 +batch_size = 100 + +dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, + n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) +dnn.train() +test_predict = dnn.predict(X_test) + +# accuracy score from scikit library +print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) + +# equivalent in numpy +def accuracy_score_numpy(Y_test, Y_pred): + return np.sum(Y_test == Y_pred) / len(Y_test) + +#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict)) +!ec + +!split +===== Adjust hyperparameters ===== + +We now perform a grid search to find the optimal hyperparameters for the network. +Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\%$ ($2\%$ error rate). + +!bc pycod eta_vals = np.logspace(-5, 1, 7) lmbd_vals = np.logspace(-5, 1, 7) -# store models for later use -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) -epochs = 100 +# store the models for later use +DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) +# grid search for i, eta in enumerate(eta_vals): for j, lmbd in enumerate(lmbd_vals): - dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', - alpha=lmbd, learning_rate_init=eta, max_iter=epochs) - dnn.fit(X, yXOR) - DNN_scikit[i][j] = dnn + dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, + n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) + dnn.train() + + DNN_numpy[i][j] = dnn + + test_predict = dnn.predict(X_test) + print("Learning rate = ", eta) print("Lambda = ", lmbd) - print("Accuracy score on data set: ", dnn.score(X, yXOR)) + print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) print() +!ec + +!split +===== Visualization ===== + +!bc pycod +# visual representation of grid search +# uses seaborn heatmap, you can also do this with matplotlib imshow +import seaborn as sns sns.set() + +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) + for i in range(len(eta_vals)): for j in range(len(lmbd_vals)): - dnn = DNN_scikit[i][j] - test_pred = dnn.predict(X) - test_accuracy[i][j] = accuracy_score(yXOR, test_pred) + dnn = DNN_numpy[i][j] + + train_pred = dnn.predict(X_train) + test_pred = dnn.predict(X_test) + + train_accuracy[i][j] = accuracy_score(Y_train, train_pred) + test_accuracy[i][j] = accuracy_score(Y_test, test_pred) + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() fig, ax = plt.subplots(figsize = (10, 10)) sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") @@ -312,9 +1172,482 @@ ax.set_title("Test Accuracy") ax.set_ylabel("$\eta$") ax.set_xlabel("$\lambda$") plt.show() +!ec + +!split +===== scikit-learn implementation ===== + +_scikit-learn_ focuses more +on traditional machine learning methods, such as regression, +clustering, decision trees, etc. As such, it has only two types of +neural networks: Multi Layer Perceptron outputting continuous values, +*MPLRegressor*, and Multi Layer Perceptron outputting labels, +*MLPClassifier*. We will see how simple it is to use these classes. + +_scikit-learn_ implements a few improvements from our neural network, +such as early stopping, a varying learning rate, different +optimization methods, etc. We would therefore expect a better +performance overall. + +!bc pycod +from sklearn.neural_network import MLPClassifier +# store models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, Y_train) + + DNN_scikit[i][j] = dnn + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Accuracy score on test set: ", dnn.score(X_test, Y_test)) + print() +!ec + + +!split +===== Visualization ===== +!bc pycod +# optional +# visual representation of grid search +# uses seaborn heatmap, could probably do this in matplotlib +import seaborn as sns + +sns.set() + +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) + +for i in range(len(eta_vals)): + for j in range(len(lmbd_vals)): + dnn = DNN_scikit[i][j] + + train_pred = dnn.predict(X_train) + test_pred = dnn.predict(X_test) + + train_accuracy[i][j] = accuracy_score(Y_train, train_pred) + test_accuracy[i][j] = accuracy_score(Y_test, test_pred) + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Test Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() +!ec + + + + + + + + + +!split +===== Building neural networks in Tensorflow and Keras ===== + +Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. + +In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. + +!split +===== Tensorflow ===== + +Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. + +Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. + +"Tensorflow uses":"https://www.tensorflow.org/guide/graphs" so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph* +to represent your model, and then create a Tensorflow *session* to run the graph. + +In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. + +To install tensorflow on Unix/Linux systems, use pip as +!bc pycod +pip3 install tensorflow +!ec +and/or if you use _anaconda_, just write (or install from the graphical user interface) +(current release of CPU-only TensorFlow) +!bc pycod +conda create -n tf tensorflow +conda activate tf +!ec +To install the current release of GPU TensorFlow +!bc pycod +conda create -n tf-gpu tensorflow-gpu +conda activate tf-gpu +!ec + +!split +===== Using Keras ===== + +Keras is a high level "neural network":"https://en.wikipedia.org/wiki/Application_programming_interface" +that supports Tensorflow, CTNK and Theano as backends. +If you have Anaconda installed you may run the following command +!bc pycod +conda install keras +!ec +You can look up the "instructions here":"https://keras.io/" for more information. + +We will to a large extent use _keras_ in this course. + +!split +===== Collect and pre-process data ===== + +Let us look again at the MINST data set. + +!bc pycod +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +import tensorflow as tf +from sklearn import datasets + + +# ensure the same random numbers appear every time +np.random.seed(0) + +# display images in notebook +%matplotlib inline +plt.rcParams['figure.figsize'] = (12,12) + + +# download MNIST dataset +digits = datasets.load_digits() + +# define inputs and labels +inputs = digits.images +labels = digits.target + +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) +print("labels = (n_inputs) = " + str(labels.shape)) + + +# flatten the image +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 +n_inputs = len(inputs) +inputs = inputs.reshape(n_inputs, -1) +print("X = (n_inputs, n_features) = " + str(inputs.shape)) + + +# choose some random images to display +indices = np.arange(n_inputs) +random_indices = np.random.choice(indices, size=5) + +for i, image in enumerate(digits.images[random_indices]): + plt.subplot(1, 5, i+1) + plt.axis('off') + plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') + plt.title("Label: %d" % digits.target[random_indices[i]]) +plt.show() +!ec + +!bc pycod +from tensorflow.keras.layers import Input +from tensorflow.keras.models import Sequential #This allows appending layers to existing models +from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer +from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop) +from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2) +from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function + +from sklearn.model_selection import train_test_split + +# one-hot representation of labels +labels = to_categorical(labels) + +# split into train and test data +train_size = 0.8 +test_size = 1 - train_size +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, + test_size=test_size) +!ec + + + +!bc pycod + +epochs = 100 +batch_size = 100 +n_neurons_layer1 = 100 +n_neurons_layer2 = 50 +n_categories = 10 +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd): + model = Sequential() + model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd))) + model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd))) + model.add(Dense(n_categories, activation='softmax')) + + sgd = optimizers.SGD(lr=eta) + model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) + + return model +!ec + +!bc pycod +DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, + eta=eta, lmbd=lmbd) + DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) + scores = DNN.evaluate(X_test, Y_test) + + DNN_keras[i][j] = DNN + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Test accuracy: %.3f" % scores[1]) + print() +!ec + + + +!bc pycod +# optional +# visual representation of grid search +# uses seaborn heatmap, could probably do this in matplotlib +import seaborn as sns + +sns.set() + +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) + +for i in range(len(eta_vals)): + for j in range(len(lmbd_vals)): + DNN = DNN_keras[i][j] + + train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1] + test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1] + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Test Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() +!ec + + + +!split +===== The Breast Cancer Data, now with Keras ===== + +!bc pycod + +import tensorflow as tf +from tensorflow.keras.layers import Input +from tensorflow.keras.models import Sequential #This allows appending layers to existing models +from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer +from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop) +from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2) +from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function +import numpy as np +import matplotlib.pyplot as plt +import seaborn as sns +from sklearn.model_selection import train_test_split as splitter +from sklearn.datasets import load_breast_cancer +import pickle +import os + + +"""Load breast cancer dataset""" + +np.random.seed(0) #create same seed for random number every time + +cancer=load_breast_cancer() #Download breast cancer dataset + +inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters) +outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant) +labels=cancer.feature_names[0:30] + +print('The content of the breast cancer dataset is:') #Print information about the datasets +print(labels) +print('-------------------------') +print("inputs = " + str(inputs.shape)) +print("outputs = " + str(outputs.shape)) +print("labels = "+ str(labels.shape)) + +x=inputs #Reassign the Feature and Label matrices to other variables +y=outputs + +#%% + +# Visualisation of dataset (for correlation analysis) + +plt.figure() +plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral) +plt.xlabel('Mean radius',fontweight='bold') +plt.ylabel('Mean perimeter',fontweight='bold') +plt.show() + +plt.figure() +plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral) +plt.xlabel('Mean compactness',fontweight='bold') +plt.ylabel('Mean concavity',fontweight='bold') +plt.show() + + +plt.figure() +plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) +plt.xlabel('Mean radius',fontweight='bold') +plt.ylabel('Mean texture',fontweight='bold') +plt.show() + +plt.figure() +plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) +plt.xlabel('Mean perimeter',fontweight='bold') +plt.ylabel('Mean compactness',fontweight='bold') +plt.show() + + +# Generate training and testing datasets + +#Select features relevant to classification (texture,perimeter,compactness and symmetery) +#and add to input matrix + +temp1=np.reshape(x[:,1],(len(x[:,1]),1)) +temp2=np.reshape(x[:,2],(len(x[:,2]),1)) +X=np.hstack((temp1,temp2)) +temp=np.reshape(x[:,5],(len(x[:,5]),1)) +X=np.hstack((X,temp)) +temp=np.reshape(x[:,8],(len(x[:,8]),1)) +X=np.hstack((X,temp)) + +X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing + +y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy +y_test=to_categorical(y_test) + +del temp1,temp2,temp + +# %% + +# Define tunable parameters" + +eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser) +lamda=0.01 #Define hyperparameter +n_layers=2 #Define number of hidden layers in the model +n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer +epochs=100 #Number of reiterations over the input data +batch_size=100 #Number of samples per gradient update + +# %% + +"""Define function to return Deep Neural Network model""" + +def NN_model(inputsize,n_layers,n_neuron,eta,lamda): + model=Sequential() + for i in range(n_layers): #Run loop to add hidden layers to the model + if (i==0): #First layer requires input dimensions + model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize)) + else: #Subsequent layers are capable of automatic shape inferencing + model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda))) + model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob) + sgd=optimizers.SGD(lr=eta) + model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy']) + return model + + +Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function +Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for + +for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate + for j in range(len(eta)): #accuracy scores + DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda) + DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1) + Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1] + Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1] + + +def plot_data(x,y,data,title=None): + + # plot results + fontsize=16 + + + fig = plt.figure() + ax = fig.add_subplot(111) + cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1) + + cbar=fig.colorbar(cax) + cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize) + cbar.set_ticks([0,.2,.4,0.6,0.8,1.0]) + cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%']) + + # put text on matrix elements + for i, x_val in enumerate(np.arange(len(x))): + for j, y_val in enumerate(np.arange(len(y))): + c = "${0:.1f}\\%$".format( 100*data[j,i]) + ax.text(x_val, y_val, c, va='center', ha='center') + + # convert axis vaues to to string labels + x=[str(i) for i in x] + y=[str(i) for i in y] + + + ax.set_xticklabels(['']+x) + ax.set_yticklabels(['']+y) + + ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize) + ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize) + if title is not None: + ax.set_title(title) + + plt.tight_layout() + + plt.show() + +plot_data(eta,n_neuron,Train_accuracy, 'training') +plot_data(eta,n_neuron,Test_accuracy, 'testing') !ec + + + + !split ===== Building a neural network code ===== @@ -1326,1518 +2659,6 @@ scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000) !ec Not bad, but the results depend strongly on the learning reate. Try different learning rates. -!split -===== Lecture Thursday October 26 ===== - -!split -===== Developing a code for doing neural networks with back propagation ===== - -We repeat some of the elements discussed last week. The first part of -the material for Thursday was contained in the slides for last -week as well. We will repeat some of the topics here before we move into -applications to differential equations and other examples. - -One can identify a set of key steps when using neural networks to solve supervised learning problems: - -o Collect and pre-process data -o Define model and architecture -o Choose cost function and optimizer -o Train the model -o Evaluate model performance on test data -o Adjust hyperparameters (if necessary, network architecture) - -!split -===== Collect and pre-process data ===== - -Here we will be using the MNIST dataset, which is readily available through the _scikit-learn_ -package. You may also find it for example "here":"http://yann.lecun.com/exdb/mnist/". -The *MNIST* (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size $28\times 28$ pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\times 8$ collected and processed from this database. - -To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each -row represents an *input*, in this case a handwritten digit, and -each column represents a *feature*, in this case a pixel. The -correct answers, also known as *labels* or *targets* are -represented as a 1D array of integers -$Y = (n_{inputs}) = (5, 3, 1, 8,...)$. - -As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: - -$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ - -and the targets would be: - -$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ - -Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. - - -!bc pycod -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# flatten the image -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 -n_inputs = len(inputs) -inputs = inputs.reshape(n_inputs, -1) -print("X = (n_inputs, n_features) = " + str(inputs.shape)) - - -# choose some random images to display -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -!ec - -!split -===== Train and test datasets ===== - -Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. - -We will reserve $80 \%$ of our dataset for training and $20 \%$ for testing. - -It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. - - -!bc pycod -from sklearn.model_selection import train_test_split - -# one-liner from scikit-learn library -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) - -# equivalently in numpy -def train_test_split_numpy(inputs, labels, train_size, test_size): - n_inputs = len(inputs) - inputs_shuffled = inputs.copy() - labels_shuffled = labels.copy() - - np.random.shuffle(inputs_shuffled) - np.random.shuffle(labels_shuffled) - - train_end = int(n_inputs*train_size) - X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] - Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] - - return X_train, X_test, Y_train, Y_test - -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size) - -print("Number of training images: " + str(len(X_train))) -print("Number of test images: " + str(len(X_test))) -!ec - -!split -===== Define model and architecture ===== - -Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have - -$$ z = \sum_{i=1}^n w_i a_i ,$$ - -$$ y = f(z) ,$$ - -where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer -and $w_i$ is the weight to input $i$. -The activation of the neurons in the input layer is just the features (e.g. a pixel value). - -The simplest activation function for a neuron is the *Heaviside* function: - -$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ - -A feed-forward neural network with this activation is known as a *perceptron*. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), -and we call these architectures *multiclass perceptrons*. - -However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. - -Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function $\sigma(x)$: - -$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$ - -which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions. - -!split -===== Layers ===== - -* Input -Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. - -* Hidden layer -We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. - -* Output -If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. - -For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. - -Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: - -$$ P(\text{class $j$} \mid \text{input $\bm{a}$}) = \frac{\exp{(\bm{a}^T \bm{w}_j)}} -{\sum_{c=0}^{9} \exp{(\bm{a}^T \bm{w}_c)}} ,$$ - -i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\bm{a}$, with $\bm{w}_j$ the weights of neuron $j$ to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: - -$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ - -Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. - -!split -===== Weights and biases ===== - -Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. - -Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: - -$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ - -The bias weights $\bm{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle. -!bc pycod -# building our neural network - -n_inputs, n_features = X_train.shape -n_hidden_neurons = 50 -n_categories = 10 - -# we make the weights normally distributed using numpy.random.randn - -# weights and bias in the hidden layer -hidden_weights = np.random.randn(n_features, n_hidden_neurons) -hidden_bias = np.zeros(n_hidden_neurons) + 0.01 - -# weights and bias in the output layer -output_weights = np.random.randn(n_hidden_neurons, n_categories) -output_bias = np.zeros(n_categories) + 0.01 -!ec - -!split -===== Feed-forward pass ===== - -Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: - -$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ - -this is then passed through our activation function - -$$ a_{j}^{l} = f(z_{j}^{l}) .$$ - -We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: - -$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ - -Finally we calculate the output of neuron $j$ in the output layer using the softmax function: - -$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ - -!split -===== Matrix multiplications ===== - -Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden -layer have the dimensions -$W_{hidden} = (n_{features}, n_{hidden})$, -we can easily feed the network all our training data in one go by taking the matrix product - -$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ - -and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: - -$$ \bm{z}^{l} = \bm{X} \bm{W}^{l} + \bm{b}^{l} ,$$ - -meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: - -$$ \bm{a}^{l} = f(\bm{z}^l) .$$ - -This is fed to the output layer: - -$$ \bm{z}^{L} = \bm{a}^{L} \bm{W}^{L} + \bm{b}^{L} .$$ - -Finally we receive our output values for each image and each category by passing it through the softmax function: - -$$ output = softmax (\bm{z}^{L}) = (n_{inputs}, n_{categories}) .$$ - - -!bc pycod -# setup the feed-forward pass, subscript h = hidden layer - -def sigmoid(x): - return 1/(1 + np.exp(-x)) - -def feed_forward(X): - # weighted sum of inputs to the hidden layer - z_h = np.matmul(X, hidden_weights) + hidden_bias - # activation in the hidden layer - a_h = sigmoid(z_h) - - # weighted sum of inputs to the output layer - z_o = np.matmul(a_h, output_weights) + output_bias - # softmax output - # axis 0 holds each input and axis 1 the probabilities of each category - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - return probabilities - -probabilities = feed_forward(X_train) -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape)) -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0])) -print("probabilities sum up to: " + str(probabilities[0].sum())) -print() - -# we obtain a prediction by taking the class with the highest likelihood -def predict(X): - probabilities = feed_forward(X) - return np.argmax(probabilities, axis=1) - -predictions = predict(X_train) -print("predictions = (n_inputs) = " + str(predictions.shape)) -print("prediction for image 0: " + str(predictions[0])) -print("correct label for image 0: " + str(Y_train[0])) -!ec - -!split -===== Choose cost function and optimizer ===== - -To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the *loss* function, and the function -that gives the total error of our network across all samples the *cost* function. -A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. - -In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: - -$$ y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ - - -$$ y = 1 \quad \rightarrow \quad \bm{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ - - -i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. - -Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. -We define the cost function $\mathcal{C}$ as a sum over the cross-entropy loss for each point $\bm{x}_i$ in the dataset. - -In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category $c'$ -(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\bm{\theta}$ represents the parameters of our network, i.e. all the weights and biases. - - -!split -===== Optimizing the cost function ===== - -The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. -Each parameter $\theta$ is iteratively adjusted according to the rule - -$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ - -where $\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. - -A simple and effective improvement is a variant called *Batch Gradient Descent*. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a *minibatch*. -If there are $N$ data points and we have a minibatch size of $M$, the total number of batches -is $N/M$. -We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: - -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ - -i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. - -This has two important benefits: -o Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. -o It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. - -The various optmization methods, with codes and algorithms, are discussed in our lectures on "Gradient descent approaches":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". - -!split -===== Regularization ===== - -It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces *overfitting*. - -We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: - -$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \bm{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ - -i.e. we sum up all the weights squared. The factor $\lambda$ is known as a regularization parameter. - - -In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has $(64 + 1)\times 50=3250$ weights in -the hidden layer and $(50 + 1)\times 10=510$ weights to the output -layer ($+1$ for the bias), and the gradient must be calculated for -every parameter. We use the *backpropagation* algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. - - -!split -===== Matrix multiplication ===== - -To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with $\bm{t}$ being our targets, - -$$ \delta_L = \bm{t} - \bm{y} = (n_{inputs}, n_{categories}) .$$ - -The gradient for the output weights is calculated as - -$$ \nabla W_{L} = \bm{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ - -where $\bm{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. - -The gradient with respect to the output bias is then - -$$ \nabla \bm{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ - -The error in the hidden layer is - -$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ - -where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol $\circ$ denotes -the *Hadamard product*, meaning element-wise multiplication. - -This again gives us the gradients in the hidden layer: - -$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ - -$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ - - -!bc pycod -# to categorical turns our integer vector into a onehot representation -from sklearn.metrics import accuracy_score - -# one-hot in numpy -def to_categorical_numpy(integer_vector): - n_inputs = len(integer_vector) - n_categories = np.max(integer_vector) + 1 - onehot_vector = np.zeros((n_inputs, n_categories)) - onehot_vector[range(n_inputs), integer_vector] = 1 - - return onehot_vector - -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test) -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test) - -def feed_forward_train(X): - # weighted sum of inputs to the hidden layer - z_h = np.matmul(X, hidden_weights) + hidden_bias - # activation in the hidden layer - a_h = sigmoid(z_h) - - # weighted sum of inputs to the output layer - z_o = np.matmul(a_h, output_weights) + output_bias - # softmax output - # axis 0 holds each input and axis 1 the probabilities of each category - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - # for backpropagation need activations in hidden and output layers - return a_h, probabilities - -def backpropagation(X, Y): - a_h, probabilities = feed_forward_train(X) - - # error in the output layer - error_output = probabilities - Y - # error in the hidden layer - error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h) - - # gradients for the output layer - output_weights_gradient = np.matmul(a_h.T, error_output) - output_bias_gradient = np.sum(error_output, axis=0) - - # gradient for the hidden layer - hidden_weights_gradient = np.matmul(X.T, error_hidden) - hidden_bias_gradient = np.sum(error_hidden, axis=0) - - return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient - -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) - -eta = 0.01 -lmbd = 0.01 -for i in range(1000): - # calculate gradients - dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot) - - # regularization term gradients - dWo += lmbd * output_weights - dWh += lmbd * hidden_weights - - # update weights and biases - output_weights -= eta * dWo - output_bias -= eta * dBo - hidden_weights -= eta * dWh - hidden_bias -= eta * dBh - -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) -!ec - -!split -===== Improving performance ===== - -As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. - -The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\lambda = 10^{-6},...,10^{-0}$. - -Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period -going through the entire dataset ($n/M$ batches) an *epoch*. - -If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this "video":"https://youtu.be/F1ka6a13S9I". You can find a summary of the video "here":"https://kevinzakka.github.io/2016/09/26/applying-deep-learning/". - -!split -===== Full object-oriented implementation ===== - -It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. - - -!bc pycod -class NeuralNetwork: - def __init__( - self, - X_data, - Y_data, - n_hidden_neurons=50, - n_categories=10, - epochs=10, - batch_size=100, - eta=0.1, - lmbd=0.0): - - self.X_data_full = X_data - self.Y_data_full = Y_data - - self.n_inputs = X_data.shape[0] - self.n_features = X_data.shape[1] - self.n_hidden_neurons = n_hidden_neurons - self.n_categories = n_categories - - self.epochs = epochs - self.batch_size = batch_size - self.iterations = self.n_inputs // self.batch_size - self.eta = eta - self.lmbd = lmbd - - self.create_biases_and_weights() - - def create_biases_and_weights(self): - self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons) - self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01 - - self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories) - self.output_bias = np.zeros(self.n_categories) + 0.01 - - def feed_forward(self): - # feed-forward for training - self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias - self.a_h = sigmoid(self.z_h) - - self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias - - exp_term = np.exp(self.z_o) - self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - def feed_forward_out(self, X): - # feed-forward for output - z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias - a_h = sigmoid(z_h) - - z_o = np.matmul(a_h, self.output_weights) + self.output_bias - - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - return probabilities - - def backpropagation(self): - error_output = self.probabilities - self.Y_data - error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h) - - self.output_weights_gradient = np.matmul(self.a_h.T, error_output) - self.output_bias_gradient = np.sum(error_output, axis=0) - - self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden) - self.hidden_bias_gradient = np.sum(error_hidden, axis=0) - - if self.lmbd > 0.0: - self.output_weights_gradient += self.lmbd * self.output_weights - self.hidden_weights_gradient += self.lmbd * self.hidden_weights - - self.output_weights -= self.eta * self.output_weights_gradient - self.output_bias -= self.eta * self.output_bias_gradient - self.hidden_weights -= self.eta * self.hidden_weights_gradient - self.hidden_bias -= self.eta * self.hidden_bias_gradient - - def predict(self, X): - probabilities = self.feed_forward_out(X) - return np.argmax(probabilities, axis=1) - - def predict_probabilities(self, X): - probabilities = self.feed_forward_out(X) - return probabilities - - def train(self): - data_indices = np.arange(self.n_inputs) - - for i in range(self.epochs): - for j in range(self.iterations): - # pick datapoints with replacement - chosen_datapoints = np.random.choice( - data_indices, size=self.batch_size, replace=False - ) - - # minibatch training data - self.X_data = self.X_data_full[chosen_datapoints] - self.Y_data = self.Y_data_full[chosen_datapoints] - - self.feed_forward() - self.backpropagation() -!ec - -!split -===== Evaluate model performance on test data ===== - -To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the *accuracy* score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. - -$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ - -where $I$ is the indicator function, $1$ if $\tilde{y}_i = y_i$ and $0$ otherwise. - - -!bc pycod -epochs = 100 -batch_size = 100 - -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, - n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) -dnn.train() -test_predict = dnn.predict(X_test) - -# accuracy score from scikit library -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) - -# equivalent in numpy -def accuracy_score_numpy(Y_test, Y_pred): - return np.sum(Y_test == Y_pred) / len(Y_test) - -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict)) -!ec - -!split -===== Adjust hyperparameters ===== - -We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\%$ ($2\%$ error rate). - -!bc pycod -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -# store the models for later use -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -# grid search -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, - n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) - dnn.train() - - DNN_numpy[i][j] = dnn - - test_predict = dnn.predict(X_test) - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) - print() -!ec - -!split -===== Visualization ===== - -!bc pycod -# visual representation of grid search -# uses seaborn heatmap, you can also do this with matplotlib imshow -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - dnn = DNN_numpy[i][j] - - train_pred = dnn.predict(X_train) - test_pred = dnn.predict(X_test) - - train_accuracy[i][j] = accuracy_score(Y_train, train_pred) - test_accuracy[i][j] = accuracy_score(Y_test, test_pred) - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - -!split -===== scikit-learn implementation ===== - -_scikit-learn_ focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -*MPLRegressor*, and Multi Layer Perceptron outputting labels, -*MLPClassifier*. We will see how simple it is to use these classes. - -_scikit-learn_ implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. - -!bc pycod -from sklearn.neural_network import MLPClassifier -# store models for later use -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', - alpha=lmbd, learning_rate_init=eta, max_iter=epochs) - dnn.fit(X_train, Y_train) - - DNN_scikit[i][j] = dnn - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Accuracy score on test set: ", dnn.score(X_test, Y_test)) - print() -!ec - - -!split -===== Visualization ===== -!bc pycod -# optional -# visual representation of grid search -# uses seaborn heatmap, could probably do this in matplotlib -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - dnn = DNN_scikit[i][j] - - train_pred = dnn.predict(X_train) - test_pred = dnn.predict(X_test) - - train_accuracy[i][j] = accuracy_score(Y_train, train_pred) - test_accuracy[i][j] = accuracy_score(Y_test, test_pred) - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - - - -!split -===== Building neural networks in Tensorflow and Keras ===== - -Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. - -In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. - -!split -===== Tensorflow ===== - -Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. - -Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. - -"Tensorflow uses":"https://www.tensorflow.org/guide/graphs" so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph* -to represent your model, and then create a Tensorflow *session* to run the graph. - -In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. - -To install tensorflow on Unix/Linux systems, use pip as -!bc pycod -pip3 install tensorflow -!ec -and/or if you use _anaconda_, just write (or install from the graphical user interface) -(current release of CPU-only TensorFlow) -!bc pycod -conda create -n tf tensorflow -conda activate tf -!ec -To install the current release of GPU TensorFlow -!bc pycod -conda create -n tf-gpu tensorflow-gpu -conda activate tf-gpu -!ec - -!split -===== Using Keras ===== - -Keras is a high level "neural network":"https://en.wikipedia.org/wiki/Application_programming_interface" -that supports Tensorflow, CTNK and Theano as backends. -If you have Anaconda installed you may run the following command -!bc pycod -conda install keras -!ec -You can look up the "instructions here":"https://keras.io/" for more information. - -We will to a large extent use _keras_ in our examples.. - -!split -===== Collect and pre-process data ===== - -Let us look again at the MINST data set. - -!bc pycod -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -import tensorflow as tf -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# flatten the image -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 -n_inputs = len(inputs) -inputs = inputs.reshape(n_inputs, -1) -print("X = (n_inputs, n_features) = " + str(inputs.shape)) - - -# choose some random images to display -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -!ec - -!bc pycod -from tensorflow.keras.layers import Input -from tensorflow.keras.models import Sequential #This allows appending layers to existing models -from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer -from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop) -from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2) -from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function - -from sklearn.model_selection import train_test_split - -# one-hot representation of labels -labels = to_categorical(labels) - -# split into train and test data -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) -!ec - - - -!bc pycod - -epochs = 100 -batch_size = 100 -n_neurons_layer1 = 100 -n_neurons_layer2 = 50 -n_categories = 10 -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd): - model = Sequential() - model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd))) - model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd))) - model.add(Dense(n_categories, activation='softmax')) - - sgd = optimizers.SGD(lr=eta) - model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) - - return model -!ec - -!bc pycod -DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, - eta=eta, lmbd=lmbd) - DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) - scores = DNN.evaluate(X_test, Y_test) - - DNN_keras[i][j] = DNN - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % scores[1]) - print() -!ec - - - -!bc pycod -# optional -# visual representation of grid search -# uses seaborn heatmap, could probably do this in matplotlib -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - DNN = DNN_keras[i][j] - - train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1] - test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1] - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - - - -!split -===== The Breast Cancer Data, now with Keras ===== - -!bc pycod - -import tensorflow as tf -from tensorflow.keras.layers import Input -from tensorflow.keras.models import Sequential #This allows appending layers to existing models -from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer -from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop) -from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2) -from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function -import numpy as np -import matplotlib.pyplot as plt -import seaborn as sns -from sklearn.model_selection import train_test_split as splitter -from sklearn.datasets import load_breast_cancer -import pickle -import os - - -"""Load breast cancer dataset""" - -np.random.seed(0) #create same seed for random number every time - -cancer=load_breast_cancer() #Download breast cancer dataset - -inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters) -outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant) -labels=cancer.feature_names[0:30] - -print('The content of the breast cancer dataset is:') #Print information about the datasets -print(labels) -print('-------------------------') -print("inputs = " + str(inputs.shape)) -print("outputs = " + str(outputs.shape)) -print("labels = "+ str(labels.shape)) - -x=inputs #Reassign the Feature and Label matrices to other variables -y=outputs - -#%% - -# Visualisation of dataset (for correlation analysis) - -plt.figure() -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral) -plt.xlabel('Mean radius',fontweight='bold') -plt.ylabel('Mean perimeter',fontweight='bold') -plt.show() - -plt.figure() -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral) -plt.xlabel('Mean compactness',fontweight='bold') -plt.ylabel('Mean concavity',fontweight='bold') -plt.show() - - -plt.figure() -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) -plt.xlabel('Mean radius',fontweight='bold') -plt.ylabel('Mean texture',fontweight='bold') -plt.show() - -plt.figure() -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) -plt.xlabel('Mean perimeter',fontweight='bold') -plt.ylabel('Mean compactness',fontweight='bold') -plt.show() - - -# Generate training and testing datasets - -#Select features relevant to classification (texture,perimeter,compactness and symmetery) -#and add to input matrix - -temp1=np.reshape(x[:,1],(len(x[:,1]),1)) -temp2=np.reshape(x[:,2],(len(x[:,2]),1)) -X=np.hstack((temp1,temp2)) -temp=np.reshape(x[:,5],(len(x[:,5]),1)) -X=np.hstack((X,temp)) -temp=np.reshape(x[:,8],(len(x[:,8]),1)) -X=np.hstack((X,temp)) - -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing - -y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy -y_test=to_categorical(y_test) - -del temp1,temp2,temp - -# %% - -# Define tunable parameters" - -eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser) -lamda=0.01 #Define hyperparameter -n_layers=2 #Define number of hidden layers in the model -n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer -epochs=100 #Number of reiterations over the input data -batch_size=100 #Number of samples per gradient update - -# %% - -"""Define function to return Deep Neural Network model""" - -def NN_model(inputsize,n_layers,n_neuron,eta,lamda): - model=Sequential() - for i in range(n_layers): #Run loop to add hidden layers to the model - if (i==0): #First layer requires input dimensions - model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize)) - else: #Subsequent layers are capable of automatic shape inferencing - model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda))) - model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob) - sgd=optimizers.SGD(lr=eta) - model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy']) - return model - - -Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function -Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for - -for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate - for j in range(len(eta)): #accuracy scores - DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda) - DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1) - Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1] - Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1] - - -def plot_data(x,y,data,title=None): - - # plot results - fontsize=16 - - - fig = plt.figure() - ax = fig.add_subplot(111) - cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1) - - cbar=fig.colorbar(cax) - cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize) - cbar.set_ticks([0,.2,.4,0.6,0.8,1.0]) - cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%']) - - # put text on matrix elements - for i, x_val in enumerate(np.arange(len(x))): - for j, y_val in enumerate(np.arange(len(y))): - c = "${0:.1f}\\%$".format( 100*data[j,i]) - ax.text(x_val, y_val, c, va='center', ha='center') - - # convert axis vaues to to string labels - x=[str(i) for i in x] - y=[str(i) for i in y] - - - ax.set_xticklabels(['']+x) - ax.set_yticklabels(['']+y) - - ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize) - ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize) - if title is not None: - ax.set_title(title) - - plt.tight_layout() - - plt.show() - -plot_data(eta,n_neuron,Train_accuracy, 'training') -plot_data(eta,n_neuron,Test_accuracy, 'testing') - -!ec - - - - - - -!split -===== Fine-tuning neural network hyperparameters ===== - -The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are interconnected), -but even in a simple FFNN you can change the number of layers, the -number of neurons per layer, the type of activation function to use in -each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you -know what combination of hyperparameters is the best for your task? - -* You can use grid search with cross-validation to find the right hyperparameters. - -However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. - - -* You can use randomized search. -* Or use tools like "Oscar":"http://oscar.calldesk.ai/", which implements more complex algorithms to help you find a good set of hyperparameters quickly. - -!split -===== Hidden layers ===== - - - -For many problems you can start with just one or two hidden layers and it will work just fine. -For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a -few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of -neurons, in roughly the same amount of training time. - -For more complex problems, you can gradually -ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such -as large image classification or speech recognition, typically require networks with dozens of layers -and they need a huge amount -of training data. However, you will rarely have to train such networks from scratch: it is much more -common to reuse parts of a pretrained state-of-the-art network that performs a similar task. - - - - -!split -===== Which activation function should I use? ===== - -The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. - - -Unfortunately for us, the gradients often get smaller and smaller as the -algorithm progresses down to the first hidden layers. As a result, the -GD update leaves the lower layer connection weights -virtually unchanged, and training never converges to a good -solution. This is known in the literature as -_the vanishing gradients problem_. - -In other cases, the opposite can happen, namely the the gradients can grow bigger and -bigger. The result is that many of the layers get large updates of the -weights the -algorithm diverges. This is the _exploding gradients problem_, which is -mostly encountered in recurrent neural networks. More generally, deep -neural networks suffer from unstable gradients, different layers may -learn at widely different speeds - - - -!split -===== Is the Logistic activation function (Sigmoid) our choice? ===== - -Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. - -A paper titled "Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio":"http://proceedings.mlr.press/v9/glorot10a.html" found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. - -They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). - - -!split -===== The derivative of the Logistic funtion ===== - -Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. - -In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. - - - -One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). - - -!split -===== The RELU function family ===== - -The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. - -In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. - -To solve this problem, nowadays practitioners use a variant of the ReLU -function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function - - -!bt -\[ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -\] -!et - -!split -===== Which activation function should we use? ===== - -In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than $\tanh$ which in turn performs better -than the logistic function. - -If runtime -performance is an issue, then you may opt for the leaky ReLU function over the -ELU function If you don’t -want to tweak yet another hyperparameter, you may just use the default -$\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have -spare time and computing power, you can use cross-validation or -bootstrap to evaluate other activation functions. - - -!split -===== More on activation functions, output layers ===== - -In most cases you can use the ReLU activation function in the hidden layers (or one of its variants). - -It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck. - -_For the output layer:_ - -* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive). -* For regression tasks, you can simply use no activation function at all. - - - - -!split -===== Batch Normalization ===== - -Batch Normalization -aims to address the vanishing/exploding gradients problems, and more generally the problem that the -distribution of each layer’s inputs changes during training, as the parameters of the previous layers change. - -The technique consists of adding an operation in the model just before the activation function of each -layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new -parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model -learn the optimal scale and mean of the inputs for each layer. -In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and -standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current -mini-batch, from this the name batch normalization. - -!split -===== Dropout ===== - -It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but -excluding the output neurons) has a probability $p$ of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active during the next step. - -The -hyperparameter $p$ is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore. - It is viewed as one of the most popular regularization techniques. - -!split -===== Gradient Clipping ===== - -A popular technique to lessen the exploding gradients problem is to simply clip the gradients during -backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural -networks). - -This technique is called Gradient Clipping. - -In general however, Batch -Normalization is preferred. - -!split -===== A very nice website on Neural Networks ===== - -You may find this "website":"https://playground.tensorflow.org/#activation=tanh&batchSize=10&dataset=circle®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=4,2&seed=0.29243&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false" very useful. - -!split -===== A top-down perspective on Neural networks ===== - - -The first thing we would like to do is divide the data into two or three -parts. A training set, a validation or dev (development) set, and a -test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: - - -* Estimate optimal error rate - -* Minimize underfitting (bias) on training data set. - -* Make sure you are not overfitting. - -If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. - -However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. - -!split -===== Limitations of supervised learning with deep networks ===== - -Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). - -Here we list some of the important limitations of supervised neural network based models. - - - -* _Need labeled data_. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images). -* _Supervised neural networks are extremely data intensive._ DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs. -* _Homogeneous data._ Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e.~some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types. -* _Many problems are not about prediction._ In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science. - -Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems. - -