diff --git a/doc/pub/week40/html/._week40-bs000.html b/doc/pub/week40/html/._week40-bs000.html index 4c47dc9ba..a7a4a3ac7 100644 --- a/doc/pub/week40/html/._week40-bs000.html +++ b/doc/pub/week40/html/._week40-bs000.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
-

 

 

 

- - - -
-

Week 40: From Stochastic Gradient Descent to Neural networks

+
+

Week 40: From Stochastic Gradient Descent to Neural networks

+
-

-

Morten Hjorth-Jensen [1, 2]
- -

+

+[1] Department of Physics, University of Oslo, Norway +
+
+[2] Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA +
+
+
+

Nov 2, 2021

+
+
-
[1] Department of Physics, University of Oslo, Norway
-
[2] Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA
-
-

-

Oct 9, 2021

-
-

Read »

@@ -366,25 +354,18 @@ MathJax.Hub.Config({
  • »
  • -
    - - -
    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week40/html/._week40-bs001.html b/doc/pub/week40/html/._week40-bs001.html index 682a4d5fa..e4c8686da 100644 --- a/doc/pub/week40/html/._week40-bs001.html +++ b/doc/pub/week40/html/._week40-bs001.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - -
    -
    -

     

     

     

    - -

    Plan for week 40

    - -Reading suggestions for both days: Aurelien Geron's chapter 10 and Hastie et al chapter 11. +

    Reading suggestions for both days: Aurelien Geron's chapter 10 and Hastie et al chapter 11. For Stochastic Gradient Descent, we recommend chapter 4 of Geron's text. For neural networks we recommend Goodfellow et al chapters 6 and 7 and Bishop 5.1-5.4 +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs002.html b/doc/pub/week40/html/._week40-bs002.html index 3d0d318bc..80e8d8432 100644 --- a/doc/pub/week40/html/._week40-bs002.html +++ b/doc/pub/week40/html/._week40-bs002.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Overview video on Stochastic Gradient Descent

    -

    What is Stochastic Gradient Descent -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs003.html b/doc/pub/week40/html/._week40-bs003.html index 83a4d133f..95d3d1689 100644 --- a/doc/pub/week40/html/._week40-bs003.html +++ b/doc/pub/week40/html/._week40-bs003.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Batches and mini-batches

    -

    -In gradient descent we compute the cost function and its gradient for all data points we have. +

    In gradient descent we compute the cost function and its gradient for all data points we have.

    -

    -In large-scale applications such as the ILSVRC challenge, the +

    In large-scale applications such as the ILSVRC challenge, the training data can have on order of millions of examples. Hence, it seems wasteful to compute the full cost function over the entire training set in order to perform only a single parameter update. A @@ -334,8 +320,8 @@ gradient over batches of the training data. For example, in current a typical batch could contain some thousand examples from an entire training set of several millions. This batch is then used to perform a parameter update. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs004.html b/doc/pub/week40/html/._week40-bs004.html index bf45af70f..5a6fd731f 100644 --- a/doc/pub/week40/html/._week40-bs004.html +++ b/doc/pub/week40/html/._week40-bs004.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Stochastic Gradient Descent (SGD)

    -

    -In stochastic gradient descent, the extreme case is the case where we +

    In stochastic gradient descent, the extreme case is the case where we have only one batch, that is we include the whole data set. +

    -

    -This process is called Stochastic Gradient +

    This process is called Stochastic Gradient Descent (SGD) (or also sometimes on-line gradient descent). This is relatively less common to see because in practice due to vectorized code optimizations it can be computationally much more efficient to @@ -342,11 +329,10 @@ usually based on memory constraints (if any), or set to some value, e.g. 32, 64 or 128. We use powers of 2 in practice because many vectorized operation implementations work faster when their inputs are sized in powers of 2. +

    -

    -In our notes with SGD we mean stochastic gradient descent with mini-batches. +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs005.html b/doc/pub/week40/html/._week40-bs005.html index b7605413a..c6dcd9f51 100644 --- a/doc/pub/week40/html/._week40-bs005.html +++ b/doc/pub/week40/html/._week40-bs005.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Stochastic Gradient Descent

    -

    -Stochastic gradient descent (SGD) and variants thereof address some of +

    Stochastic gradient descent (SGD) and variants thereof address some of the shortcomings of the Gradient descent method discussed above. +

    -

    -The underlying idea of SGD comes from the observation that the cost +

    The underlying idea of SGD comes from the observation that the cost function, which we want to minimize, can almost always be written as a sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

    $$ C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, \mathbf{\beta}). $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs006.html b/doc/pub/week40/html/._week40-bs006.html index 18c0d7b3f..052afafbe 100644 --- a/doc/pub/week40/html/._week40-bs006.html +++ b/doc/pub/week40/html/._week40-bs006.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Computation of gradients

    -

    -This in turn means that the gradient can be +

    This in turn means that the gradient can be computed as a sum over \( i \)-gradients +

    $$ \nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, \mathbf{\beta}). $$ -

    -Stochasticity/randomness is introduced by only taking the +

    Stochasticity/randomness is introduced by only taking the gradient on a subset of the data called minibatches. If there are \( n \) data points and the size of each minibatch is \( M \), there will be \( n/M \) minibatches. We denote these minibatches by \( B_k \) where \( k=1,\cdots,n/M \). +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs007.html b/doc/pub/week40/html/._week40-bs007.html index 7cee0cf65..72f9fc4df 100644 --- a/doc/pub/week40/html/._week40-bs007.html +++ b/doc/pub/week40/html/._week40-bs007.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    SGD example

    -

    -As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) and we choose to have \( M=5 \) minibathces, then each minibatch contains two data points. In particular we have \( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = @@ -330,11 +317,12 @@ then each minibatch contains two data points. In particular we have have only a single batch with all data points and on the other extreme, you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e \( B_k = \mathbf{x}_k \). +

    -

    -The idea is now to approximate the gradient by replacing the sum over +

    The idea is now to approximate the gradient by replacing the sum over all data points with a sum over the data points in one the minibatches picked at random in each gradient descent step +

    $$ \nabla_{\beta} C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, @@ -342,7 +330,7 @@ C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, c_i(\mathbf{x}_i, \mathbf{\beta}). $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs008.html b/doc/pub/week40/html/._week40-bs008.html index d678f83c2..db6766213 100644 --- a/doc/pub/week40/html/._week40-bs008.html +++ b/doc/pub/week40/html/._week40-bs008.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    The gradient step

    -

    -Thus a gradient descent step now looks like +

    Thus a gradient descent step now looks like

    $$ \beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, \mathbf{\beta}) $$ -

    -where \( k \) is picked at random with equal +

    where \( k \) is picked at random with equal probability from \( [1,n/M] \). An iteration over the number of minibathces (n/M) is commonly referred to as an epoch. Thus it is typical to choose a number of epochs and for each epoch iterate over the number of minibatches, as exemplified in the code below. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs009.html b/doc/pub/week40/html/._week40-bs009.html index 98b02a100..b5c482792 100644 --- a/doc/pub/week40/html/._week40-bs009.html +++ b/doc/pub/week40/html/._week40-bs009.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Simple example code

    -

    -

    import numpy as np 
    +
    +
    +
    +
    +
    +
    import numpy as np 
     
     n = 100 #100 datapoints 
     M = 5   #size of each mini-batche
    @@ -338,17 +330,30 @@ j = 0
             #Compute the gradient using the data in minibatch Bk
             #Compute new suggestion for 
             j += 1
    -
    -

    -Taking the gradient only on a subset of the data has two important +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Taking the gradient only on a subset of the data has two important benefits. First, it introduces randomness which decreases the chance that our opmization scheme gets stuck in a local minima. Second, if the size of the minibatches are small relative to the number of datapoints (\( M < n \)), the computation of the gradient is much cheaper since we sum over the datapoints in the \( k-th \) minibatch and not all \( n \) datapoints. +

    -

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs010.html b/doc/pub/week40/html/._week40-bs010.html index c0ea643ee..1c50beea0 100644 --- a/doc/pub/week40/html/._week40-bs010.html +++ b/doc/pub/week40/html/._week40-bs010.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    When do we stop?

    -

    -A natural question is when do we stop the search for a new minimum? +

    A natural question is when do we stop the search for a new minimum? One possibility is to compute the full gradient after a given number of epochs and check if the norm of the gradient is smaller than some threshold and stop if true. However, the condition that the gradient @@ -332,8 +319,8 @@ evaluate the cost function at this point, store the result and continue the search. If the test kicks in at a later stage we can compare the values of the cost function and keep the \( \beta \) that gave the lowest value. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs011.html b/doc/pub/week40/html/._week40-bs011.html index fdcd48991..3683b4fd8 100644 --- a/doc/pub/week40/html/._week40-bs011.html +++ b/doc/pub/week40/html/._week40-bs011.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Slightly different approach

    -

    -Another approach is to let the step length \( \gamma_j \) depend on the +

    Another approach is to let the step length \( \gamma_j \) depend on the number of epochs in such a way that it becomes very small after a reasonable time such that we do not move at all. +

    -

    -As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \). +

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    -

    -In this way we can fix the number of epochs, compute \( \beta \) and +

    In this way we can fix the number of epochs, compute \( \beta \) and evaluate the cost function at the end. Repeating the computation will give a different result since the scheme is random by design. Then we pick the final \( \beta \) that gives the lowest value of the cost function. +

    -

    -

    import numpy as np 
    +
    +
    +
    +
    +
    +
    import numpy as np 
     
     def step_length(t,t0,t1):
         return t0/(t+t1)
    @@ -363,11 +354,23 @@ j = 0
             j += 1
     
     print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    -
    -

    -We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters \( t_0 \) and \( t_1 \). +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters \( t_0 \) and \( t_1 \).

    -

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs012.html b/doc/pub/week40/html/._week40-bs012.html index e615e00a8..e7945abc7 100644 --- a/doc/pub/week40/html/._week40-bs012.html +++ b/doc/pub/week40/html/._week40-bs012.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Program for stochastic gradient

    -

    -

    # Importing various packages
    +
    +
    +
    +
    +
    +
    # Importing various packages
     from math import exp, sqrt
     from random import random, seed
     import numpy as np
    @@ -374,8 +366,8 @@ theta = np.for epoch in range(n_epochs):
         for i in range(m):
             random_index = np.random.randint(m)
    -        xi = X[random_index:random_index+1]
    -        yi = y[random_index:random_index+1]
    +        xi = X[random_index:random_index+m]
    +        yi = y[random_index:random_index+m]
             gradients = 2.0* xi.T @ ((xi @ theta)-yi)
             eta = learning_schedule(epoch*m+i)
             theta = theta - eta*gradients
    @@ -390,8 +382,22 @@ plt.xlabel(r
     plt.ylabel(r'$y$')
     plt.title(r'Random numbers ')
     plt.show()
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs013.html b/doc/pub/week40/html/._week40-bs013.html index 52bcdb722..d6293922f 100644 --- a/doc/pub/week40/html/._week40-bs013.html +++ b/doc/pub/week40/html/._week40-bs013.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Momentum based GD

    -

    -The stochastic gradient descent (SGD) is almost always used with a +

    The stochastic gradient descent (SGD) is almost always used with a momentum or inertia term that serves as a memory of the direction we are moving in parameter space. This is typically implemented as follows +

    $$ \begin{align} @@ -335,8 +323,7 @@ $$ \end{align} $$ -

    -where we have introduced a momentum parameter \( \gamma \), with +

    where we have introduced a momentum parameter \( \gamma \), with \( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to indicate the gradient is to be taken over a different mini-batch at each step. We call this algorithm gradient descent with momentum @@ -346,14 +333,14 @@ running average of recently encountered gradients and used in the averaging procedure. Consistent with this, when \( \gamma=0 \), this just reduces down to ordinary SGD as discussed earlier. An equivalent way of writing the updates is +

    $$ \Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), $$ -where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \). +

    where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs014.html b/doc/pub/week40/html/._week40-bs014.html index 6f76dc3e2..ebf860da0 100644 --- a/doc/pub/week40/html/._week40-bs014.html +++ b/doc/pub/week40/html/._week40-bs014.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    More on momentum based approaches

    -

    -Let us try to get more intuition from these equations. It is helpful +

    Let us try to get more intuition from these equations. It is helpful to consider a simple physical analogy with a particle of mass \( m \) moving in a viscous medium with drag coefficient \( \mu \) and potential \( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), then its motion is described by +

    $$ m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). $$ -

    -We can discretize this equation in the usual way to get +

    We can discretize this equation in the usual way to get

    $$ m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). $$ -

    -Rearranging this equation, we can rewrite this as +

    Rearranging this equation, we can rewrite this as

    $$ \Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs015.html b/doc/pub/week40/html/._week40-bs015.html index cca1c9cae..4de3964d0 100644 --- a/doc/pub/week40/html/._week40-bs015.html +++ b/doc/pub/week40/html/._week40-bs015.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Momentum parameter

    -

    -Notice that this equation is identical to previous one if we identify +

    Notice that this equation is identical to previous one if we identify the position of the particle, \( \mathbf{w} \), with the parameters \( \boldsymbol{\theta} \). This allows us to identify the momentum parameter and learning rate with the mass of the particle and the viscous drag as: +

    $$ \gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. $$ -

    -Thus, as the name suggests, the momentum parameter is proportional to +

    Thus, as the name suggests, the momentum parameter is proportional to the mass of the particle and effectively provides inertia. Furthermore, in the large viscosity/small learning rate limit, our memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). +

    -

    -Why is momentum useful? SGD momentum helps the gradient descent +

    Why is momentum useful? SGD momentum helps the gradient descent algorithm gain speed in directions with persistent but small gradients even in the presence of stochasticity, while suppressing oscillations in high-curvature directions. This becomes especially important in @@ -348,18 +335,19 @@ and narrow and steep in others. It has been argued that first-order methods (with appropriate initial conditions) can perform comparable to more expensive second order methods, especially in the context of complex deep learning models. +

    -

    -These beneficial properties of momentum can sometimes become even more +

    These beneficial properties of momentum can sometimes become even more pronounced by using a slight modification of the classical momentum algorithm called Nesterov Accelerated Gradient (NAG). +

    -

    -In the NAG algorithm, rather than calculating the gradient at the +

    In the NAG algorithm, rather than calculating the gradient at the current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one calculates the gradient at the expected value of the parameters given our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \). This yields the NAG update rule +

    $$ \begin{align} @@ -369,10 +357,8 @@ $$ \end{align} $$ -

    -One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \). +

    One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs016.html b/doc/pub/week40/html/._week40-bs016.html index a88f937a8..0e939d684 100644 --- a/doc/pub/week40/html/._week40-bs016.html +++ b/doc/pub/week40/html/._week40-bs016.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Second moment of the gradient

    -

    -In stochastic gradient descent, with and without momentum, we still +

    In stochastic gradient descent, with and without momentum, we still have to specify a schedule for tuning the learning rates \( \eta_t \) as a function of time. As discussed in the context of Newton's method, this presents a number of dilemmas. The learning rate is @@ -337,14 +324,14 @@ extremely large models. Ideally, we would like to be able to adaptively change the step size to match the landscape without paying the steep computational price of calculating or approximating Hessians. +

    -

    -Recently, a number of methods have been introduced that accomplish +

    Recently, a number of methods have been introduced that accomplish this by tracking not only the gradient, but also the second moment of the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and ADAM. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs017.html b/doc/pub/week40/html/._week40-bs017.html index 60bb6c9cf..ef9041568 100644 --- a/doc/pub/week40/html/._week40-bs017.html +++ b/doc/pub/week40/html/._week40-bs017.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    RMS prop

    -

    -In RMS prop, in addition to keeping a running average of the first +

    In RMS prop, in addition to keeping a running average of the first moment of the gradient, we also keep track of the second moment denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule for RMS prop is given by +

    $$ \begin{align} @@ -336,8 +324,7 @@ $$ \end{align} $$ -

    -where \( \beta \) controls the averaging time of the second moment and is +

    where \( \beta \) controls the averaging time of the second moment and is typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a small regularization constant to prevent divergences. Multiplication @@ -346,8 +333,8 @@ is clear from this formula that the learning rate is reduced in directions where the norm of the gradient is consistently large. This greatly speeds up the convergence by allowing us to use a larger learning rate for flat directions. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs018.html b/doc/pub/week40/html/._week40-bs018.html index 8a1f80ba4..2859f8531 100644 --- a/doc/pub/week40/html/._week40-bs018.html +++ b/doc/pub/week40/html/._week40-bs018.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    ADAM optimizer

    -

    -A related algorithm is the ADAM optimizer. In ADAM, we keep a running +

    A related algorithm is the ADAM optimizer. In ADAM, we keep a running average of both the first and second moment of the gradient and use this information to adaptively change the learning rate for different parameters. In addition to keeping a running average of the first and @@ -334,6 +321,7 @@ are estimating the first two moments of the gradient using a running average (denoted by the hats in the update rule below). The update rule for ADAM is given by (where multiplication and division are once again understood to be element-wise operations below) +

    $$ \begin{align} @@ -348,24 +336,24 @@ $$ \end{align} $$ -

    -where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +

    where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. +

    -

    -Like in RMSprop, the effective step size of a parameter depends on the +

    Like in RMSprop, the effective step size of a parameter depends on the magnitude of its gradient squared. To understand this better, let us rewrite this expression in terms of the variance \( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t - (\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The update rule for this parameter is given by +

    $$ \Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs019.html b/doc/pub/week40/html/._week40-bs019.html index efcf603e5..2e250dac9 100644 --- a/doc/pub/week40/html/._week40-bs019.html +++ b/doc/pub/week40/html/._week40-bs019.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Practical tips

    +

    Geron's text, see chapter 11, has several interesting discussions.

    -Geron's text, see chapter 11, has several interesting discussions. - -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs020.html b/doc/pub/week40/html/._week40-bs020.html index 66ff7d74a..d2491df8b 100644 --- a/doc/pub/week40/html/._week40-bs020.html +++ b/doc/pub/week40/html/._week40-bs020.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Automatic differentiation

    -

    -Automatic differentiation (AD), +

    Automatic differentiation (AD), also called algorithmic differentiation or computational differentiation,is a set of techniques to numerically evaluate the derivative of a function @@ -335,38 +322,42 @@ operations, derivatives of arbitrary order can be computed automatically, accurately to working precision, and using at most a small constant factor more arithmetic operations than the original program. +

    -

    -Automatic differentiation is neither: +

    Automatic differentiation is neither:

    - -Symbolic differentiation can lead to inefficient code and faces the +

    Symbolic differentiation can lead to inefficient code and faces the difficulty of converting a computer program into a single expression, while numerical differentiation can introduce round-off errors in the discretization process and cancellation +

    -

    -Python has tools for so-called automatic differentiation. +

    Python has tools for so-called automatic differentiation. Consider the following example +

    $$ f(x) = \sin\left(2\pi x + x^2\right) $$ -which has the following derivative +

    which has the following derivative

    $$ f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right) $$ -Using autograd we have +

    Using autograd we have

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     
     # To do elementwise differentiation:
     from autograd import elementwise_grad as egrad 
    @@ -400,8 +391,22 @@ plt.legend()
     plt.show()
     
     print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs021.html b/doc/pub/week40/html/._week40-bs021.html index 9e3792162..fd7becad0 100644 --- a/doc/pub/week40/html/._week40-bs021.html +++ b/doc/pub/week40/html/._week40-bs021.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Using autograd

    -

    -Here we +

    Here we experiment with what kind of functions Autograd is capable of finding the gradient of. The following Python functions are just meant to illustrate what Autograd can do, but please feel free to experiment with other, possibly more complicated, functions as well. +

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     
     def f1(x):
    @@ -348,8 +340,22 @@ a = 1.0
     # Compare with the analytical derivative, that is f1'(x) = 3*x**2 
     grad_analytical = 3*a**2
     print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical))
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs022.html b/doc/pub/week40/html/._week40-bs022.html index 518797738..ff3256338 100644 --- a/doc/pub/week40/html/._week40-bs022.html +++ b/doc/pub/week40/html/._week40-bs022.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Autograd with more complicated functions

    -

    -To differentiate with respect to two (or more) arguments of a Python +

    To differentiate with respect to two (or more) arguments of a Python function, Autograd need to know at which variable the function if being differentiated with respect to. +

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f2(x1,x2):
         return 3*x1**3 + x2*(x1 - 5) + 1
    @@ -362,11 +354,23 @@ f2_grad_x2_analytical = x1 print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
     print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
    -
    -

    -Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable. +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.

    -

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs023.html b/doc/pub/week40/html/._week40-bs023.html index 1a320c8c0..e39ab7ea5 100644 --- a/doc/pub/week40/html/._week40-bs023.html +++ b/doc/pub/week40/html/._week40-bs023.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    More complicated functions using the elements of their arguments directly

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f3(x): # Assumes x is an array of length 5 or higher
         return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
    @@ -341,16 +333,29 @@ f3_grad_analytical = np# Print the analytical gradient:
     print("The analytical gradient of f3 is: ", f3_grad_analytical)
    -
    -

    -Note that in this case, when sending an array as input argument, the +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Note that in this case, when sending an array as input argument, the output from Autograd is another array. This is the true gradient of the function, as opposed to the function in the previous example. By using arrays to represent the variables, the output from Autograd might be easier to work with, as the output is closer to what one could expect form a gradient-evaluting function. +

    -

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs024.html b/doc/pub/week40/html/._week40-bs024.html index 416008fa2..609b119cb 100644 --- a/doc/pub/week40/html/._week40-bs024.html +++ b/doc/pub/week40/html/._week40-bs024.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Functions using mathematical functions from Numpy

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f4(x):
         return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
    @@ -341,8 +333,22 @@ f4_grad_analytical = x# Print the analytical gradient:
     print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical))
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs025.html b/doc/pub/week40/html/._week40-bs025.html index 85abec724..043db0862 100644 --- a/doc/pub/week40/html/._week40-bs025.html +++ b/doc/pub/week40/html/._week40-bs025.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    More autograd

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f5(x):
         if x >= 0:
    @@ -338,8 +330,22 @@ x = 2.7
     
     # Print the computed derivative:
     print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs026.html b/doc/pub/week40/html/._week40-bs026.html index eadaf863f..fb7eba59e 100644 --- a/doc/pub/week40/html/._week40-bs026.html +++ b/doc/pub/week40/html/._week40-bs026.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    And with loops

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f6_for(x):
         val = 0
    @@ -348,11 +340,29 @@ x = 0.5
     # Print the computed derivaties of f6_for and f6_while
     print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
     print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + -
    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     # Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
     # The analytical derivative is: sum(i*x**(i-1)) 
    @@ -361,8 +371,22 @@ f6_grad_analytical = += i*x**(i-1)
     
     print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs027.html b/doc/pub/week40/html/._week40-bs027.html index 6e3b758a8..2d16d375a 100644 --- a/doc/pub/week40/html/._week40-bs027.html +++ b/doc/pub/week40/html/._week40-bs027.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Using recursion

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     
     def f7(n): # Assume that n is an integer
    @@ -350,11 +342,23 @@ f7_grad_analytical = += tmp
     
     print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
    -
    -

    -Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.

    -

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs028.html b/doc/pub/week40/html/._week40-bs028.html index 9e4f97dac..abd7262e7 100644 --- a/doc/pub/week40/html/._week40-bs028.html +++ b/doc/pub/week40/html/._week40-bs028.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Unsupported functions

    -Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. +

    Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.

    -

    -Assigning a value to the variable being differentiated with respect to -

    +

    Assigning a value to the variable being differentiated with respect to

    -
    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f8(x): # Assume x is an array
         x[2] = 3
    @@ -338,11 +329,23 @@ f8_grad = grad(f8)
     x = 8.4
     
     print("The derivative of f8 is:",f8_grad(x))
    -
    -

    -Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.

    -

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs029.html b/doc/pub/week40/html/._week40-bs029.html index 257779594..b6c9d2c98 100644 --- a/doc/pub/week40/html/._week40-bs029.html +++ b/doc/pub/week40/html/._week40-bs029.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    The syntax a.dot(b) when finding the dot product

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f9(a): # Assume a is an array with 2 elements
         b = np.array([1.0,2.0])
    @@ -334,16 +326,34 @@ f9_grad = grad(f9)
     x = np.array([1.0,0.0])
     
     print("The derivative of f9 is:",f9_grad(x))
    -
    -

    -Here we are told that the 'dot' function does not belong to Autograd's +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here we are told that the 'dot' function does not belong to Autograd's version of a Numpy array. To overcome this, an alternative syntax which also computed the dot product can be used: +

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f9_alternative(x): # Assume a is an array with 2 elements
         b = np.array([1.0,2.0])
    @@ -357,8 +367,22 @@ x = np.a
     
     # The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively
     # w.r.t x is (b_1, b_2).
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs030.html b/doc/pub/week40/html/._week40-bs030.html index a9c9d8dde..f9643411b 100644 --- a/doc/pub/week40/html/._week40-bs030.html +++ b/doc/pub/week40/html/._week40-bs030.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - - -The documentation recommends to avoid inplace operations such as -

    +

    The documentation recommends to avoid inplace operations such as

    -
    a += b
    +
    +
    +
    +
    +
    +
    a += b
     a -= b
     a*= b
     a /=b
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs031.html b/doc/pub/week40/html/._week40-bs031.html index 168bb8e69..9c7fb2e15 100644 --- a/doc/pub/week40/html/._week40-bs031.html +++ b/doc/pub/week40/html/._week40-bs031.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Videos on Neural Networks

    -

    Neural Networks demystified -

    Building Neural Networks from scratch -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs032.html b/doc/pub/week40/html/._week40-bs032.html index 2c50d316b..33bd0624c 100644 --- a/doc/pub/week40/html/._week40-bs032.html +++ b/doc/pub/week40/html/._week40-bs032.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Neural networks

    -

    -Artificial neural networks are computational systems that can learn to +

    Artificial neural networks are computational systems that can learn to perform tasks by considering examples, generally without being programmed with any task-specific rules. It is supposed to mimic a biological system, wherein neurons interact by sending signals in the form of mathematical functions between layers. All layers can contain an arbitrary number of neurons, and each connection is represented by a weight variable. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs033.html b/doc/pub/week40/html/._week40-bs033.html index 4eed41089..eac572db7 100644 --- a/doc/pub/week40/html/._week40-bs033.html +++ b/doc/pub/week40/html/._week40-bs033.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Artificial neurons

    -

    -The field of artificial neural networks has a long history of +

    The field of artificial neural networks has a long history of development, and is closely connected with the advancement of computer science and computers in general. A model of artificial neurons was first developed by McCulloch and Pitts in 1943 to study signal @@ -333,9 +320,9 @@ sending electrical signals. Each neuron accumulates its incoming signals, which must exceed an activation threshold to yield an output. If the threshold is not overcome, the neuron remains inactive, i.e. has zero output. +

    -

    -This behaviour has inspired a simple mathematical model for an artificial neuron. +

    This behaviour has inspired a simple mathematical model for an artificial neuron.

    $$ \begin{equation} @@ -344,21 +331,20 @@ $$ \end{equation} $$ -Here, the output \( y \) of the neuron is the value of its activation function, which have as input +

    Here, the output \( y \) of the neuron is the value of its activation function, which have as input a weighted sum of signals \( x_i, \dots ,x_n \) received by \( n \) other neurons. +

    -

    -Conceptually, it is helpful to divide neural networks into four +

    Conceptually, it is helpful to divide neural networks into four categories: - +

    1. general purpose neural networks for supervised learning,
    2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),
    3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and
    4. neural networks for unsupervised learning such as Deep Boltzmann Machines.
    - -In natural science, DNNs and CNNs have already found numerous +

    In natural science, DNNs and CNNs have already found numerous applications. In statistical physics, they have been applied to detect phase transitions in 2D Ising and Potts models, lattice gauge theories, and different phases of polymers, or solving the @@ -369,17 +355,17 @@ topological phases, and even non-equilibrium many-body localization. Representing quantum states as DNNs quantum state tomography are among some of the impressive achievements to reveal the potential of DNNs to facilitate the study of quantum systems. +

    -

    -In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. +

    In quantum information theory, it has been shown that one can perform +gate decompositions with the help of neural. +

    -

    -The applications are not limited to the natural sciences. There is a +

    The applications are not limited to the natural sciences. There is a plethora of applications in essentially all disciplines, from the humanities to life science and medicine. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs034.html b/doc/pub/week40/html/._week40-bs034.html index 16337bc06..7777bba1a 100644 --- a/doc/pub/week40/html/._week40-bs034.html +++ b/doc/pub/week40/html/._week40-bs034.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Neural network types

    -

    -An artificial neural network (ANN), is a computational model that +

    An artificial neural network (ANN), is a computational model that consists of layers of connected neurons, or nodes or units. We will refer to these interchangeably as units or nodes, and sometimes as neurons. +

    -

    -It is supposed to mimic a biological nervous system by letting each +

    It is supposed to mimic a biological nervous system by letting each neuron interact with other neurons by sending signals in the form of mathematical functions between layers. A wide variety of different ANNs have been developed, but most of them consist of an input layer, an output layer and eventual layers in-between, called hidden layers. All layers can contain an arbitrary number of nodes, and each connection between two nodes is associated with a weight variable. +

    -

    -Neural networks (also called neural nets) are neural-inspired +

    Neural networks (also called neural nets) are neural-inspired nonlinear models for supervised learning. As we will see, neural nets can be viewed as natural, more powerful extensions of supervised learning methods such as linear and logistic regression and soft-max methods we discussed earlier. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs035.html b/doc/pub/week40/html/._week40-bs035.html index 98195a9a6..f17e1168c 100644 --- a/doc/pub/week40/html/._week40-bs035.html +++ b/doc/pub/week40/html/._week40-bs035.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Feed-forward neural networks

    -

    -The feed-forward neural network (FFNN) was the first and simplest type +

    The feed-forward neural network (FFNN) was the first and simplest type of ANNs that were devised. In this network, the information moves in only one direction: forward through the layers. +

    -

    -Nodes are represented by circles, while the arrows display the +

    Nodes are represented by circles, while the arrows display the connections between the nodes, including the direction of information flow. Additionally, each arrow corresponds to a weight variable (figure to come). We observe that each node in a layer is connected to all nodes in the subsequent layer, making this a so-called fully-connected FFNN. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs036.html b/doc/pub/week40/html/._week40-bs036.html index 1b99889de..efcf7f9f2 100644 --- a/doc/pub/week40/html/._week40-bs036.html +++ b/doc/pub/week40/html/._week40-bs036.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Convolutional Neural Network

    -

    -A different variant of FFNNs are convolutional neural networks +

    A different variant of FFNNs are convolutional neural networks (CNNs), which have a connectivity pattern inspired by the animal visual cortex. Individual neurons in the visual cortex only respond to stimuli from small sub-regions of the visual field, called a receptive @@ -330,9 +317,9 @@ field. This makes the neurons well-suited to exploit the strong spatially local correlation present in natural images. The response of each neuron can be approximated mathematically as a convolution operation. (figure to come) +

    -

    -Convolutional neural networks emulate the behaviour of neurons in the +

    Convolutional neural networks emulate the behaviour of neurons in the visual cortex by enforcing a local connectivity pattern between nodes of adjacent layers: Each node in a convolutional layer is connected only to a subset of the nodes in the previous layer, in @@ -341,8 +328,8 @@ convolutional layers that learn local features of the input, with a fully-connected layer at the end, which gathers all the local data and produces the outputs. They have wide applications in image and video recognition. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs037.html b/doc/pub/week40/html/._week40-bs037.html index a3f8bc102..43e67ac95 100644 --- a/doc/pub/week40/html/._week40-bs037.html +++ b/doc/pub/week40/html/._week40-bs037.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Recurrent neural networks

    -

    -So far we have only mentioned ANNs where information flows in one +

    So far we have only mentioned ANNs where information flows in one direction: forward. Recurrent neural networks on the other hand, have connections between nodes that form directed cycles. This creates a form of internal memory which are able to capture @@ -332,8 +319,8 @@ sequential information by performing the same task for every element in a sequence, where each element depends on previous elements. An example of such information is sentences, making recurrent NNs especially well-suited for handwriting and speech recognition. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs038.html b/doc/pub/week40/html/._week40-bs038.html index f79c52e51..b95fe1339 100644 --- a/doc/pub/week40/html/._week40-bs038.html +++ b/doc/pub/week40/html/._week40-bs038.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Other types of networks

    -

    -There are many other kinds of ANNs that have been developed. One type +

    There are many other kinds of ANNs that have been developed. One type that is specifically designed for interpolation in multidimensional space is the radial basis function (RBF) network. RBFs are typically made up of three layers: an input layer, a hidden layer with @@ -332,8 +319,8 @@ linear activation function). The layers are normally fully-connected and there are no cycles, thus RBFs can be viewed as a type of fully-connected FFNN. They are however usually treated as a separate type of NN due the unusual activation functions. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs039.html b/doc/pub/week40/html/._week40-bs039.html index 8a0bf9246..c55789cb6 100644 --- a/doc/pub/week40/html/._week40-bs039.html +++ b/doc/pub/week40/html/._week40-bs039.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Multilayer perceptrons

    -

    -One uses often so-called fully-connected feed-forward neural networks +

    One uses often so-called fully-connected feed-forward neural networks with three or more layers (an input layer, one or more hidden layers and an output layer) consisting of neurons that have non-linear activation functions. +

    -

    -Such networks are often called multilayer perceptrons (MLPs). +

    Such networks are often called multilayer perceptrons (MLPs).

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs040.html b/doc/pub/week40/html/._week40-bs040.html index 98c9b24af..d79458a07 100644 --- a/doc/pub/week40/html/._week40-bs040.html +++ b/doc/pub/week40/html/._week40-bs040.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Why multilayer perceptrons?

    -

    -According to the Universal approximation theorem, a feed-forward +

    According to the Universal approximation theorem, a feed-forward neural network with just a single hidden layer containing a finite number of neurons can approximate a continuous multidimensional function to arbitrary accuracy, assuming the activation function for the hidden layer is a non-constant, bounded and monotonically-increasing continuous function. +

    -

    -Note that the requirements on the activation function only applies to +

    Note that the requirements on the activation function only applies to the hidden layer, the output nodes are always assumed to be linear, so as to not restrict the range of output values. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs041.html b/doc/pub/week40/html/._week40-bs041.html index 3fa8fae51..2ba8449c8 100644 --- a/doc/pub/week40/html/._week40-bs041.html +++ b/doc/pub/week40/html/._week40-bs041.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Illustration of a single perceptropn model and a multi-perceptron model

    -


    -

    Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

    -

    +
    +

    Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

    +
    +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs042.html b/doc/pub/week40/html/._week40-bs042.html index 2441c081c..b5b074ec5 100644 --- a/doc/pub/week40/html/._week40-bs042.html +++ b/doc/pub/week40/html/._week40-bs042.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Examples of XOR, OR and AND gates

    -

    -Let us first try to fit various gates using standard linear +

    Let us first try to fit various gates using standard linear regression. The gates we are thinking of are the classical XOR, OR and AND gates, well-known elements in computer science. The tables here show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a specific target \( y_i \). +

    -

    -

    """
    +
    +
    +
    +
    +
    +
    """
     Simple code that tests XOR, OR and AND gates with linear regression
     """
     
    @@ -361,11 +353,23 @@ yAND = np.= Xinv @ X.T @ yAND
     print(f"The values of theta for the AND gate:{ThetaAND}")
     print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
    -
    -

    -What is happening here? +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    What is happening here?

    -

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs043.html b/doc/pub/week40/html/._week40-bs043.html index 41719af0c..e1108f77b 100644 --- a/doc/pub/week40/html/._week40-bs043.html +++ b/doc/pub/week40/html/._week40-bs043.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Does Logistic Regression do a better Job?

    -

    -

    """
    +
    +
    +
    +
    +
    +
    """
     Simple code that tests XOR and OR gates with linear regression
     and logistic regression
     """
    @@ -373,11 +365,23 @@ logreg.fit(X, yXOR)
     
     logreg.fit(X, yAND)
     print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND)))
    -
    -

    -Not exactly impressive, but somewhat better. +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Not exactly impressive, but somewhat better.

    -

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs044.html b/doc/pub/week40/html/._week40-bs044.html index 4189d3d6e..fd6093e1c 100644 --- a/doc/pub/week40/html/._week40-bs044.html +++ b/doc/pub/week40/html/._week40-bs044.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Adding Neural Networks

    -

    -

    # and now neural networks with Scikit-Learn and the XOR
    +
    +
    +
    +
    +
    +
    # and now neural networks with Scikit-Learn and the XOR
     
     from sklearn.neural_network import MLPClassifier
     from sklearn.datasets import make_classification
    @@ -332,8 +324,22 @@ X, yXOR = make_classification(n_samples= MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)
     FFNN.predict_proba(X)
     print(f"Test set accuracy with Feed Forward Neural Network  for XOR gate:{FFNN.score(X, yXOR)}")
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs045.html b/doc/pub/week40/html/._week40-bs045.html index 3f304a915..8b0b38bda 100644 --- a/doc/pub/week40/html/._week40-bs045.html +++ b/doc/pub/week40/html/._week40-bs045.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Mathematical model

    -

    -The output \( y \) is produced via the activation function \( f \) +

    The output \( y \) is produced via the activation function \( f \)

    $$ y = f\left(\sum_{i=1}^n w_ix_i + b_i\right) = f(z), $$ -This function receives \( x_i \) as inputs. +

    This function receives \( x_i \) as inputs. Here the activation \( z=(\sum_{i=1}^n w_ix_i+b_i) \). In an FFNN of such neurons, the inputs \( x_i \) are the outputs of the neurons in the preceding layer. Furthermore, an MLP is fully-connected, which means that each neuron receives a weighted sum of the outputs of all neurons in the previous layer. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs046.html b/doc/pub/week40/html/._week40-bs046.html index e15d0450c..ab8fa0df7 100644 --- a/doc/pub/week40/html/._week40-bs046.html +++ b/doc/pub/week40/html/._week40-bs046.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Mathematical model

    -

    -First, for each node \( i \) in the first hidden layer, we calculate a weighted sum \( z_i^1 \) of the input coordinates \( x_j \), +

    First, for each node \( i \) in the first hidden layer, we calculate a weighted sum \( z_i^1 \) of the input coordinates \( x_j \),

    $$ \begin{equation} z_i^1 = \sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1 @@ -330,13 +317,13 @@ $$ \end{equation} $$ -

    -Here \( b_i \) is the so-called bias which is normally needed in +

    Here \( b_i \) is the so-called bias which is normally needed in case of zero activation weights or inputs. How to fix the biases and the weights will be discussed below. The value of \( z_i^1 \) is the argument to the activation function \( f_i \) of each node \( i \), The variable \( M \) stands for all possible inputs to a given node \( i \) in the first layer. We define the output \( y_i^1 \) of all neurons in layer 1 as +

    $$ \begin{equation} @@ -345,10 +332,10 @@ $$ \end{equation} $$ -

    -where we assume that all nodes in the same layer have identical +

    where we assume that all nodes in the same layer have identical activation functions, hence the notation \( f \). In general, we could assume in the more general case that different layers have different activation functions. In this case we would identify these functions with a superscript \( l \) for the \( l \)-th layer, +

    $$ \begin{equation} @@ -357,13 +344,12 @@ $$ \end{equation} $$ -

    -where \( N_l \) is the number of nodes in layer \( l \). When the output of +

    where \( N_l \) is the number of nodes in layer \( l \). When the output of all the nodes in the first hidden layer are computed, the values of the subsequent layer can be calculated and so forth until the output is obtained. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs047.html b/doc/pub/week40/html/._week40-bs047.html index 57141c9f1..b6d793eda 100644 --- a/doc/pub/week40/html/._week40-bs047.html +++ b/doc/pub/week40/html/._week40-bs047.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Mathematical model

    -

    -The output of neuron \( i \) in layer 2 is thus, +

    The output of neuron \( i \) in layer 2 is thus,

    $$ \begin{align} @@ -333,7 +320,7 @@ $$ \end{align} $$ -where we have substituted \( y_k^1 \) with the inputs \( x_k \). Finally, the ANN output reads +

    where we have substituted \( y_k^1 \) with the inputs \( x_k \). Finally, the ANN output reads

    $$ \begin{align} @@ -345,7 +332,7 @@ $$ \end{align} $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs048.html b/doc/pub/week40/html/._week40-bs048.html index c3cb405c3..d22973675 100644 --- a/doc/pub/week40/html/._week40-bs048.html +++ b/doc/pub/week40/html/._week40-bs048.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Mathematical model

    -

    -We can generalize this expression to an MLP with \( l \) hidden +

    We can generalize this expression to an MLP with \( l \) hidden layers. The complete functional form is, +

    $$ \begin{align} @@ -332,11 +320,10 @@ $$ \end{align} $$ -

    -which illustrates a basic property of MLPs: The only independent +

    which illustrates a basic property of MLPs: The only independent variables are the input values \( x_n \). +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs049.html b/doc/pub/week40/html/._week40-bs049.html index 384602606..4ea70bbc1 100644 --- a/doc/pub/week40/html/._week40-bs049.html +++ b/doc/pub/week40/html/._week40-bs049.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Mathematical model

    -

    -This confirms that an MLP, despite its quite convoluted mathematical +

    This confirms that an MLP, despite its quite convoluted mathematical form, is nothing more than an analytic function, specifically a mapping of real-valued vectors \( \hat{x} \in \mathbb{R}^n \rightarrow \hat{y} \in \mathbb{R}^m \). +

    -

    -Furthermore, the flexibility and universality of an MLP can be +

    Furthermore, the flexibility and universality of an MLP can be illustrated by realizing that the expression is essentially a nested sum of scaled activation functions of the form +

    $$ \begin{equation} @@ -339,13 +327,12 @@ $$ \end{equation} $$ -

    -where the parameters \( c_i \) are weights and biases. By adjusting these +

    where the parameters \( c_i \) are weights and biases. By adjusting these parameters, the activation functions can be shifted up and down or left and right, change slope or be rescaled which is the key to the flexibility of a neural network. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs050.html b/doc/pub/week40/html/._week40-bs050.html index d9af18a2e..8107966fb 100644 --- a/doc/pub/week40/html/._week40-bs050.html +++ b/doc/pub/week40/html/._week40-bs050.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Matrix-vector notation

    -

    -We can introduce a more convenient notation for the activations in an A NN. +

    We can introduce a more convenient notation for the activations in an A NN.

    -

    -Additionally, we can represent the biases and activations +

    Additionally, we can represent the biases and activations as layer-wise column vectors \( \hat{b}_l \) and \( \hat{y}_l \), so that the \( i \)-th element of each vector -is the bias \( b_i^l \) and activation \( y_i^l \) of node \( i \) in layer \( l \) respectively. +is the bias \( b_i^l \) and activation \( y_i^l \) of node \( i \) in layer \( l \) respectively. +

    -

    -We have that \( \mathrm{W}_l \) is an \( N_{l-1} \times N_l \) matrix, while \( \hat{b}_l \) and \( \hat{y}_l \) are \( N_l \times 1 \) column vectors. +

    We have that \( \mathrm{W}_l \) is an \( N_{l-1} \times N_l \) matrix, while \( \hat{b}_l \) and \( \hat{y}_l \) are \( N_l \times 1 \) column vectors. With this notation, the sum becomes a matrix-vector multiplication, and we can write the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as +

    $$ \begin{equation} \hat{y}_2 = f_2(\mathrm{W}_2 \hat{y}_{1} + \hat{b}_{2}) = @@ -355,7 +342,7 @@ $$ \end{equation} $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs051.html b/doc/pub/week40/html/._week40-bs051.html index 0d9716b32..4aeeca19a 100644 --- a/doc/pub/week40/html/._week40-bs051.html +++ b/doc/pub/week40/html/._week40-bs051.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Matrix-vector notation and activation

    -

    -The activation of node \( i \) in layer 2 is +

    The activation of node \( i \) in layer 2 is

    $$ \begin{equation} @@ -332,14 +319,13 @@ $$ \end{equation} $$ -

    -This is not just a convenient and compact notation, but also a useful +

    This is not just a convenient and compact notation, but also a useful and intuitive way to think about MLPs: The output is calculated by a series of matrix-vector multiplications and vector additions that are used as input to the activation functions. For each operation \( \mathrm{W}_l \hat{y}_{l-1} \) we move forward one layer. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs052.html b/doc/pub/week40/html/._week40-bs052.html index cad2e326f..304ab3df6 100644 --- a/doc/pub/week40/html/._week40-bs052.html +++ b/doc/pub/week40/html/._week40-bs052.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Activation functions

    -

    -A property that characterizes a neural network, other than its +

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

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs053.html b/doc/pub/week40/html/._week40-bs053.html index 85f3c6505..71984f6c7 100644 --- a/doc/pub/week40/html/._week40-bs053.html +++ b/doc/pub/week40/html/._week40-bs053.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Activation functions, Logistic and Hyperbolic ones

    -

    -The second requirement excludes all linear functions. Furthermore, in +

    The second requirement excludes all linear functions. Furthermore, in a MLP with only linear activation functions, each layer simply performs a linear transformation of its inputs. +

    -

    -Regardless of the number of layers, the output of the NN will be +

    Regardless of the number of layers, the output of the NN will be nothing but a linear function of the inputs. Thus we need to introduce some kind of non-linearity to the NN to be able to fit non-linear functions Typical examples are the logistic Sigmoid +

    $$ f(x) = \frac{1}{1 + e^{-x}}, $$ -and the hyperbolic tangent function +

    and the hyperbolic tangent function

    $$ f(x) = \tanh(x) $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs054.html b/doc/pub/week40/html/._week40-bs054.html index cfcdd1cbe..4226d9a6e 100644 --- a/doc/pub/week40/html/._week40-bs054.html +++ b/doc/pub/week40/html/._week40-bs054.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Relevance

    -

    -The sigmoid function are more biologically plausible because the +

    The sigmoid function are more biologically plausible because the output of inactive neurons are zero. Such activation function are called one-sided. However, it has been shown that the hyperbolic tangent performs better than the sigmoid for training MLPs. has become the most popular for deep neural networks +

    -

    -

    """The sigmoid function (or the logistic curve) is a 
    +
    +
    +
    +
    +
    +
    """The sigmoid function (or the logistic curve) is a 
     function that takes any real number, z, and outputs a number (0,1).
     It is useful in neural networks for assigning weights on a relative scale.
     The value z is the weighted sum of parameters involved in the learning algorithm."""
    @@ -402,8 +394,22 @@ ax.set_xlabel(&
     ax.set_title('Rectified linear unit')
     
     plt.show()
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs055.html b/doc/pub/week40/html/._week40-bs055.html index b901bedb5..5d2952cce 100644 --- a/doc/pub/week40/html/._week40-bs055.html +++ b/doc/pub/week40/html/._week40-bs055.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    The multilayer perceptron (MLP)

    -

    -The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of - +

    The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of

    1. A neural network with one or more layers of nodes between the input and the output nodes.
    2. The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.
    3. The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.
    - -As a convention it is normal to call a network with one layer of input units, one layer of hidden +

    As a convention it is normal to call a network with one layer of input units, one layer of hidden units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc. +

    -

    -For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. +

    For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. Hereafter we will call the various entities of a layer for nodes. There are also no connections within a single layer. +

    -

    -The number of input nodes does not need to equal the number of output +

    The number of input nodes does not need to equal the number of output nodes. This applies also to the hidden layers. Each layer may have its own number of nodes and activation functions. +

    -

    -The hidden layers have their name from the fact that they are not +

    The hidden layers have their name from the fact that they are not linked to observables and as we will see below when we define the so-called activation \( \hat{z} \), we can think of this as a basis expansion of the original inputs \( \hat{x} \). The difference however @@ -353,8 +338,8 @@ basis functions (which will correspond to the weights in the network) are learned from data. This results in an important difference between neural networks and deep learning approaches on one side and methods like logistic regression or linear regression and their modifications on the other side. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs056.html b/doc/pub/week40/html/._week40-bs056.html index 7b9585409..076ac3c1a 100644 --- a/doc/pub/week40/html/._week40-bs056.html +++ b/doc/pub/week40/html/._week40-bs056.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    From one to many layers, the universal approximation theorem

    -

    -A neural network with only one layer, what we called the simple +

    A neural network with only one layer, what we called the simple perceptron, is best suited if we have a standard binary model with clear (linear) boundaries between the outcomes. As such it could equally well be replaced by standard linear regression or logistic regression. Networks with one or more hidden layers approximate systems with more complex boundaries. +

    -

    -As stated earlier, +

    As stated earlier, an important theorem in studies of neural networks, restated without proof here, is the universal approximation theorem. +

    -

    -It states that a feed-forward network with a single hidden layer +

    It states that a feed-forward network with a single hidden layer containing a finite number of neurons can approximate continuous functions on compact subsets of real functions. The theorem thus states that simple neural networks can represent a wide variety of interesting functions when given appropriate parameters. It is the multilayer feedforward architecture itself which gives neural networks the potential of being universal approximators. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs057.html b/doc/pub/week40/html/._week40-bs057.html index 9a5fcc203..47807c5b3 100644 --- a/doc/pub/week40/html/._week40-bs057.html +++ b/doc/pub/week40/html/._week40-bs057.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Deriving the back propagation code for a multilayer perceptron model

    -

    -As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. +

    As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. The unknowwn quantities are our weights \( w_{ij} \) and we need to find an algorithm for changing them so that our errors are as small as possible. This leads us to the famous back propagation algorithm. +

    -

    -The questions we want to ask are how do changes in the biases and the +

    The questions we want to ask are how do changes in the biases and the weights in our network change the cost function and how can we use the final output to modify the weights? +

    -

    -To derive these equations let us start with a plain regression problem +

    To derive these equations let us start with a plain regression problem and define our cost function as +

    $$ {\cal C}(\hat{W}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2, $$ -

    -where the $t_i$s are our \( n \) targets (the values we want to +

    where the $t_i$s are our \( n \) targets (the values we want to reproduce), while the outputs of the network after having propagated all inputs \( \hat{x} \) are given by \( y_i \). Below we will demonstrate how the basic equations arising from the back propagation algorithm can be modified in order to study classification problems with \( K \) classes. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs058.html b/doc/pub/week40/html/._week40-bs058.html index 189ca1fbb..0e908a97c 100644 --- a/doc/pub/week40/html/._week40-bs058.html +++ b/doc/pub/week40/html/._week40-bs058.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Definitions

    -

    -With our definition of the targets \( \hat{t} \), the outputs of the +

    With our definition of the targets \( \hat{t} \), the outputs of the network \( \hat{y} \) and the inputs \( \hat{x} \) we define now the activation \( z_j^l \) of node/neuron/unit \( j \) of the \( l \)-th layer as a function of the bias, the weights which add up from the previous layer \( l-1 \) and the forward passes/outputs \( \hat{a}^{l-1} \) from the previous layer as +

    $$ z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, $$ -

    -where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) +

    where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) represents the total number of nodes/neurons/units of layer \( l-1 \). The figure here illustrates this equation. We can rewrite this in a more compact form as the matrix-vector products we discussed earlier, +

    $$ \hat{z}^l = \left(\hat{W}^l\right)^T\hat{a}^{l-1}+\hat{b}^l. $$ -

    -With the activation values \( \hat{z}^l \) we can in turn define the +

    With the activation values \( \hat{z}^l \) we can in turn define the output of layer \( l \) as \( \hat{a}^l = f(\hat{z}^l) \) where \( f \) is our activation function. In the examples here we will use the sigmoid function discussed in our logistic regression lectures. We will also use the same activation function \( f \) for all layers and their nodes. It means we have +

    $$ a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs059.html b/doc/pub/week40/html/._week40-bs059.html index 815d7bc3c..9f8b83b33 100644 --- a/doc/pub/week40/html/._week40-bs059.html +++ b/doc/pub/week40/html/._week40-bs059.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Derivatives and the chain rule

    -

    -From the definition of the activation \( z_j^l \) we have +

    From the definition of the activation \( z_j^l \) we have

    $$ \frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, $$ -and +

    and

    $$ \frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. $$ -

    -With our definition of the activation function we have that (note that this function depends only on \( z_j^l \)) +

    With our definition of the activation function we have that (note that this function depends only on \( z_j^l \))

    $$ \frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)). $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs060.html b/doc/pub/week40/html/._week40-bs060.html index 03c2aa9e9..271eb6ff0 100644 --- a/doc/pub/week40/html/._week40-bs060.html +++ b/doc/pub/week40/html/._week40-bs060.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Derivative of the cost function

    -

    -With these definitions we can now compute the derivative of the cost function in terms of the weights. +

    With these definitions we can now compute the derivative of the cost function in terms of the weights.

    -

    -Let us specialize to the output layer \( l=L \). Our cost function is +

    Let us specialize to the output layer \( l=L \). Our cost function is

    $$ {\cal C}(\hat{W^L}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - t_i\right)^2, $$ -The derivative of this function with respect to the weights is +

    The derivative of this function with respect to the weights is

    $$ \frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}}, $$ -The last partial derivative can easily be computed and reads (by applying the chain rule) +

    The last partial derivative can easily be computed and reads (by applying the chain rule)

    $$ \frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1}, $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs061.html b/doc/pub/week40/html/._week40-bs061.html index 17f9e3d14..077fb626c 100644 --- a/doc/pub/week40/html/._week40-bs061.html +++ b/doc/pub/week40/html/._week40-bs061.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Bringing it together, first back propagation equation

    -

    -We have thus +

    We have thus

    $$ \frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)a_j^L(1-a_j^L)a_k^{L-1}, $$ -

    -Defining +

    Defining

    $$ \delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - t_j\right) = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, $$ -and using the Hadamard product of two vectors we can write this as +

    and using the Hadamard product of two vectors we can write this as

    $$ \hat{\delta}^L = f'(\hat{z}^L)\circ\frac{\partial {\cal C}}{\partial (\hat{a}^L)}. $$ -

    -This is an important expression. The second term on the right handside +

    This is an important expression. The second term on the right handside measures how fast the cost function is changing as a function of the $j$th output activation. If, for example, the cost function doesn't depend much on a particular output node \( j \), then \( \delta_j^L \) will be small, which is what we would expect. The first term on the right, measures how fast the activation function \( f \) is changing at a given activation value \( z_j^L \). +

    -

    -Notice that everything in the above equations is easily computed. In +

    Notice that everything in the above equations is easily computed. In particular, we compute \( z_j^L \) while computing the behaviour of the network, and it is only a small additional overhead to compute \( f'(z^L_j) \). The exact form of the derivative with respect to the output depends on the form of the cost function. However, provided the cost function is known there should be little trouble in calculating +

    $$ \frac{\partial {\cal C}}{\partial (a_j^L)} $$ -

    -With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely +

    With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely

    $$ \frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}. $$ -

    +

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs062.html b/doc/pub/week40/html/._week40-bs062.html index 4d717fafe..3dee1f0aa 100644 --- a/doc/pub/week40/html/._week40-bs062.html +++ b/doc/pub/week40/html/._week40-bs062.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - +

    Derivatives in terms of \( z_j^L \)

    -

    Derivatives in terms of \( z_j^L \)

    - -

    -It is also easy to see that our previous equation can be written as +

    It is also easy to see that our previous equation can be written as

    $$ \delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, $$ -which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely +

    which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely

    $$ \delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, $$ -That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias. +

    That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias.

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs063.html b/doc/pub/week40/html/._week40-bs063.html index a5d98fa4a..17f67c295 100644 --- a/doc/pub/week40/html/._week40-bs063.html +++ b/doc/pub/week40/html/._week40-bs063.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Bringing it together

    -

    -We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are +

    We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are

    -

    -

    + $$ \begin{equation} @@ -336,7 +322,7 @@ $$ \end{equation} $$ -and +

    and

    $$ \begin{equation} \delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, @@ -344,7 +330,7 @@ $$ \end{equation} $$ -and +

    and

    $$ \begin{equation} @@ -356,29 +342,28 @@ $$
    -

    -An interesting consequence of the above equations is that when the +

    An interesting consequence of the above equations is that when the activation \( a_k^{L-1} \) is small, the gradient term, that is the derivative of the cost function with respect to the weights, will also tend to be small. We say then that the weight learns slowly, meaning that it changes slowly when we minimize the weights via say gradient descent. In this case we say the system learns slowly. +

    -

    -Another interesting feature is that is when the activation function, +

    Another interesting feature is that is when the activation function, represented by the sigmoid function here, is rather flat when we move towards its end values \( 0 \) and \( 1 \) (see the above Python codes). In these cases, the derivatives of the activation function will also be close to zero, meaning again that the gradients will be small and the network learns slowly again. +

    -

    -We need a fourth equation and we are set. We are going to propagate +

    We need a fourth equation and we are set. We are going to propagate backwards in order to the determine the weights and biases. In order to do so we need to represent the error in the layer before the final one \( L-1 \) in terms of the errors in the final output layer. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs064.html b/doc/pub/week40/html/._week40-bs064.html index ce86adb50..5c90ef914 100644 --- a/doc/pub/week40/html/._week40-bs064.html +++ b/doc/pub/week40/html/._week40-bs064.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - -
    -
    -

     

     

     

    - -

    Final back propagating equation

    -

    -We have that (replacing \( L \) with a general layer \( l \)) +

    We have that (replacing \( L \) with a general layer \( l \))

    $$ \delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. $$ -We want to express this in terms of the equations for layer \( l+1 \). Using the chain rule and summing over all \( k \) entries we have +

    We want to express this in terms of the equations for layer \( l+1 \). Using the chain rule and summing over all \( k \) entries we have

    $$ \delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, $$ -and recalling that +

    and recalling that

    $$ z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, $$ -with \( M_l \) being the number of nodes in layer \( l \), we obtain +

    with \( M_l \) being the number of nodes in layer \( l \), we obtain

    $$ \delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l), $$ -This is our final equation. +

    This is our final equation.

    -

    -We are now ready to set up the algorithm for back propagation and learning the weights and biases. +

    We are now ready to set up the algorithm for back propagation and learning the weights and biases.

    -

    -
    - - -
    - - - diff --git a/doc/pub/week40/html/._week40-bs065.html b/doc/pub/week40/html/._week40-bs065.html index 26d83458d..fe2c66bc9 100644 --- a/doc/pub/week40/html/._week40-bs065.html +++ b/doc/pub/week40/html/._week40-bs065.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - - -
    -

     

     

     

    - -

    Setting up the Back propagation algorithm

    -

    -The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm. +

    The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.

    -

    -

    -First, we set up the input data \( \hat{x} \) and the activations + +

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

    -

    -

    -Secondly, we perform then the feed forward till we reach the output + +

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

    -

    -

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

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

    $$ \delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. $$ @@ -359,11 +345,10 @@ $$
    -

    -

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

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

    $$ \delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l). $$ @@ -371,11 +356,10 @@ $$
    -

    -

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

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

    $$ w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, $$ @@ -388,11 +372,9 @@ $$
    -

    -The parameter \( \eta \) is the learning parameter discussed in connection with the gradient descent methods. +

    The parameter \( \eta \) is the learning parameter discussed in connection with the gradient descent methods. Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training. - -

    +

    @@ -411,25 +393,18 @@ Here it is convenient to use stochastic gradient descent (see the examples below

  • 66
  • -
    - - -
    - - - diff --git a/doc/pub/week40/html/week40-bs.html b/doc/pub/week40/html/week40-bs.html index 4c47dc9ba..a7a4a3ac7 100644 --- a/doc/pub/week40/html/week40-bs.html +++ b/doc/pub/week40/html/week40-bs.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - + - - -
    -
    -

     

     

     

    - - - -
    -

    Week 40: From Stochastic Gradient Descent to Neural networks

    +
    +

    Week 40: From Stochastic Gradient Descent to Neural networks

    +
    -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo, Norway +
    +
    +[2] Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA +
    +
    +
    +

    Nov 2, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo, Norway
    -
    [2] Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA
    -
    -

    -

    Oct 9, 2021

    -
    -

    Read »

    @@ -366,25 +354,18 @@ MathJax.Hub.Config({
  • »
  • -
    - - -
    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week40/html/week40-reveal.html b/doc/pub/week40/html/week40-reveal.html index 2b9b6c603..ff1024f38 100644 --- a/doc/pub/week40/html/week40-reveal.html +++ b/doc/pub/week40/html/week40-reveal.html @@ -1,18 +1,17 @@ + - + + - Week 40: From Stochastic Gradient Descent to Neural networks - - - - - - @@ -55,36 +54,81 @@ document.getElementsByTagName( 'head' )[0].appendChild( link ); - - - +
    +

    Week 40: From Stochastic Gradient Descent to Neural networks

    +
    - - -

    Week 40: From Stochastic Gradient Descent to Neural networks

    - -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo, Norway +
    +
    +[2] Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA +
    +
    +
    +

    Nov 2, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo, Norway
    -
    [2] Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA
    -
    -

    -

    Oct 9, 2021

    -
    -











    -

    Plan for week 40

    • Thursday: Stochastic Gradient descent with examples and automatic differentiation and begin Neural Networks.
    • - -
    • Friday: Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
    • - -
    - -Reading suggestions for both days: Aurelien Geron's chapter 10 and Hastie et al chapter 11. +

    Reading suggestions for both days: Aurelien Geron's chapter 10 and Hastie et al chapter 11. For Stochastic Gradient Descent, we recommend chapter 4 of Geron's text. For neural networks we recommend Goodfellow et al chapters 6 and 7 and Bishop 5.1-5.4 +

    -











    -

    Overview video on Stochastic Gradient Descent

    -

    What is Stochastic Gradient Descent -











    -

    Batches and mini-batches

    -

    -In gradient descent we compute the cost function and its gradient for all data points we have. +

    In gradient descent we compute the cost function and its gradient for all data points we have.

    -

    -In large-scale applications such as the ILSVRC challenge, the +

    In large-scale applications such as the ILSVRC challenge, the training data can have on order of millions of examples. Hence, it seems wasteful to compute the full cost function over the entire training set in order to perform only a single parameter update. A @@ -315,18 +302,16 @@ gradient over batches of the training data. For example, in current a typical batch could contain some thousand examples from an entire training set of several millions. This batch is then used to perform a parameter update. +

    -











    -

    Stochastic Gradient Descent (SGD)

    -

    -In stochastic gradient descent, the extreme case is the case where we +

    In stochastic gradient descent, the extreme case is the case where we have only one batch, that is we include the whole data set. +

    -

    -This process is called Stochastic Gradient +

    This process is called Stochastic Gradient Descent (SGD) (or also sometimes on-line gradient descent). This is relatively less common to see because in practice due to vectorized code optimizations it can be computationally much more efficient to @@ -342,55 +327,49 @@ usually based on memory constraints (if any), or set to some value, e.g. 32, 64 or 128. We use powers of 2 in practice because many vectorized operation implementations work faster when their inputs are sized in powers of 2. +

    -

    -In our notes with SGD we mean stochastic gradient descent with mini-batches. +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    -











    -

    Stochastic Gradient Descent

    -

    -Stochastic gradient descent (SGD) and variants thereof address some of +

    Stochastic gradient descent (SGD) and variants thereof address some of the shortcomings of the Gradient descent method discussed above. +

    -

    -The underlying idea of SGD comes from the observation that the cost +

    The underlying idea of SGD comes from the observation that the cost function, which we want to minimize, can almost always be written as a sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

    $$ C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, \mathbf{\beta}). $$ -

    -









    +









    Computation of gradients

    -

    -This in turn means that the gradient can be +

    This in turn means that the gradient can be computed as a sum over \( i \)-gradients +

    $$ \nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, \mathbf{\beta}). $$ -

    -Stochasticity/randomness is introduced by only taking the +

    Stochasticity/randomness is introduced by only taking the gradient on a subset of the data called minibatches. If there are \( n \) data points and the size of each minibatch is \( M \), there will be \( n/M \) minibatches. We denote these minibatches by \( B_k \) where \( k=1,\cdots,n/M \). +

    -











    -

    SGD example

    -

    -As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) and we choose to have \( M=5 \) minibathces, then each minibatch contains two data points. In particular we have \( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = @@ -398,11 +377,12 @@ then each minibatch contains two data points. In particular we have have only a single batch with all data points and on the other extreme, you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e \( B_k = \mathbf{x}_k \). +

    -

    -The idea is now to approximate the gradient by replacing the sum over +

    The idea is now to approximate the gradient by replacing the sum over all data points with a sum over the data points in one the minibatches picked at random in each gradient descent step +

    $$ \nabla_{\beta} C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, @@ -410,34 +390,34 @@ C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, c_i(\mathbf{x}_i, \mathbf{\beta}). $$ -

    -









    +









    The gradient step

    -

    -Thus a gradient descent step now looks like +

    Thus a gradient descent step now looks like

    $$ \beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, \mathbf{\beta}) $$ -

    -where \( k \) is picked at random with equal +

    where \( k \) is picked at random with equal probability from \( [1,n/M] \). An iteration over the number of minibathces (n/M) is commonly referred to as an epoch. Thus it is typical to choose a number of epochs and for each epoch iterate over the number of minibatches, as exemplified in the code below. +

    -











    -

    Simple example code

    -

    -

    import numpy as np 
    +
    +
    +
    +
    +
    +
    import numpy as np 
     
     n = 100 #100 datapoints 
     M = 5   #size of each mini-batche
    @@ -451,23 +431,34 @@ j = 0
             #Compute the gradient using the data in minibatch Bk
             #Compute new suggestion for 
             j += 1
    -
    -

    -Taking the gradient only on a subset of the data has two important +

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Taking the gradient only on a subset of the data has two important benefits. First, it introduces randomness which decreases the chance that our opmization scheme gets stuck in a local minima. Second, if the size of the minibatches are small relative to the number of datapoints (\( M < n \)), the computation of the gradient is much cheaper since we sum over the datapoints in the \( k-th \) minibatch and not all \( n \) datapoints. +

    -











    -

    When do we stop?

    -

    -A natural question is when do we stop the search for a new minimum? +

    A natural question is when do we stop the search for a new minimum? One possibility is to compute the full gradient after a given number of epochs and check if the norm of the gradient is smaller than some threshold and stop if true. However, the condition that the gradient @@ -477,31 +468,33 @@ evaluate the cost function at this point, store the result and continue the search. If the test kicks in at a later stage we can compare the values of the cost function and keep the \( \beta \) that gave the lowest value. +

    -











    -

    Slightly different approach

    -

    -Another approach is to let the step length \( \gamma_j \) depend on the +

    Another approach is to let the step length \( \gamma_j \) depend on the number of epochs in such a way that it becomes very small after a reasonable time such that we do not move at all. +

    -

    -As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \). +

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    -

    -In this way we can fix the number of epochs, compute \( \beta \) and +

    In this way we can fix the number of epochs, compute \( \beta \) and evaluate the cost function at the end. Repeating the computation will give a different result since the scheme is random by design. Then we pick the final \( \beta \) that gives the lowest value of the cost function. +

    -

    -

    import numpy as np 
    +
    +
    +
    +
    +
    +
    import numpy as np 
     
     def step_length(t,t0,t1):
         return t0/(t+t1)
    @@ -525,19 +518,34 @@ j = 0
             j += 1
     
     print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    -
    -

    -We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters \( t_0 \) and \( t_1 \). +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters \( t_0 \) and \( t_1 \).

    -











    -

    Program for stochastic gradient

    -

    -

    # Importing various packages
    +
    +
    +
    +
    +
    +
    # Importing various packages
     from math import exp, sqrt
     from random import random, seed
     import numpy as np
    @@ -587,8 +595,8 @@ theta = np.random.randn(2,for epoch in range(n_epochs):
         for i in range(m):
             random_index = np.random.randint(m)
    -        xi = X[random_index:random_index+1]
    -        yi = y[random_index:random_index+1]
    +        xi = X[random_index:random_index+m]
    +        yi = y[random_index:random_index+m]
             gradients = 2.0* xi.T @ ((xi @ theta)-yi)
             eta = learning_schedule(epoch*m+i)
             theta = theta - eta*gradients
    @@ -603,17 +611,30 @@ plt.xlabel(r'$x$')
     plt.ylabel(r'$y$')
     plt.title(r'Random numbers ')
     plt.show()
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Momentum based GD

    -

    -The stochastic gradient descent (SGD) is almost always used with a +

    The stochastic gradient descent (SGD) is almost always used with a momentum or inertia term that serves as a memory of the direction we are moving in parameter space. This is typically implemented as follows +

    $$ \begin{align} @@ -623,8 +644,7 @@ $$ \end{align} $$ -

    -where we have introduced a momentum parameter \( \gamma \), with +

    where we have introduced a momentum parameter \( \gamma \), with \( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to indicate the gradient is to be taken over a different mini-batch at each step. We call this algorithm gradient descent with momentum @@ -634,67 +654,62 @@ running average of recently encountered gradients and used in the averaging procedure. Consistent with this, when \( \gamma=0 \), this just reduces down to ordinary SGD as discussed earlier. An equivalent way of writing the updates is +

    $$ \Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), $$ -where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \). +

    where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).

    -











    -

    More on momentum based approaches

    -

    -Let us try to get more intuition from these equations. It is helpful +

    Let us try to get more intuition from these equations. It is helpful to consider a simple physical analogy with a particle of mass \( m \) moving in a viscous medium with drag coefficient \( \mu \) and potential \( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), then its motion is described by +

    $$ m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). $$ -

    -We can discretize this equation in the usual way to get +

    We can discretize this equation in the usual way to get

    $$ m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). $$ -

    -Rearranging this equation, we can rewrite this as +

    Rearranging this equation, we can rewrite this as

    $$ \Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. $$ -

    -









    +









    Momentum parameter

    -

    -Notice that this equation is identical to previous one if we identify +

    Notice that this equation is identical to previous one if we identify the position of the particle, \( \mathbf{w} \), with the parameters \( \boldsymbol{\theta} \). This allows us to identify the momentum parameter and learning rate with the mass of the particle and the viscous drag as: +

    $$ \gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. $$ -

    -Thus, as the name suggests, the momentum parameter is proportional to +

    Thus, as the name suggests, the momentum parameter is proportional to the mass of the particle and effectively provides inertia. Furthermore, in the large viscosity/small learning rate limit, our memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). +

    -

    -Why is momentum useful? SGD momentum helps the gradient descent +

    Why is momentum useful? SGD momentum helps the gradient descent algorithm gain speed in directions with persistent but small gradients even in the presence of stochasticity, while suppressing oscillations in high-curvature directions. This becomes especially important in @@ -703,18 +718,19 @@ and narrow and steep in others. It has been argued that first-order methods (with appropriate initial conditions) can perform comparable to more expensive second order methods, especially in the context of complex deep learning models. +

    -

    -These beneficial properties of momentum can sometimes become even more +

    These beneficial properties of momentum can sometimes become even more pronounced by using a slight modification of the classical momentum algorithm called Nesterov Accelerated Gradient (NAG). +

    -

    -In the NAG algorithm, rather than calculating the gradient at the +

    In the NAG algorithm, rather than calculating the gradient at the current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one calculates the gradient at the expected value of the parameters given our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \). This yields the NAG update rule +

    $$ \begin{align} @@ -724,16 +740,12 @@ $$ \end{align} $$ -

    -One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \). +

    One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).

    -











    -

    Second moment of the gradient

    -

    -In stochastic gradient descent, with and without momentum, we still +

    In stochastic gradient descent, with and without momentum, we still have to specify a schedule for tuning the learning rates \( \eta_t \) as a function of time. As discussed in the context of Newton's method, this presents a number of dilemmas. The learning rate is @@ -748,23 +760,22 @@ extremely large models. Ideally, we would like to be able to adaptively change the step size to match the landscape without paying the steep computational price of calculating or approximating Hessians. +

    -

    -Recently, a number of methods have been introduced that accomplish +

    Recently, a number of methods have been introduced that accomplish this by tracking not only the gradient, but also the second moment of the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and ADAM. +

    -











    -

    RMS prop

    -

    -In RMS prop, in addition to keeping a running average of the first +

    In RMS prop, in addition to keeping a running average of the first moment of the gradient, we also keep track of the second moment denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule for RMS prop is given by +

    $$ \begin{align} @@ -775,8 +786,7 @@ $$ \end{align} $$ -

    -where \( \beta \) controls the averaging time of the second moment and is +

    where \( \beta \) controls the averaging time of the second moment and is typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a small regularization constant to prevent divergences. Multiplication @@ -785,14 +795,12 @@ is clear from this formula that the learning rate is reduced in directions where the norm of the gradient is consistently large. This greatly speeds up the convergence by allowing us to use a larger learning rate for flat directions. +

    -











    -

    ADAM optimizer

    -

    -A related algorithm is the ADAM optimizer. In ADAM, we keep a running +

    A related algorithm is the ADAM optimizer. In ADAM, we keep a running average of both the first and second moment of the gradient and use this information to adaptively change the learning rate for different parameters. In addition to keeping a running average of the first and @@ -804,6 +812,7 @@ are estimating the first two moments of the gradient using a running average (denoted by the hats in the update rule below). The update rule for ADAM is given by (where multiplication and division are once again understood to be element-wise operations below) +

    $$ \begin{align} @@ -818,26 +827,25 @@ $$ \end{align} $$ -

    -where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +

    where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. +

    -

    -Like in RMSprop, the effective step size of a parameter depends on the +

    Like in RMSprop, the effective step size of a parameter depends on the magnitude of its gradient squared. To understand this better, let us rewrite this expression in terms of the variance \( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t - (\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The update rule for this parameter is given by +

    $$ \Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. $$ -

    -









    +









    Practical tips

    +

    Geron's text, see chapter 11, has several interesting discussions.

    -Geron's text, see chapter 11, has several interesting discussions. - -











    -

    Automatic differentiation

    -

    -Automatic differentiation (AD), +

    Automatic differentiation (AD), also called algorithmic differentiation or computational differentiation,is a set of techniques to numerically evaluate the derivative of a function @@ -868,38 +872,42 @@ operations, derivatives of arbitrary order can be computed automatically, accurately to working precision, and using at most a small constant factor more arithmetic operations than the original program. +

    -

    -Automatic differentiation is neither: +

    Automatic differentiation is neither:

    - -Symbolic differentiation can lead to inefficient code and faces the +

    Symbolic differentiation can lead to inefficient code and faces the difficulty of converting a computer program into a single expression, while numerical differentiation can introduce round-off errors in the discretization process and cancellation +

    -

    -Python has tools for so-called automatic differentiation. +

    Python has tools for so-called automatic differentiation. Consider the following example +

    $$ f(x) = \sin\left(2\pi x + x^2\right) $$ -which has the following derivative +

    which has the following derivative

    $$ f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right) $$ -Using autograd we have +

    Using autograd we have

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     
     # To do elementwise differentiation:
     from autograd import elementwise_grad as egrad 
    @@ -933,23 +941,40 @@ plt.legend()
     plt.show()
     
     print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
    -
    -

    - +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Using autograd

    -

    -Here we +

    Here we experiment with what kind of functions Autograd is capable of finding the gradient of. The following Python functions are just meant to illustrate what Autograd can do, but please feel free to experiment with other, possibly more complicated, functions as well. +

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     
     def f1(x):
    @@ -966,21 +991,38 @@ a = 1.0
     # Compare with the analytical derivative, that is f1'(x) = 3*x**2 
     grad_analytical = 3*a**2
     print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Autograd with more complicated functions

    -

    -To differentiate with respect to two (or more) arguments of a Python +

    To differentiate with respect to two (or more) arguments of a Python function, Autograd need to know at which variable the function if being differentiated with respect to. +

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f2(x1,x2):
         return 3*x1**3 + x2*(x1 - 5) + 1
    @@ -1013,19 +1055,34 @@ f2_grad_x2_analytical = x1 - 5
     
     print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
     print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
    -
    -

    -Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.

    -











    -

    More complicated functions using the elements of their arguments directly

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f3(x): # Assumes x is an array of length 5 or higher
         return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
    @@ -1042,24 +1099,40 @@ f3_grad_analytical = np.array([2, # Print the analytical gradient:
     print("The analytical gradient of f3 is: ", f3_grad_analytical)
    -
    -

    -Note that in this case, when sending an array as input argument, the +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Note that in this case, when sending an array as input argument, the output from Autograd is another array. This is the true gradient of the function, as opposed to the function in the previous example. By using arrays to represent the variables, the output from Autograd might be easier to work with, as the output is closer to what one could expect form a gradient-evaluting function. +

    -

    -

    Functions using mathematical functions from Numpy

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f4(x):
         return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
    @@ -1076,16 +1149,33 @@ f4_grad_analytical = x/np.sqrt(1 + x**# Print the analytical gradient:
     print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    More autograd

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f5(x):
         if x >= 0:
    @@ -1099,16 +1189,33 @@ x = 2.7
     
     # Print the computed derivative:
     print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    And with loops

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f6_for(x):
         val = 0
    @@ -1132,11 +1239,29 @@ x = 0.5
     # Print the computed derivaties of f6_for and f6_while
     print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
     print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + -
    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     # Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
     # The analytical derivative is: sum(i*x**(i-1)) 
    @@ -1145,15 +1270,32 @@ f6_grad_analytical = 0
         f6_grad_analytical += i*x**(i-1)
     
     print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Using recursion

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     
     def f7(n): # Assume that n is an integer
    @@ -1180,22 +1322,36 @@ f7_grad_analytical = 0
         f7_grad_analytical += tmp
     
     print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
    -
    -

    -Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.

    -











    -

    Unsupported functions

    -Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. +

    Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.

    -

    -Assigning a value to the variable being differentiated with respect to -

    +

    Assigning a value to the variable being differentiated with respect to

    -
    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f8(x): # Assume x is an array
         x[2] = 3
    @@ -1206,18 +1362,33 @@ f8_grad = grad(f8)
     x = 8.4
     
     print("The derivative of f8 is:",f8_grad(x))
    -
    -

    -Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.

    -











    -

    The syntax a.dot(b) when finding the dot product

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f9(a): # Assume a is an array with 2 elements
         b = np.array([1.0,2.0])
    @@ -1228,16 +1399,34 @@ f9_grad = grad(f9)
     x = np.array([1.0,0.0])
     
     print("The derivative of f9 is:",f9_grad(x))
    -
    -

    -Here we are told that the 'dot' function does not belong to Autograd's +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here we are told that the 'dot' function does not belong to Autograd's version of a Numpy array. To overcome this, an alternative syntax which also computed the dot product can be used: +

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f9_alternative(x): # Assume a is an array with 2 elements
         b = np.array([1.0,2.0])
    @@ -1251,52 +1440,75 @@ x = np.array([3.0,# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively
     # w.r.t x is (b_1, b_2).
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    -The documentation recommends to avoid inplace operations such as -

    +

    The documentation recommends to avoid inplace operations such as

    -
    a += b
    +
    +
    +
    +
    +
    +
    a += b
     a -= b
     a*= b
     a /=b
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Videos on Neural Networks

    -

    Neural Networks demystified -

    Building Neural Networks from scratch -











    -

    Neural networks

    -

    -Artificial neural networks are computational systems that can learn to +

    Artificial neural networks are computational systems that can learn to perform tasks by considering examples, generally without being programmed with any task-specific rules. It is supposed to mimic a biological system, wherein neurons interact by sending signals in the form of mathematical functions between layers. All layers can contain an arbitrary number of neurons, and each connection is represented by a weight variable. +

    -











    -

    Artificial neurons

    -

    -The field of artificial neural networks has a long history of +

    The field of artificial neural networks has a long history of development, and is closely connected with the advancement of computer science and computers in general. A model of artificial neurons was first developed by McCulloch and Pitts in 1943 to study signal @@ -1307,9 +1519,9 @@ sending electrical signals. Each neuron accumulates its incoming signals, which must exceed an activation threshold to yield an output. If the threshold is not overcome, the neuron remains inactive, i.e. has zero output. +

    -

    -This behaviour has inspired a simple mathematical model for an artificial neuron. +

    This behaviour has inspired a simple mathematical model for an artificial neuron.

    $$ \begin{equation} @@ -1318,21 +1530,20 @@ $$ \end{equation} $$ -Here, the output \( y \) of the neuron is the value of its activation function, which have as input +

    Here, the output \( y \) of the neuron is the value of its activation function, which have as input a weighted sum of signals \( x_i, \dots ,x_n \) received by \( n \) other neurons. +

    -

    -Conceptually, it is helpful to divide neural networks into four +

    Conceptually, it is helpful to divide neural networks into four categories: - +

    1. general purpose neural networks for supervised learning,
    2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),
    3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and
    4. neural networks for unsupervised learning such as Deep Boltzmann Machines.
    - -In natural science, DNNs and CNNs have already found numerous +

    In natural science, DNNs and CNNs have already found numerous applications. In statistical physics, they have been applied to detect phase transitions in 2D Ising and Potts models, lattice gauge theories, and different phases of polymers, or solving the @@ -1343,68 +1554,62 @@ topological phases, and even non-equilibrium many-body localization. Representing quantum states as DNNs quantum state tomography are among some of the impressive achievements to reveal the potential of DNNs to facilitate the study of quantum systems. +

    -

    -In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. +

    In quantum information theory, it has been shown that one can perform +gate decompositions with the help of neural. +

    -

    -The applications are not limited to the natural sciences. There is a +

    The applications are not limited to the natural sciences. There is a plethora of applications in essentially all disciplines, from the humanities to life science and medicine. +

    -











    -

    Neural network types

    -

    -An artificial neural network (ANN), is a computational model that +

    An artificial neural network (ANN), is a computational model that consists of layers of connected neurons, or nodes or units. We will refer to these interchangeably as units or nodes, and sometimes as neurons. +

    -

    -It is supposed to mimic a biological nervous system by letting each +

    It is supposed to mimic a biological nervous system by letting each neuron interact with other neurons by sending signals in the form of mathematical functions between layers. A wide variety of different ANNs have been developed, but most of them consist of an input layer, an output layer and eventual layers in-between, called hidden layers. All layers can contain an arbitrary number of nodes, and each connection between two nodes is associated with a weight variable. +

    -

    -Neural networks (also called neural nets) are neural-inspired +

    Neural networks (also called neural nets) are neural-inspired nonlinear models for supervised learning. As we will see, neural nets can be viewed as natural, more powerful extensions of supervised learning methods such as linear and logistic regression and soft-max methods we discussed earlier. +

    -











    -

    Feed-forward neural networks

    -

    -The feed-forward neural network (FFNN) was the first and simplest type +

    The feed-forward neural network (FFNN) was the first and simplest type of ANNs that were devised. In this network, the information moves in only one direction: forward through the layers. +

    -

    -Nodes are represented by circles, while the arrows display the +

    Nodes are represented by circles, while the arrows display the connections between the nodes, including the direction of information flow. Additionally, each arrow corresponds to a weight variable (figure to come). We observe that each node in a layer is connected to all nodes in the subsequent layer, making this a so-called fully-connected FFNN. +

    -











    -

    Convolutional Neural Network

    -

    -A different variant of FFNNs are convolutional neural networks +

    A different variant of FFNNs are convolutional neural networks (CNNs), which have a connectivity pattern inspired by the animal visual cortex. Individual neurons in the visual cortex only respond to stimuli from small sub-regions of the visual field, called a receptive @@ -1412,9 +1617,9 @@ field. This makes the neurons well-suited to exploit the strong spatially local correlation present in natural images. The response of each neuron can be approximated mathematically as a convolution operation. (figure to come) +

    -

    -Convolutional neural networks emulate the behaviour of neurons in the +

    Convolutional neural networks emulate the behaviour of neurons in the visual cortex by enforcing a local connectivity pattern between nodes of adjacent layers: Each node in a convolutional layer is connected only to a subset of the nodes in the previous layer, in @@ -1423,14 +1628,12 @@ convolutional layers that learn local features of the input, with a fully-connected layer at the end, which gathers all the local data and produces the outputs. They have wide applications in image and video recognition. +

    -











    -

    Recurrent neural networks

    -

    -So far we have only mentioned ANNs where information flows in one +

    So far we have only mentioned ANNs where information flows in one direction: forward. Recurrent neural networks on the other hand, have connections between nodes that form directed cycles. This creates a form of internal memory which are able to capture @@ -1440,14 +1643,12 @@ sequential information by performing the same task for every element in a sequence, where each element depends on previous elements. An example of such information is sentences, making recurrent NNs especially well-suited for handwriting and speech recognition. +

    -











    -

    Other types of networks

    -

    -There are many other kinds of ANNs that have been developed. One type +

    There are many other kinds of ANNs that have been developed. One type that is specifically designed for interpolation in multidimensional space is the radial basis function (RBF) network. RBFs are typically made up of three layers: an input layer, a hidden layer with @@ -1457,67 +1658,64 @@ linear activation function). The layers are normally fully-connected and there are no cycles, thus RBFs can be viewed as a type of fully-connected FFNN. They are however usually treated as a separate type of NN due the unusual activation functions. +

    -











    -

    Multilayer perceptrons

    -

    -One uses often so-called fully-connected feed-forward neural networks +

    One uses often so-called fully-connected feed-forward neural networks with three or more layers (an input layer, one or more hidden layers and an output layer) consisting of neurons that have non-linear activation functions. +

    -

    -Such networks are often called multilayer perceptrons (MLPs). +

    Such networks are often called multilayer perceptrons (MLPs).

    -











    -

    Why multilayer perceptrons?

    -

    -According to the Universal approximation theorem, a feed-forward +

    According to the Universal approximation theorem, a feed-forward neural network with just a single hidden layer containing a finite number of neurons can approximate a continuous multidimensional function to arbitrary accuracy, assuming the activation function for the hidden layer is a non-constant, bounded and monotonically-increasing continuous function. +

    -

    -Note that the requirements on the activation function only applies to +

    Note that the requirements on the activation function only applies to the hidden layer, the output nodes are always assumed to be linear, so as to not restrict the range of output values. +

    -











    -

    Illustration of a single perceptropn model and a multi-perceptron model

    -


    -

    Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

    -

    +
    +

    Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

    +
    +

    -











    -

    Examples of XOR, OR and AND gates

    -

    -Let us first try to fit various gates using standard linear +

    Let us first try to fit various gates using standard linear regression. The gates we are thinking of are the classical XOR, OR and AND gates, well-known elements in computer science. The tables here show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a specific target \( y_i \). +

    -

    -

    """
    +
    +
    +
    +
    +
    +
    """
     Simple code that tests XOR, OR and AND gates with linear regression
     """
     
    @@ -1547,19 +1745,34 @@ yAND = np.array( [ 0, print(f"The values of theta for the AND gate:{ThetaAND}")
     print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
    -
    -

    -What is happening here? +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    What is happening here?

    -











    -

    Does Logistic Regression do a better Job?

    -

    -

    """
    +
    +
    +
    +
    +
    +
    """
     Simple code that tests XOR and OR gates with linear regression
     and logistic regression
     """
    @@ -1608,19 +1821,34 @@ logreg.fit(X, yXOR)
     
     logreg.fit(X, yAND)
     print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND)))
    -
    -

    -Not exactly impressive, but somewhat better. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Not exactly impressive, but somewhat better.

    -











    -

    Adding Neural Networks

    -

    -

    # and now neural networks with Scikit-Learn and the XOR
    +
    +
    +
    +
    +
    +
    # and now neural networks with Scikit-Learn and the XOR
     
     from sklearn.neural_network import MLPClassifier
     from sklearn.datasets import make_classification
    @@ -1628,32 +1856,42 @@ X, yXOR = make_classification(n_samples=100,
     FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)
     FFNN.predict_proba(X)
     print(f"Test set accuracy with Feed Forward Neural Network  for XOR gate:{FFNN.score(X, yXOR)}")
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Mathematical model

    -

    -The output \( y \) is produced via the activation function \( f \) +

    The output \( y \) is produced via the activation function \( f \)

    $$ y = f\left(\sum_{i=1}^n w_ix_i + b_i\right) = f(z), $$ -This function receives \( x_i \) as inputs. +

    This function receives \( x_i \) as inputs. Here the activation \( z=(\sum_{i=1}^n w_ix_i+b_i) \). In an FFNN of such neurons, the inputs \( x_i \) are the outputs of the neurons in the preceding layer. Furthermore, an MLP is fully-connected, which means that each neuron receives a weighted sum of the outputs of all neurons in the previous layer. +

    -











    -

    Mathematical model

    -

    -First, for each node \( i \) in the first hidden layer, we calculate a weighted sum \( z_i^1 \) of the input coordinates \( x_j \), +

    First, for each node \( i \) in the first hidden layer, we calculate a weighted sum \( z_i^1 \) of the input coordinates \( x_j \),

    $$ \begin{equation} z_i^1 = \sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1 @@ -1661,13 +1899,13 @@ $$ \end{equation} $$ -

    -Here \( b_i \) is the so-called bias which is normally needed in +

    Here \( b_i \) is the so-called bias which is normally needed in case of zero activation weights or inputs. How to fix the biases and the weights will be discussed below. The value of \( z_i^1 \) is the argument to the activation function \( f_i \) of each node \( i \), The variable \( M \) stands for all possible inputs to a given node \( i \) in the first layer. We define the output \( y_i^1 \) of all neurons in layer 1 as +

    $$ \begin{equation} @@ -1676,10 +1914,10 @@ $$ \end{equation} $$ -

    -where we assume that all nodes in the same layer have identical +

    where we assume that all nodes in the same layer have identical activation functions, hence the notation \( f \). In general, we could assume in the more general case that different layers have different activation functions. In this case we would identify these functions with a superscript \( l \) for the \( l \)-th layer, +

    $$ \begin{equation} @@ -1688,19 +1926,16 @@ $$ \end{equation} $$ -

    -where \( N_l \) is the number of nodes in layer \( l \). When the output of +

    where \( N_l \) is the number of nodes in layer \( l \). When the output of all the nodes in the first hidden layer are computed, the values of the subsequent layer can be calculated and so forth until the output is obtained. +

    -











    -

    Mathematical model

    -

    -The output of neuron \( i \) in layer 2 is thus, +

    The output of neuron \( i \) in layer 2 is thus,

    $$ \begin{align} @@ -1711,7 +1946,7 @@ $$ \end{align} $$ -where we have substituted \( y_k^1 \) with the inputs \( x_k \). Finally, the ANN output reads +

    where we have substituted \( y_k^1 \) with the inputs \( x_k \). Finally, the ANN output reads

    $$ \begin{align} @@ -1723,14 +1958,13 @@ $$ \end{align} $$ -

    -









    +









    Mathematical model

    -

    -We can generalize this expression to an MLP with \( l \) hidden +

    We can generalize this expression to an MLP with \( l \) hidden layers. The complete functional form is, +

    $$ \begin{align} @@ -1739,25 +1973,23 @@ $$ \end{align} $$ -

    -which illustrates a basic property of MLPs: The only independent +

    which illustrates a basic property of MLPs: The only independent variables are the input values \( x_n \). +

    -











    -

    Mathematical model

    -

    -This confirms that an MLP, despite its quite convoluted mathematical +

    This confirms that an MLP, despite its quite convoluted mathematical form, is nothing more than an analytic function, specifically a mapping of real-valued vectors \( \hat{x} \in \mathbb{R}^n \rightarrow \hat{y} \in \mathbb{R}^m \). +

    -

    -Furthermore, the flexibility and universality of an MLP can be +

    Furthermore, the flexibility and universality of an MLP can be illustrated by realizing that the expression is essentially a nested sum of scaled activation functions of the form +

    $$ \begin{equation} @@ -1766,29 +1998,26 @@ $$ \end{equation} $$ -

    -where the parameters \( c_i \) are weights and biases. By adjusting these +

    where the parameters \( c_i \) are weights and biases. By adjusting these parameters, the activation functions can be shifted up and down or left and right, change slope or be rescaled which is the key to the flexibility of a neural network. +

    -











    -

    Matrix-vector notation

    -

    -We can introduce a more convenient notation for the activations in an A NN. +

    We can introduce a more convenient notation for the activations in an A NN.

    -

    -Additionally, we can represent the biases and activations +

    Additionally, we can represent the biases and activations as layer-wise column vectors \( \hat{b}_l \) and \( \hat{y}_l \), so that the \( i \)-th element of each vector -is the bias \( b_i^l \) and activation \( y_i^l \) of node \( i \) in layer \( l \) respectively. +is the bias \( b_i^l \) and activation \( y_i^l \) of node \( i \) in layer \( l \) respectively. +

    -

    -We have that \( \mathrm{W}_l \) is an \( N_{l-1} \times N_l \) matrix, while \( \hat{b}_l \) and \( \hat{y}_l \) are \( N_l \times 1 \) column vectors. +

    We have that \( \mathrm{W}_l \) is an \( N_{l-1} \times N_l \) matrix, while \( \hat{b}_l \) and \( \hat{y}_l \) are \( N_l \times 1 \) column vectors. With this notation, the sum becomes a matrix-vector multiplication, and we can write the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as +

    $$ \begin{equation} \hat{y}_2 = f_2(\mathrm{W}_2 \hat{y}_{1} + \hat{b}_{2}) = @@ -1811,13 +2040,11 @@ $$ \end{equation} $$ -

    -









    +









    Matrix-vector notation and activation

    -

    -The activation of node \( i \) in layer 2 is +

    The activation of node \( i \) in layer 2 is

    $$ \begin{equation} @@ -1827,23 +2054,21 @@ $$ \end{equation} $$ -

    -This is not just a convenient and compact notation, but also a useful +

    This is not just a convenient and compact notation, but also a useful and intuitive way to think about MLPs: The output is calculated by a series of matrix-vector multiplications and vector additions that are used as input to the activation functions. For each operation \( \mathrm{W}_l \hat{y}_{l-1} \) we move forward one layer. +

    -











    -

    Activation functions

    -

    -A property that characterizes a neural network, other than its +

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

    -









    -

    Activation functions, Logistic and Hyperbolic ones

    -

    -The second requirement excludes all linear functions. Furthermore, in +

    The second requirement excludes all linear functions. Furthermore, in a MLP with only linear activation functions, each layer simply performs a linear transformation of its inputs. +

    -

    -Regardless of the number of layers, the output of the NN will be +

    Regardless of the number of layers, the output of the NN will be nothing but a linear function of the inputs. Thus we need to introduce some kind of non-linearity to the NN to be able to fit non-linear functions Typical examples are the logistic Sigmoid +

    $$ f(x) = \frac{1}{1 + e^{-x}}, $$ -and the hyperbolic tangent function +

    and the hyperbolic tangent function

    $$ f(x) = \tanh(x) $$ -

    -









    +









    Relevance

    -

    -The sigmoid function are more biologically plausible because the +

    The sigmoid function are more biologically plausible because the output of inactive neurons are zero. Such activation function are called one-sided. However, it has been shown that the hyperbolic tangent performs better than the sigmoid for training MLPs. has become the most popular for deep neural networks +

    -

    -

    """The sigmoid function (or the logistic curve) is a 
    +
    +
    +
    +
    +
    +
    """The sigmoid function (or the logistic curve) is a 
     function that takes any real number, z, and outputs a number (0,1).
     It is useful in neural networks for assigning weights on a relative scale.
     The value z is the weighted sum of parameters involved in the learning algorithm."""
    @@ -1900,7 +2126,7 @@ become the most popular for deep neural networks
     import matplotlib.pyplot as plt
     import math as mt
     
    -z = numpy.arange(-5, 5, .1)
    +z = numpy.arange(-5, 5, .1)
     sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
     sigma = sigma_fn(z)
     
    @@ -1916,7 +2142,7 @@ ax.set_title('sigmoid function')
     plt.show()
     
     """Step Function"""
    -z = numpy.arange(-5, 5, .02)
    +z = numpy.arange(-5, 5, .02)
     step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
     step = step_fn(z)
     
    @@ -1948,7 +2174,7 @@ plt.show()
     
     """Plots a graph of the squashing function used by a rectified linear
     unit"""
    -z = numpy.arange(-2, 2, .1)
    +z = numpy.arange(-2, 2, .1)
     zero = numpy.zeros(len(z))
     y = numpy.max([zero, z], axis=0)
     
    @@ -1962,36 +2188,46 @@ ax.set_xlabel('z')
     ax.set_title('Rectified linear unit')
     
     plt.show()
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    The multilayer perceptron (MLP)

    -

    -The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of - +

    The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of

    1. A neural network with one or more layers of nodes between the input and the output nodes.
    2. The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.
    3. The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.
    - -As a convention it is normal to call a network with one layer of input units, one layer of hidden +

    As a convention it is normal to call a network with one layer of input units, one layer of hidden units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc. +

    -

    -For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. +

    For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. Hereafter we will call the various entities of a layer for nodes. There are also no connections within a single layer. +

    -

    -The number of input nodes does not need to equal the number of output +

    The number of input nodes does not need to equal the number of output nodes. This applies also to the hidden layers. Each layer may have its own number of nodes and activation functions. +

    -

    -The hidden layers have their name from the fact that they are not +

    The hidden layers have their name from the fact that they are not linked to observables and as we will see below when we define the so-called activation \( \hat{z} \), we can think of this as a basis expansion of the original inputs \( \hat{x} \). The difference however @@ -2000,227 +2236,207 @@ basis functions (which will correspond to the weights in the network) are learned from data. This results in an important difference between neural networks and deep learning approaches on one side and methods like logistic regression or linear regression and their modifications on the other side. +

    -











    -

    From one to many layers, the universal approximation theorem

    -

    -A neural network with only one layer, what we called the simple +

    A neural network with only one layer, what we called the simple perceptron, is best suited if we have a standard binary model with clear (linear) boundaries between the outcomes. As such it could equally well be replaced by standard linear regression or logistic regression. Networks with one or more hidden layers approximate systems with more complex boundaries. +

    -

    -As stated earlier, +

    As stated earlier, an important theorem in studies of neural networks, restated without proof here, is the universal approximation theorem. +

    -

    -It states that a feed-forward network with a single hidden layer +

    It states that a feed-forward network with a single hidden layer containing a finite number of neurons can approximate continuous functions on compact subsets of real functions. The theorem thus states that simple neural networks can represent a wide variety of interesting functions when given appropriate parameters. It is the multilayer feedforward architecture itself which gives neural networks the potential of being universal approximators. +

    -











    -

    Deriving the back propagation code for a multilayer perceptron model

    -

    -As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. +

    As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. The unknowwn quantities are our weights \( w_{ij} \) and we need to find an algorithm for changing them so that our errors are as small as possible. This leads us to the famous back propagation algorithm. +

    -

    -The questions we want to ask are how do changes in the biases and the +

    The questions we want to ask are how do changes in the biases and the weights in our network change the cost function and how can we use the final output to modify the weights? +

    -

    -To derive these equations let us start with a plain regression problem +

    To derive these equations let us start with a plain regression problem and define our cost function as +

    $$ {\cal C}(\hat{W}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2, $$ -

    -where the $t_i$s are our \( n \) targets (the values we want to +

    where the $t_i$s are our \( n \) targets (the values we want to reproduce), while the outputs of the network after having propagated all inputs \( \hat{x} \) are given by \( y_i \). Below we will demonstrate how the basic equations arising from the back propagation algorithm can be modified in order to study classification problems with \( K \) classes. +

    -











    -

    Definitions

    -

    -With our definition of the targets \( \hat{t} \), the outputs of the +

    With our definition of the targets \( \hat{t} \), the outputs of the network \( \hat{y} \) and the inputs \( \hat{x} \) we define now the activation \( z_j^l \) of node/neuron/unit \( j \) of the \( l \)-th layer as a function of the bias, the weights which add up from the previous layer \( l-1 \) and the forward passes/outputs \( \hat{a}^{l-1} \) from the previous layer as +

    $$ z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, $$ -

    -where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) +

    where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) represents the total number of nodes/neurons/units of layer \( l-1 \). The figure here illustrates this equation. We can rewrite this in a more compact form as the matrix-vector products we discussed earlier, +

    $$ \hat{z}^l = \left(\hat{W}^l\right)^T\hat{a}^{l-1}+\hat{b}^l. $$ -

    -With the activation values \( \hat{z}^l \) we can in turn define the +

    With the activation values \( \hat{z}^l \) we can in turn define the output of layer \( l \) as \( \hat{a}^l = f(\hat{z}^l) \) where \( f \) is our activation function. In the examples here we will use the sigmoid function discussed in our logistic regression lectures. We will also use the same activation function \( f \) for all layers and their nodes. It means we have +

    $$ a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. $$ -

    -









    +









    Derivatives and the chain rule

    -

    -From the definition of the activation \( z_j^l \) we have +

    From the definition of the activation \( z_j^l \) we have

    $$ \frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, $$ -and +

    and

    $$ \frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. $$ -

    -With our definition of the activation function we have that (note that this function depends only on \( z_j^l \)) +

    With our definition of the activation function we have that (note that this function depends only on \( z_j^l \))

    $$ \frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)). $$ -

    -









    +









    Derivative of the cost function

    -

    -With these definitions we can now compute the derivative of the cost function in terms of the weights. +

    With these definitions we can now compute the derivative of the cost function in terms of the weights.

    -

    -Let us specialize to the output layer \( l=L \). Our cost function is +

    Let us specialize to the output layer \( l=L \). Our cost function is

    $$ {\cal C}(\hat{W^L}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - t_i\right)^2, $$ -The derivative of this function with respect to the weights is +

    The derivative of this function with respect to the weights is

    $$ \frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}}, $$ -The last partial derivative can easily be computed and reads (by applying the chain rule) +

    The last partial derivative can easily be computed and reads (by applying the chain rule)

    $$ \frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1}, $$ -

    -









    +









    Bringing it together, first back propagation equation

    -

    -We have thus +

    We have thus

    $$ \frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)a_j^L(1-a_j^L)a_k^{L-1}, $$ -

    -Defining +

    Defining

    $$ \delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - t_j\right) = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, $$ -and using the Hadamard product of two vectors we can write this as +

    and using the Hadamard product of two vectors we can write this as

    $$ \hat{\delta}^L = f'(\hat{z}^L)\circ\frac{\partial {\cal C}}{\partial (\hat{a}^L)}. $$ -

    -This is an important expression. The second term on the right handside +

    This is an important expression. The second term on the right handside measures how fast the cost function is changing as a function of the $j$th output activation. If, for example, the cost function doesn't depend much on a particular output node \( j \), then \( \delta_j^L \) will be small, which is what we would expect. The first term on the right, measures how fast the activation function \( f \) is changing at a given activation value \( z_j^L \). +

    -

    -Notice that everything in the above equations is easily computed. In +

    Notice that everything in the above equations is easily computed. In particular, we compute \( z_j^L \) while computing the behaviour of the network, and it is only a small additional overhead to compute \( f'(z^L_j) \). The exact form of the derivative with respect to the output depends on the form of the cost function. However, provided the cost function is known there should be little trouble in calculating +

    $$ \frac{\partial {\cal C}}{\partial (a_j^L)} $$ -

    -With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely +

    With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely

    $$ \frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}. $$ -

    +









    +

    Derivatives in terms of \( z_j^L \)

    -

    Derivatives in terms of \( z_j^L \)

    - -

    -It is also easy to see that our previous equation can be written as +

    It is also easy to see that our previous equation can be written as

    $$ \delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, $$ -which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely +

    which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely

    $$ \delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, $$ -That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias. +

    That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias.











    -

    Bringing it together

    -

    -We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are +

    We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are

    -

    The starting equations

    @@ -2232,7 +2448,7 @@ $$ \end{equation} $$ -and +

    and

    $$ \begin{equation} \delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, @@ -2240,7 +2456,7 @@ $$ \end{equation} $$ -and +

    and

    $$ \begin{equation} @@ -2251,116 +2467,106 @@ $$
    -

    -An interesting consequence of the above equations is that when the +

    An interesting consequence of the above equations is that when the activation \( a_k^{L-1} \) is small, the gradient term, that is the derivative of the cost function with respect to the weights, will also tend to be small. We say then that the weight learns slowly, meaning that it changes slowly when we minimize the weights via say gradient descent. In this case we say the system learns slowly. +

    -

    -Another interesting feature is that is when the activation function, +

    Another interesting feature is that is when the activation function, represented by the sigmoid function here, is rather flat when we move towards its end values \( 0 \) and \( 1 \) (see the above Python codes). In these cases, the derivatives of the activation function will also be close to zero, meaning again that the gradients will be small and the network learns slowly again. +

    -

    -We need a fourth equation and we are set. We are going to propagate +

    We need a fourth equation and we are set. We are going to propagate backwards in order to the determine the weights and biases. In order to do so we need to represent the error in the layer before the final one \( L-1 \) in terms of the errors in the final output layer. +

    -











    -

    Final back propagating equation

    -

    -We have that (replacing \( L \) with a general layer \( l \)) +

    We have that (replacing \( L \) with a general layer \( l \))

    $$ \delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. $$ -We want to express this in terms of the equations for layer \( l+1 \). Using the chain rule and summing over all \( k \) entries we have +

    We want to express this in terms of the equations for layer \( l+1 \). Using the chain rule and summing over all \( k \) entries we have

    $$ \delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, $$ -and recalling that +

    and recalling that

    $$ z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, $$ -with \( M_l \) being the number of nodes in layer \( l \), we obtain +

    with \( M_l \) being the number of nodes in layer \( l \), we obtain

    $$ \delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l), $$ -This is our final equation. +

    This is our final equation.

    -

    -We are now ready to set up the algorithm for back propagation and learning the weights and biases. +

    We are now ready to set up the algorithm for back propagation and learning the weights and biases.

    -











    -

    Setting up the Back propagation algorithm

    -

    -The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm. +

    The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.

    -

    -First, we set up the input data \( \hat{x} \) and the activations +

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

    -

    -Secondly, we perform then the feed forward till we reach the output +

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

    -

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

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

    $$ \delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. $$
    -

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

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

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

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

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

    $$ w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, $$ @@ -2372,21 +2578,14 @@ $$
    -

    -The parameter \( \eta \) is the learning parameter discussed in connection with the gradient descent methods. +

    The parameter \( \eta \) is the learning parameter discussed in connection with the gradient descent methods. Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training. - -

    +

    - -
    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week40/html/week40.html b/doc/pub/week40/html/week40.html index 931014cb8..5d49816a9 100644 --- a/doc/pub/week40/html/week40.html +++ b/doc/pub/week40/html/week40.html @@ -1,6 +1,7 @@ @@ -8,29 +9,97 @@ Automatically generated HTML file from DocOnce source - Week 40: From Stochastic Gradient Descent to Neural networks - - - - +
    +

    Week 40: From Stochastic Gradient Descent to Neural networks

    +
    - - -

    Week 40: From Stochastic Gradient Descent to Neural networks

    - -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo, Norway +
    +
    +[2] Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA +
    +
    +
    +

    Nov 2, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo, Norway
    -
    [2] Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA
    -
    -

    -

    Oct 9, 2021

    -
    -











    -

    Plan for week 40

    - -Reading suggestions for both days: Aurelien Geron's chapter 10 and Hastie et al chapter 11. +

    Reading suggestions for both days: Aurelien Geron's chapter 10 and Hastie et al chapter 11. For Stochastic Gradient Descent, we recommend chapter 4 of Geron's text. For neural networks we recommend Goodfellow et al chapters 6 and 7 and Bishop 5.1-5.4 +

    -











    -

    Overview video on Stochastic Gradient Descent

    -

    What is Stochastic Gradient Descent -











    -

    Batches and mini-batches

    -

    -In gradient descent we compute the cost function and its gradient for all data points we have. +

    In gradient descent we compute the cost function and its gradient for all data points we have.

    -

    -In large-scale applications such as the ILSVRC challenge, the +

    In large-scale applications such as the ILSVRC challenge, the training data can have on order of millions of examples. Hence, it seems wasteful to compute the full cost function over the entire training set in order to perform only a single parameter update. A @@ -320,18 +379,16 @@ gradient over batches of the training data. For example, in current a typical batch could contain some thousand examples from an entire training set of several millions. This batch is then used to perform a parameter update. +

    -











    -

    Stochastic Gradient Descent (SGD)

    -

    -In stochastic gradient descent, the extreme case is the case where we +

    In stochastic gradient descent, the extreme case is the case where we have only one batch, that is we include the whole data set. +

    -

    -This process is called Stochastic Gradient +

    This process is called Stochastic Gradient Descent (SGD) (or also sometimes on-line gradient descent). This is relatively less common to see because in practice due to vectorized code optimizations it can be computationally much more efficient to @@ -347,55 +404,49 @@ usually based on memory constraints (if any), or set to some value, e.g. 32, 64 or 128. We use powers of 2 in practice because many vectorized operation implementations work faster when their inputs are sized in powers of 2. +

    -

    -In our notes with SGD we mean stochastic gradient descent with mini-batches. +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    -











    -

    Stochastic Gradient Descent

    -

    -Stochastic gradient descent (SGD) and variants thereof address some of +

    Stochastic gradient descent (SGD) and variants thereof address some of the shortcomings of the Gradient descent method discussed above. +

    -

    -The underlying idea of SGD comes from the observation that the cost +

    The underlying idea of SGD comes from the observation that the cost function, which we want to minimize, can almost always be written as a sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

    $$ C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, \mathbf{\beta}). $$ -

    -









    +









    Computation of gradients

    -

    -This in turn means that the gradient can be +

    This in turn means that the gradient can be computed as a sum over \( i \)-gradients +

    $$ \nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, \mathbf{\beta}). $$ -

    -Stochasticity/randomness is introduced by only taking the +

    Stochasticity/randomness is introduced by only taking the gradient on a subset of the data called minibatches. If there are \( n \) data points and the size of each minibatch is \( M \), there will be \( n/M \) minibatches. We denote these minibatches by \( B_k \) where \( k=1,\cdots,n/M \). +

    -











    -

    SGD example

    -

    -As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) and we choose to have \( M=5 \) minibathces, then each minibatch contains two data points. In particular we have \( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = @@ -403,11 +454,12 @@ then each minibatch contains two data points. In particular we have have only a single batch with all data points and on the other extreme, you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e \( B_k = \mathbf{x}_k \). +

    -

    -The idea is now to approximate the gradient by replacing the sum over +

    The idea is now to approximate the gradient by replacing the sum over all data points with a sum over the data points in one the minibatches picked at random in each gradient descent step +

    $$ \nabla_{\beta} C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, @@ -415,34 +467,34 @@ C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, c_i(\mathbf{x}_i, \mathbf{\beta}). $$ -

    -









    +









    The gradient step

    -

    -Thus a gradient descent step now looks like +

    Thus a gradient descent step now looks like

    $$ \beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, \mathbf{\beta}) $$ -

    -where \( k \) is picked at random with equal +

    where \( k \) is picked at random with equal probability from \( [1,n/M] \). An iteration over the number of minibathces (n/M) is commonly referred to as an epoch. Thus it is typical to choose a number of epochs and for each epoch iterate over the number of minibatches, as exemplified in the code below. +

    -











    -

    Simple example code

    -

    -

    import numpy as np 
    +
    +
    +
    +
    +
    +
    import numpy as np 
     
     n = 100 #100 datapoints 
     M = 5   #size of each mini-batche
    @@ -456,23 +508,34 @@ j = 0
             #Compute the gradient using the data in minibatch Bk
             #Compute new suggestion for 
             j += 1
    -
    -

    -Taking the gradient only on a subset of the data has two important +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Taking the gradient only on a subset of the data has two important benefits. First, it introduces randomness which decreases the chance that our opmization scheme gets stuck in a local minima. Second, if the size of the minibatches are small relative to the number of datapoints (\( M < n \)), the computation of the gradient is much cheaper since we sum over the datapoints in the \( k-th \) minibatch and not all \( n \) datapoints. +

    -











    -

    When do we stop?

    -

    -A natural question is when do we stop the search for a new minimum? +

    A natural question is when do we stop the search for a new minimum? One possibility is to compute the full gradient after a given number of epochs and check if the norm of the gradient is smaller than some threshold and stop if true. However, the condition that the gradient @@ -482,31 +545,33 @@ evaluate the cost function at this point, store the result and continue the search. If the test kicks in at a later stage we can compare the values of the cost function and keep the \( \beta \) that gave the lowest value. +

    -











    -

    Slightly different approach

    -

    -Another approach is to let the step length \( \gamma_j \) depend on the +

    Another approach is to let the step length \( \gamma_j \) depend on the number of epochs in such a way that it becomes very small after a reasonable time such that we do not move at all. +

    -

    -As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \). +

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    -

    -In this way we can fix the number of epochs, compute \( \beta \) and +

    In this way we can fix the number of epochs, compute \( \beta \) and evaluate the cost function at the end. Repeating the computation will give a different result since the scheme is random by design. Then we pick the final \( \beta \) that gives the lowest value of the cost function. +

    -

    -

    import numpy as np 
    +
    +
    +
    +
    +
    +
    import numpy as np 
     
     def step_length(t,t0,t1):
         return t0/(t+t1)
    @@ -530,19 +595,34 @@ j = 0
             j += 1
     
     print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    -
    -

    -We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters \( t_0 \) and \( t_1 \). +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters \( t_0 \) and \( t_1 \).

    -











    -

    Program for stochastic gradient

    -

    -

    # Importing various packages
    +
    +
    +
    +
    +
    +
    # Importing various packages
     from math import exp, sqrt
     from random import random, seed
     import numpy as np
    @@ -592,8 +672,8 @@ theta = np.for epoch in range(n_epochs):
         for i in range(m):
             random_index = np.random.randint(m)
    -        xi = X[random_index:random_index+1]
    -        yi = y[random_index:random_index+1]
    +        xi = X[random_index:random_index+m]
    +        yi = y[random_index:random_index+m]
             gradients = 2.0* xi.T @ ((xi @ theta)-yi)
             eta = learning_schedule(epoch*m+i)
             theta = theta - eta*gradients
    @@ -608,17 +688,30 @@ plt.xlabel(r
     plt.ylabel(r'$y$')
     plt.title(r'Random numbers ')
     plt.show()
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Momentum based GD

    -

    -The stochastic gradient descent (SGD) is almost always used with a +

    The stochastic gradient descent (SGD) is almost always used with a momentum or inertia term that serves as a memory of the direction we are moving in parameter space. This is typically implemented as follows +

    $$ \begin{align} @@ -628,8 +721,7 @@ $$ \end{align} $$ -

    -where we have introduced a momentum parameter \( \gamma \), with +

    where we have introduced a momentum parameter \( \gamma \), with \( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to indicate the gradient is to be taken over a different mini-batch at each step. We call this algorithm gradient descent with momentum @@ -639,67 +731,62 @@ running average of recently encountered gradients and used in the averaging procedure. Consistent with this, when \( \gamma=0 \), this just reduces down to ordinary SGD as discussed earlier. An equivalent way of writing the updates is +

    $$ \Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), $$ -where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \). +

    where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).

    -











    -

    More on momentum based approaches

    -

    -Let us try to get more intuition from these equations. It is helpful +

    Let us try to get more intuition from these equations. It is helpful to consider a simple physical analogy with a particle of mass \( m \) moving in a viscous medium with drag coefficient \( \mu \) and potential \( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), then its motion is described by +

    $$ m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). $$ -

    -We can discretize this equation in the usual way to get +

    We can discretize this equation in the usual way to get

    $$ m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). $$ -

    -Rearranging this equation, we can rewrite this as +

    Rearranging this equation, we can rewrite this as

    $$ \Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. $$ -

    -









    +









    Momentum parameter

    -

    -Notice that this equation is identical to previous one if we identify +

    Notice that this equation is identical to previous one if we identify the position of the particle, \( \mathbf{w} \), with the parameters \( \boldsymbol{\theta} \). This allows us to identify the momentum parameter and learning rate with the mass of the particle and the viscous drag as: +

    $$ \gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. $$ -

    -Thus, as the name suggests, the momentum parameter is proportional to +

    Thus, as the name suggests, the momentum parameter is proportional to the mass of the particle and effectively provides inertia. Furthermore, in the large viscosity/small learning rate limit, our memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). +

    -

    -Why is momentum useful? SGD momentum helps the gradient descent +

    Why is momentum useful? SGD momentum helps the gradient descent algorithm gain speed in directions with persistent but small gradients even in the presence of stochasticity, while suppressing oscillations in high-curvature directions. This becomes especially important in @@ -708,18 +795,19 @@ and narrow and steep in others. It has been argued that first-order methods (with appropriate initial conditions) can perform comparable to more expensive second order methods, especially in the context of complex deep learning models. +

    -

    -These beneficial properties of momentum can sometimes become even more +

    These beneficial properties of momentum can sometimes become even more pronounced by using a slight modification of the classical momentum algorithm called Nesterov Accelerated Gradient (NAG). +

    -

    -In the NAG algorithm, rather than calculating the gradient at the +

    In the NAG algorithm, rather than calculating the gradient at the current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one calculates the gradient at the expected value of the parameters given our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \). This yields the NAG update rule +

    $$ \begin{align} @@ -729,16 +817,12 @@ $$ \end{align} $$ -

    -One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \). +

    One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).

    -











    -

    Second moment of the gradient

    -

    -In stochastic gradient descent, with and without momentum, we still +

    In stochastic gradient descent, with and without momentum, we still have to specify a schedule for tuning the learning rates \( \eta_t \) as a function of time. As discussed in the context of Newton's method, this presents a number of dilemmas. The learning rate is @@ -753,23 +837,22 @@ extremely large models. Ideally, we would like to be able to adaptively change the step size to match the landscape without paying the steep computational price of calculating or approximating Hessians. +

    -

    -Recently, a number of methods have been introduced that accomplish +

    Recently, a number of methods have been introduced that accomplish this by tracking not only the gradient, but also the second moment of the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and ADAM. +

    -











    -

    RMS prop

    -

    -In RMS prop, in addition to keeping a running average of the first +

    In RMS prop, in addition to keeping a running average of the first moment of the gradient, we also keep track of the second moment denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule for RMS prop is given by +

    $$ \begin{align} @@ -780,8 +863,7 @@ $$ \end{align} $$ -

    -where \( \beta \) controls the averaging time of the second moment and is +

    where \( \beta \) controls the averaging time of the second moment and is typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a small regularization constant to prevent divergences. Multiplication @@ -790,14 +872,12 @@ is clear from this formula that the learning rate is reduced in directions where the norm of the gradient is consistently large. This greatly speeds up the convergence by allowing us to use a larger learning rate for flat directions. +

    -











    -

    ADAM optimizer

    -

    -A related algorithm is the ADAM optimizer. In ADAM, we keep a running +

    A related algorithm is the ADAM optimizer. In ADAM, we keep a running average of both the first and second moment of the gradient and use this information to adaptively change the learning rate for different parameters. In addition to keeping a running average of the first and @@ -809,6 +889,7 @@ are estimating the first two moments of the gradient using a running average (denoted by the hats in the update rule below). The update rule for ADAM is given by (where multiplication and division are once again understood to be element-wise operations below) +

    $$ \begin{align} @@ -823,26 +904,25 @@ $$ \end{align} $$ -

    -where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +

    where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. +

    -

    -Like in RMSprop, the effective step size of a parameter depends on the +

    Like in RMSprop, the effective step size of a parameter depends on the magnitude of its gradient squared. To understand this better, let us rewrite this expression in terms of the variance \( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t - (\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The update rule for this parameter is given by +

    $$ \Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. $$ -

    -









    +









    Practical tips

    +

    Geron's text, see chapter 11, has several interesting discussions.

    -Geron's text, see chapter 11, has several interesting discussions. - -











    -

    Automatic differentiation

    -

    -Automatic differentiation (AD), +

    Automatic differentiation (AD), also called algorithmic differentiation or computational differentiation,is a set of techniques to numerically evaluate the derivative of a function @@ -873,38 +949,42 @@ operations, derivatives of arbitrary order can be computed automatically, accurately to working precision, and using at most a small constant factor more arithmetic operations than the original program. +

    -

    -Automatic differentiation is neither: +

    Automatic differentiation is neither:

    - -Symbolic differentiation can lead to inefficient code and faces the +

    Symbolic differentiation can lead to inefficient code and faces the difficulty of converting a computer program into a single expression, while numerical differentiation can introduce round-off errors in the discretization process and cancellation +

    -

    -Python has tools for so-called automatic differentiation. +

    Python has tools for so-called automatic differentiation. Consider the following example +

    $$ f(x) = \sin\left(2\pi x + x^2\right) $$ -which has the following derivative +

    which has the following derivative

    $$ f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right) $$ -Using autograd we have +

    Using autograd we have

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     
     # To do elementwise differentiation:
     from autograd import elementwise_grad as egrad 
    @@ -938,23 +1018,40 @@ plt.legend()
     plt.show()
     
     print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
    -
    -

    - +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Using autograd

    -

    -Here we +

    Here we experiment with what kind of functions Autograd is capable of finding the gradient of. The following Python functions are just meant to illustrate what Autograd can do, but please feel free to experiment with other, possibly more complicated, functions as well. +

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     
     def f1(x):
    @@ -971,21 +1068,38 @@ a = 1.0
     # Compare with the analytical derivative, that is f1'(x) = 3*x**2 
     grad_analytical = 3*a**2
     print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Autograd with more complicated functions

    -

    -To differentiate with respect to two (or more) arguments of a Python +

    To differentiate with respect to two (or more) arguments of a Python function, Autograd need to know at which variable the function if being differentiated with respect to. +

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f2(x1,x2):
         return 3*x1**3 + x2*(x1 - 5) + 1
    @@ -1018,19 +1132,34 @@ f2_grad_x2_analytical = x1 print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
     print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
    -
    -

    -Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.

    -











    -

    More complicated functions using the elements of their arguments directly

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f3(x): # Assumes x is an array of length 5 or higher
         return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
    @@ -1047,24 +1176,40 @@ f3_grad_analytical = np# Print the analytical gradient:
     print("The analytical gradient of f3 is: ", f3_grad_analytical)
    -
    -

    -Note that in this case, when sending an array as input argument, the +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Note that in this case, when sending an array as input argument, the output from Autograd is another array. This is the true gradient of the function, as opposed to the function in the previous example. By using arrays to represent the variables, the output from Autograd might be easier to work with, as the output is closer to what one could expect form a gradient-evaluting function. +

    -

    -

    Functions using mathematical functions from Numpy

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f4(x):
         return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
    @@ -1081,16 +1226,33 @@ f4_grad_analytical = x# Print the analytical gradient:
     print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    More autograd

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f5(x):
         if x >= 0:
    @@ -1104,16 +1266,33 @@ x = 2.7
     
     # Print the computed derivative:
     print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    And with loops

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f6_for(x):
         val = 0
    @@ -1137,11 +1316,29 @@ x = 0.5
     # Print the computed derivaties of f6_for and f6_while
     print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
     print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + -
    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     # Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
     # The analytical derivative is: sum(i*x**(i-1)) 
    @@ -1150,15 +1347,32 @@ f6_grad_analytical = += i*x**(i-1)
     
     print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Using recursion

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     
     def f7(n): # Assume that n is an integer
    @@ -1185,22 +1399,36 @@ f7_grad_analytical = += tmp
     
     print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
    -
    -

    -Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.

    -











    -

    Unsupported functions

    -Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. +

    Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.

    -

    -Assigning a value to the variable being differentiated with respect to -

    +

    Assigning a value to the variable being differentiated with respect to

    -
    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f8(x): # Assume x is an array
         x[2] = 3
    @@ -1211,18 +1439,33 @@ f8_grad = grad(f8)
     x = 8.4
     
     print("The derivative of f8 is:",f8_grad(x))
    -
    -

    -Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.

    -











    -

    The syntax a.dot(b) when finding the dot product

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f9(a): # Assume a is an array with 2 elements
         b = np.array([1.0,2.0])
    @@ -1233,16 +1476,34 @@ f9_grad = grad(f9)
     x = np.array([1.0,0.0])
     
     print("The derivative of f9 is:",f9_grad(x))
    -
    -

    -Here we are told that the 'dot' function does not belong to Autograd's +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here we are told that the 'dot' function does not belong to Autograd's version of a Numpy array. To overcome this, an alternative syntax which also computed the dot product can be used: +

    -

    -

    import autograd.numpy as np
    +
    +
    +
    +
    +
    +
    import autograd.numpy as np
     from autograd import grad
     def f9_alternative(x): # Assume a is an array with 2 elements
         b = np.array([1.0,2.0])
    @@ -1256,52 +1517,75 @@ x = np.a
     
     # The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively
     # w.r.t x is (b_1, b_2).
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    -The documentation recommends to avoid inplace operations such as -

    +

    The documentation recommends to avoid inplace operations such as

    -
    a += b
    +
    +
    +
    +
    +
    +
    a += b
     a -= b
     a*= b
     a /=b
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Videos on Neural Networks

    -

    Neural Networks demystified -

    Building Neural Networks from scratch -











    -

    Neural networks

    -

    -Artificial neural networks are computational systems that can learn to +

    Artificial neural networks are computational systems that can learn to perform tasks by considering examples, generally without being programmed with any task-specific rules. It is supposed to mimic a biological system, wherein neurons interact by sending signals in the form of mathematical functions between layers. All layers can contain an arbitrary number of neurons, and each connection is represented by a weight variable. +

    -











    -

    Artificial neurons

    -

    -The field of artificial neural networks has a long history of +

    The field of artificial neural networks has a long history of development, and is closely connected with the advancement of computer science and computers in general. A model of artificial neurons was first developed by McCulloch and Pitts in 1943 to study signal @@ -1312,9 +1596,9 @@ sending electrical signals. Each neuron accumulates its incoming signals, which must exceed an activation threshold to yield an output. If the threshold is not overcome, the neuron remains inactive, i.e. has zero output. +

    -

    -This behaviour has inspired a simple mathematical model for an artificial neuron. +

    This behaviour has inspired a simple mathematical model for an artificial neuron.

    $$ \begin{equation} @@ -1323,21 +1607,20 @@ $$ \end{equation} $$ -Here, the output \( y \) of the neuron is the value of its activation function, which have as input +

    Here, the output \( y \) of the neuron is the value of its activation function, which have as input a weighted sum of signals \( x_i, \dots ,x_n \) received by \( n \) other neurons. +

    -

    -Conceptually, it is helpful to divide neural networks into four +

    Conceptually, it is helpful to divide neural networks into four categories: - +

    1. general purpose neural networks for supervised learning,
    2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),
    3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and
    4. neural networks for unsupervised learning such as Deep Boltzmann Machines.
    - -In natural science, DNNs and CNNs have already found numerous +

    In natural science, DNNs and CNNs have already found numerous applications. In statistical physics, they have been applied to detect phase transitions in 2D Ising and Potts models, lattice gauge theories, and different phases of polymers, or solving the @@ -1348,68 +1631,62 @@ topological phases, and even non-equilibrium many-body localization. Representing quantum states as DNNs quantum state tomography are among some of the impressive achievements to reveal the potential of DNNs to facilitate the study of quantum systems. +

    -

    -In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. +

    In quantum information theory, it has been shown that one can perform +gate decompositions with the help of neural. +

    -

    -The applications are not limited to the natural sciences. There is a +

    The applications are not limited to the natural sciences. There is a plethora of applications in essentially all disciplines, from the humanities to life science and medicine. +

    -











    -

    Neural network types

    -

    -An artificial neural network (ANN), is a computational model that +

    An artificial neural network (ANN), is a computational model that consists of layers of connected neurons, or nodes or units. We will refer to these interchangeably as units or nodes, and sometimes as neurons. +

    -

    -It is supposed to mimic a biological nervous system by letting each +

    It is supposed to mimic a biological nervous system by letting each neuron interact with other neurons by sending signals in the form of mathematical functions between layers. A wide variety of different ANNs have been developed, but most of them consist of an input layer, an output layer and eventual layers in-between, called hidden layers. All layers can contain an arbitrary number of nodes, and each connection between two nodes is associated with a weight variable. +

    -

    -Neural networks (also called neural nets) are neural-inspired +

    Neural networks (also called neural nets) are neural-inspired nonlinear models for supervised learning. As we will see, neural nets can be viewed as natural, more powerful extensions of supervised learning methods such as linear and logistic regression and soft-max methods we discussed earlier. +

    -











    -

    Feed-forward neural networks

    -

    -The feed-forward neural network (FFNN) was the first and simplest type +

    The feed-forward neural network (FFNN) was the first and simplest type of ANNs that were devised. In this network, the information moves in only one direction: forward through the layers. +

    -

    -Nodes are represented by circles, while the arrows display the +

    Nodes are represented by circles, while the arrows display the connections between the nodes, including the direction of information flow. Additionally, each arrow corresponds to a weight variable (figure to come). We observe that each node in a layer is connected to all nodes in the subsequent layer, making this a so-called fully-connected FFNN. +

    -











    -

    Convolutional Neural Network

    -

    -A different variant of FFNNs are convolutional neural networks +

    A different variant of FFNNs are convolutional neural networks (CNNs), which have a connectivity pattern inspired by the animal visual cortex. Individual neurons in the visual cortex only respond to stimuli from small sub-regions of the visual field, called a receptive @@ -1417,9 +1694,9 @@ field. This makes the neurons well-suited to exploit the strong spatially local correlation present in natural images. The response of each neuron can be approximated mathematically as a convolution operation. (figure to come) +

    -

    -Convolutional neural networks emulate the behaviour of neurons in the +

    Convolutional neural networks emulate the behaviour of neurons in the visual cortex by enforcing a local connectivity pattern between nodes of adjacent layers: Each node in a convolutional layer is connected only to a subset of the nodes in the previous layer, in @@ -1428,14 +1705,12 @@ convolutional layers that learn local features of the input, with a fully-connected layer at the end, which gathers all the local data and produces the outputs. They have wide applications in image and video recognition. +

    -











    -

    Recurrent neural networks

    -

    -So far we have only mentioned ANNs where information flows in one +

    So far we have only mentioned ANNs where information flows in one direction: forward. Recurrent neural networks on the other hand, have connections between nodes that form directed cycles. This creates a form of internal memory which are able to capture @@ -1445,14 +1720,12 @@ sequential information by performing the same task for every element in a sequence, where each element depends on previous elements. An example of such information is sentences, making recurrent NNs especially well-suited for handwriting and speech recognition. +

    -











    -

    Other types of networks

    -

    -There are many other kinds of ANNs that have been developed. One type +

    There are many other kinds of ANNs that have been developed. One type that is specifically designed for interpolation in multidimensional space is the radial basis function (RBF) network. RBFs are typically made up of three layers: an input layer, a hidden layer with @@ -1462,67 +1735,64 @@ linear activation function). The layers are normally fully-connected and there are no cycles, thus RBFs can be viewed as a type of fully-connected FFNN. They are however usually treated as a separate type of NN due the unusual activation functions. +

    -











    -

    Multilayer perceptrons

    -

    -One uses often so-called fully-connected feed-forward neural networks +

    One uses often so-called fully-connected feed-forward neural networks with three or more layers (an input layer, one or more hidden layers and an output layer) consisting of neurons that have non-linear activation functions. +

    -

    -Such networks are often called multilayer perceptrons (MLPs). +

    Such networks are often called multilayer perceptrons (MLPs).

    -











    -

    Why multilayer perceptrons?

    -

    -According to the Universal approximation theorem, a feed-forward +

    According to the Universal approximation theorem, a feed-forward neural network with just a single hidden layer containing a finite number of neurons can approximate a continuous multidimensional function to arbitrary accuracy, assuming the activation function for the hidden layer is a non-constant, bounded and monotonically-increasing continuous function. +

    -

    -Note that the requirements on the activation function only applies to +

    Note that the requirements on the activation function only applies to the hidden layer, the output nodes are always assumed to be linear, so as to not restrict the range of output values. +

    -











    -

    Illustration of a single perceptropn model and a multi-perceptron model

    -


    -

    Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

    -

    +
    +

    Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

    +
    +

    -











    -

    Examples of XOR, OR and AND gates

    -

    -Let us first try to fit various gates using standard linear +

    Let us first try to fit various gates using standard linear regression. The gates we are thinking of are the classical XOR, OR and AND gates, well-known elements in computer science. The tables here show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a specific target \( y_i \). +

    -

    -

    """
    +
    +
    +
    +
    +
    +
    """
     Simple code that tests XOR, OR and AND gates with linear regression
     """
     
    @@ -1552,19 +1822,34 @@ yAND = np.= Xinv @ X.T @ yAND
     print(f"The values of theta for the AND gate:{ThetaAND}")
     print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
    -
    -

    -What is happening here? +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    What is happening here?

    -











    -

    Does Logistic Regression do a better Job?

    -

    -

    """
    +
    +
    +
    +
    +
    +
    """
     Simple code that tests XOR and OR gates with linear regression
     and logistic regression
     """
    @@ -1613,19 +1898,34 @@ logreg.fit(X, yXOR)
     
     logreg.fit(X, yAND)
     print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND)))
    -
    -

    -Not exactly impressive, but somewhat better. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Not exactly impressive, but somewhat better.

    -











    -

    Adding Neural Networks

    -

    -

    # and now neural networks with Scikit-Learn and the XOR
    +
    +
    +
    +
    +
    +
    # and now neural networks with Scikit-Learn and the XOR
     
     from sklearn.neural_network import MLPClassifier
     from sklearn.datasets import make_classification
    @@ -1633,32 +1933,42 @@ X, yXOR = make_classification(n_samples= MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)
     FFNN.predict_proba(X)
     print(f"Test set accuracy with Feed Forward Neural Network  for XOR gate:{FFNN.score(X, yXOR)}")
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Mathematical model

    -

    -The output \( y \) is produced via the activation function \( f \) +

    The output \( y \) is produced via the activation function \( f \)

    $$ y = f\left(\sum_{i=1}^n w_ix_i + b_i\right) = f(z), $$ -This function receives \( x_i \) as inputs. +

    This function receives \( x_i \) as inputs. Here the activation \( z=(\sum_{i=1}^n w_ix_i+b_i) \). In an FFNN of such neurons, the inputs \( x_i \) are the outputs of the neurons in the preceding layer. Furthermore, an MLP is fully-connected, which means that each neuron receives a weighted sum of the outputs of all neurons in the previous layer. +

    -











    -

    Mathematical model

    -

    -First, for each node \( i \) in the first hidden layer, we calculate a weighted sum \( z_i^1 \) of the input coordinates \( x_j \), +

    First, for each node \( i \) in the first hidden layer, we calculate a weighted sum \( z_i^1 \) of the input coordinates \( x_j \),

    $$ \begin{equation} z_i^1 = \sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1 @@ -1666,13 +1976,13 @@ $$ \end{equation} $$ -

    -Here \( b_i \) is the so-called bias which is normally needed in +

    Here \( b_i \) is the so-called bias which is normally needed in case of zero activation weights or inputs. How to fix the biases and the weights will be discussed below. The value of \( z_i^1 \) is the argument to the activation function \( f_i \) of each node \( i \), The variable \( M \) stands for all possible inputs to a given node \( i \) in the first layer. We define the output \( y_i^1 \) of all neurons in layer 1 as +

    $$ \begin{equation} @@ -1681,10 +1991,10 @@ $$ \end{equation} $$ -

    -where we assume that all nodes in the same layer have identical +

    where we assume that all nodes in the same layer have identical activation functions, hence the notation \( f \). In general, we could assume in the more general case that different layers have different activation functions. In this case we would identify these functions with a superscript \( l \) for the \( l \)-th layer, +

    $$ \begin{equation} @@ -1693,19 +2003,16 @@ $$ \end{equation} $$ -

    -where \( N_l \) is the number of nodes in layer \( l \). When the output of +

    where \( N_l \) is the number of nodes in layer \( l \). When the output of all the nodes in the first hidden layer are computed, the values of the subsequent layer can be calculated and so forth until the output is obtained. +

    -











    -

    Mathematical model

    -

    -The output of neuron \( i \) in layer 2 is thus, +

    The output of neuron \( i \) in layer 2 is thus,

    $$ \begin{align} @@ -1716,7 +2023,7 @@ $$ \end{align} $$ -where we have substituted \( y_k^1 \) with the inputs \( x_k \). Finally, the ANN output reads +

    where we have substituted \( y_k^1 \) with the inputs \( x_k \). Finally, the ANN output reads

    $$ \begin{align} @@ -1728,14 +2035,13 @@ $$ \end{align} $$ -

    -









    +









    Mathematical model

    -

    -We can generalize this expression to an MLP with \( l \) hidden +

    We can generalize this expression to an MLP with \( l \) hidden layers. The complete functional form is, +

    $$ \begin{align} @@ -1744,25 +2050,23 @@ $$ \end{align} $$ -

    -which illustrates a basic property of MLPs: The only independent +

    which illustrates a basic property of MLPs: The only independent variables are the input values \( x_n \). +

    -











    -

    Mathematical model

    -

    -This confirms that an MLP, despite its quite convoluted mathematical +

    This confirms that an MLP, despite its quite convoluted mathematical form, is nothing more than an analytic function, specifically a mapping of real-valued vectors \( \hat{x} \in \mathbb{R}^n \rightarrow \hat{y} \in \mathbb{R}^m \). +

    -

    -Furthermore, the flexibility and universality of an MLP can be +

    Furthermore, the flexibility and universality of an MLP can be illustrated by realizing that the expression is essentially a nested sum of scaled activation functions of the form +

    $$ \begin{equation} @@ -1771,29 +2075,26 @@ $$ \end{equation} $$ -

    -where the parameters \( c_i \) are weights and biases. By adjusting these +

    where the parameters \( c_i \) are weights and biases. By adjusting these parameters, the activation functions can be shifted up and down or left and right, change slope or be rescaled which is the key to the flexibility of a neural network. +

    -











    -

    Matrix-vector notation

    -

    -We can introduce a more convenient notation for the activations in an A NN. +

    We can introduce a more convenient notation for the activations in an A NN.

    -

    -Additionally, we can represent the biases and activations +

    Additionally, we can represent the biases and activations as layer-wise column vectors \( \hat{b}_l \) and \( \hat{y}_l \), so that the \( i \)-th element of each vector -is the bias \( b_i^l \) and activation \( y_i^l \) of node \( i \) in layer \( l \) respectively. +is the bias \( b_i^l \) and activation \( y_i^l \) of node \( i \) in layer \( l \) respectively. +

    -

    -We have that \( \mathrm{W}_l \) is an \( N_{l-1} \times N_l \) matrix, while \( \hat{b}_l \) and \( \hat{y}_l \) are \( N_l \times 1 \) column vectors. +

    We have that \( \mathrm{W}_l \) is an \( N_{l-1} \times N_l \) matrix, while \( \hat{b}_l \) and \( \hat{y}_l \) are \( N_l \times 1 \) column vectors. With this notation, the sum becomes a matrix-vector multiplication, and we can write the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as +

    $$ \begin{equation} \hat{y}_2 = f_2(\mathrm{W}_2 \hat{y}_{1} + \hat{b}_{2}) = @@ -1816,13 +2117,11 @@ $$ \end{equation} $$ -

    -









    +









    Matrix-vector notation and activation

    -

    -The activation of node \( i \) in layer 2 is +

    The activation of node \( i \) in layer 2 is

    $$ \begin{equation} @@ -1832,23 +2131,21 @@ $$ \end{equation} $$ -

    -This is not just a convenient and compact notation, but also a useful +

    This is not just a convenient and compact notation, but also a useful and intuitive way to think about MLPs: The output is calculated by a series of matrix-vector multiplications and vector additions that are used as input to the activation functions. For each operation \( \mathrm{W}_l \hat{y}_{l-1} \) we move forward one layer. +

    -











    -

    Activation functions

    -

    -A property that characterizes a neural network, other than its +

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

    -









    -

    Activation functions, Logistic and Hyperbolic ones

    -

    -The second requirement excludes all linear functions. Furthermore, in +

    The second requirement excludes all linear functions. Furthermore, in a MLP with only linear activation functions, each layer simply performs a linear transformation of its inputs. +

    -

    -Regardless of the number of layers, the output of the NN will be +

    Regardless of the number of layers, the output of the NN will be nothing but a linear function of the inputs. Thus we need to introduce some kind of non-linearity to the NN to be able to fit non-linear functions Typical examples are the logistic Sigmoid +

    $$ f(x) = \frac{1}{1 + e^{-x}}, $$ -and the hyperbolic tangent function +

    and the hyperbolic tangent function

    $$ f(x) = \tanh(x) $$ -

    -









    +









    Relevance

    -

    -The sigmoid function are more biologically plausible because the +

    The sigmoid function are more biologically plausible because the output of inactive neurons are zero. Such activation function are called one-sided. However, it has been shown that the hyperbolic tangent performs better than the sigmoid for training MLPs. has become the most popular for deep neural networks +

    -

    -

    """The sigmoid function (or the logistic curve) is a 
    +
    +
    +
    +
    +
    +
    """The sigmoid function (or the logistic curve) is a 
     function that takes any real number, z, and outputs a number (0,1).
     It is useful in neural networks for assigning weights on a relative scale.
     The value z is the weighted sum of parameters involved in the learning algorithm."""
    @@ -1967,36 +2265,46 @@ ax.set_xlabel(&
     ax.set_title('Rectified linear unit')
     
     plt.show()
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    The multilayer perceptron (MLP)

    -

    -The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of - +

    The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of

    1. A neural network with one or more layers of nodes between the input and the output nodes.
    2. The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.
    3. The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.
    - -As a convention it is normal to call a network with one layer of input units, one layer of hidden +

    As a convention it is normal to call a network with one layer of input units, one layer of hidden units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc. +

    -

    -For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. +

    For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. Hereafter we will call the various entities of a layer for nodes. There are also no connections within a single layer. +

    -

    -The number of input nodes does not need to equal the number of output +

    The number of input nodes does not need to equal the number of output nodes. This applies also to the hidden layers. Each layer may have its own number of nodes and activation functions. +

    -

    -The hidden layers have their name from the fact that they are not +

    The hidden layers have their name from the fact that they are not linked to observables and as we will see below when we define the so-called activation \( \hat{z} \), we can think of this as a basis expansion of the original inputs \( \hat{x} \). The difference however @@ -2005,227 +2313,207 @@ basis functions (which will correspond to the weights in the network) are learned from data. This results in an important difference between neural networks and deep learning approaches on one side and methods like logistic regression or linear regression and their modifications on the other side. +

    -











    -

    From one to many layers, the universal approximation theorem

    -

    -A neural network with only one layer, what we called the simple +

    A neural network with only one layer, what we called the simple perceptron, is best suited if we have a standard binary model with clear (linear) boundaries between the outcomes. As such it could equally well be replaced by standard linear regression or logistic regression. Networks with one or more hidden layers approximate systems with more complex boundaries. +

    -

    -As stated earlier, +

    As stated earlier, an important theorem in studies of neural networks, restated without proof here, is the universal approximation theorem. +

    -

    -It states that a feed-forward network with a single hidden layer +

    It states that a feed-forward network with a single hidden layer containing a finite number of neurons can approximate continuous functions on compact subsets of real functions. The theorem thus states that simple neural networks can represent a wide variety of interesting functions when given appropriate parameters. It is the multilayer feedforward architecture itself which gives neural networks the potential of being universal approximators. +

    -











    -

    Deriving the back propagation code for a multilayer perceptron model

    -

    -As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. +

    As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. The unknowwn quantities are our weights \( w_{ij} \) and we need to find an algorithm for changing them so that our errors are as small as possible. This leads us to the famous back propagation algorithm. +

    -

    -The questions we want to ask are how do changes in the biases and the +

    The questions we want to ask are how do changes in the biases and the weights in our network change the cost function and how can we use the final output to modify the weights? +

    -

    -To derive these equations let us start with a plain regression problem +

    To derive these equations let us start with a plain regression problem and define our cost function as +

    $$ {\cal C}(\hat{W}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2, $$ -

    -where the $t_i$s are our \( n \) targets (the values we want to +

    where the $t_i$s are our \( n \) targets (the values we want to reproduce), while the outputs of the network after having propagated all inputs \( \hat{x} \) are given by \( y_i \). Below we will demonstrate how the basic equations arising from the back propagation algorithm can be modified in order to study classification problems with \( K \) classes. +

    -











    -

    Definitions

    -

    -With our definition of the targets \( \hat{t} \), the outputs of the +

    With our definition of the targets \( \hat{t} \), the outputs of the network \( \hat{y} \) and the inputs \( \hat{x} \) we define now the activation \( z_j^l \) of node/neuron/unit \( j \) of the \( l \)-th layer as a function of the bias, the weights which add up from the previous layer \( l-1 \) and the forward passes/outputs \( \hat{a}^{l-1} \) from the previous layer as +

    $$ z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, $$ -

    -where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) +

    where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) represents the total number of nodes/neurons/units of layer \( l-1 \). The figure here illustrates this equation. We can rewrite this in a more compact form as the matrix-vector products we discussed earlier, +

    $$ \hat{z}^l = \left(\hat{W}^l\right)^T\hat{a}^{l-1}+\hat{b}^l. $$ -

    -With the activation values \( \hat{z}^l \) we can in turn define the +

    With the activation values \( \hat{z}^l \) we can in turn define the output of layer \( l \) as \( \hat{a}^l = f(\hat{z}^l) \) where \( f \) is our activation function. In the examples here we will use the sigmoid function discussed in our logistic regression lectures. We will also use the same activation function \( f \) for all layers and their nodes. It means we have +

    $$ a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. $$ -

    -









    +









    Derivatives and the chain rule

    -

    -From the definition of the activation \( z_j^l \) we have +

    From the definition of the activation \( z_j^l \) we have

    $$ \frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, $$ -and +

    and

    $$ \frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. $$ -

    -With our definition of the activation function we have that (note that this function depends only on \( z_j^l \)) +

    With our definition of the activation function we have that (note that this function depends only on \( z_j^l \))

    $$ \frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)). $$ -

    -









    +









    Derivative of the cost function

    -

    -With these definitions we can now compute the derivative of the cost function in terms of the weights. +

    With these definitions we can now compute the derivative of the cost function in terms of the weights.

    -

    -Let us specialize to the output layer \( l=L \). Our cost function is +

    Let us specialize to the output layer \( l=L \). Our cost function is

    $$ {\cal C}(\hat{W^L}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - t_i\right)^2, $$ -The derivative of this function with respect to the weights is +

    The derivative of this function with respect to the weights is

    $$ \frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}}, $$ -The last partial derivative can easily be computed and reads (by applying the chain rule) +

    The last partial derivative can easily be computed and reads (by applying the chain rule)

    $$ \frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1}, $$ -

    -









    +









    Bringing it together, first back propagation equation

    -

    -We have thus +

    We have thus

    $$ \frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)a_j^L(1-a_j^L)a_k^{L-1}, $$ -

    -Defining +

    Defining

    $$ \delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - t_j\right) = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, $$ -and using the Hadamard product of two vectors we can write this as +

    and using the Hadamard product of two vectors we can write this as

    $$ \hat{\delta}^L = f'(\hat{z}^L)\circ\frac{\partial {\cal C}}{\partial (\hat{a}^L)}. $$ -

    -This is an important expression. The second term on the right handside +

    This is an important expression. The second term on the right handside measures how fast the cost function is changing as a function of the $j$th output activation. If, for example, the cost function doesn't depend much on a particular output node \( j \), then \( \delta_j^L \) will be small, which is what we would expect. The first term on the right, measures how fast the activation function \( f \) is changing at a given activation value \( z_j^L \). +

    -

    -Notice that everything in the above equations is easily computed. In +

    Notice that everything in the above equations is easily computed. In particular, we compute \( z_j^L \) while computing the behaviour of the network, and it is only a small additional overhead to compute \( f'(z^L_j) \). The exact form of the derivative with respect to the output depends on the form of the cost function. However, provided the cost function is known there should be little trouble in calculating +

    $$ \frac{\partial {\cal C}}{\partial (a_j^L)} $$ -

    -With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely +

    With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely

    $$ \frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}. $$ -

    +









    +

    Derivatives in terms of \( z_j^L \)

    -

    Derivatives in terms of \( z_j^L \)

    - -

    -It is also easy to see that our previous equation can be written as +

    It is also easy to see that our previous equation can be written as

    $$ \delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, $$ -which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely +

    which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely

    $$ \delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, $$ -That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias. +

    That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias.











    -

    Bringing it together

    -

    -We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are +

    We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are

    -

    The starting equations

    @@ -2237,7 +2525,7 @@ $$ \end{equation} $$ -and +

    and

    $$ \begin{equation} \delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, @@ -2245,7 +2533,7 @@ $$ \end{equation} $$ -and +

    and

    $$ \begin{equation} @@ -2256,116 +2544,106 @@ $$
    -

    -An interesting consequence of the above equations is that when the +

    An interesting consequence of the above equations is that when the activation \( a_k^{L-1} \) is small, the gradient term, that is the derivative of the cost function with respect to the weights, will also tend to be small. We say then that the weight learns slowly, meaning that it changes slowly when we minimize the weights via say gradient descent. In this case we say the system learns slowly. +

    -

    -Another interesting feature is that is when the activation function, +

    Another interesting feature is that is when the activation function, represented by the sigmoid function here, is rather flat when we move towards its end values \( 0 \) and \( 1 \) (see the above Python codes). In these cases, the derivatives of the activation function will also be close to zero, meaning again that the gradients will be small and the network learns slowly again. +

    -

    -We need a fourth equation and we are set. We are going to propagate +

    We need a fourth equation and we are set. We are going to propagate backwards in order to the determine the weights and biases. In order to do so we need to represent the error in the layer before the final one \( L-1 \) in terms of the errors in the final output layer. +

    -











    -

    Final back propagating equation

    -

    -We have that (replacing \( L \) with a general layer \( l \)) +

    We have that (replacing \( L \) with a general layer \( l \))

    $$ \delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. $$ -We want to express this in terms of the equations for layer \( l+1 \). Using the chain rule and summing over all \( k \) entries we have +

    We want to express this in terms of the equations for layer \( l+1 \). Using the chain rule and summing over all \( k \) entries we have

    $$ \delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, $$ -and recalling that +

    and recalling that

    $$ z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, $$ -with \( M_l \) being the number of nodes in layer \( l \), we obtain +

    with \( M_l \) being the number of nodes in layer \( l \), we obtain

    $$ \delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l), $$ -This is our final equation. +

    This is our final equation.

    -

    -We are now ready to set up the algorithm for back propagation and learning the weights and biases. +

    We are now ready to set up the algorithm for back propagation and learning the weights and biases.

    -











    -

    Setting up the Back propagation algorithm

    -

    -The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm. +

    The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.

    -

    -First, we set up the input data \( \hat{x} \) and the activations +

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

    -

    -Secondly, we perform then the feed forward till we reach the output +

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

    -

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

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

    $$ \delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. $$
    -

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

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

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

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

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

    $$ w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, $$ @@ -2377,21 +2655,14 @@ $$
    -

    -The parameter \( \eta \) is the learning parameter discussed in connection with the gradient descent methods. +

    The parameter \( \eta \) is the learning parameter discussed in connection with the gradient descent methods. Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training. - -

    +

    - -
    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week40/ipynb/ipynb-week40-src.tar.gz b/doc/pub/week40/ipynb/ipynb-week40-src.tar.gz index 14a4ca369..44284d7bd 100644 Binary files a/doc/pub/week40/ipynb/ipynb-week40-src.tar.gz and b/doc/pub/week40/ipynb/ipynb-week40-src.tar.gz differ diff --git a/doc/pub/week40/ipynb/week40.ipynb b/doc/pub/week40/ipynb/week40.ipynb index d2a86b7c9..a86a23c43 100644 --- a/doc/pub/week40/ipynb/week40.ipynb +++ b/doc/pub/week40/ipynb/week40.ipynb @@ -2,44 +2,72 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "33a7f33a", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "eb6961f1", + "metadata": { + "editable": true + }, "source": [ - "\n", "# Week 40: From Stochastic Gradient Descent to Neural networks\n", - "\n", - " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo, Norway and Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA\n", "\n", - "Date: **Oct 9, 2021**\n", - "\n", - "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", - "\n", - "\n", - "\n", + "Date: **Nov 2, 2021**\n", "\n", + "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" + ] + }, + { + "cell_type": "markdown", + "id": "5d9b6f73", + "metadata": { + "editable": true + }, + "source": [ "## Plan for week 40\n", "\n", "* Thursday: Stochastic Gradient descent with examples and automatic differentiation and begin Neural Networks. \n", "\n", " * [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober7.mp4?vrtx=view-as-webpage)\n", "\n", - "\n", "* Friday: Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model. \n", "\n", " * [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober8.mp4?vrtx=view-as-webpage)\n", "\n", - "\n", "Reading suggestions for both days: [Aurelien Geron's chapter 10](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf) and Hastie et al chapter 11.\n", "For Stochastic Gradient Descent, we recommend chapter 4 of Geron's text.\n", - "For neural networks we recommend Goodfellow et al chapters 6 and 7 and Bishop 5.1-5.4\n", - "\n", - "\n", - "\n", + "For neural networks we recommend Goodfellow et al chapters 6 and 7 and Bishop 5.1-5.4" + ] + }, + { + "cell_type": "markdown", + "id": "896b7e7c", + "metadata": { + "editable": true + }, + "source": [ "## Overview video on Stochastic Gradient Descent\n", "\n", - "[What is Stochastic Gradient Descent](https://www.youtube.com/watch?v=vMh0zPT0tLI&ab_channel=StatQuestwithJoshStarmer)\n", - "\n", - "\n", + "[What is Stochastic Gradient Descent](https://www.youtube.com/watch?v=vMh0zPT0tLI&ab_channel=StatQuestwithJoshStarmer)" + ] + }, + { + "cell_type": "markdown", + "id": "5285634a", + "metadata": { + "editable": true + }, + "source": [ "## Batches and mini-batches\n", "\n", "In gradient descent we compute the cost function and its gradient for all data points we have.\n", @@ -52,8 +80,16 @@ "gradient over batches of the training data. For example, in current\n", "a typical batch could contain some thousand examples from\n", "an entire training set of several millions. This batch is then used to\n", - "perform a parameter update.\n", - "\n", + "perform a parameter update." + ] + }, + { + "cell_type": "markdown", + "id": "3a063b42", + "metadata": { + "editable": true + }, + "source": [ "## Stochastic Gradient Descent (SGD)\n", "\n", "In stochastic gradient descent, the extreme case is the case where we\n", @@ -76,9 +112,16 @@ "vectorized operation implementations work faster when their inputs are\n", "sized in powers of 2.\n", "\n", - "In our notes with SGD we mean stochastic gradient descent with mini-batches.\n", - "\n", - "\n", + "In our notes with SGD we mean stochastic gradient descent with mini-batches." + ] + }, + { + "cell_type": "markdown", + "id": "286abf6d", + "metadata": { + "editable": true + }, + "source": [ "## Stochastic Gradient Descent\n", "\n", "Stochastic gradient descent (SGD) and variants thereof address some of\n", @@ -91,7 +134,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "91f5da81", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n", @@ -101,7 +147,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d9a38f58", + "metadata": { + "editable": true + }, "source": [ "## Computation of gradients\n", "\n", @@ -111,7 +160,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d782cea1", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", @@ -121,14 +173,25 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6b196224", + "metadata": { + "editable": true + }, "source": [ "Stochasticity/randomness is introduced by only taking the\n", "gradient on a subset of the data called minibatches. If there are $n$\n", "data points and the size of each minibatch is $M$, there will be $n/M$\n", "minibatches. We denote these minibatches by $B_k$ where\n", - "$k=1,\\cdots,n/M$.\n", - "\n", + "$k=1,\\cdots,n/M$." + ] + }, + { + "cell_type": "markdown", + "id": "5ec16fda", + "metadata": { + "editable": true + }, + "source": [ "## SGD example\n", "\n", "As an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \n", @@ -147,7 +210,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e1f93c6a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\nabla_{\\beta}\n", @@ -159,7 +225,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dcbae038", + "metadata": { + "editable": true + }, "source": [ "## The gradient step\n", "\n", @@ -168,7 +237,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c18ff285", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\beta_{j+1} = \\beta_j - \\gamma_j \\sum_{i \\in B_k}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", @@ -178,21 +250,36 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5288661b", + "metadata": { + "editable": true + }, "source": [ "where $k$ is picked at random with equal\n", "probability from $[1,n/M]$. An iteration over the number of\n", "minibathces (n/M) is commonly referred to as an epoch. Thus it is\n", "typical to choose a number of epochs and for each epoch iterate over\n", - "the number of minibatches, as exemplified in the code below.\n", - "\n", + "the number of minibatches, as exemplified in the code below." + ] + }, + { + "cell_type": "markdown", + "id": "ddfb5d51", + "metadata": { + "editable": true + }, + "source": [ "## Simple example code" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 1, + "id": "be52d134", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import numpy as np \n", @@ -213,7 +300,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cd8c6d07", + "metadata": { + "editable": true + }, "source": [ "Taking the gradient only on a subset of the data has two important\n", "benefits. First, it introduces randomness which decreases the chance\n", @@ -221,8 +311,16 @@ "the size of the minibatches are small relative to the number of\n", "datapoints ($M < n$), the computation of the gradient is much\n", "cheaper since we sum over the datapoints in the $k-th$ minibatch and not\n", - "all $n$ datapoints.\n", - "\n", + "all $n$ datapoints." + ] + }, + { + "cell_type": "markdown", + "id": "3d3fd6f2", + "metadata": { + "editable": true + }, + "source": [ "## When do we stop?\n", "\n", "A natural question is when do we stop the search for a new minimum?\n", @@ -234,8 +332,16 @@ "evaluate the cost function at this point, store the result and\n", "continue the search. If the test kicks in at a later stage we can\n", "compare the values of the cost function and keep the $\\beta$ that\n", - "gave the lowest value.\n", - "\n", + "gave the lowest value." + ] + }, + { + "cell_type": "markdown", + "id": "4809cc99", + "metadata": { + "editable": true + }, + "source": [ "## Slightly different approach\n", "\n", "Another approach is to let the step length $\\gamma_j$ depend on the\n", @@ -253,8 +359,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 2, + "id": "aac7dff1", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import numpy as np \n", @@ -285,18 +395,32 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5396bd45", + "metadata": { + "editable": true + }, + "source": [ + "We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters $t_0$ and $t_1$." + ] + }, + { + "cell_type": "markdown", + "id": "69a3b8e1", + "metadata": { + "editable": true + }, "source": [ - "We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters $t_0$ and $t_1$.\n", - "\n", - "\n", "## Program for stochastic gradient" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 3, + "id": "596c9872", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "%matplotlib inline\n", @@ -351,8 +475,8 @@ "for epoch in range(n_epochs):\n", " for i in range(m):\n", " random_index = np.random.randint(m)\n", - " xi = X[random_index:random_index+1]\n", - " yi = y[random_index:random_index+1]\n", + " xi = X[random_index:random_index+m]\n", + " yi = y[random_index:random_index+m]\n", " gradients = 2.0* xi.T @ ((xi @ theta)-yi)\n", " eta = learning_schedule(epoch*m+i)\n", " theta = theta - eta*gradients\n", @@ -371,7 +495,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "915d2dc5", + "metadata": { + "editable": true + }, "source": [ "## Momentum based GD\n", "\n", @@ -383,7 +510,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d79babcd", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", @@ -392,7 +522,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f6717923", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -407,7 +540,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9f63c31d", + "metadata": { + "editable": true + }, "source": [ "where we have introduced a momentum parameter $\\gamma$, with\n", "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", @@ -423,7 +559,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "428883d0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", @@ -432,10 +571,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d558ee18", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." + ] + }, + { + "cell_type": "markdown", + "id": "ff54e584", + "metadata": { + "editable": true + }, "source": [ - "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$.\n", - "\n", "## More on momentum based approaches\n", "\n", "Let us try to get more intuition from these equations. It is helpful\n", @@ -447,7 +597,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a7aa3431", + "metadata": { + "editable": true + }, "source": [ "$$\n", "m {d^2 \\mathbf{w} \\over dt^2} + \\mu {d \\mathbf{w} \\over dt }= -\\nabla_w E(\\mathbf{w}).\n", @@ -456,14 +609,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "052fe58d", + "metadata": { + "editable": true + }, "source": [ "We can discretize this equation in the usual way to get" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d8d61c87", + "metadata": { + "editable": true + }, "source": [ "$$\n", "m { \\mathbf{w}_{t+\\Delta t}-2 \\mathbf{w}_{t} +\\mathbf{w}_{t-\\Delta t} \\over (\\Delta t)^2}+\\mu {\\mathbf{w}_{t+\\Delta t}- \\mathbf{w}_{t} \\over \\Delta t} = -\\nabla_w E(\\mathbf{w}).\n", @@ -472,14 +631,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "787f6c88", + "metadata": { + "editable": true + }, "source": [ "Rearranging this equation, we can rewrite this as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b52e2113", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\Delta \\mathbf{w}_{t +\\Delta t}= - { (\\Delta t)^2 \\over m +\\mu \\Delta t} \\nabla_w E(\\mathbf{w})+ {m \\over m +\\mu \\Delta t} \\Delta \\mathbf{w}_t.\n", @@ -488,7 +653,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9644066b", + "metadata": { + "editable": true + }, "source": [ "## Momentum parameter\n", "\n", @@ -501,7 +669,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "97ee29bc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n", @@ -510,7 +681,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4178c6d4", + "metadata": { + "editable": true + }, "source": [ "Thus, as the name suggests, the momentum parameter is proportional to\n", "the mass of the particle and effectively provides inertia.\n", @@ -540,7 +714,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8bb012ed", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1}) \\nonumber\n", @@ -549,7 +726,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c0f2506e", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -564,14 +744,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8ebfdb6d", + "metadata": { + "editable": true + }, + "source": [ + "One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\\gamma$." + ] + }, + { + "cell_type": "markdown", + "id": "306ed0d4", + "metadata": { + "editable": true + }, "source": [ - "One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\\gamma$.\n", - "\n", - "\n", "## Second moment of the gradient\n", "\n", - "\n", "In stochastic gradient descent, with and without momentum, we still\n", "have to specify a schedule for tuning the learning rates $\\eta_t$\n", "as a function of time. As discussed in the context of Newton's\n", @@ -591,8 +780,16 @@ "Recently, a number of methods have been introduced that accomplish\n", "this by tracking not only the gradient, but also the second moment of\n", "the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and\n", - "ADAM.\n", - "\n", + "ADAM." + ] + }, + { + "cell_type": "markdown", + "id": "d21b15f3", + "metadata": { + "editable": true + }, + "source": [ "## RMS prop\n", "\n", "In RMS prop, in addition to keeping a running average of the first\n", @@ -603,7 +800,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c1c6244b", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -618,7 +818,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ddedc4f9", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n", @@ -627,7 +830,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1f9233f3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\mathbf{g}_t \\over \\sqrt{\\mathbf{s}_t +\\epsilon}}, \\nonumber\n", @@ -636,7 +842,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6d297d02", + "metadata": { + "editable": true + }, "source": [ "where $\\beta$ controls the averaging time of the second moment and is\n", "typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate\n", @@ -646,9 +855,16 @@ "is clear from this formula that the learning rate is reduced in\n", "directions where the norm of the gradient is consistently large. This\n", "greatly speeds up the convergence by allowing us to use a larger\n", - "learning rate for flat directions.\n", - "\n", - "\n", + "learning rate for flat directions." + ] + }, + { + "cell_type": "markdown", + "id": "20736543", + "metadata": { + "editable": true + }, + "source": [ "## ADAM optimizer\n", "\n", "A related algorithm is the ADAM optimizer. In ADAM, we keep a running\n", @@ -667,7 +883,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "df520812", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -682,7 +901,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "799b0364", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n", @@ -691,7 +913,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fc4260a2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n", @@ -700,7 +925,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "abe10b9e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", @@ -709,7 +937,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3a313288", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", @@ -718,7 +949,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "86099421", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\boldsymbol{\\mathbf{m}}_t \\over \\sqrt{\\boldsymbol{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n", @@ -727,7 +961,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c7943b16", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -741,7 +978,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "43af0139", + "metadata": { + "editable": true + }, "source": [ "where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and\n", "second moment and are typically taken to be $0.9$ and $0.99$\n", @@ -757,7 +997,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1ed36e1b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\Delta \\theta_{t+1}= -\\eta_t { \\boldsymbol{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n", @@ -766,7 +1009,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1db90757", + "metadata": { + "editable": true + }, "source": [ "## Practical tips\n", "\n", @@ -778,10 +1024,16 @@ "\n", "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.\n", "\n", - "Geron's text, see chapter 11, has several interesting discussions.\n", - "\n", - "\n", - "\n", + "Geron's text, see chapter 11, has several interesting discussions." + ] + }, + { + "cell_type": "markdown", + "id": "ee252d4e", + "metadata": { + "editable": true + }, + "source": [ "## Automatic differentiation\n", "\n", "[Automatic differentiation (AD)](https://en.wikipedia.org/wiki/Automatic_differentiation), \n", @@ -809,15 +1061,16 @@ "while numerical differentiation can introduce round-off errors in the\n", "discretization process and cancellation\n", "\n", - "\n", - "\n", "Python has tools for so-called **automatic differentiation**.\n", "Consider the following example" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8b90c6db", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n", @@ -826,14 +1079,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9260c457", + "metadata": { + "editable": true + }, "source": [ "which has the following derivative" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "15c207ef", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f'(x) = \\cos\\left(2\\pi x + x^2\\right)\\left(2\\pi + 2x\\right)\n", @@ -842,15 +1101,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7e261104", + "metadata": { + "editable": true + }, "source": [ "Using **autograd** we have" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 4, + "id": "77001fff", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -891,9 +1157,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5d3b0dc1", + "metadata": { + "editable": true + }, "source": [ - "\n", "## Using autograd\n", "\n", "Here we\n", @@ -905,8 +1173,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 5, + "id": "1ffc9379", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -930,7 +1202,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fd871f0b", + "metadata": { + "editable": true + }, "source": [ "## Autograd with more complicated functions\n", "\n", @@ -941,8 +1216,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 6, + "id": "ddbbd672", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -982,18 +1261,32 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4d6a7aea", + "metadata": { + "editable": true + }, + "source": [ + "Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable." + ] + }, + { + "cell_type": "markdown", + "id": "ca7c075b", + "metadata": { + "editable": true + }, "source": [ - "Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.\n", - "\n", - "\n", "## More complicated functions using the elements of their arguments directly" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 7, + "id": "9229568b", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1017,23 +1310,37 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6bc3b22b", + "metadata": { + "editable": true + }, "source": [ "Note that in this case, when sending an array as input argument, the\n", "output from Autograd is another array. This is the true gradient of\n", "the function, as opposed to the function in the previous example. By\n", "using arrays to represent the variables, the output from Autograd\n", "might be easier to work with, as the output is closer to what one\n", - "could expect form a gradient-evaluting function.\n", - "\n", - "\n", + "could expect form a gradient-evaluting function." + ] + }, + { + "cell_type": "markdown", + "id": "ed6fc569", + "metadata": { + "editable": true + }, + "source": [ "## Functions using mathematical functions from Numpy" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 8, + "id": "41ee08d4", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1057,15 +1364,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9734523b", + "metadata": { + "editable": true + }, "source": [ "## More autograd" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 9, + "id": "ee6fed3e", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1086,45 +1400,58 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d1a17448", + "metadata": { + "editable": true + }, "source": [ "## And with loops" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": 10, + "id": "f5a52deb", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ - "9\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "C\n", - "O\n", - "D\n", - "E\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K\n", - " \n", - " \n", - "p\n", - "y\n", - "c\n", - "o\n", - "d" + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f6_for(x):\n", + " val = 0\n", + " for i in range(10):\n", + " val = val + x**i\n", + " return val\n", + "\n", + "def f6_while(x):\n", + " val = 0\n", + " i = 0\n", + " while i < 10:\n", + " val = val + x**i\n", + " i = i + 1\n", + " return val\n", + "\n", + "f6_for_grad = grad(f6_for)\n", + "f6_while_grad = grad(f6_while)\n", + "\n", + "x = 0.5\n", + "\n", + "# Print the computed derivaties of f6_for and f6_while\n", + "print(\"The computed derivative of f6_for at x = %g is: %g\"%(x,f6_for_grad(x)))\n", + "print(\"The computed derivative of f6_while at x = %g is: %g\"%(x,f6_while_grad(x)))" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 11, + "id": "b11ffbe8", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1140,15 +1467,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f17fe635", + "metadata": { + "editable": true + }, "source": [ "## Using recursion" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 12, + "id": "9b13fd12", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1182,10 +1516,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "120d5d12", + "metadata": { + "editable": true + }, + "source": [ + "Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input." + ] + }, + { + "cell_type": "markdown", + "id": "c1a37a71", + "metadata": { + "editable": true + }, "source": [ - "Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.\n", - "\n", "## Unsupported functions\n", "Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.\n", "\n", @@ -1194,8 +1539,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 13, + "id": "94b90bdb", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1213,17 +1562,32 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ca11f81b", + "metadata": { + "editable": true + }, + "source": [ + "Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible." + ] + }, + { + "cell_type": "markdown", + "id": "0b54c45e", + "metadata": { + "editable": true + }, "source": [ - "Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.\n", - "\n", "## The syntax a.dot(b) when finding the dot product" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 14, + "id": "0c11abcc", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1241,7 +1605,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a8667c75", + "metadata": { + "editable": true + }, "source": [ "Here we are told that the 'dot' function does not belong to Autograd's\n", "version of a Numpy array. To overcome this, an alternative syntax\n", @@ -1250,8 +1617,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 15, + "id": "80798223", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1272,7 +1643,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "34635399", + "metadata": { + "editable": true + }, "source": [ "## Recommended to avoid\n", "The documentation recommends to avoid inplace operations such as" @@ -1280,8 +1654,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 16, + "id": "65e2eb3b", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "a += b\n", @@ -1292,18 +1670,25 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ada71b25", + "metadata": { + "editable": true + }, "source": [ "## Videos on Neural Networks\n", "\n", - "\n", "[Neural Networks demystified](https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs)\n", "\n", - "[Building Neural Networks from scratch](https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex)\n", - "\n", - "\n", - "\n", - "\n", + "[Building Neural Networks from scratch](https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex)" + ] + }, + { + "cell_type": "markdown", + "id": "70f34d32", + "metadata": { + "editable": true + }, + "source": [ "## Neural networks\n", "\n", "Artificial neural networks are computational systems that can learn to\n", @@ -1312,9 +1697,16 @@ "biological system, wherein neurons interact by sending signals in the\n", "form of mathematical functions between layers. All layers can contain\n", "an arbitrary number of neurons, and each connection is represented by\n", - "a weight variable.\n", - "\n", - "\n", + "a weight variable." + ] + }, + { + "cell_type": "markdown", + "id": "7050c8c3", + "metadata": { + "editable": true + }, + "source": [ "## Artificial neurons\n", "\n", "The field of artificial neural networks has a long history of\n", @@ -1334,7 +1726,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d03113ff", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1349,7 +1744,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a5dbf267", + "metadata": { + "editable": true + }, "source": [ "Here, the output $y$ of the neuron is the value of its activation function, which have as input\n", "a weighted sum of signals $x_i, \\dots ,x_n$ received by $n$ other neurons.\n", @@ -1381,8 +1779,16 @@ "\n", "The applications are not limited to the natural sciences. There is a\n", "plethora of applications in essentially all disciplines, from the\n", - "humanities to life science and medicine.\n", - "\n", + "humanities to life science and medicine." + ] + }, + { + "cell_type": "markdown", + "id": "0bc22463", + "metadata": { + "editable": true + }, + "source": [ "## Neural network types\n", "\n", "An artificial neural network (ANN), is a computational model that\n", @@ -1402,9 +1808,16 @@ "nonlinear models for supervised learning. As we will see, neural nets\n", "can be viewed as natural, more powerful extensions of supervised\n", "learning methods such as linear and logistic regression and soft-max\n", - "methods we discussed earlier.\n", - "\n", - "\n", + "methods we discussed earlier." + ] + }, + { + "cell_type": "markdown", + "id": "3332e77d", + "metadata": { + "editable": true + }, + "source": [ "## Feed-forward neural networks\n", "\n", "The feed-forward neural network (FFNN) was the first and simplest type\n", @@ -1416,10 +1829,16 @@ "flow. Additionally, each arrow corresponds to a weight variable\n", "(figure to come). We observe that each node in a layer is connected\n", "to *all* nodes in the subsequent layer, making this a so-called\n", - "*fully-connected* FFNN.\n", - "\n", - "\n", - "\n", + "*fully-connected* FFNN." + ] + }, + { + "cell_type": "markdown", + "id": "b15611ef", + "metadata": { + "editable": true + }, + "source": [ "## Convolutional Neural Network\n", "\n", "A different variant of FFNNs are *convolutional neural networks*\n", @@ -1439,8 +1858,16 @@ "convolutional layers that learn local features of the input, with a\n", "fully-connected layer at the end, which gathers all the local data and\n", "produces the outputs. They have wide applications in image and video\n", - "recognition.\n", - "\n", + "recognition." + ] + }, + { + "cell_type": "markdown", + "id": "49b24b7e", + "metadata": { + "editable": true + }, + "source": [ "## Recurrent neural networks\n", "\n", "So far we have only mentioned ANNs where information flows in one\n", @@ -1452,8 +1879,16 @@ "sequential information by performing the same task for every element\n", "in a sequence, where each element depends on previous elements. An\n", "example of such information is sentences, making recurrent NNs\n", - "especially well-suited for handwriting and speech recognition.\n", - "\n", + "especially well-suited for handwriting and speech recognition." + ] + }, + { + "cell_type": "markdown", + "id": "7149cbc4", + "metadata": { + "editable": true + }, + "source": [ "## Other types of networks\n", "\n", "There are many other kinds of ANNs that have been developed. One type\n", @@ -1465,8 +1900,16 @@ "linear activation function). The layers are normally fully-connected\n", "and there are no cycles, thus RBFs can be viewed as a type of\n", "fully-connected FFNN. They are however usually treated as a separate\n", - "type of NN due the unusual activation functions.\n", - "\n", + "type of NN due the unusual activation functions." + ] + }, + { + "cell_type": "markdown", + "id": "126894d9", + "metadata": { + "editable": true + }, + "source": [ "## Multilayer perceptrons\n", "\n", "One uses often so-called fully-connected feed-forward neural networks\n", @@ -1474,8 +1917,16 @@ "and an output layer) consisting of neurons that have non-linear\n", "activation functions.\n", "\n", - "Such networks are often called *multilayer perceptrons* (MLPs).\n", - "\n", + "Such networks are often called *multilayer perceptrons* (MLPs)." + ] + }, + { + "cell_type": "markdown", + "id": "e335c763", + "metadata": { + "editable": true + }, + "source": [ "## Why multilayer perceptrons?\n", "\n", "According to the *Universal approximation theorem*, a feed-forward\n", @@ -1487,21 +1938,34 @@ "\n", "Note that the requirements on the activation function only applies to\n", "the hidden layer, the output nodes are always assumed to be linear, so\n", - "as to not restrict the range of output values.\n", - "\n", - "\n", + "as to not restrict the range of output values." + ] + }, + { + "cell_type": "markdown", + "id": "479c95b7", + "metadata": { + "editable": true + }, + "source": [ "## Illustration of a single perceptropn model and a multi-perceptron model\n", "\n", "\n", "\n", - "

    Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

    \n", - "\n", - "\n", "\n", + "

    Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

    \n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "e490ff39", + "metadata": { + "editable": true + }, + "source": [ "## Examples of XOR, OR and AND gates\n", "\n", - "\n", - "\n", "Let us first try to fit various gates using standard linear\n", "regression. The gates we are thinking of are the classical XOR, OR and\n", "AND gates, well-known elements in computer science. The tables here\n", @@ -1511,8 +1975,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 17, + "id": "609e4e46", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\"\"\"\n", @@ -1549,17 +2017,32 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5d6ebae1", + "metadata": { + "editable": true + }, + "source": [ + "What is happening here?" + ] + }, + { + "cell_type": "markdown", + "id": "51096d56", + "metadata": { + "editable": true + }, "source": [ - "What is happening here?\n", - "\n", "## Does Logistic Regression do a better Job?" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 18, + "id": "9b722481", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\"\"\"\n", @@ -1615,17 +2098,32 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "597ac9d4", + "metadata": { + "editable": true + }, + "source": [ + "Not exactly impressive, but somewhat better." + ] + }, + { + "cell_type": "markdown", + "id": "7e317222", + "metadata": { + "editable": true + }, "source": [ - "Not exactly impressive, but somewhat better.\n", - "\n", "## Adding Neural Networks" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 19, + "id": "63bb7b09", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\n", @@ -1641,7 +2139,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d39fc490", + "metadata": { + "editable": true + }, "source": [ "## Mathematical model\n", "\n", @@ -1650,7 +2151,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1d27b52e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y = f\\left(\\sum_{i=1}^n w_ix_i + b_i\\right) = f(z),\n", @@ -1659,15 +2163,26 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "51579d55", + "metadata": { + "editable": true + }, "source": [ "This function receives $x_i$ as inputs.\n", "Here the activation $z=(\\sum_{i=1}^n w_ix_i+b_i)$. \n", "In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of\n", "the neurons in the preceding layer. Furthermore, an MLP is\n", "fully-connected, which means that each neuron receives a weighted sum\n", - "of the outputs of *all* neurons in the previous layer.\n", - "\n", + "of the outputs of *all* neurons in the previous layer." + ] + }, + { + "cell_type": "markdown", + "id": "e9dcbe0d", + "metadata": { + "editable": true + }, + "source": [ "## Mathematical model\n", "\n", "First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$," @@ -1675,7 +2190,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e6cf9e06", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1689,7 +2207,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "31bcac14", + "metadata": { + "editable": true + }, "source": [ "Here $b_i$ is the so-called bias which is normally needed in\n", "case of zero activation weights or inputs. How to fix the biases and\n", @@ -1701,7 +2222,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "64fbd634", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1716,7 +2240,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "79c06827", + "metadata": { + "editable": true + }, "source": [ "where we assume that all nodes in the same layer have identical\n", "activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.\n", @@ -1725,7 +2252,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "177b422a", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1740,15 +2270,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d178534a", + "metadata": { + "editable": true + }, "source": [ "where $N_l$ is the number of nodes in layer $l$. When the output of\n", "all the nodes in the first hidden layer are computed, the values of\n", "the subsequent layer can be calculated and so forth until the output\n", - "is obtained.\n", - "\n", - "\n", - "\n", + "is obtained." + ] + }, + { + "cell_type": "markdown", + "id": "07204e90", + "metadata": { + "editable": true + }, + "source": [ "## Mathematical model\n", "\n", "The output of neuron $i$ in layer 2 is thus," @@ -1756,7 +2295,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7f545b82", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1771,7 +2313,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "416c4399", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1786,14 +2331,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "53157449", + "metadata": { + "editable": true + }, "source": [ "where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4ae0cc46", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1808,7 +2359,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c6893135", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1824,7 +2378,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "461e12b1", + "metadata": { + "editable": true + }, "source": [ "## Mathematical model\n", "\n", @@ -1834,7 +2391,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "57d82440", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1849,11 +2409,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6a1c9c0e", + "metadata": { + "editable": true + }, "source": [ "which illustrates a basic property of MLPs: The only independent\n", - "variables are the input values $x_n$.\n", - "\n", + "variables are the input values $x_n$." + ] + }, + { + "cell_type": "markdown", + "id": "864d28f2", + "metadata": { + "editable": true + }, + "source": [ "## Mathematical model\n", "\n", "This confirms that an MLP, despite its quite convoluted mathematical\n", @@ -1868,7 +2439,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f765f92b", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1883,13 +2457,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b9fc9109", + "metadata": { + "editable": true + }, "source": [ "where the parameters $c_i$ are weights and biases. By adjusting these\n", "parameters, the activation functions can be shifted up and down or\n", "left and right, change slope or be rescaled which is the key to the\n", - "flexibility of a neural network.\n", - "\n", + "flexibility of a neural network." + ] + }, + { + "cell_type": "markdown", + "id": "9fb6b2b5", + "metadata": { + "editable": true + }, + "source": [ "### Matrix-vector notation\n", "\n", "We can introduce a more convenient notation for the activations in an A NN. \n", @@ -1905,7 +2490,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "00b0cdd3", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1935,7 +2523,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6bbe5eb6", + "metadata": { + "editable": true + }, "source": [ "### Matrix-vector notation and activation\n", "\n", @@ -1944,7 +2535,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "955277a1", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1960,15 +2554,25 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "85dbde51", + "metadata": { + "editable": true + }, "source": [ "This is not just a convenient and compact notation, but also a useful\n", "and intuitive way to think about MLPs: The output is calculated by a\n", "series of matrix-vector multiplications and vector additions that are\n", "used as input to the activation functions. For each operation\n", - "$\\mathrm{W}_l \\hat{y}_{l-1}$ we move forward one layer.\n", - "\n", - "\n", + "$\\mathrm{W}_l \\hat{y}_{l-1}$ we move forward one layer." + ] + }, + { + "cell_type": "markdown", + "id": "15a3f221", + "metadata": { + "editable": true + }, + "source": [ "### Activation functions\n", "\n", "A property that characterizes a neural network, other than its\n", @@ -1982,8 +2586,16 @@ "\n", " * Monotonically-increasing\n", "\n", - " * Continuous\n", - "\n", + " * Continuous" + ] + }, + { + "cell_type": "markdown", + "id": "5da193b4", + "metadata": { + "editable": true + }, + "source": [ "### Activation functions, Logistic and Hyperbolic ones\n", "\n", "The second requirement excludes all linear functions. Furthermore, in\n", @@ -1998,7 +2610,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1698ade8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(x) = \\frac{1}{1 + e^{-x}},\n", @@ -2007,14 +2622,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "897ae188", + "metadata": { + "editable": true + }, "source": [ "and the *hyperbolic tangent* function" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "ece1ed87", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(x) = \\tanh(x)\n", @@ -2023,7 +2644,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "417a7ba7", + "metadata": { + "editable": true + }, "source": [ "### Relevance\n", "\n", @@ -2036,8 +2660,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 20, + "id": "5ec3241b", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\"\"\"The sigmoid function (or the logistic curve) is a \n", @@ -2115,7 +2743,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "97f15041", + "metadata": { + "editable": true + }, "source": [ "## The multilayer perceptron (MLP)\n", "\n", @@ -2145,12 +2776,18 @@ "basis functions (which will correspond to the weights in the network)\n", "are learned from data. This results in an important difference between\n", "neural networks and deep learning approaches on one side and methods\n", - "like logistic regression or linear regression and their modifications on the other side.\n", - "\n", - "\n", + "like logistic regression or linear regression and their modifications on the other side." + ] + }, + { + "cell_type": "markdown", + "id": "f3fa1b4e", + "metadata": { + "editable": true + }, + "source": [ "## From one to many layers, the universal approximation theorem\n", "\n", - "\n", "A neural network with only one layer, what we called the simple\n", "perceptron, is best suited if we have a standard binary model with\n", "clear (linear) boundaries between the outcomes. As such it could\n", @@ -2169,13 +2806,18 @@ "states that simple neural networks can represent a wide variety of\n", "interesting functions when given appropriate parameters. It is the\n", "multilayer feedforward architecture itself which gives neural networks\n", - "the potential of being universal approximators.\n", - "\n", - "\n", + "the potential of being universal approximators." + ] + }, + { + "cell_type": "markdown", + "id": "21e86c9d", + "metadata": { + "editable": true + }, + "source": [ "## Deriving the back propagation code for a multilayer perceptron model\n", "\n", - "\n", - "\n", "As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications.\n", "The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible.\n", "This leads us to the famous [back propagation algorithm](https://www.nature.com/articles/323533a0).\n", @@ -2190,7 +2832,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e772cdce", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\cal C}(\\hat{W}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2,\n", @@ -2199,15 +2844,26 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "698958e9", + "metadata": { + "editable": true + }, "source": [ "where the $t_i$s are our $n$ targets (the values we want to\n", "reproduce), while the outputs of the network after having propagated\n", "all inputs $\\hat{x}$ are given by $y_i$. Below we will demonstrate\n", "how the basic equations arising from the back propagation algorithm\n", "can be modified in order to study classification problems with $K$\n", - "classes.\n", - "\n", + "classes." + ] + }, + { + "cell_type": "markdown", + "id": "a28d2d91", + "metadata": { + "editable": true + }, + "source": [ "## Definitions\n", "\n", "With our definition of the targets $\\hat{t}$, the outputs of the\n", @@ -2220,7 +2876,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d166896b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "z_j^l = \\sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,\n", @@ -2229,7 +2888,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "83d8a52c", + "metadata": { + "editable": true + }, "source": [ "where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$\n", "represents the total number of nodes/neurons/units of layer $l-1$. The\n", @@ -2239,7 +2901,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9043e67e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\hat{z}^l = \\left(\\hat{W}^l\\right)^T\\hat{a}^{l-1}+\\hat{b}^l.\n", @@ -2248,7 +2913,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "38ef410a", + "metadata": { + "editable": true + }, "source": [ "With the activation values $\\hat{z}^l$ we can in turn define the\n", "output of layer $l$ as $\\hat{a}^l = f(\\hat{z}^l)$ where $f$ is our\n", @@ -2259,7 +2927,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "05b1fa07", + "metadata": { + "editable": true + }, "source": [ "$$\n", "a_j^l = f(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n", @@ -2268,7 +2939,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9038c068", + "metadata": { + "editable": true + }, "source": [ "## Derivatives and the chain rule\n", "\n", @@ -2277,7 +2951,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a87dd367", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n", @@ -2286,14 +2963,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c0e44d26", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6fe053b3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n", @@ -2302,14 +2985,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ab2ee7cb", + "metadata": { + "editable": true + }, "source": [ "With our definition of the activation function we have that (note that this function depends only on $z_j^l$)" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8eb8e72c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial a_j^l}{\\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)).\n", @@ -2318,7 +3007,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "eaa9d407", + "metadata": { + "editable": true + }, "source": [ "## Derivative of the cost function\n", "\n", @@ -2329,7 +3021,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "020c12af", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\cal C}(\\hat{W^L}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2=\\frac{1}{2}\\sum_{i=1}^n\\left(a_i^L - t_i\\right)^2,\n", @@ -2338,14 +3033,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "14cfc5fa", + "metadata": { + "editable": true + }, "source": [ "The derivative of this function with respect to the weights is" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c3c665c2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}},\n", @@ -2354,14 +3055,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "553452a0", + "metadata": { + "editable": true + }, "source": [ "The last partial derivative can easily be computed and reads (by applying the chain rule)" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c23c4b45", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}} = \\frac{\\partial a_j^L}{\\partial z_{j}^{L}}\\frac{\\partial z_j^L}{\\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1},\n", @@ -2370,7 +3077,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f3e24109", + "metadata": { + "editable": true + }, "source": [ "## Bringing it together, first back propagation equation\n", "\n", @@ -2379,7 +3089,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "99e69f17", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)a_j^L(1-a_j^L)a_k^{L-1},\n", @@ -2388,14 +3101,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d0413cbf", + "metadata": { + "editable": true + }, "source": [ "Defining" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "243c6e25", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\delta_j^L = a_j^L(1-a_j^L)\\left(a_j^L - t_j\\right) = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", @@ -2404,14 +3123,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cdf0babe", + "metadata": { + "editable": true + }, "source": [ "and using the Hadamard product of two vectors we can write this as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d332ef89", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\hat{\\delta}^L = f'(\\hat{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\hat{a}^L)}.\n", @@ -2420,7 +3145,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6dee62e2", + "metadata": { + "editable": true + }, "source": [ "This is an important expression. The second term on the right handside\n", "measures how fast the cost function is changing as a function of the $j$th\n", @@ -2441,7 +3169,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e6b1b7c2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n", @@ -2450,14 +3181,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "25fa99aa", + "metadata": { + "editable": true + }, "source": [ "With the definition of $\\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "2f20e502", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1}.\n", @@ -2466,7 +3203,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "40c1ebc1", + "metadata": { + "editable": true + }, "source": [ "## Derivatives in terms of $z_j^L$\n", "\n", @@ -2475,7 +3215,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "932d51af", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\delta_j^L =\\frac{\\partial {\\cal C}}{\\partial z_j^L}= \\frac{\\partial {\\cal C}}{\\partial a_j^L}\\frac{\\partial a_j^L}{\\partial z_j^L},\n", @@ -2484,14 +3227,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6ac07ae0", + "metadata": { + "editable": true + }, "source": [ "which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8f9b3b42", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L}\\frac{\\partial b_j^L}{\\partial z_j^L}=\\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", @@ -2500,9 +3249,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ba4701b4", + "metadata": { + "editable": true + }, + "source": [ + "That is, the error $\\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias." + ] + }, + { + "cell_type": "markdown", + "id": "9f3dd13f", + "metadata": { + "editable": true + }, "source": [ - "That is, the error $\\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias. \n", "## Bringing it together\n", "\n", "We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are\n", @@ -2512,7 +3273,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f46643d3", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -2527,14 +3291,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "72c17c61", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4a4b9cd6", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -2549,14 +3319,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "660de22f", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d91e1536", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -2571,7 +3347,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "28b057da", + "metadata": { + "editable": true + }, "source": [ "An interesting consequence of the above equations is that when the\n", "activation $a_k^{L-1}$ is small, the gradient term, that is the\n", @@ -2587,13 +3366,19 @@ "to zero, meaning again that the gradients will be small and the\n", "network learns slowly again.\n", "\n", - "\n", - "\n", "We need a fourth equation and we are set. We are going to propagate\n", "backwards in order to the determine the weights and biases. In order\n", "to do so we need to represent the error in the layer before the final\n", - "one $L-1$ in terms of the errors in the final output layer.\n", - "\n", + "one $L-1$ in terms of the errors in the final output layer." + ] + }, + { + "cell_type": "markdown", + "id": "cbee200c", + "metadata": { + "editable": true + }, + "source": [ "## Final back propagating equation\n", "\n", "We have that (replacing $L$ with a general layer $l$)" @@ -2601,7 +3386,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cfd8e707", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n", @@ -2610,14 +3398,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9c059e74", + "metadata": { + "editable": true + }, "source": [ "We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "87b9c575", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\delta_j^l =\\sum_k \\frac{\\partial {\\cal C}}{\\partial z_k^{l+1}}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}}=\\sum_k \\delta_k^{l+1}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}},\n", @@ -2626,14 +3420,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9417f6ec", + "metadata": { + "editable": true + }, "source": [ "and recalling that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "07278244", + "metadata": { + "editable": true + }, "source": [ "$$\n", "z_j^{l+1} = \\sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},\n", @@ -2642,14 +3442,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3d2ebc91", + "metadata": { + "editable": true + }, "source": [ "with $M_l$ being the number of nodes in layer $l$, we obtain" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "68aee93b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\delta_j^l =\\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),\n", @@ -2658,37 +3464,45 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a65994f4", + "metadata": { + "editable": true + }, "source": [ "This is our final equation.\n", "\n", - "We are now ready to set up the algorithm for back propagation and learning the weights and biases.\n", - "\n", + "We are now ready to set up the algorithm for back propagation and learning the weights and biases." + ] + }, + { + "cell_type": "markdown", + "id": "d86a2149", + "metadata": { + "editable": true + }, + "source": [ "## Setting up the Back propagation algorithm\n", "\n", - "\n", - "\n", "The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", "\n", "First, we set up the input data $\\hat{x}$ and the activations\n", "$\\hat{z}_1$ of the input layer and compute the activation function and\n", "the pertinent outputs $\\hat{a}^1$.\n", "\n", - "\n", - "\n", "Secondly, we perform then the feed forward till we reach the output\n", "layer and compute all $\\hat{z}_l$ of the input layer and compute the\n", "activation function and the pertinent outputs $\\hat{a}^l$ for\n", "$l=2,3,\\dots,L$.\n", "\n", - "\n", - "\n", "Thereafter we compute the ouput error $\\hat{\\delta}^L$ by computing all" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f18e1be4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", @@ -2697,14 +3511,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "61435fe1", + "metadata": { + "editable": true + }, "source": [ "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "bbf8110f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", @@ -2713,14 +3533,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3a518090", + "metadata": { + "editable": true + }, "source": [ "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "85824270", + "metadata": { + "editable": true + }, "source": [ "$$\n", "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", @@ -2729,7 +3555,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "815818ed", + "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", @@ -2738,32 +3567,17 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fda6b470", + "metadata": { + "editable": true + }, "source": [ "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." ] } ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.5" - } - }, + "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 } diff --git a/doc/src/week40/week40.do.txt b/doc/src/week40/week40.do.txt index d0bb146f0..ba7cf4a32 100644 --- a/doc/src/week40/week40.do.txt +++ b/doc/src/week40/week40.do.txt @@ -280,8 +280,8 @@ theta = np.random.randn(2,1) for epoch in range(n_epochs): for i in range(m): random_index = np.random.randint(m) - xi = X[random_index:random_index+1] - yi = y[random_index:random_index+1] + xi = X[random_index:random_index+m] + yi = y[random_index:random_index+m] gradients = 2.0* xi.T @ ((xi @ theta)-yi) eta = learning_schedule(epoch*m+i) theta = theta - eta*gradients