diff --git a/doc/pub/week41/html/._week41-bs000.html b/doc/pub/week41/html/._week41-bs000.html index e1eadc26b..b4a6ab7a9 100644 --- a/doc/pub/week41/html/._week41-bs000.html +++ b/doc/pub/week41/html/._week41-bs000.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -472,7 +477,7 @@ MathJax.Hub.Config({
-

Oct 9, 2022

+

Oct 15, 2022


@@ -497,7 +502,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs001.html b/doc/pub/week41/html/._week41-bs001.html index 65a23e882..df1e273df 100644 --- a/doc/pub/week41/html/._week41-bs001.html +++ b/doc/pub/week41/html/._week41-bs001.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -480,7 +485,7 @@ For a more in depth discussion on neural networks we recommend Goodfellow et al
  • 10
  • 11
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs002.html b/doc/pub/week41/html/._week41-bs002.html index 95bb4d61d..b9e50f21b 100644 --- a/doc/pub/week41/html/._week41-bs002.html +++ b/doc/pub/week41/html/._week41-bs002.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -477,7 +482,7 @@ MathJax.Hub.Config({
  • 11
  • 12
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs003.html b/doc/pub/week41/html/._week41-bs003.html index 6769774c0..e6c490265 100644 --- a/doc/pub/week41/html/._week41-bs003.html +++ b/doc/pub/week41/html/._week41-bs003.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,73 +459,12 @@ MathJax.Hub.Config({

     

     

     

    -

    Setting up the Back propagation algorithm

    +

    Review of the back propagation algorithm

    -

    The four equations derived last week 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 \( \boldsymbol{x} \) and the activations -\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and -the pertinent outputs \( \boldsymbol{a}^1 \). -

    -
    -
    - - -
    -
    - -

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

    -
    -
    - - -
    -
    - -

    Thereafter we compute the ouput error \( \boldsymbol{\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

    -$$ -\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

    -$$ -w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, -$$ - - -$$ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -$$ -
    -
    - - -

    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. +

    During the last lecture we discussed in detail the back propagation +algorithm. This algorithm is based on a repeated application of the +chain rule. Let us bring back the basic equation and at the same time +link this with the basic mathematics of automatic differentiation.

    @@ -541,7 +485,7 @@ Here it is convenient to use stochastic gradient descent (see the examples below

  • 12
  • 13
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs004.html b/doc/pub/week41/html/._week41-bs004.html index 0a04f3f96..0a154a12a 100644 --- a/doc/pub/week41/html/._week41-bs004.html +++ b/doc/pub/week41/html/._week41-bs004.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,43 +458,76 @@ MathJax.Hub.Config({

     

     

     

    - -

    Setting up a Multi-layer perceptron model for classification

    + +

    Setting up the Back propagation algorithm

    -

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

    +

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

    -

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

    +
    + +

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

    +
    +
    -

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

    +
    + +

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

    +
    +
    + + +
    +
    + +

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

    $$ -P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , +\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

    +$$ +\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

    +$$ +w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, $$ -

    and

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

    where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases -of our network. +$$ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +$$ +

    +
    + + +

    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.

    -

    diff --git a/doc/pub/week41/html/._week41-bs005.html b/doc/pub/week41/html/._week41-bs005.html index 4a4312a64..e2fd8a290 100644 --- a/doc/pub/week41/html/._week41-bs005.html +++ b/doc/pub/week41/html/._week41-bs005.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,57 +458,42 @@ MathJax.Hub.Config({

     

     

     

    - -

    Defining the cost function

    + +

    Setting up a Multi-layer perceptron model for classification

    -

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

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

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

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

    -

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

    - -

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

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

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

    - -

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

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

    +

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

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

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

    and

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

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

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

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

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

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

    - -

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

    @@ -525,7 +515,7 @@ $$

  • 14
  • 15
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs006.html b/doc/pub/week41/html/._week41-bs006.html index c91d11e22..5869f16b2 100644 --- a/doc/pub/week41/html/._week41-bs006.html +++ b/doc/pub/week41/html/._week41-bs006.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,50 +459,56 @@ MathJax.Hub.Config({

     

     

     

    -

    Example: binary classification problem

    +

    Defining the cost function

    -

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

    +

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

    $$ -\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right), +\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n +y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . $$ -

    where we had defined the logistic (sigmoid) function

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

    and

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

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

    - -

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

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

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

    with

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

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

    -

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

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

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

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

    + +

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

    + $$ -\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), +P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} +{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , $$ -

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

    +

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

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

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

    +

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

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

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

    + +

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

    @@ -520,7 +531,7 @@ $$

  • 15
  • 16
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs007.html b/doc/pub/week41/html/._week41-bs007.html index f824f0d2a..9bc0e9049 100644 --- a/doc/pub/week41/html/._week41-bs007.html +++ b/doc/pub/week41/html/._week41-bs007.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,24 +459,50 @@ MathJax.Hub.Config({

     

     

     

    -

    The Softmax function

    -

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

    +

    Example: binary classification problem

    + +

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

    $$ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. +\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right), $$ -

    For the Softmax function we have

    +

    where we had defined the logistic (sigmoid) function

    $$ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. +p(y_i =1\vert x_i,\boldsymbol{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, $$ -

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

    +

    and

    $$ -\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), +p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). $$ -

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

    +

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

    + +

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

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

    with

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

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

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

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

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

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

    @@ -495,7 +526,7 @@ $$

  • 16
  • 17
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs008.html b/doc/pub/week41/html/._week41-bs008.html index f62acf57b..d0f3ed26c 100644 --- a/doc/pub/week41/html/._week41-bs008.html +++ b/doc/pub/week41/html/._week41-bs008.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,19 +458,26 @@ MathJax.Hub.Config({

     

     

     

    - -

    Developing a code for doing neural networks with back propagation

    + +

    The Softmax function

    +

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

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

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

    +

    For the Softmax function we have

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

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

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

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

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

    diff --git a/doc/pub/week41/html/._week41-bs009.html b/doc/pub/week41/html/._week41-bs009.html index 211fc9b49..cca9d7aec 100644 --- a/doc/pub/week41/html/._week41-bs009.html +++ b/doc/pub/week41/html/._week41-bs009.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,118 +458,19 @@ MathJax.Hub.Config({

     

     

     

    - -

    Collect and pre-process data

    - -

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

    - -

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

    - -

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

    - -

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

    - -

    and the targets would be:

    - -

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

    - -

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

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

    Developing a code for doing neural networks with back propagation

    +

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

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

    diff --git a/doc/pub/week41/html/._week41-bs010.html b/doc/pub/week41/html/._week41-bs010.html index 29ddc59e5..2697cd36c 100644 --- a/doc/pub/week41/html/._week41-bs010.html +++ b/doc/pub/week41/html/._week41-bs010.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,17 +459,50 @@ MathJax.Hub.Config({

     

     

     

    -

    Train and test datasets

    +

    Collect and pre-process data

    -

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

    +

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

    -

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

    +

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

    -

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

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

    + +

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

    + +

    and the targets would be:

    + +

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

    + +

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

    @@ -474,33 +512,48 @@ collected from 12.00 to 24.00.
    -
    from sklearn.model_selection import train_test_split
    +  
    # import necessary packages
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from sklearn import datasets
     
    -# one-liner from scikit-learn library
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
     
    -# equivalently in numpy
    -def train_test_split_numpy(inputs, labels, train_size, test_size):
    -    n_inputs = len(inputs)
    -    inputs_shuffled = inputs.copy()
    -    labels_shuffled = labels.copy()
    -    
    -    np.random.shuffle(inputs_shuffled)
    -    np.random.shuffle(labels_shuffled)
    -    
    -    train_end = int(n_inputs*train_size)
    -    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    -    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    -    
    -    return X_train, X_test, Y_train, Y_test
    +# ensure the same random numbers appear every time
    +np.random.seed(0)
     
    -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
     
    -print("Number of training images: " + str(len(X_train)))
    -print("Number of test images: " + str(len(X_test)))
    +
    +# download MNIST dataset
    +digits = datasets.load_digits()
    +
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
     
    @@ -542,7 +595,7 @@ X_train, X_test, Y_train, Y_test = train_tes
  • 19
  • 20
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs011.html b/doc/pub/week41/html/._week41-bs011.html index 3e2fbb2ab..ab9b18bd0 100644 --- a/doc/pub/week41/html/._week41-bs011.html +++ b/doc/pub/week41/html/._week41-bs011.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,46 +459,68 @@ MathJax.Hub.Config({

     

     

     

    -

    Define model and architecture

    +

    Train and test datasets

    -

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

    +

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

    -

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

    +

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

    -

    $$ y = f(z) ,$$

    - -

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

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

    -

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

    -

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

    + +
    +
    +
    +
    +
    +
    from sklearn.model_selection import train_test_split
     
    -

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

    +# one-liner from scikit-learn library +train_size = 0.8 +test_size = 1 - train_size +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, + test_size=test_size) -

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

    +# equivalently in numpy +def train_test_split_numpy(inputs, labels, train_size, test_size): + n_inputs = len(inputs) + inputs_shuffled = inputs.copy() + labels_shuffled = labels.copy() + + np.random.shuffle(inputs_shuffled) + np.random.shuffle(labels_shuffled) + + train_end = int(n_inputs*train_size) + X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] + Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] + + return X_train, X_test, Y_train, Y_test -

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

    +#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size) -

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

    +print("Number of training images: " + str(len(X_train))) +print("Number of test images: " + str(len(X_test))) +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

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

    @@ -520,7 +547,7 @@ We will be using the sigmoid function \( \sigma(x) \):

  • 20
  • 21
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs012.html b/doc/pub/week41/html/._week41-bs012.html index 45af71443..b34512c2a 100644 --- a/doc/pub/week41/html/._week41-bs012.html +++ b/doc/pub/week41/html/._week41-bs012.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,47 +458,48 @@ MathJax.Hub.Config({

     

     

     

    - -

    Layers

    + +

    Define model and architecture

    -
      -
    • Input
    • -
    -

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

    +

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

    -
      -
    • Hidden layer
    • -
    -

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

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

    + +

    $$ y = f(z) ,$$

    + +

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

    -
      -
    • Output
    • -
    -

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

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

    + +

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

    -

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

    - -

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

    - -

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

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

    -

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

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

    -

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

    - -

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

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

    +

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

    + +

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

    +

      @@ -519,7 +525,7 @@ weights to the output layer.
    • 21
    • 22
    • ...
    • -
    • 102
    • +
    • 103
    • »
    diff --git a/doc/pub/week41/html/._week41-bs013.html b/doc/pub/week41/html/._week41-bs013.html index 4baef03ec..e424caee4 100644 --- a/doc/pub/week41/html/._week41-bs013.html +++ b/doc/pub/week41/html/._week41-bs013.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,56 +459,45 @@ MathJax.Hub.Config({

     

     

     

    -

    Weights and biases

    +

    Layers

    -

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

      +
    • Input
    • +
    +

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

    + +
      +
    • Hidden layer
    • +
    +

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

    -

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

      +
    • Output
    • +
    +

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

    -

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

    +

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

    -

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

    +

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

    - -
    -
    -
    -
    -
    -
    # building our neural network
    +

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

    -n_inputs, n_features = X_train.shape -n_hidden_neurons = 50 -n_categories = 10 +

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

    -# we make the weights normally distributed using numpy.random.randn - -# weights and bias in the hidden layer -hidden_weights = np.random.randn(n_features, n_hidden_neurons) -hidden_bias = np.zeros(n_hidden_neurons) + 0.01 - -# weights and bias in the output layer -output_weights = np.random.randn(n_hidden_neurons, n_categories) -output_bias = np.zeros(n_categories) + 0.01 -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

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

    +

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

    @@ -530,7 +524,7 @@ output_bias = np22

  • 23
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs014.html b/doc/pub/week41/html/._week41-bs014.html index 9fd373d11..3eea1e76b 100644 --- a/doc/pub/week41/html/._week41-bs014.html +++ b/doc/pub/week41/html/._week41-bs014.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,29 +458,58 @@ MathJax.Hub.Config({

     

     

     

    - -

    Feed-forward pass

    + +

    Weights and biases

    -

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

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

    -

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

    - -

    this is then passed through our activation function

    - -

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

    - -

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

    - -

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

    - -

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

    - -

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

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

    +

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

    + +

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

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

      @@ -501,7 +535,7 @@ For each input image we calculate a weighted sum of input features (pixel values
    • 23
    • 24
    • ...
    • -
    • 102
    • +
    • 103
    • »
    diff --git a/doc/pub/week41/html/._week41-bs015.html b/doc/pub/week41/html/._week41-bs015.html index 552a9e380..6a32e090e 100644 --- a/doc/pub/week41/html/._week41-bs015.html +++ b/doc/pub/week41/html/._week41-bs015.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,96 +458,29 @@ MathJax.Hub.Config({

     

     

     

    - -

    Matrix multiplications

    + +

    Feed-forward pass

    -

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

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

    -

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

    +

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

    -

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

    this is then passed through our activation function

    + +

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

    + +

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

    + +

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

    + +

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

    + +

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

    -

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

    - -

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

    - -

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

    - -

    This is fed to the output layer:

    - -

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

    - -

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

    - -

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

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

      @@ -568,7 +506,7 @@ predictions = predict(X_train)
    • 24
    • 25
    • ...
    • -
    • 102
    • +
    • 103
    • »
    diff --git a/doc/pub/week41/html/._week41-bs016.html b/doc/pub/week41/html/._week41-bs016.html index 3d34e4273..cdfaeccc9 100644 --- a/doc/pub/week41/html/._week41-bs016.html +++ b/doc/pub/week41/html/._week41-bs016.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,33 +458,95 @@ MathJax.Hub.Config({

     

     

     

    - -

    Choose cost function and optimizer

    + +

    Matrix multiplications

    -

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

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

    -

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

    +

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

    -

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

    - -

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

    - -

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

    - -

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

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

    -

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

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

    + +

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

    +

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

    + +

    This is fed to the output layer:

    + +

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

    + +

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

    + +

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

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

    @@ -506,7 +573,7 @@ you got the correct label. The probability of category \( c \) is given by the s

  • 25
  • 26
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs017.html b/doc/pub/week41/html/._week41-bs017.html index 512535839..979b35780 100644 --- a/doc/pub/week41/html/._week41-bs017.html +++ b/doc/pub/week41/html/._week41-bs017.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,39 +459,32 @@ MathJax.Hub.Config({

     

     

     

    -

    Optimizing the cost function

    +

    Choose cost function and optimizer

    -

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

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

    -

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

    +

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

    -

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

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

    + +

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

    + +

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

    + +

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

    -

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

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

    -

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

    - -

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

    - -

    This has two important benefits:

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

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

    @@ -513,7 +511,7 @@ We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient th

  • 26
  • 27
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs018.html b/doc/pub/week41/html/._week41-bs018.html index 0848021b7..c6c13e5ba 100644 --- a/doc/pub/week41/html/._week41-bs018.html +++ b/doc/pub/week41/html/._week41-bs018.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,36 +458,41 @@ MathJax.Hub.Config({

     

     

     

    - -

    Regularization

    + +

    Optimizing the cost function

    -

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

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

    -

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

    +

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

    -

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

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

    -

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

    - -

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

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

    +

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

    + +

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

    + +

    This has two important benefits:

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

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

    +

      @@ -508,7 +518,7 @@ calculate the gradient efficently.
    • 27
    • 28
    • ...
    • -
    • 102
    • +
    • 103
    • »
    diff --git a/doc/pub/week41/html/._week41-bs019.html b/doc/pub/week41/html/._week41-bs019.html index cdb8acb63..8c26fb718 100644 --- a/doc/pub/week41/html/._week41-bs019.html +++ b/doc/pub/week41/html/._week41-bs019.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,133 +458,36 @@ MathJax.Hub.Config({

     

     

     

    - -

    Matrix multiplication

    + +

    Regularization

    -

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

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

    -

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

    +

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

    -

    The gradient for the output weights is calculated as

    - -

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

    - -

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

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

    -

    The gradient with respect to the output bias is then

    +

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

    -

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

    - -

    The error in the hidden layer is

    - -

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

    - -

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

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

    -

    This again gives us the gradients in the hidden layer:

    - -

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

    - -

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

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

    diff --git a/doc/pub/week41/html/._week41-bs020.html b/doc/pub/week41/html/._week41-bs020.html index a622c4e49..ba19e6683 100644 --- a/doc/pub/week41/html/._week41-bs020.html +++ b/doc/pub/week41/html/._week41-bs020.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,22 +459,132 @@ MathJax.Hub.Config({

     

     

     

    -

    Improving performance

    +

    Matrix multiplication

    -

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

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

    -

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

    +

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

    -

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

    The gradient for the output weights is calculated as

    + +

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

    + +

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

    -

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

    The gradient with respect to the output bias is then

    + +

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

    + +

    The error in the hidden layer is

    + +

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

    + +

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

    +

    This again gives us the gradients in the hidden layer:

    + +

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

    + +

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

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

      @@ -495,7 +610,7 @@ Andrew Ng goes through some of these considerations in this 29
    • 30
    • ...
    • -
    • 102
    • +
    • 103
    • »
    diff --git a/doc/pub/week41/html/._week41-bs021.html b/doc/pub/week41/html/._week41-bs021.html index 378a327aa..eca2a4c58 100644 --- a/doc/pub/week41/html/._week41-bs021.html +++ b/doc/pub/week41/html/._week41-bs021.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,133 +459,21 @@ MathJax.Hub.Config({

     

     

     

    -

    Full object-oriented implementation

    +

    Improving performance

    -

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

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

    +

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

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

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

    +

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

    @@ -607,7 +500,7 @@ being realizations of this object with different hyperparameters. An implementat

  • 30
  • 31
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs022.html b/doc/pub/week41/html/._week41-bs022.html index 73827330f..e403dc64d 100644 --- a/doc/pub/week41/html/._week41-bs022.html +++ b/doc/pub/week41/html/._week41-bs022.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,17 +459,12 @@ MathJax.Hub.Config({

     

     

     

    -

    Evaluate model performance on test data

    +

    Full object-oriented implementation

    -

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

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

    -

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

    - -

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

    -
    @@ -472,22 +472,105 @@ The accuracy is as you would expect just the number of images correctly labeled
    -
    epochs = 100
    -batch_size = 100
    +  
    class NeuralNetwork:
    +    def __init__(
    +            self,
    +            X_data,
    +            Y_data,
    +            n_hidden_neurons=50,
    +            n_categories=10,
    +            epochs=10,
    +            batch_size=100,
    +            eta=0.1,
    +            lmbd=0.0):
     
    -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -dnn.train()
    -test_predict = dnn.predict(X_test)
    +        self.X_data_full = X_data
    +        self.Y_data_full = Y_data
     
    -# accuracy score from scikit library
    -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +        self.n_inputs = X_data.shape[0]
    +        self.n_features = X_data.shape[1]
    +        self.n_hidden_neurons = n_hidden_neurons
    +        self.n_categories = n_categories
     
    -# equivalent in numpy
    -def accuracy_score_numpy(Y_test, Y_pred):
    -    return np.sum(Y_test == Y_pred) / len(Y_test)
    +        self.epochs = epochs
    +        self.batch_size = batch_size
    +        self.iterations = self.n_inputs // self.batch_size
    +        self.eta = eta
    +        self.lmbd = lmbd
     
    -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    +        self.create_biases_and_weights()
    +
    +    def create_biases_and_weights(self):
    +        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    +        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    +
    +        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    +        self.output_bias = np.zeros(self.n_categories) + 0.01
    +
    +    def feed_forward(self):
    +        # feed-forward for training
    +        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    +        self.a_h = sigmoid(self.z_h)
    +
    +        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    +
    +        exp_term = np.exp(self.z_o)
    +        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +
    +    def feed_forward_out(self, X):
    +        # feed-forward for output
    +        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    +        a_h = sigmoid(z_h)
    +
    +        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    +        
    +        exp_term = np.exp(z_o)
    +        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    +        return probabilities
    +
    +    def backpropagation(self):
    +        error_output = self.probabilities - self.Y_data
    +        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    +
    +        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    +        self.output_bias_gradient = np.sum(error_output, axis=0)
    +
    +        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    +        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    +
    +        if self.lmbd > 0.0:
    +            self.output_weights_gradient += self.lmbd * self.output_weights
    +            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    +
    +        self.output_weights -= self.eta * self.output_weights_gradient
    +        self.output_bias -= self.eta * self.output_bias_gradient
    +        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    +        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    +
    +    def predict(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return np.argmax(probabilities, axis=1)
    +
    +    def predict_probabilities(self, X):
    +        probabilities = self.feed_forward_out(X)
    +        return probabilities
    +
    +    def train(self):
    +        data_indices = np.arange(self.n_inputs)
    +
    +        for i in range(self.epochs):
    +            for j in range(self.iterations):
    +                # pick datapoints with replacement
    +                chosen_datapoints = np.random.choice(
    +                    data_indices, size=self.batch_size, replace=False
    +                )
    +
    +                # minibatch training data
    +                self.X_data = self.X_data_full[chosen_datapoints]
    +                self.Y_data = self.Y_data_full[chosen_datapoints]
    +
    +                self.feed_forward()
    +                self.backpropagation()
     
    @@ -529,7 +612,7 @@ test_predict = dnn31
  • 32
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs023.html b/doc/pub/week41/html/._week41-bs023.html index b0420e923..8d7f7d8da 100644 --- a/doc/pub/week41/html/._week41-bs023.html +++ b/doc/pub/week41/html/._week41-bs023.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,12 +459,17 @@ MathJax.Hub.Config({

     

     

     

    -

    Adjust hyperparameters

    +

    Evaluate model performance on test data

    -

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

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

    +

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

    + +

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

    +
    @@ -467,26 +477,22 @@ Note that we are only using 1 layer with 50 neurons, and human performance is es
    -
    eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -# store the models for later use
    -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +  
    epochs = 100
    +batch_size = 100
     
    -# grid search
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -        dnn.train()
    -        
    -        DNN_numpy[i][j] = dnn
    -        
    -        test_predict = dnn.predict(X_test)
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -        print()
    +dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +dnn.train()
    +test_predict = dnn.predict(X_test)
    +
    +# accuracy score from scikit library
    +print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +
    +# equivalent in numpy
    +def accuracy_score_numpy(Y_test, Y_pred):
    +    return np.sum(Y_test == Y_pred) / len(Y_test)
    +
    +#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
     
    @@ -528,7 +534,7 @@ DNN_numpy = np.
  • 32
  • 33
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs024.html b/doc/pub/week41/html/._week41-bs024.html index 20ae96cdd..cc87a0cfe 100644 --- a/doc/pub/week41/html/._week41-bs024.html +++ b/doc/pub/week41/html/._week41-bs024.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,7 +459,11 @@ MathJax.Hub.Config({

     

     

     

    -

    Visualization

    +

    Adjust hyperparameters

    + +

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

    @@ -463,39 +472,26 @@ MathJax.Hub.Config({
    -
    # visual representation of grid search
    -# uses seaborn heatmap, you can also do this with matplotlib imshow
    -import seaborn as sns
    +  
    eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +# store the models for later use
    +DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
     
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_numpy[i][j]
    +# grid search
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    +                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    +        dnn.train()
             
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    +        DNN_numpy[i][j] = dnn
             
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    +        test_predict = dnn.predict(X_test)
    +        
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    +        print()
     
    @@ -537,7 +533,7 @@ plt.show()
  • 33
  • 34
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs025.html b/doc/pub/week41/html/._week41-bs025.html index bdef08761..8c2ca60f6 100644 --- a/doc/pub/week41/html/._week41-bs025.html +++ b/doc/pub/week41/html/._week41-bs025.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,21 +459,7 @@ MathJax.Hub.Config({

     

     

     

    -

    scikit-learn implementation

    - -

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

    - -

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

    +

    Visualization

    @@ -477,22 +468,39 @@ performance overall.
    -
    from sklearn.neural_network import MLPClassifier
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +  
    # visual representation of grid search
    +# uses seaborn heatmap, you can also do this with matplotlib imshow
    +import seaborn as sns
     
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X_train, Y_train)
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_numpy[i][j]
             
    -        DNN_scikit[i][j] = dnn
    +        train_pred = dnn.predict(X_train) 
    +        test_pred = dnn.predict(X_test)
    +
    +        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    +        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    +
             
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    -        print()
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
     
    @@ -534,7 +542,7 @@ DNN_scikit = np
  • 34
  • 35
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs026.html b/doc/pub/week41/html/._week41-bs026.html index 024c9c633..6128cd466 100644 --- a/doc/pub/week41/html/._week41-bs026.html +++ b/doc/pub/week41/html/._week41-bs026.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,7 +459,22 @@ MathJax.Hub.Config({

     

     

     

    -

    Visualization

    +

    scikit-learn implementation

    + +

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

    + +

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

    +
    @@ -462,40 +482,22 @@ MathJax.Hub.Config({
    -
    # optional
    -# visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    +  
    from sklearn.neural_network import MLPClassifier
    +# store models for later use
    +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
     
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    +                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    +        dnn.fit(X_train, Y_train)
             
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    +        DNN_scikit[i][j] = dnn
             
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    +        print()
     
    @@ -537,7 +539,7 @@ plt.show()
  • 35
  • 36
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs027.html b/doc/pub/week41/html/._week41-bs027.html index d8197f4b5..fe3ba9a96 100644 --- a/doc/pub/week41/html/._week41-bs027.html +++ b/doc/pub/week41/html/._week41-bs027.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,29 +459,63 @@ MathJax.Hub.Config({

     

     

     

    -

    Testing our code for the XOR, OR and AND gates

    +

    Visualization

    -

    Last week we discussed three different types of gates, the so-called -XOR, the OR and the AND gates. Their inputs and outputs can be -summarized using the following tables, first for the OR gate with -inputs \( x_1 \) and \( x_2 \) and outputs \( y \): -

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

    @@ -503,7 +542,7 @@ inputs \( x_1 \) and \( x_2 \) and outputs \( y \):

  • 36
  • 37
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs028.html b/doc/pub/week41/html/._week41-bs028.html index df30cb79e..23434feb7 100644 --- a/doc/pub/week41/html/._week41-bs028.html +++ b/doc/pub/week41/html/._week41-bs028.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,27 +459,13 @@ MathJax.Hub.Config({

     

     

     

    -

    The AND and XOR Gates

    +

    Testing our code for the XOR, OR and AND gates

    -

    The AND gate is defined as

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

    And finally we have the XOR gate

    +

    Last week we discussed three different types of gates, the so-called +XOR, the OR and the AND gates. Their inputs and outputs can be +summarized using the following tables, first for the OR gate with +inputs \( x_1 \) and \( x_2 \) and outputs \( y \): +

    @@ -486,7 +477,7 @@ MathJax.Hub.Config({ 0 0 0 0 1 1 1 0 1 - 1 1 0 + 1 1 1
    @@ -517,7 +508,7 @@ MathJax.Hub.Config({
  • 37
  • 38
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs029.html b/doc/pub/week41/html/._week41-bs029.html index 11631c441..0f6201499 100644 --- a/doc/pub/week41/html/._week41-bs029.html +++ b/doc/pub/week41/html/._week41-bs029.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,18 +459,43 @@ MathJax.Hub.Config({

     

     

     

    -

    Representing the Data Sets

    +

    The AND and XOR Gates

    -

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

    +

    The AND gate is defined as

    -$$ -\boldsymbol{X}=\begin{bmatrix} 0 & 0 \\ - 0 & 1 \\ - 1 & 0 \\ - 1 & 1 \end{bmatrix}, -$$ +
    +
    + + + + + + + + + + +
    \( x_1 \) \( x_2 \) \( y \)
    0 0 0
    0 1 0
    1 0 0
    1 1 1
    +
    +
    -

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

    +

    And finally we have the XOR gate

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

    @@ -492,7 +522,7 @@ $$

  • 38
  • 39
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs030.html b/doc/pub/week41/html/._week41-bs030.html index 1f8e4c04d..1aae77c9b 100644 --- a/doc/pub/week41/html/._week41-bs030.html +++ b/doc/pub/week41/html/._week41-bs030.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,98 +459,18 @@ MathJax.Hub.Config({

     

     

     

    -

    Setting up the Neural Network

    +

    Representing the Data Sets

    -

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

    +

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

    +$$ +\boldsymbol{X}=\begin{bmatrix} 0 & 0 \\ + 0 & 1 \\ + 1 & 0 \\ + 1 & 1 \end{bmatrix}, +$$ - -
    -
    -
    -
    -
    -
    """
    -Simple code that tests XOR, OR and AND gates with linear regression
    -"""
    -
    -# import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn import datasets
    -
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    probabilities = sigmoid(z_o)
    -    return probabilities
    -
    -# we obtain a prediction by taking the class with the highest likelihood
    -def predict(X):
    -    probabilities = feed_forward(X)
    -    return np.argmax(probabilities, axis=1)
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# Design matrix
    -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    -
    -# The XOR gate
    -yXOR = np.array( [ 0, 1 ,1, 0])
    -# The OR gate
    -yOR = np.array( [ 0, 1 ,1, 1])
    -# The AND gate
    -yAND = np.array( [ 0, 0 ,0, 1])
    -
    -# Defining the neural network
    -n_inputs, n_features = X.shape
    -n_hidden_neurons = 2
    -n_categories = 2
    -n_features = 2
    -
    -# we make the weights normally distributed using numpy.random.randn
    -
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    -
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
    -
    -probabilities = feed_forward(X)
    -print(probabilities)
    -
    -
    -predictions = predict(X)
    -print(predictions)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

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

    +

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

    @@ -572,7 +497,7 @@ predictions = predict(X)

  • 39
  • 40
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs031.html b/doc/pub/week41/html/._week41-bs031.html index 62d07efb1..41981c576 100644 --- a/doc/pub/week41/html/._week41-bs031.html +++ b/doc/pub/week41/html/._week41-bs031.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,7 +459,9 @@ MathJax.Hub.Config({

     

     

     

    -

    The Code using Scikit-Learn

    +

    Setting up the Neural Network

    + +

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

    @@ -463,12 +470,35 @@ MathJax.Hub.Config({
    -
    # import necessary packages
    +  
    """
    +Simple code that tests XOR, OR and AND gates with linear regression
    +"""
    +
    +# import necessary packages
     import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.neural_network import MLPClassifier
    -from sklearn.metrics import accuracy_score
    -import seaborn as sns
    +from sklearn import datasets
    +
    +def sigmoid(x):
    +    return 1/(1 + np.exp(-x))
    +
    +def feed_forward(X):
    +    # weighted sum of inputs to the hidden layer
    +    z_h = np.matmul(X, hidden_weights) + hidden_bias
    +    # activation in the hidden layer
    +    a_h = sigmoid(z_h)
    +    
    +    # weighted sum of inputs to the output layer
    +    z_o = np.matmul(a_h, output_weights) + output_bias
    +    # softmax output
    +    # axis 0 holds each input and axis 1 the probabilities of each category
    +    probabilities = sigmoid(z_o)
    +    return probabilities
    +
    +# we obtain a prediction by taking the class with the highest likelihood
    +def predict(X):
    +    probabilities = feed_forward(X)
    +    return np.argmax(probabilities, axis=1)
     
     # ensure the same random numbers appear every time
     np.random.seed(0)
    @@ -489,37 +519,22 @@ n_hidden_neurons = = 2
     n_features = 2
     
    -eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -epochs = 100
    +# we make the weights normally distributed using numpy.random.randn
     
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X, yXOR)
    -        DNN_scikit[i][j] = dnn
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on data set: ", dnn.score(X, yXOR))
    -        print()
    +# weights and bias in the hidden layer
    +hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    +hidden_bias = np.zeros(n_hidden_neurons) + 0.01
     
    -sns.set()
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        dnn = DNN_scikit[i][j]
    -        test_pred = dnn.predict(X)
    -        test_accuracy[i][j] = accuracy_score(yXOR, test_pred)
    +# weights and bias in the output layer
    +output_weights = np.random.randn(n_hidden_neurons, n_categories)
    +output_bias = np.zeros(n_categories) + 0.01
     
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    +probabilities = feed_forward(X)
    +print(probabilities)
    +
    +
    +predictions = predict(X)
    +print(predictions)
     
    @@ -535,6 +550,7 @@ plt.show()
    +

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

    @@ -561,7 +577,7 @@ plt.show()

  • 40
  • 41
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs032.html b/doc/pub/week41/html/._week41-bs032.html index fb9221257..0d00424c1 100644 --- a/doc/pub/week41/html/._week41-bs032.html +++ b/doc/pub/week41/html/._week41-bs032.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,17 +459,87 @@ MathJax.Hub.Config({

     

     

     

    -

    Building neural networks in Tensorflow and Keras

    +

    The Code using Scikit-Learn

    -

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

    -

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

    + +
    +
    +
    +
    +
    +
    # import necessary packages
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from sklearn.neural_network import MLPClassifier
    +from sklearn.metrics import accuracy_score
    +import seaborn as sns
    +
    +# ensure the same random numbers appear every time
    +np.random.seed(0)
    +
    +# Design matrix
    +X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
    +
    +# The XOR gate
    +yXOR = np.array( [ 0, 1 ,1, 0])
    +# The OR gate
    +yOR = np.array( [ 0, 1 ,1, 1])
    +# The AND gate
    +yAND = np.array( [ 0, 0 ,0, 1])
    +
    +# Defining the neural network
    +n_inputs, n_features = X.shape
    +n_hidden_neurons = 2
    +n_categories = 2
    +n_features = 2
    +
    +eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +# store models for later use
    +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +epochs = 100
    +
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    +                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    +        dnn.fit(X, yXOR)
    +        DNN_scikit[i][j] = dnn
    +        print("Learning rate  = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Accuracy score on data set: ", dnn.score(X, yXOR))
    +        print()
    +
    +sns.set()
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        dnn = DNN_scikit[i][j]
    +        test_pred = dnn.predict(X)
    +        test_accuracy[i][j] = accuracy_score(yXOR, test_pred)
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    @@ -491,7 +566,7 @@ NumPy arrays.

  • 41
  • 42
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs033.html b/doc/pub/week41/html/._week41-bs033.html index b2cca0e30..d8817353f 100644 --- a/doc/pub/week41/html/._week41-bs033.html +++ b/doc/pub/week41/html/._week41-bs033.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,111 +459,18 @@ MathJax.Hub.Config({

     

     

     

    -

    Tensorflow

    +

    Building neural networks in Tensorflow and Keras

    -

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

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

    -

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

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

    -

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

    - -

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

    - -

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

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

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

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

    To install the current release of GPU TensorFlow

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

    diff --git a/doc/pub/week41/html/._week41-bs034.html b/doc/pub/week41/html/._week41-bs034.html index 7d758114f..07a87d948 100644 --- a/doc/pub/week41/html/._week41-bs034.html +++ b/doc/pub/week41/html/._week41-bs034.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,20 +459,43 @@ MathJax.Hub.Config({

     

     

     

    -

    Using Keras

    +

    Tensorflow

    -

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

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

    +

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

    + +

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

    + +

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

    + +

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

    +
    -
    conda install keras
    +  
    pip3 install tensorflow
     
    @@ -483,9 +511,58 @@ If you have Anaconda installed you may run the following command
    -

    You can look up the instructions here for more information.

    +

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

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

    To install the current release of GPU TensorFlow

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

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

    @@ -512,7 +589,7 @@ If you have Anaconda installed you may run the following command

  • 43
  • 44
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs035.html b/doc/pub/week41/html/._week41-bs035.html index af5eb6443..f2fd97c7b 100644 --- a/doc/pub/week41/html/._week41-bs035.html +++ b/doc/pub/week41/html/._week41-bs035.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,10 +459,12 @@ MathJax.Hub.Config({

     

     

     

    -

    Collect and pre-process data

    - -

    Let us look again at the MINST data set.

    +

    Using Keras

    +

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

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

    You can look up the instructions here for more information.

    + +

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

    @@ -705,7 +517,7 @@ plt.show()

  • 44
  • 45
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs036.html b/doc/pub/week41/html/._week41-bs036.html index 84ac24f73..a4c1b7065 100644 --- a/doc/pub/week41/html/._week41-bs036.html +++ b/doc/pub/week41/html/._week41-bs036.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,7 +459,9 @@ MathJax.Hub.Config({

     

     

     

    -

    The Breast Cancer Data, now with Keras

    +

    Collect and pre-process data

    + +

    Let us look again at the MINST data set.

    @@ -463,171 +470,205 @@ MathJax.Hub.Config({
    -
    import tensorflow as tf
    -from tensorflow.keras.layers import Input
    +  
    # import necessary packages
    +import numpy as np
    +import matplotlib.pyplot as plt
    +import tensorflow as tf
    +from sklearn import datasets
    +
    +
    +# ensure the same random numbers appear every time
    +np.random.seed(0)
    +
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
    +
    +
    +# download MNIST dataset
    +digits = datasets.load_digits()
    +
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# flatten the image
    +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    +n_inputs = len(inputs)
    +inputs = inputs.reshape(n_inputs, -1)
    +print("X = (n_inputs, n_features) = " + str(inputs.shape))
    +
    +
    +# choose some random images to display
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    from tensorflow.keras.layers import Input
     from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
     from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
     from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
     from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
     from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import seaborn as sns
    -from sklearn.model_selection import train_test_split as splitter
    -from sklearn.datasets import load_breast_cancer
    -import pickle
    -import os 
     
    +from sklearn.model_selection import train_test_split
     
    -"""Load breast cancer dataset"""
    +# one-hot representation of labels
    +labels = to_categorical(labels)
     
    -np.random.seed(0)        #create same seed for random number every time
    -
    -cancer=load_breast_cancer()      #Download breast cancer dataset
    -
    -inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    -outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    -labels=cancer.feature_names[0:30]
    -
    -print('The content of the breast cancer dataset is:')      #Print information about the datasets
    -print(labels)
    -print('-------------------------')
    -print("inputs =  " + str(inputs.shape))
    -print("outputs =  " + str(outputs.shape))
    -print("labels =  "+ str(labels.shape))
    -
    -x=inputs      #Reassign the Feature and Label matrices to other variables
    -y=outputs
    -
    -#%% 
    -
    -# Visualisation of dataset (for correlation analysis)
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean perimeter',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    -plt.xlabel('Mean compactness',fontweight='bold')
    -plt.ylabel('Mean concavity',fontweight='bold')
    -plt.show()
    -
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean texture',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean perimeter',fontweight='bold')
    -plt.ylabel('Mean compactness',fontweight='bold')
    -plt.show()
    -
    -
    -# Generate training and testing datasets
    -
    -#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    -#and add to input matrix
    -
    -temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    -temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    -X=np.hstack((temp1,temp2))      
    -temp=np.reshape(x[:,5],(len(x[:,5]),1))
    -X=np.hstack((X,temp))       
    -temp=np.reshape(x[:,8],(len(x[:,8]),1))
    -X=np.hstack((X,temp))       
    -
    -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    -
    -y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    -y_test=to_categorical(y_test)
    -
    -del temp1,temp2,temp
    -
    -# %%
    -
    -# Define tunable parameters"
    -
    -eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    -lamda=0.01                                  #Define hyperparameter
    -n_layers=2                                  #Define number of hidden layers in the model
    -n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    -epochs=100                                   #Number of reiterations over the input data
    -batch_size=100                              #Number of samples per gradient update
    -
    -# %%
    -
    -"""Define function to return Deep Neural Network model"""
    -
    -def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    -    model=Sequential()      
    -    for i in range(n_layers):       #Run loop to add hidden layers to the model
    -        if (i==0):                  #First layer requires input dimensions
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    -        else:                       #Subsequent layers are capable of automatic shape inferencing
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    -    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    -    sgd=optimizers.SGD(lr=eta)
    -    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    +# split into train and test data
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    epochs = 100
    +batch_size = 100
    +n_neurons_layer1 = 100
    +n_neurons_layer2 = 50
    +n_categories = 10
    +eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
    +    model = Sequential()
    +    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(Dense(n_categories, activation='softmax'))
    +    
    +    sgd = optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    +    
         return model
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +        
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
    +                                         eta=eta, lmbd=lmbd)
    +        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    +        scores = DNN.evaluate(X_test, Y_test)
    +        
    +        DNN_keras[i][j] = DNN
    +        
    +        print("Learning rate = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Test accuracy: %.3f" % scores[1])
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    # optional
    +# visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
     
    -    
    -Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    -Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    +sns.set()
     
    -for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    -    for j in range(len(eta)):      #accuracy scores 
    -        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    -        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    -        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    -        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    -               
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
     
    -def plot_data(x,y,data,title=None):
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        DNN = DNN_keras[i][j]
     
    -    # plot results
    -    fontsize=16
    +        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
    +        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
     
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
     
    -    fig = plt.figure()
    -    ax = fig.add_subplot(111)
    -    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    -    
    -    cbar=fig.colorbar(cax)
    -    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    -    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    -    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    -
    -    # put text on matrix elements
    -    for i, x_val in enumerate(np.arange(len(x))):
    -        for j, y_val in enumerate(np.arange(len(y))):
    -            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    -            ax.text(x_val, y_val, c, va='center', ha='center')
    -
    -    # convert axis vaues to to string labels
    -    x=[str(i) for i in x]
    -    y=[str(i) for i in y]
    -
    -
    -    ax.set_xticklabels(['']+x)
    -    ax.set_yticklabels(['']+y)
    -
    -    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    -    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    -    if title is not None:
    -        ax.set_title(title)
    -
    -    plt.tight_layout()
    -
    -    plt.show()
    -    
    -plot_data(eta,n_neuron,Train_accuracy, 'training')
    -plot_data(eta,n_neuron,Test_accuracy, 'testing')
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
     
    @@ -669,7 +710,7 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing&
  • 45
  • 46
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs037.html b/doc/pub/week41/html/._week41-bs037.html index d2cf9d96e..e05c7122b 100644 --- a/doc/pub/week41/html/._week41-bs037.html +++ b/doc/pub/week41/html/._week41-bs037.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,15 +459,195 @@ MathJax.Hub.Config({

     

     

     

    -

    The Mathematics of Neural Networks

    +

    The Breast Cancer Data, now with Keras

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

    Text will be added here. They contain a discussion on

    -
      -
    1. Activation functions and vanishing gradients
    2. -
    3. Brief summary of gradient methods
    4. -
    5. Approximation theorems, in particular the universal approximation theorem for neural networks by Cybenko and Hornik
    6. -
    -

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

    @@ -489,7 +674,7 @@ MathJax.Hub.Config({

  • 46
  • 47
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs038.html b/doc/pub/week41/html/._week41-bs038.html index aa10de418..50594d830 100644 --- a/doc/pub/week41/html/._week41-bs038.html +++ b/doc/pub/week41/html/._week41-bs038.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,29 +459,16 @@ MathJax.Hub.Config({

     

     

     

    -

    Fine-tuning neural network hyperparameters

    +

    The Mathematics of Neural Networks

    -

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

    +

    Text will be added here. They contain a discussion on

    +
      +
    1. Activation functions and vanishing gradients
    2. +
    3. Brief summary of gradient methods
    4. +
    5. Approximation theorems, in particular the universal approximation theorem for neural networks by Cybenko and Hornik
    6. +
    +

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

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

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

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

      @@ -502,7 +494,7 @@ will only be able to explore a tiny part of the hyperparameter space.
    • 47
    • 48
    • ...
    • -
    • 102
    • +
    • 103
    • »
    diff --git a/doc/pub/week41/html/._week41-bs039.html b/doc/pub/week41/html/._week41-bs039.html index 2b66ee6b8..8aaa74129 100644 --- a/doc/pub/week41/html/._week41-bs039.html +++ b/doc/pub/week41/html/._week41-bs039.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,23 +459,29 @@ MathJax.Hub.Config({

     

     

     

    -

    Hidden layers

    +

    Fine-tuning neural network hyperparameters

    -

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

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

    -

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

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

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

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

      @@ -496,7 +507,7 @@ common to reuse parts of a pretrained state-of-the-art network that performs a s
    • 48
    • 49
    • ...
    • -
    • 102
    • +
    • 103
    • »
    diff --git a/doc/pub/week41/html/._week41-bs040.html b/doc/pub/week41/html/._week41-bs040.html index b2b8ca1d2..ddd15e55e 100644 --- a/doc/pub/week41/html/._week41-bs040.html +++ b/doc/pub/week41/html/._week41-bs040.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,31 +458,22 @@ MathJax.Hub.Config({

     

     

     

    - -

    Which activation function should I use?

    + +

    Hidden layers

    -

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

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

    -

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

    - -

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

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

    @@ -505,7 +501,7 @@ learn at widely different speeds

  • 49
  • 50
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs041.html b/doc/pub/week41/html/._week41-bs041.html index 85c78fc8d..573fe75ac 100644 --- a/doc/pub/week41/html/._week41-bs041.html +++ b/doc/pub/week41/html/._week41-bs041.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,31 +459,30 @@ MathJax.Hub.Config({

     

     

     

    -

    Is the Logistic activation function (Sigmoid) our choice?

    +

    Which activation function should I use?

    -

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

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

    -

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

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

    -

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

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

    @@ -506,7 +510,7 @@ better than the logistic function in deep networks).

  • 50
  • 51
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs042.html b/doc/pub/week41/html/._week41-bs042.html index 0d24f898f..3ddcf6bd0 100644 --- a/doc/pub/week41/html/._week41-bs042.html +++ b/doc/pub/week41/html/._week41-bs042.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,38 +458,32 @@ MathJax.Hub.Config({

     

     

     

    - -

    The derivative of the Logistic funtion

    + +

    Is the Logistic activation function (Sigmoid) our choice?

    -

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

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

    -

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

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

    -

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

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

    @@ -512,7 +511,7 @@ fast to compute).

  • 51
  • 52
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs043.html b/doc/pub/week41/html/._week41-bs043.html index 9c345f3b1..ea835b5c2 100644 --- a/doc/pub/week41/html/._week41-bs043.html +++ b/doc/pub/week41/html/._week41-bs043.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,31 +459,39 @@ MathJax.Hub.Config({

     

     

     

    -

    The RELU function family

    +

    The derivative of the Logistic funtion

    -

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

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

    -

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

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

    -

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

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

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

    diff --git a/doc/pub/week41/html/._week41-bs044.html b/doc/pub/week41/html/._week41-bs044.html index f64d89519..4aab279be 100644 --- a/doc/pub/week41/html/._week41-bs044.html +++ b/doc/pub/week41/html/._week41-bs044.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,23 +459,31 @@ MathJax.Hub.Config({

     

     

     

    -

    Which activation function should we use?

    +

    The RELU function family

    -

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

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

    -

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

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

    +

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

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

      @@ -496,7 +509,7 @@ bootstrap to evaluate other activation functions.
    • 53
    • 54
    • ...
    • -
    • 102
    • +
    • 103
    • »
    diff --git a/doc/pub/week41/html/._week41-bs045.html b/doc/pub/week41/html/._week41-bs045.html index f0a525533..c924ea098 100644 --- a/doc/pub/week41/html/._week41-bs045.html +++ b/doc/pub/week41/html/._week41-bs045.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,18 +459,23 @@ MathJax.Hub.Config({

     

     

     

    -

    More on activation functions, output layers

    +

    Which activation function should we use?

    -

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

    +

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

    -

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

    +

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

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

    diff --git a/doc/pub/week41/html/._week41-bs046.html b/doc/pub/week41/html/._week41-bs046.html index b69852db4..4a6034915 100644 --- a/doc/pub/week41/html/._week41-bs046.html +++ b/doc/pub/week41/html/._week41-bs046.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,22 +459,18 @@ MathJax.Hub.Config({

     

     

     

    -

    Batch Normalization

    +

    More on activation functions, output layers

    -

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

    +

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

    -

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

    +

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

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

      @@ -495,7 +496,7 @@ mini-batch, from this the name batch normalization.
    • 55
    • 56
    • ...
    • -
    • 102
    • +
    • 103
    • »
    diff --git a/doc/pub/week41/html/._week41-bs047.html b/doc/pub/week41/html/._week41-bs047.html index d0c70b739..cd7e3763b 100644 --- a/doc/pub/week41/html/._week41-bs047.html +++ b/doc/pub/week41/html/._week41-bs047.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,16 +459,20 @@ MathJax.Hub.Config({

     

     

     

    -

    Dropout

    +

    Batch Normalization

    -

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

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

    -

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

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

    @@ -491,7 +500,7 @@ hyperparameter \( p \) is called the dropout rate, and it is typically set to 50

  • 56
  • 57
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs048.html b/doc/pub/week41/html/._week41-bs048.html index b543ec871..4b99c4e9f 100644 --- a/doc/pub/week41/html/._week41-bs048.html +++ b/doc/pub/week41/html/._week41-bs048.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,17 +459,16 @@ MathJax.Hub.Config({

     

     

     

    -

    Gradient Clipping

    +

    Dropout

    -

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

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

    -

    This technique is called Gradient Clipping.

    - -

    In general however, Batch -Normalization is preferred. +

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

    @@ -492,7 +496,7 @@ Normalization is preferred.

  • 57
  • 58
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs049.html b/doc/pub/week41/html/._week41-bs049.html index 7734210e9..4e914e56b 100644 --- a/doc/pub/week41/html/._week41-bs049.html +++ b/doc/pub/week41/html/._week41-bs049.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,9 +459,18 @@ MathJax.Hub.Config({

     

     

     

    -

    A very nice website on Neural Networks

    +

    Gradient Clipping

    -

    You may find this website very useful. Thx a million to Ghadi for sharing.

    +

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

    + +

    This technique is called Gradient Clipping.

    + +

    In general however, Batch +Normalization is preferred. +

    @@ -483,7 +497,7 @@ MathJax.Hub.Config({

  • 58
  • 59
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs050.html b/doc/pub/week41/html/._week41-bs050.html index 362499440..4c20ca7c3 100644 --- a/doc/pub/week41/html/._week41-bs050.html +++ b/doc/pub/week41/html/._week41-bs050.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,45 +458,10 @@ MathJax.Hub.Config({

     

     

     

    - -

    A top-down perspective on Neural networks

    + +

    A very nice website on Neural Networks

    -

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

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

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

    - -

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

    +

    You may find this website very useful. Thx a million to Ghadi for sharing.

    @@ -518,7 +488,7 @@ supervised learning.

  • 59
  • 60
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs051.html b/doc/pub/week41/html/._week41-bs051.html index 68684b9db..a4b3c2e40 100644 --- a/doc/pub/week41/html/._week41-bs051.html +++ b/doc/pub/week41/html/._week41-bs051.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -453,27 +458,45 @@ MathJax.Hub.Config({

     

     

     

    - -

    Limitations of supervised learning with deep networks

    + +

    A top-down perspective on Neural networks

    -

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

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

    -

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

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

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

    +

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

    + +

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

    @@ -500,7 +523,7 @@ features).

  • 60
  • 61
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs052.html b/doc/pub/week41/html/._week41-bs052.html index 4c1b6d190..d4282d204 100644 --- a/doc/pub/week41/html/._week41-bs052.html +++ b/doc/pub/week41/html/._week41-bs052.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,30 +459,26 @@ MathJax.Hub.Config({

     

     

     

    -

    Overarching Views, a personal note

    +

    Limitations of supervised learning with deep networks

    -

    The author of these lecture notes has an overarching take on many of -the machine learning algorithms we discuss here. +

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

    -

    If we wish to understand complex systems, we need to find some -effective degrees of freedom or features that we find essential, -simply in order to reduce the complexity of the systems we are -studying. This leads, in one way or the other to dimensionality -reductions. Most of the Machine Learning methods we encounter deal -with this, whether we opt for a principal component analysis, or -clustering, or convolutional neural networks, or Ridge or Lasso -regression or random forest, yes, perhaps most machine learning -methods at large. -

    +

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

    -

    For neural networks and our previous discussion, we have seen that we -in essence end up with matrix-matrix and matrix-vector -multiplications. In all cases, our matrices are dense ones, and the -more data we deal with the larger the dimensionalities of the matrices -and vectors. How can we reduce such dimensionalities? One possible -answer is offered by convolutional neural networks (CNN), to be discussed next week. -

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

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

    @@ -504,7 +505,7 @@ answer is offered by convolutional neural networks (CNN), to be discussed

  • 61
  • 62
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs053.html b/doc/pub/week41/html/._week41-bs053.html index 08c5b8de7..d0f6abfea 100644 --- a/doc/pub/week41/html/._week41-bs053.html +++ b/doc/pub/week41/html/._week41-bs053.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,10 +459,29 @@ MathJax.Hub.Config({

     

     

     

    -

    Using Automatic differentiation

    +

    Overarching Views, a personal note

    -

    In our discussions of ordinary differential equations -we will also study the usage of Autograd in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from week 40 and the Autograd documentation. +

    The author of these lecture notes has an overarching take on many of +the machine learning algorithms we discuss here. +

    + +

    If we wish to understand complex systems, we need to find some +effective degrees of freedom or features that we find essential, +simply in order to reduce the complexity of the systems we are +studying. This leads, in one way or the other to dimensionality +reductions. Most of the Machine Learning methods we encounter deal +with this, whether we opt for a principal component analysis, or +clustering, or convolutional neural networks, or Ridge or Lasso +regression or random forest, yes, perhaps most machine learning +methods at large. +

    + +

    For neural networks and our previous discussion, we have seen that we +in essence end up with matrix-matrix and matrix-vector +multiplications. In all cases, our matrices are dense ones, and the +more data we deal with the larger the dimensionalities of the matrices +and vectors. How can we reduce such dimensionalities? One possible +answer is offered by convolutional neural networks (CNN), to be discussed next week.

    @@ -485,7 +509,7 @@ we will also study the usage of 62

  • 63
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs054.html b/doc/pub/week41/html/._week41-bs054.html index 807331cf5..5ef10b46f 100644 --- a/doc/pub/week41/html/._week41-bs054.html +++ b/doc/pub/week41/html/._week41-bs054.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,36 +459,11 @@ MathJax.Hub.Config({

     

     

     

    -

    Solving ODEs with Deep Learning

    +

    Using Automatic differentiation

    -
    -
    - -

    The Universal Approximation Theorem states that a neural network can -approximate any function at a single hidden layer along with one input -and output layer to any given precision. +

    In our discussions of ordinary differential equations +we will also study the usage of Autograd in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from week 40 and the Autograd documentation.

    -
    -
    - - - - - -
    -
    - -

    The lectures on differential equations were developed by Kristine Baluka Hein, now PhD student at IFI. -A great thanks to Kristine. -

    -
    -
    -

    @@ -510,7 +490,7 @@ A great thanks to Kristine.

  • 63
  • 64
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs055.html b/doc/pub/week41/html/._week41-bs055.html index 88859f255..06aaff09c 100644 --- a/doc/pub/week41/html/._week41-bs055.html +++ b/doc/pub/week41/html/._week41-bs055.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,26 +459,36 @@ MathJax.Hub.Config({

     

     

     

    -

    Ordinary Differential Equations

    +

    Solving ODEs with Deep Learning

    -

    An ordinary differential equation (ODE) is an equation involving functions having one variable.

    - -

    In general, an ordinary differential equation looks like

    - -$$ -\begin{equation} \tag{1} -f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) = 0 -\end{equation} -$$ - -

    where \( g(x) \) is the function to find, and \( g^{(n)}(x) \) is the \( n \)-th derivative of \( g(x) \).

    - -

    The \( f\left(x, g(x), g'(x), g''(x), \, \dots \, , g^{(n)}(x)\right) \) is just a way to write that there is an expression involving \( x \) and \( g(x), \ g'(x), \ g''(x), \, \dots \, , \text{ and } g^{(n)}(x) \) on the left side of the equality sign in (1). -The highest order of derivative, that is the value of \( n \), determines to the order of the equation. -The equation is referred to as a \( n \)-th order ODE. -Along with (1), some additional conditions of the function \( g(x) \) are typically given -for the solution to be unique. +

    +
    + +

    The Universal Approximation Theorem states that a neural network can +approximate any function at a single hidden layer along with one input +and output layer to any given precision.

    +
    +
    + + + + + +
    +
    + +

    The lectures on differential equations were developed by Kristine Baluka Hein, now PhD student at IFI. +A great thanks to Kristine. +

    +
    +
    +

    @@ -500,7 +515,7 @@ for the solution to be unique.

  • 64
  • 65
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs056.html b/doc/pub/week41/html/._week41-bs056.html index 3bccfa9a2..7e785f0bc 100644 --- a/doc/pub/week41/html/._week41-bs056.html +++ b/doc/pub/week41/html/._week41-bs056.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,31 +459,27 @@ MathJax.Hub.Config({

     

     

     

    -

    The trial solution

    +

    Ordinary Differential Equations

    -

    Let the trial solution \( g_t(x) \) be

    +

    An ordinary differential equation (ODE) is an equation involving functions having one variable.

    + +

    In general, an ordinary differential equation looks like

    $$ -\begin{equation} - g_t(x) = h_1(x) + h_2(x,N(x,P)) -\tag{2} +\begin{equation} \tag{1} +f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) = 0 \end{equation} $$ -

    where \( h_1(x) \) is a function that makes \( g_t(x) \) satisfy a given set -of conditions, \( N(x,P) \) a neural network with weights and biases -described by \( P \) and \( h_2(x, N(x,P)) \) some expression involving the -neural network. The role of the function \( h_2(x, N(x,P)) \), is to -ensure that the output from \( N(x,P) \) is zero when \( g_t(x) \) is -evaluated at the values of \( x \) where the given conditions must be -satisfied. The function \( h_1(x) \) should alone make \( g_t(x) \) satisfy -the conditions. +

    where \( g(x) \) is the function to find, and \( g^{(n)}(x) \) is the \( n \)-th derivative of \( g(x) \).

    + +

    The \( f\left(x, g(x), g'(x), g''(x), \, \dots \, , g^{(n)}(x)\right) \) is just a way to write that there is an expression involving \( x \) and \( g(x), \ g'(x), \ g''(x), \, \dots \, , \text{ and } g^{(n)}(x) \) on the left side of the equality sign in (1). +The highest order of derivative, that is the value of \( n \), determines to the order of the equation. +The equation is referred to as a \( n \)-th order ODE. +Along with (1), some additional conditions of the function \( g(x) \) are typically given +for the solution to be unique.

    -

    But what about the network \( N(x,P) \)?

    - -

    As described previously, an optimization method could be used to minimize the parameters of a neural network, that being its weights and biases, through backward propagation.

    -

    diff --git a/doc/pub/week41/html/._week41-bs057.html b/doc/pub/week41/html/._week41-bs057.html index ea67249b9..820880c5b 100644 --- a/doc/pub/week41/html/._week41-bs057.html +++ b/doc/pub/week41/html/._week41-bs057.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,34 +459,31 @@ MathJax.Hub.Config({

     

     

     

    -

    Minimization process

    +

    The trial solution

    -

    For the minimization to be defined, we need to have a cost function at hand to minimize.

    - -

    It is given that \( f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) \) should be equal to zero in (1). -We can choose to consider the mean squared error as the cost function for an input \( x \). -Since we are looking at one input, the cost function is just \( f \) squared. -The cost function \( c\left(x, P \right) \) can therefore be expressed as -

    +

    Let the trial solution \( g_t(x) \) be

    $$ -C\left(x, P\right) = \big(f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right)\big)^2 -$$ - -

    If \( N \) inputs are given as a vector \( \boldsymbol{x} \) with elements \( x_i \) for \( i = 1,\dots,N \), -the cost function becomes -

    - -$$ -\begin{equation} \tag{3} - C\left(\boldsymbol{x}, P\right) = \frac{1}{N} \sum_{i=1}^N \big(f\left(x_i, \, g(x_i), \, g'(x_i), \, g''(x_i), \, \dots \, , \, g^{(n)}(x_i)\right)\big)^2 +\begin{equation} + g_t(x) = h_1(x) + h_2(x,N(x,P)) +\tag{2} \end{equation} $$ -

    The neural net should then find the parameters \( P \) that minimizes the cost function in -(3) for a set of \( N \) training samples \( x_i \). +

    where \( h_1(x) \) is a function that makes \( g_t(x) \) satisfy a given set +of conditions, \( N(x,P) \) a neural network with weights and biases +described by \( P \) and \( h_2(x, N(x,P)) \) some expression involving the +neural network. The role of the function \( h_2(x, N(x,P)) \), is to +ensure that the output from \( N(x,P) \) is zero when \( g_t(x) \) is +evaluated at the values of \( x \) where the given conditions must be +satisfied. The function \( h_1(x) \) should alone make \( g_t(x) \) satisfy +the conditions.

    +

    But what about the network \( N(x,P) \)?

    + +

    As described previously, an optimization method could be used to minimize the parameters of a neural network, that being its weights and biases, through backward propagation.

    +

    diff --git a/doc/pub/week41/html/._week41-bs058.html b/doc/pub/week41/html/._week41-bs058.html index 6368597d8..6cce000b8 100644 --- a/doc/pub/week41/html/._week41-bs058.html +++ b/doc/pub/week41/html/._week41-bs058.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,14 +459,32 @@ MathJax.Hub.Config({

     

     

     

    -

    Minimizing the cost function using gradient descent and automatic differentiation

    +

    Minimization process

    -

    To perform the minimization using gradient descent, the gradient of \( C\left(\boldsymbol{x}, P\right) \) is needed. -It might happen so that finding an analytical expression of the gradient of \( C(\boldsymbol{x}, P) \) from (3) gets too messy, depending on which cost function one desires to use. +

    For the minimization to be defined, we need to have a cost function at hand to minimize.

    + +

    It is given that \( f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) \) should be equal to zero in (1). +We can choose to consider the mean squared error as the cost function for an input \( x \). +Since we are looking at one input, the cost function is just \( f \) squared. +The cost function \( c\left(x, P \right) \) can therefore be expressed as

    -

    Luckily, there exists libraries that makes the job for us through automatic differentiation. -Automatic differentiation is a method of finding the derivatives numerically with very high precision. +$$ +C\left(x, P\right) = \big(f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right)\big)^2 +$$ + +

    If \( N \) inputs are given as a vector \( \boldsymbol{x} \) with elements \( x_i \) for \( i = 1,\dots,N \), +the cost function becomes +

    + +$$ +\begin{equation} \tag{3} + C\left(\boldsymbol{x}, P\right) = \frac{1}{N} \sum_{i=1}^N \big(f\left(x_i, \, g(x_i), \, g'(x_i), \, g''(x_i), \, \dots \, , \, g^{(n)}(x_i)\right)\big)^2 +\end{equation} +$$ + +

    The neural net should then find the parameters \( P \) that minimizes the cost function in +(3) for a set of \( N \) training samples \( x_i \).

    @@ -489,7 +512,7 @@ Automatic differentiation is a method of finding the derivatives numerically wit

  • 67
  • 68
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs059.html b/doc/pub/week41/html/._week41-bs059.html index be5192063..239ca3d74 100644 --- a/doc/pub/week41/html/._week41-bs059.html +++ b/doc/pub/week41/html/._week41-bs059.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,28 +459,15 @@ MathJax.Hub.Config({

     

     

     

    -

    Example: Exponential decay

    +

    Minimizing the cost function using gradient descent and automatic differentiation

    -

    An exponential decay of a quantity \( g(x) \) is described by the equation

    +

    To perform the minimization using gradient descent, the gradient of \( C\left(\boldsymbol{x}, P\right) \) is needed. +It might happen so that finding an analytical expression of the gradient of \( C(\boldsymbol{x}, P) \) from (3) gets too messy, depending on which cost function one desires to use. +

    -$$ -\begin{equation} \tag{4} - g'(x) = -\gamma g(x) -\end{equation} -$$ - -

    with \( g(0) = g_0 \) for some chosen initial value \( g_0 \).

    - -

    The analytical solution of (4) is

    - -$$ -\begin{equation} - g(x) = g_0 \exp\left(-\gamma x\right) -\tag{5} -\end{equation} -$$ - -

    Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of (4).

    +

    Luckily, there exists libraries that makes the job for us through automatic differentiation. +Automatic differentiation is a method of finding the derivatives numerically with very high precision. +

    @@ -502,7 +494,7 @@ $$

  • 68
  • 69
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs060.html b/doc/pub/week41/html/._week41-bs060.html index 73fb879df..6b2b0d139 100644 --- a/doc/pub/week41/html/._week41-bs060.html +++ b/doc/pub/week41/html/._week41-bs060.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,19 +459,28 @@ MathJax.Hub.Config({

     

     

     

    -

    The function to solve for

    +

    Example: Exponential decay

    -

    The program will use a neural network to solve

    +

    An exponential decay of a quantity \( g(x) \) is described by the equation

    $$ -\begin{equation} \tag{6} -g'(x) = -\gamma g(x) +\begin{equation} \tag{4} + g'(x) = -\gamma g(x) \end{equation} $$ -

    where \( g(0) = g_0 \) with \( \gamma \) and \( g_0 \) being some chosen values.

    +

    with \( g(0) = g_0 \) for some chosen initial value \( g_0 \).

    -

    In this example, \( \gamma = 2 \) and \( g_0 = 10 \).

    +

    The analytical solution of (4) is

    + +$$ +\begin{equation} + g(x) = g_0 \exp\left(-\gamma x\right) +\tag{5} +\end{equation} +$$ + +

    Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of (4).

    @@ -493,7 +507,7 @@ $$

  • 69
  • 70
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs061.html b/doc/pub/week41/html/._week41-bs061.html index 0a2276a4b..7787863e3 100644 --- a/doc/pub/week41/html/._week41-bs061.html +++ b/doc/pub/week41/html/._week41-bs061.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,14 +459,19 @@ MathJax.Hub.Config({

     

     

     

    -

    The trial solution

    -

    To begin with, a trial solution \( g_t(t) \) must be chosen. A general trial solution for ordinary differential equations could be

    +

    The function to solve for

    + +

    The program will use a neural network to solve

    $$ -g_t(x, P) = h_1(x) + h_2(x, N(x, P)) +\begin{equation} \tag{6} +g'(x) = -\gamma g(x) +\end{equation} $$ -

    with \( h_1(x) \) ensuring that \( g_t(x) \) satisfies some conditions and \( h_2(x,N(x, P)) \) an expression involving \( x \) and the output from the neural network \( N(x,P) \) with \( P \) being the collection of the weights and biases for each layer. For now, it is assumed that the network consists of one input layer, one hidden layer, and one output layer.

    +

    where \( g(0) = g_0 \) with \( \gamma \) and \( g_0 \) being some chosen values.

    + +

    In this example, \( \gamma = 2 \) and \( g_0 = 10 \).

    @@ -488,7 +498,7 @@ $$

  • 70
  • 71
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs062.html b/doc/pub/week41/html/._week41-bs062.html index 8c0a014ad..2545a0aff 100644 --- a/doc/pub/week41/html/._week41-bs062.html +++ b/doc/pub/week41/html/._week41-bs062.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,26 +459,14 @@ MathJax.Hub.Config({

     

     

     

    -

    Setup of Network

    - -

    In this network, there are no weights and bias at the input layer, so \( P = \{ P_{\text{hidden}}, P_{\text{output}} \} \). -If there are \( N_{\text{hidden} } \) neurons in the hidden layer, then \( P_{\text{hidden}} \) is a \( N_{\text{hidden} } \times (1 + N_{\text{input}}) \) matrix, given that there are \( N_{\text{input}} \) neurons in the input layer. -

    - -

    The first column in \( P_{\text{hidden} } \) represents the bias for each neuron in the hidden layer and the second column represents the weights for each neuron in the hidden layer from the input layer. -If there are \( N_{\text{output} } \) neurons in the output layer, then \( P_{\text{output}} \) is a \( N_{\text{output} } \times (1 + N_{\text{hidden} }) \) matrix. -

    - -

    Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron.

    - -

    It is given that \( g(0) = g_0 \). The trial solution must fulfill this condition to be a proper solution of (6). A possible way to ensure that \( g_t(0, P) = g_0 \), is to let \( F(N(x,P)) = x \cdot N(x,P) \) and \( A(x) = g_0 \). This gives the following trial solution:

    +

    The trial solution

    +

    To begin with, a trial solution \( g_t(t) \) must be chosen. A general trial solution for ordinary differential equations could be

    $$ -\begin{equation} \tag{7} -g_t(x, P) = g_0 + x \cdot N(x, P) -\end{equation} +g_t(x, P) = h_1(x) + h_2(x, N(x, P)) $$ +

    with \( h_1(x) \) ensuring that \( g_t(x) \) satisfies some conditions and \( h_2(x,N(x, P)) \) an expression involving \( x \) and the output from the neural network \( N(x,P) \) with \( P \) being the collection of the weights and biases for each layer. For now, it is assumed that the network consists of one input layer, one hidden layer, and one output layer.

    @@ -500,7 +493,7 @@ $$

  • 71
  • 72
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs063.html b/doc/pub/week41/html/._week41-bs063.html index 204c558f9..7c56301ea 100644 --- a/doc/pub/week41/html/._week41-bs063.html +++ b/doc/pub/week41/html/._week41-bs063.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,31 +459,26 @@ MathJax.Hub.Config({

     

     

     

    -

    Reformulating the problem

    +

    Setup of Network

    -

    We wish that our neural network manages to minimize a given cost function.

    - -

    A reformulation of out equation, (6), must therefore be done, -such that it describes the problem a neural network can solve for. +

    In this network, there are no weights and bias at the input layer, so \( P = \{ P_{\text{hidden}}, P_{\text{output}} \} \). +If there are \( N_{\text{hidden} } \) neurons in the hidden layer, then \( P_{\text{hidden}} \) is a \( N_{\text{hidden} } \times (1 + N_{\text{input}}) \) matrix, given that there are \( N_{\text{input}} \) neurons in the input layer.

    -

    The neural network must find the set of weights and biases \( P \) such that the trial solution in (7) satisfies (6).

    +

    The first column in \( P_{\text{hidden} } \) represents the bias for each neuron in the hidden layer and the second column represents the weights for each neuron in the hidden layer from the input layer. +If there are \( N_{\text{output} } \) neurons in the output layer, then \( P_{\text{output}} \) is a \( N_{\text{output} } \times (1 + N_{\text{hidden} }) \) matrix. +

    -

    The trial solution

    +

    Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron.

    + +

    It is given that \( g(0) = g_0 \). The trial solution must fulfill this condition to be a proper solution of (6). A possible way to ensure that \( g_t(0, P) = g_0 \), is to let \( F(N(x,P)) = x \cdot N(x,P) \) and \( A(x) = g_0 \). This gives the following trial solution:

    $$ +\begin{equation} \tag{7} g_t(x, P) = g_0 + x \cdot N(x, P) -$$ - -

    has been chosen such that it already solves the condition \( g(0) = g_0 \). What remains, is to find \( P \) such that

    - -$$ -\begin{equation} \tag{8} -g_t'(x, P) = - \gamma g_t(x, P) \end{equation} $$ -

    is fulfilled as best as possible.

    @@ -505,7 +505,7 @@ $$

  • 72
  • 73
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs064.html b/doc/pub/week41/html/._week41-bs064.html index 3d5cf57e3..9f5db30b7 100644 --- a/doc/pub/week41/html/._week41-bs064.html +++ b/doc/pub/week41/html/._week41-bs064.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,28 +459,31 @@ MathJax.Hub.Config({

     

     

     

    -

    More technicalities

    +

    Reformulating the problem

    -

    The left hand side and right hand side of (8) must be computed separately, and then the neural network must choose weights and biases, contained in \( P \), such that the sides are equal as best as possible. -This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero. -In this case, the difference squared shows to be an appropriate measurement of how erroneous the trial solution is with respect to \( P \) of the neural network. +

    We wish that our neural network manages to minimize a given cost function.

    + +

    A reformulation of out equation, (6), must therefore be done, +such that it describes the problem a neural network can solve for.

    -

    This gives the following cost function our neural network must solve for:

    +

    The neural network must find the set of weights and biases \( P \) such that the trial solution in (7) satisfies (6).

    + +

    The trial solution

    $$ -\min_{P}\Big\{ \big(g_t'(x, P) - ( -\gamma g_t(x, P) \big)^2 \Big\} +g_t(x, P) = g_0 + x \cdot N(x, P) $$ -

    (the notation \( \min_{P}\{ f(x, P) \} \) means that we desire to find \( P \) that yields the minimum of \( f(x, P) \))

    - -

    or, in terms of weights and biases for the hidden and output layer in our network:

    +

    has been chosen such that it already solves the condition \( g(0) = g_0 \). What remains, is to find \( P \) such that

    $$ -\min_{P_{\text{hidden} }, \ P_{\text{output} }}\Big\{ \big(g_t'(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) - ( -\gamma g_t(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) \big)^2 \Big\} +\begin{equation} \tag{8} +g_t'(x, P) = - \gamma g_t(x, P) +\end{equation} $$ -

    for an input value \( x \).

    +

    is fulfilled as best as possible.

    @@ -502,7 +510,7 @@ $$

  • 73
  • 74
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs065.html b/doc/pub/week41/html/._week41-bs065.html index cb096ffe2..a9193715a 100644 --- a/doc/pub/week41/html/._week41-bs065.html +++ b/doc/pub/week41/html/._week41-bs065.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,29 +459,29 @@ MathJax.Hub.Config({

     

     

     

    -

    More details

    +

    More technicalities

    -

    If the neural network evaluates \( g_t(x, P) \) at more values for \( x \), say \( N \) values \( x_i \) for \( i = 1, \dots, N \), then the total error to minimize becomes

    - -$$ -\begin{equation} \tag{9} -\min_{P}\Big\{\frac{1}{N} \sum_{i=1}^N \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \Big\} -\end{equation} -$$ - -

    Letting \( \boldsymbol{x} \) be a vector with elements \( x_i \) and \( C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \) denote the cost function, the minimization problem that our network must solve, becomes

    - -$$ -\min_{P} C(\boldsymbol{x}, P) -$$ - -

    In terms of \( P_{\text{hidden} } \) and \( P_{\text{output} } \), this could also be expressed as

    - -

    $$ -\min_{P_{\text{hidden} }, \ P_{\text{output} }} C(\boldsymbol{x}, \{P_{\text{hidden} }, P_{\text{output} }\}) -$$ +

    The left hand side and right hand side of (8) must be computed separately, and then the neural network must choose weights and biases, contained in \( P \), such that the sides are equal as best as possible. +This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero. +In this case, the difference squared shows to be an appropriate measurement of how erroneous the trial solution is with respect to \( P \) of the neural network.

    +

    This gives the following cost function our neural network must solve for:

    + +$$ +\min_{P}\Big\{ \big(g_t'(x, P) - ( -\gamma g_t(x, P) \big)^2 \Big\} +$$ + +

    (the notation \( \min_{P}\{ f(x, P) \} \) means that we desire to find \( P \) that yields the minimum of \( f(x, P) \))

    + +

    or, in terms of weights and biases for the hidden and output layer in our network:

    + +$$ +\min_{P_{\text{hidden} }, \ P_{\text{output} }}\Big\{ \big(g_t'(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) - ( -\gamma g_t(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) \big)^2 \Big\} +$$ + +

    for an input value \( x \).

    +

    diff --git a/doc/pub/week41/html/._week41-bs066.html b/doc/pub/week41/html/._week41-bs066.html index 6b4a5f066..85c2f017c 100644 --- a/doc/pub/week41/html/._week41-bs066.html +++ b/doc/pub/week41/html/._week41-bs066.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,13 +459,27 @@ MathJax.Hub.Config({

     

     

     

    -

    A possible implementation of a neural network

    +

    More details

    -

    For simplicity, it is assumed that the input is an array \( \boldsymbol{x} = (x_1, \dots, x_N) \) with \( N \) elements. It is at these points the neural network should find \( P \) such that it fulfills (9).

    +

    If the neural network evaluates \( g_t(x, P) \) at more values for \( x \), say \( N \) values \( x_i \) for \( i = 1, \dots, N \), then the total error to minimize becomes

    -

    First, the neural network must feed forward the inputs. -This means that \( \boldsymbol{x}s \) must be passed through an input layer, a hidden layer and a output layer. The input layer in this case, does not need to process the data any further. -The input layer will consist of \( N_{\text{input} } \) neurons, passing its element to each neuron in the hidden layer. The number of neurons in the hidden layer will be \( N_{\text{hidden} } \). +$$ +\begin{equation} \tag{9} +\min_{P}\Big\{\frac{1}{N} \sum_{i=1}^N \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \Big\} +\end{equation} +$$ + +

    Letting \( \boldsymbol{x} \) be a vector with elements \( x_i \) and \( C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \) denote the cost function, the minimization problem that our network must solve, becomes

    + +$$ +\min_{P} C(\boldsymbol{x}, P) +$$ + +

    In terms of \( P_{\text{hidden} } \) and \( P_{\text{output} } \), this could also be expressed as

    + +

    $$ +\min_{P_{\text{hidden} }, \ P_{\text{output} }} C(\boldsymbol{x}, \{P_{\text{hidden} }, P_{\text{output} }\}) +$$

    @@ -488,7 +507,7 @@ The input layer will consist of \( N_{\text{input} } \) neurons, passing its ele

  • 75
  • 76
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs067.html b/doc/pub/week41/html/._week41-bs067.html index 50876d1cb..705ad5dce 100644 --- a/doc/pub/week41/html/._week41-bs067.html +++ b/doc/pub/week41/html/._week41-bs067.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,24 +459,14 @@ MathJax.Hub.Config({

     

     

     

    -

    Technicalities

    +

    A possible implementation of a neural network

    -

    For the \( i \)-th in the hidden layer with weight \( w_i^{\text{hidden} } \) and bias \( b_i^{\text{hidden} } \), the weighting from the \( j \)-th neuron at the input layer is:

    - -$$ -\begin{aligned} -z_{i,j}^{\text{hidden}} &= b_i^{\text{hidden}} + w_i^{\text{hidden}}x_j \\ -&= -\begin{pmatrix} -b_i^{\text{hidden}} & w_i^{\text{hidden}} -\end{pmatrix} -\begin{pmatrix} -1 \\ -x_j -\end{pmatrix} -\end{aligned} -$$ +

    For simplicity, it is assumed that the input is an array \( \boldsymbol{x} = (x_1, \dots, x_N) \) with \( N \) elements. It is at these points the neural network should find \( P \) such that it fulfills (9).

    +

    First, the neural network must feed forward the inputs. +This means that \( \boldsymbol{x}s \) must be passed through an input layer, a hidden layer and a output layer. The input layer in this case, does not need to process the data any further. +The input layer will consist of \( N_{\text{input} } \) neurons, passing its element to each neuron in the hidden layer. The number of neurons in the hidden layer will be \( N_{\text{hidden} } \). +

    @@ -498,7 +493,7 @@ $$

  • 76
  • 77
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs068.html b/doc/pub/week41/html/._week41-bs068.html index fbaed30db..a58366f25 100644 --- a/doc/pub/week41/html/._week41-bs068.html +++ b/doc/pub/week41/html/._week41-bs068.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,22 +459,21 @@ MathJax.Hub.Config({

     

     

     

    -

    Final technicalities I

    +

    Technicalities

    -

    The result after weighting the inputs at the \( i \)-th hidden neuron can be written as a vector:

    +

    For the \( i \)-th in the hidden layer with weight \( w_i^{\text{hidden} } \) and bias \( b_i^{\text{hidden} } \), the weighting from the \( j \)-th neuron at the input layer is:

    $$ \begin{aligned} -\boldsymbol{z}_{i}^{\text{hidden}} &= \Big( b_i^{\text{hidden}} + w_i^{\text{hidden}}x_1 , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_2, \ \dots \, , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_N\Big) \\ +z_{i,j}^{\text{hidden}} &= b_i^{\text{hidden}} + w_i^{\text{hidden}}x_j \\ &= \begin{pmatrix} - b_i^{\text{hidden}} & w_i^{\text{hidden}} +b_i^{\text{hidden}} & w_i^{\text{hidden}} \end{pmatrix} \begin{pmatrix} -1 & 1 & \dots & 1 \\ -x_1 & x_2 & \dots & x_N -\end{pmatrix} \\ -&= \boldsymbol{p}_{i, \text{hidden}}^T X +1 \\ +x_j +\end{pmatrix} \end{aligned} $$ @@ -499,7 +503,7 @@ $$
  • 77
  • 78
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs069.html b/doc/pub/week41/html/._week41-bs069.html index b1272237a..3e8cf6f38 100644 --- a/doc/pub/week41/html/._week41-bs069.html +++ b/doc/pub/week41/html/._week41-bs069.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,35 +459,25 @@ MathJax.Hub.Config({

     

     

     

    -

    Final technicalities II

    +

    Final technicalities I

    -

    The vector \( \boldsymbol{p}_{i, \text{hidden}}^T \) constitutes each row in \( P_{\text{hidden} } \), which contains the weights for the neural network to minimize according to (9).

    - -

    After having found \( \boldsymbol{z}_{i}^{\text{hidden}} \) for every \( i \)-th neuron within the hidden layer, the vector will be sent to an activation function \( a_i(\boldsymbol{z}) \).

    - -

    In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron:

    +

    The result after weighting the inputs at the \( i \)-th hidden neuron can be written as a vector:

    $$ -f(z) = \frac{1}{1 + \exp{(-z)}} +\begin{aligned} +\boldsymbol{z}_{i}^{\text{hidden}} &= \Big( b_i^{\text{hidden}} + w_i^{\text{hidden}}x_1 , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_2, \ \dots \, , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_N\Big) \\ +&= +\begin{pmatrix} + b_i^{\text{hidden}} & w_i^{\text{hidden}} +\end{pmatrix} +\begin{pmatrix} +1 & 1 & \dots & 1 \\ +x_1 & x_2 & \dots & x_N +\end{pmatrix} \\ +&= \boldsymbol{p}_{i, \text{hidden}}^T X +\end{aligned} $$ -

    It is possible to use other activations functions for the hidden layer also.

    - -

    The output \( \boldsymbol{x}_i^{\text{hidden}} \) from each \( i \)-th hidden neuron is:

    - -

    $$ -\boldsymbol{x}_i^{\text{hidden} } = f\big( \boldsymbol{z}_{i}^{\text{hidden}} \big) -$$ -

    - -

    The outputs \( \boldsymbol{x}_i^{\text{hidden} } \) are then sent to the output layer.

    - -

    The output layer consists of one neuron in this case, and combines the -output from each of the neurons in the hidden layers. The output layer -combines the results from the hidden layer using some weights \( w_i^{\text{output}} \) -and biases \( b_i^{\text{output}} \). In this case, -it is assumes that the number of neurons in the output layer is one. -

    @@ -509,7 +504,7 @@ it is assumes that the number of neurons in the output layer is one.

  • 78
  • 79
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs070.html b/doc/pub/week41/html/._week41-bs070.html index a867d98f0..911ca774f 100644 --- a/doc/pub/week41/html/._week41-bs070.html +++ b/doc/pub/week41/html/._week41-bs070.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,23 +459,35 @@ MathJax.Hub.Config({

     

     

     

    -

    Final technicalities III

    +

    Final technicalities II

    -

    The procedure of weighting the output neuron \( j \) in the hidden layer to the \( i \)-th neuron in the output layer is similar as for the hidden layer described previously.

    +

    The vector \( \boldsymbol{p}_{i, \text{hidden}}^T \) constitutes each row in \( P_{\text{hidden} } \), which contains the weights for the neural network to minimize according to (9).

    + +

    After having found \( \boldsymbol{z}_{i}^{\text{hidden}} \) for every \( i \)-th neuron within the hidden layer, the vector will be sent to an activation function \( a_i(\boldsymbol{z}) \).

    + +

    In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron:

    $$ -\begin{aligned} -z_{1,j}^{\text{output}} & = -\begin{pmatrix} -b_1^{\text{output}} & \boldsymbol{w}_1^{\text{output}} -\end{pmatrix} -\begin{pmatrix} -1 \\ -\boldsymbol{x}_j^{\text{hidden}} -\end{pmatrix} -\end{aligned} +f(z) = \frac{1}{1 + \exp{(-z)}} $$ +

    It is possible to use other activations functions for the hidden layer also.

    + +

    The output \( \boldsymbol{x}_i^{\text{hidden}} \) from each \( i \)-th hidden neuron is:

    + +

    $$ +\boldsymbol{x}_i^{\text{hidden} } = f\big( \boldsymbol{z}_{i}^{\text{hidden}} \big) +$$ +

    + +

    The outputs \( \boldsymbol{x}_i^{\text{hidden} } \) are then sent to the output layer.

    + +

    The output layer consists of one neuron in this case, and combines the +output from each of the neurons in the hidden layers. The output layer +combines the results from the hidden layer using some weights \( w_i^{\text{output}} \) +and biases \( b_i^{\text{output}} \). In this case, +it is assumes that the number of neurons in the output layer is one. +

    @@ -497,7 +514,7 @@ $$

  • 79
  • 80
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs071.html b/doc/pub/week41/html/._week41-bs071.html index 068146f1d..8ec21ebf7 100644 --- a/doc/pub/week41/html/._week41-bs071.html +++ b/doc/pub/week41/html/._week41-bs071.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,22 +459,23 @@ MathJax.Hub.Config({

     

     

     

    -

    Final technicalities IV

    +

    Final technicalities III

    -

    Expressing \( z_{1,j}^{\text{output}} \) as a vector gives the following way of weighting the inputs from the hidden layer:

    +

    The procedure of weighting the output neuron \( j \) in the hidden layer to the \( i \)-th neuron in the output layer is similar as for the hidden layer described previously.

    $$ -\boldsymbol{z}_{1}^{\text{output}} = +\begin{aligned} +z_{1,j}^{\text{output}} & = \begin{pmatrix} b_1^{\text{output}} & \boldsymbol{w}_1^{\text{output}} \end{pmatrix} \begin{pmatrix} -1 & 1 & \dots & 1 \\ -\boldsymbol{x}_1^{\text{hidden}} & \boldsymbol{x}_2^{\text{hidden}} & \dots & \boldsymbol{x}_N^{\text{hidden}} +1 \\ +\boldsymbol{x}_j^{\text{hidden}} \end{pmatrix} +\end{aligned} $$ -

    In this case we seek a continuous range of values since we are approximating a function. This means that after computing \( \boldsymbol{z}_{1}^{\text{output}} \) the neural network has finished its feed forward step, and \( \boldsymbol{z}_{1}^{\text{output}} \) is the final output of the network.

    @@ -496,7 +502,7 @@ $$

  • 80
  • 81
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/._week41-bs072.html b/doc/pub/week41/html/._week41-bs072.html index e65c443ca..e909d13f2 100644 --- a/doc/pub/week41/html/._week41-bs072.html +++ b/doc/pub/week41/html/._week41-bs072.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -454,19 +459,22 @@ MathJax.Hub.Config({

     

     

     

    -

    Back propagation

    +

    Final technicalities IV

    -

    The next step is to decide how the parameters should be changed such that they minimize the cost function.

    - -

    The chosen cost function for this problem is

    +

    Expressing \( z_{1,j}^{\text{output}} \) as a vector gives the following way of weighting the inputs from the hidden layer:

    $$ -C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 +\boldsymbol{z}_{1}^{\text{output}} = +\begin{pmatrix} +b_1^{\text{output}} & \boldsymbol{w}_1^{\text{output}} +\end{pmatrix} +\begin{pmatrix} +1 & 1 & \dots & 1 \\ +\boldsymbol{x}_1^{\text{hidden}} & \boldsymbol{x}_2^{\text{hidden}} & \dots & \boldsymbol{x}_N^{\text{hidden}} +\end{pmatrix} $$ -

    In order to minimize the cost function, an optimization method must be chosen.

    - -

    Here, gradient descent with a constant step size has been chosen.

    +

    In this case we seek a continuous range of values since we are approximating a function. This means that after computing \( \boldsymbol{z}_{1}^{\text{output}} \) the neural network has finished its feed forward step, and \( \boldsymbol{z}_{1}^{\text{output}} \) is the final output of the network.

    @@ -493,7 +501,7 @@ $$

  • 81
  • 82
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/week41-bs.html b/doc/pub/week41/html/week41-bs.html index e1eadc26b..b4a6ab7a9 100644 --- a/doc/pub/week41/html/week41-bs.html +++ b/doc/pub/week41/html/week41-bs.html @@ -41,6 +41,10 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -344,105 +348,106 @@ MathJax.Hub.Config({ @@ -472,7 +477,7 @@ MathJax.Hub.Config({
    -

    Oct 9, 2022

    +

    Oct 15, 2022


    @@ -497,7 +502,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 102
  • +
  • 103
  • »
  • diff --git a/doc/pub/week41/html/week41-reveal.html b/doc/pub/week41/html/week41-reveal.html index 8b6d29ef0..d27ab499e 100644 --- a/doc/pub/week41/html/week41-reveal.html +++ b/doc/pub/week41/html/week41-reveal.html @@ -184,7 +184,7 @@ MathJax.Hub.Config({
    -

    Oct 9, 2022

    +

    Oct 15, 2022


    @@ -216,6 +216,16 @@ For a more in depth discussion on neural networks we recommend Goodfellow et al +
    +

    Review of the back propagation algorithm

    + +

    During the last lecture we discussed in detail the back propagation +algorithm. This algorithm is based on a repeated application of the +chain rule. Let us bring back the basic equation and at the same time +link this with the basic mathematics of automatic differentiation. +

    +
    +

    Setting up the Back propagation algorithm

    diff --git a/doc/pub/week41/html/week41-solarized.html b/doc/pub/week41/html/week41-solarized.html index 3888793ff..8fdae54f6 100644 --- a/doc/pub/week41/html/week41-solarized.html +++ b/doc/pub/week41/html/week41-solarized.html @@ -68,6 +68,10 @@ div.toc p,a { 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -372,7 +376,7 @@ MathJax.Hub.Config({
    -

    Oct 9, 2022

    +

    Oct 15, 2022


    @@ -394,6 +398,15 @@ For a more in depth discussion on neural networks we recommend Goodfellow et al
  • Video on Neural Networks
  • Video on the back propagation algorithm
  • +









    +

    Review of the back propagation algorithm

    + +

    During the last lecture we discussed in detail the back propagation +algorithm. This algorithm is based on a repeated application of the +chain rule. Let us bring back the basic equation and at the same time +link this with the basic mathematics of automatic differentiation. +

    +









    Setting up the Back propagation algorithm

    diff --git a/doc/pub/week41/html/week41.html b/doc/pub/week41/html/week41.html index e04f7ea0c..e403d2f07 100644 --- a/doc/pub/week41/html/week41.html +++ b/doc/pub/week41/html/week41.html @@ -145,6 +145,10 @@ div.toc p,a { 2, None, 'videos-on-neural-networks'), + ('Review of the back propagation algorithm', + 2, + None, + 'review-of-the-back-propagation-algorithm'), ('Setting up the Back propagation algorithm', 2, None, @@ -449,7 +453,7 @@ MathJax.Hub.Config({
    -

    Oct 9, 2022

    +

    Oct 15, 2022


    @@ -471,6 +475,15 @@ For a more in depth discussion on neural networks we recommend Goodfellow et al
  • Video on Neural Networks
  • Video on the back propagation algorithm
  • +









    +

    Review of the back propagation algorithm

    + +

    During the last lecture we discussed in detail the back propagation +algorithm. This algorithm is based on a repeated application of the +chain rule. Let us bring back the basic equation and at the same time +link this with the basic mathematics of automatic differentiation. +

    +









    Setting up the Back propagation algorithm

    diff --git a/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz b/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz index b8731c835..f6d773114 100644 Binary files a/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz and b/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz differ diff --git a/doc/pub/week41/ipynb/week41.ipynb b/doc/pub/week41/ipynb/week41.ipynb index 9cfaa1eb2..9da8ff5c1 100644 --- a/doc/pub/week41/ipynb/week41.ipynb +++ b/doc/pub/week41/ipynb/week41.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "1633ece4", + "id": "975262ec", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "e415a060", + "id": "b0eae28d", "metadata": { "editable": true }, @@ -22,14 +22,14 @@ "# Week 41 Constructing a Neural Network code, Tensor flow and start Convolutional Neural Networks\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", "\n", - "Date: **Oct 9, 2022**\n", + "Date: **Oct 15, 2022**\n", "\n", "Copyright 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" ] }, { "cell_type": "markdown", - "id": "a7951a6a", + "id": "4f5a6dcb", "metadata": { "editable": true }, @@ -46,7 +46,7 @@ }, { "cell_type": "markdown", - "id": "6f0828aa", + "id": "50f2936a", "metadata": { "editable": true }, @@ -60,7 +60,22 @@ }, { "cell_type": "markdown", - "id": "9ef42eed", + "id": "b827ad7e", + "metadata": { + "editable": true + }, + "source": [ + "## Review of the back propagation algorithm\n", + "\n", + "During the last lecture we discussed in detail the back propagation\n", + "algorithm. This algorithm is based on a repeated application of the\n", + "chain rule. Let us bring back the basic equation and at the same time\n", + "link this with the basic mathematics of automatic differentiation." + ] + }, + { + "cell_type": "markdown", + "id": "806dffca", "metadata": { "editable": true }, @@ -83,7 +98,7 @@ }, { "cell_type": "markdown", - "id": "e0dbf64a", + "id": "859b5d78", "metadata": { "editable": true }, @@ -95,7 +110,7 @@ }, { "cell_type": "markdown", - "id": "d39d3edc", + "id": "753d8335", "metadata": { "editable": true }, @@ -105,7 +120,7 @@ }, { "cell_type": "markdown", - "id": "ee32bbf0", + "id": "9f6d7e0b", "metadata": { "editable": true }, @@ -117,7 +132,7 @@ }, { "cell_type": "markdown", - "id": "81bc0bfa", + "id": "e0d5108f", "metadata": { "editable": true }, @@ -127,7 +142,7 @@ }, { "cell_type": "markdown", - "id": "67f48634", + "id": "4e72fbea", "metadata": { "editable": true }, @@ -139,7 +154,7 @@ }, { "cell_type": "markdown", - "id": "6ca27162", + "id": "0602f4b2", "metadata": { "editable": true }, @@ -151,7 +166,7 @@ }, { "cell_type": "markdown", - "id": "554fba63", + "id": "7bf854a6", "metadata": { "editable": true }, @@ -162,7 +177,7 @@ }, { "cell_type": "markdown", - "id": "9e424787", + "id": "7c507f5b", "metadata": { "editable": true }, @@ -190,7 +205,7 @@ }, { "cell_type": "markdown", - "id": "1c8f3e3c", + "id": "fd1e66c8", "metadata": { "editable": true }, @@ -202,7 +217,7 @@ }, { "cell_type": "markdown", - "id": "5c6554b5", + "id": "14a03523", "metadata": { "editable": true }, @@ -212,7 +227,7 @@ }, { "cell_type": "markdown", - "id": "dba6173e", + "id": "803c6861", "metadata": { "editable": true }, @@ -224,7 +239,7 @@ }, { "cell_type": "markdown", - "id": "3bb02a77", + "id": "26a7a40f", "metadata": { "editable": true }, @@ -235,7 +250,7 @@ }, { "cell_type": "markdown", - "id": "025d08d0", + "id": "33f03037", "metadata": { "editable": true }, @@ -247,7 +262,7 @@ }, { "cell_type": "markdown", - "id": "606e43ac", + "id": "83904654", "metadata": { "editable": true }, @@ -260,7 +275,7 @@ }, { "cell_type": "markdown", - "id": "81724f94", + "id": "c612a009", "metadata": { "editable": true }, @@ -285,7 +300,7 @@ }, { "cell_type": "markdown", - "id": "51119948", + "id": "4073d973", "metadata": { "editable": true }, @@ -298,7 +313,7 @@ }, { "cell_type": "markdown", - "id": "946a338d", + "id": "d077f76c", "metadata": { "editable": true }, @@ -310,7 +325,7 @@ }, { "cell_type": "markdown", - "id": "ca36f71b", + "id": "3354ad8c", "metadata": { "editable": true }, @@ -322,7 +337,7 @@ }, { "cell_type": "markdown", - "id": "2581eefb", + "id": "96a8ea69", "metadata": { "editable": true }, @@ -332,7 +347,7 @@ }, { "cell_type": "markdown", - "id": "e40e88d1", + "id": "3886730c", "metadata": { "editable": true }, @@ -344,7 +359,7 @@ }, { "cell_type": "markdown", - "id": "acfdeeb7", + "id": "1ff35269", "metadata": { "editable": true }, @@ -356,7 +371,7 @@ }, { "cell_type": "markdown", - "id": "3280e975", + "id": "8648d883", "metadata": { "editable": true }, @@ -368,7 +383,7 @@ }, { "cell_type": "markdown", - "id": "001d73c9", + "id": "e21bbc09", "metadata": { "editable": true }, @@ -380,7 +395,7 @@ }, { "cell_type": "markdown", - "id": "52e0037a", + "id": "3994187a", "metadata": { "editable": true }, @@ -390,7 +405,7 @@ }, { "cell_type": "markdown", - "id": "d2f837c8", + "id": "9c5ae70c", "metadata": { "editable": true }, @@ -402,7 +417,7 @@ }, { "cell_type": "markdown", - "id": "fb1c0f51", + "id": "b8cb3324", "metadata": { "editable": true }, @@ -412,7 +427,7 @@ }, { "cell_type": "markdown", - "id": "b7db26cd", + "id": "eb9d0b98", "metadata": { "editable": true }, @@ -424,7 +439,7 @@ }, { "cell_type": "markdown", - "id": "d3975bb0", + "id": "e7e4f6cc", "metadata": { "editable": true }, @@ -437,7 +452,7 @@ }, { "cell_type": "markdown", - "id": "975ed358", + "id": "60a0dea9", "metadata": { "editable": true }, @@ -449,7 +464,7 @@ }, { "cell_type": "markdown", - "id": "b7bd5279", + "id": "ff9153db", "metadata": { "editable": true }, @@ -459,7 +474,7 @@ }, { "cell_type": "markdown", - "id": "1fb4abda", + "id": "937e0b88", "metadata": { "editable": true }, @@ -471,7 +486,7 @@ }, { "cell_type": "markdown", - "id": "92a01f26", + "id": "d512ac32", "metadata": { "editable": true }, @@ -482,7 +497,7 @@ }, { "cell_type": "markdown", - "id": "61a7600e", + "id": "0116ab23", "metadata": { "editable": true }, @@ -494,7 +509,7 @@ }, { "cell_type": "markdown", - "id": "b185831b", + "id": "68f7ca43", "metadata": { "editable": true }, @@ -504,7 +519,7 @@ }, { "cell_type": "markdown", - "id": "6d052f23", + "id": "44352675", "metadata": { "editable": true }, @@ -516,7 +531,7 @@ }, { "cell_type": "markdown", - "id": "4f202148", + "id": "c8b434c3", "metadata": { "editable": true }, @@ -526,7 +541,7 @@ }, { "cell_type": "markdown", - "id": "f9a0d574", + "id": "28c8b238", "metadata": { "editable": true }, @@ -537,7 +552,7 @@ }, { "cell_type": "markdown", - "id": "6708141d", + "id": "634a0119", "metadata": { "editable": true }, @@ -550,7 +565,7 @@ }, { "cell_type": "markdown", - "id": "4f03d04d", + "id": "fe735cbf", "metadata": { "editable": true }, @@ -560,7 +575,7 @@ }, { "cell_type": "markdown", - "id": "a38fa823", + "id": "9e7c13c4", "metadata": { "editable": true }, @@ -572,7 +587,7 @@ }, { "cell_type": "markdown", - "id": "2ce82867", + "id": "92f3fd45", "metadata": { "editable": true }, @@ -582,7 +597,7 @@ }, { "cell_type": "markdown", - "id": "0db226a2", + "id": "b471e4a9", "metadata": { "editable": true }, @@ -594,7 +609,7 @@ }, { "cell_type": "markdown", - "id": "aa8dd5e4", + "id": "80487840", "metadata": { "editable": true }, @@ -604,7 +619,7 @@ }, { "cell_type": "markdown", - "id": "e5ceaa0b", + "id": "f6d114e4", "metadata": { "editable": true }, @@ -628,7 +643,7 @@ }, { "cell_type": "markdown", - "id": "01f5bdd6", + "id": "03e211c1", "metadata": { "editable": true }, @@ -678,7 +693,7 @@ { "cell_type": "code", "execution_count": 1, - "id": "a1543a53", + "id": "5f127181", "metadata": { "collapsed": false, "editable": true @@ -733,7 +748,7 @@ }, { "cell_type": "markdown", - "id": "241cc27b", + "id": "025321f0", "metadata": { "editable": true }, @@ -754,7 +769,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "ba9ddad1", + "id": "edd98947", "metadata": { "collapsed": false, "editable": true @@ -792,7 +807,7 @@ }, { "cell_type": "markdown", - "id": "0336758a", + "id": "1bad86a8", "metadata": { "editable": true }, @@ -836,7 +851,7 @@ }, { "cell_type": "markdown", - "id": "14663c07", + "id": "37094b97", "metadata": { "editable": true }, @@ -876,7 +891,7 @@ }, { "cell_type": "markdown", - "id": "8c028382", + "id": "fb1d2b51", "metadata": { "editable": true }, @@ -897,7 +912,7 @@ { "cell_type": "code", "execution_count": 3, - "id": "63e11155", + "id": "aa2cabf9", "metadata": { "collapsed": false, "editable": true @@ -923,7 +938,7 @@ }, { "cell_type": "markdown", - "id": "04b052bf", + "id": "3bea3936", "metadata": { "editable": true }, @@ -951,7 +966,7 @@ }, { "cell_type": "markdown", - "id": "4207be46", + "id": "af85b0df", "metadata": { "editable": true }, @@ -988,7 +1003,7 @@ { "cell_type": "code", "execution_count": 4, - "id": "0a073d99", + "id": "16a29f53", "metadata": { "collapsed": false, "editable": true @@ -1034,7 +1049,7 @@ }, { "cell_type": "markdown", - "id": "399e4451", + "id": "084ed7ba", "metadata": { "editable": true }, @@ -1065,7 +1080,7 @@ }, { "cell_type": "markdown", - "id": "d3f1bf9e", + "id": "d70e21d8", "metadata": { "editable": true }, @@ -1103,7 +1118,7 @@ }, { "cell_type": "markdown", - "id": "ee6eac7b", + "id": "23940327", "metadata": { "editable": true }, @@ -1137,7 +1152,7 @@ }, { "cell_type": "markdown", - "id": "b0fdb98a", + "id": "a7beed07", "metadata": { "editable": true }, @@ -1178,7 +1193,7 @@ { "cell_type": "code", "execution_count": 5, - "id": "a948ab9c", + "id": "36ca3c90", "metadata": { "collapsed": false, "editable": true @@ -1257,7 +1272,7 @@ }, { "cell_type": "markdown", - "id": "e6e578f9", + "id": "7e0eac4c", "metadata": { "editable": true }, @@ -1278,7 +1293,7 @@ }, { "cell_type": "markdown", - "id": "bc337801", + "id": "57e98ccc", "metadata": { "editable": true }, @@ -1292,7 +1307,7 @@ { "cell_type": "code", "execution_count": 6, - "id": "02d44f3c", + "id": "158f9158", "metadata": { "collapsed": false, "editable": true @@ -1402,7 +1417,7 @@ }, { "cell_type": "markdown", - "id": "6506a91b", + "id": "b8d26ba8", "metadata": { "editable": true }, @@ -1421,7 +1436,7 @@ { "cell_type": "code", "execution_count": 7, - "id": "af4ecc9f", + "id": "e32c4a43", "metadata": { "collapsed": false, "editable": true @@ -1448,7 +1463,7 @@ }, { "cell_type": "markdown", - "id": "67988718", + "id": "aef3f023", "metadata": { "editable": true }, @@ -1462,7 +1477,7 @@ { "cell_type": "code", "execution_count": 8, - "id": "f82a629a", + "id": "f0748a05", "metadata": { "collapsed": false, "editable": true @@ -1493,7 +1508,7 @@ }, { "cell_type": "markdown", - "id": "1d009567", + "id": "8c7200d4", "metadata": { "editable": true }, @@ -1504,7 +1519,7 @@ { "cell_type": "code", "execution_count": 9, - "id": "210f2ff9", + "id": "78b7dc25", "metadata": { "collapsed": false, "editable": true @@ -1548,7 +1563,7 @@ }, { "cell_type": "markdown", - "id": "edd1147f", + "id": "af09471a", "metadata": { "editable": true }, @@ -1571,7 +1586,7 @@ { "cell_type": "code", "execution_count": 10, - "id": "20b63c01", + "id": "481e8a94", "metadata": { "collapsed": false, "editable": true @@ -1598,7 +1613,7 @@ }, { "cell_type": "markdown", - "id": "22e564ce", + "id": "b08a0123", "metadata": { "editable": true }, @@ -1609,7 +1624,7 @@ { "cell_type": "code", "execution_count": 11, - "id": "128263bc", + "id": "2177962e", "metadata": { "collapsed": false, "editable": true @@ -1654,7 +1669,7 @@ }, { "cell_type": "markdown", - "id": "91bbf378", + "id": "b8f24e48", "metadata": { "editable": true }, @@ -1681,7 +1696,7 @@ }, { "cell_type": "markdown", - "id": "e1303471", + "id": "383d7ed1", "metadata": { "editable": true }, @@ -1719,7 +1734,7 @@ }, { "cell_type": "markdown", - "id": "781ded0d", + "id": "97373e7e", "metadata": { "editable": true }, @@ -1731,7 +1746,7 @@ }, { "cell_type": "markdown", - "id": "1d7732a1", + "id": "bcff4010", "metadata": { "editable": true }, @@ -1746,7 +1761,7 @@ }, { "cell_type": "markdown", - "id": "9b6eebaf", + "id": "00f83b12", "metadata": { "editable": true }, @@ -1756,7 +1771,7 @@ }, { "cell_type": "markdown", - "id": "78357948", + "id": "cf1d8a68", "metadata": { "editable": true }, @@ -1769,7 +1784,7 @@ { "cell_type": "code", "execution_count": 12, - "id": "3e1cc747", + "id": "4dd40dc9", "metadata": { "collapsed": false, "editable": true @@ -1845,7 +1860,7 @@ }, { "cell_type": "markdown", - "id": "a505a58d", + "id": "7d57a51a", "metadata": { "editable": true }, @@ -1855,7 +1870,7 @@ }, { "cell_type": "markdown", - "id": "6df5e9ca", + "id": "339de45f", "metadata": { "editable": true }, @@ -1866,7 +1881,7 @@ { "cell_type": "code", "execution_count": 13, - "id": "604e408d", + "id": "a70e4f4f", "metadata": { "collapsed": false, "editable": true @@ -1934,7 +1949,7 @@ }, { "cell_type": "markdown", - "id": "fb518d8b", + "id": "d963bb7a", "metadata": { "editable": true }, @@ -1952,7 +1967,7 @@ }, { "cell_type": "markdown", - "id": "cec81784", + "id": "dd4b59e7", "metadata": { "editable": true }, @@ -1987,7 +2002,7 @@ { "cell_type": "code", "execution_count": 14, - "id": "a068dd6a", + "id": "19e6be62", "metadata": { "collapsed": false, "editable": true @@ -1999,7 +2014,7 @@ }, { "cell_type": "markdown", - "id": "dd47d981", + "id": "e19a1aa7", "metadata": { "editable": true }, @@ -2011,7 +2026,7 @@ { "cell_type": "code", "execution_count": 15, - "id": "37bab548", + "id": "ac145627", "metadata": { "collapsed": false, "editable": true @@ -2024,7 +2039,7 @@ }, { "cell_type": "markdown", - "id": "fb7aa69e", + "id": "41d1f0b2", "metadata": { "editable": true }, @@ -2035,7 +2050,7 @@ { "cell_type": "code", "execution_count": 16, - "id": "68328806", + "id": "a988d71f", "metadata": { "collapsed": false, "editable": true @@ -2048,7 +2063,7 @@ }, { "cell_type": "markdown", - "id": "375e8730", + "id": "02a10b42", "metadata": { "editable": true }, @@ -2063,7 +2078,7 @@ { "cell_type": "code", "execution_count": 17, - "id": "14c77cf2", + "id": "a00076bd", "metadata": { "collapsed": false, "editable": true @@ -2075,7 +2090,7 @@ }, { "cell_type": "markdown", - "id": "2ed7d504", + "id": "efc69dbe", "metadata": { "editable": true }, @@ -2087,7 +2102,7 @@ }, { "cell_type": "markdown", - "id": "6e255f91", + "id": "6d57b48c", "metadata": { "editable": true }, @@ -2100,7 +2115,7 @@ { "cell_type": "code", "execution_count": 18, - "id": "c95e20c0", + "id": "94ee347e", "metadata": { "collapsed": false, "editable": true @@ -2155,7 +2170,7 @@ { "cell_type": "code", "execution_count": 19, - "id": "d236417f", + "id": "912152f3", "metadata": { "collapsed": false, "editable": true @@ -2184,7 +2199,7 @@ { "cell_type": "code", "execution_count": 20, - "id": "40f43646", + "id": "366b21d0", "metadata": { "collapsed": false, "editable": true @@ -2214,7 +2229,7 @@ { "cell_type": "code", "execution_count": 21, - "id": "1bdd43c6", + "id": "7a1b52ce", "metadata": { "collapsed": false, "editable": true @@ -2241,7 +2256,7 @@ { "cell_type": "code", "execution_count": 22, - "id": "ef6b4168", + "id": "c9fe1912", "metadata": { "collapsed": false, "editable": true @@ -2283,7 +2298,7 @@ }, { "cell_type": "markdown", - "id": "3f3d3bf5", + "id": "212fcfaf", "metadata": { "editable": true }, @@ -2294,7 +2309,7 @@ { "cell_type": "code", "execution_count": 23, - "id": "fd0f2e63", + "id": "bece21bd", "metadata": { "collapsed": false, "editable": true @@ -2471,7 +2486,7 @@ }, { "cell_type": "markdown", - "id": "45db0144", + "id": "e02319a1", "metadata": { "editable": true }, @@ -2490,7 +2505,7 @@ }, { "cell_type": "markdown", - "id": "d48f94f8", + "id": "1db82be9", "metadata": { "editable": true }, @@ -2518,7 +2533,7 @@ }, { "cell_type": "markdown", - "id": "6afa37cd", + "id": "36de6d0b", "metadata": { "editable": true }, @@ -2541,7 +2556,7 @@ }, { "cell_type": "markdown", - "id": "cd271a18", + "id": "87d78436", "metadata": { "editable": true }, @@ -2572,7 +2587,7 @@ }, { "cell_type": "markdown", - "id": "fdd765bb", + "id": "dda74efd", "metadata": { "editable": true }, @@ -2604,7 +2619,7 @@ }, { "cell_type": "markdown", - "id": "4ce057bb", + "id": "88908334", "metadata": { "editable": true }, @@ -2642,7 +2657,7 @@ }, { "cell_type": "markdown", - "id": "7964fc77", + "id": "35364ee3", "metadata": { "editable": true }, @@ -2667,7 +2682,7 @@ }, { "cell_type": "markdown", - "id": "7a38c53c", + "id": "aceb9e0f", "metadata": { "editable": true }, @@ -2679,7 +2694,7 @@ }, { "cell_type": "markdown", - "id": "b4c2292d", + "id": "feb5106f", "metadata": { "editable": true }, @@ -2702,7 +2717,7 @@ }, { "cell_type": "markdown", - "id": "75966265", + "id": "c9c02da1", "metadata": { "editable": true }, @@ -2722,7 +2737,7 @@ }, { "cell_type": "markdown", - "id": "89186f0b", + "id": "23a19072", "metadata": { "editable": true }, @@ -2744,7 +2759,7 @@ }, { "cell_type": "markdown", - "id": "a076679e", + "id": "a5b1214e", "metadata": { "editable": true }, @@ -2762,7 +2777,7 @@ }, { "cell_type": "markdown", - "id": "9fd0ab8a", + "id": "fc042ae9", "metadata": { "editable": true }, @@ -2781,7 +2796,7 @@ }, { "cell_type": "markdown", - "id": "57aa1beb", + "id": "959db45e", "metadata": { "editable": true }, @@ -2793,7 +2808,7 @@ }, { "cell_type": "markdown", - "id": "ca682db4", + "id": "125ce15c", "metadata": { "editable": true }, @@ -2838,7 +2853,7 @@ }, { "cell_type": "markdown", - "id": "8fca257c", + "id": "7f4dbb26", "metadata": { "editable": true }, @@ -2868,7 +2883,7 @@ }, { "cell_type": "markdown", - "id": "d1ec3070", + "id": "04ac900c", "metadata": { "editable": true }, @@ -2898,7 +2913,7 @@ }, { "cell_type": "markdown", - "id": "5b002efe", + "id": "dd5dc10e", "metadata": { "editable": true }, @@ -2911,7 +2926,7 @@ }, { "cell_type": "markdown", - "id": "c319289b", + "id": "a5bf7078", "metadata": { "editable": true }, @@ -2934,7 +2949,7 @@ }, { "cell_type": "markdown", - "id": "44cda7ac", + "id": "82fcf813", "metadata": { "editable": true }, @@ -2948,7 +2963,7 @@ }, { "cell_type": "markdown", - "id": "30b906c4", + "id": "65ebf025", "metadata": { "editable": true }, @@ -2965,7 +2980,7 @@ }, { "cell_type": "markdown", - "id": "39fd0606", + "id": "6cc0bb55", "metadata": { "editable": true }, @@ -2981,7 +2996,7 @@ }, { "cell_type": "markdown", - "id": "cb0f7ce8", + "id": "851bc49a", "metadata": { "editable": true }, @@ -2993,7 +3008,7 @@ }, { "cell_type": "markdown", - "id": "b66af253", + "id": "e6038436", "metadata": { "editable": true }, @@ -3011,7 +3026,7 @@ }, { "cell_type": "markdown", - "id": "17955abc", + "id": "f3716b02", "metadata": { "editable": true }, @@ -3032,7 +3047,7 @@ }, { "cell_type": "markdown", - "id": "11743651", + "id": "0cf0d338", "metadata": { "editable": true }, @@ -3049,7 +3064,7 @@ }, { "cell_type": "markdown", - "id": "55026eb8", + "id": "16e3dbe0", "metadata": { "editable": true }, @@ -3061,7 +3076,7 @@ }, { "cell_type": "markdown", - "id": "f129605e", + "id": "d6033d6b", "metadata": { "editable": true }, @@ -3072,7 +3087,7 @@ }, { "cell_type": "markdown", - "id": "a9667da9", + "id": "518c5c94", "metadata": { "editable": true }, @@ -3089,7 +3104,7 @@ }, { "cell_type": "markdown", - "id": "0bce86fd", + "id": "3edf1469", "metadata": { "editable": true }, @@ -3100,7 +3115,7 @@ }, { "cell_type": "markdown", - "id": "aa2118e2", + "id": "114d4727", "metadata": { "editable": true }, @@ -3116,7 +3131,7 @@ }, { "cell_type": "markdown", - "id": "a6d46680", + "id": "67d1893f", "metadata": { "editable": true }, @@ -3128,7 +3143,7 @@ }, { "cell_type": "markdown", - "id": "09ee640b", + "id": "58166a75", "metadata": { "editable": true }, @@ -3145,7 +3160,7 @@ }, { "cell_type": "markdown", - "id": "e72a6d7f", + "id": "5c6e35d9", "metadata": { "editable": true }, @@ -3157,7 +3172,7 @@ }, { "cell_type": "markdown", - "id": "305a7e23", + "id": "75205e6f", "metadata": { "editable": true }, @@ -3175,7 +3190,7 @@ }, { "cell_type": "markdown", - "id": "388febbd", + "id": "8a5a5f24", "metadata": { "editable": true }, @@ -3185,7 +3200,7 @@ }, { "cell_type": "markdown", - "id": "a14b9590", + "id": "64b1719c", "metadata": { "editable": true }, @@ -3197,7 +3212,7 @@ }, { "cell_type": "markdown", - "id": "0a3fefc3", + "id": "c1fefb6f", "metadata": { "editable": true }, @@ -3214,7 +3229,7 @@ }, { "cell_type": "markdown", - "id": "27a2fca6", + "id": "a8cc57e4", "metadata": { "editable": true }, @@ -3226,7 +3241,7 @@ }, { "cell_type": "markdown", - "id": "f65fa3f9", + "id": "9b500328", "metadata": { "editable": true }, @@ -3237,7 +3252,7 @@ }, { "cell_type": "markdown", - "id": "354a552e", + "id": "9b67eee5", "metadata": { "editable": true }, @@ -3249,7 +3264,7 @@ }, { "cell_type": "markdown", - "id": "21ddf1e6", + "id": "cce6a4e3", "metadata": { "editable": true }, @@ -3259,7 +3274,7 @@ }, { "cell_type": "markdown", - "id": "c39d17d0", + "id": "b9537f52", "metadata": { "editable": true }, @@ -3279,7 +3294,7 @@ }, { "cell_type": "markdown", - "id": "4ff778c4", + "id": "ca4e8f06", "metadata": { "editable": true }, @@ -3296,7 +3311,7 @@ }, { "cell_type": "markdown", - "id": "65303710", + "id": "0652089f", "metadata": { "editable": true }, @@ -3315,7 +3330,7 @@ }, { "cell_type": "markdown", - "id": "6a0a6cb0", + "id": "41cf6e19", "metadata": { "editable": true }, @@ -3327,7 +3342,7 @@ }, { "cell_type": "markdown", - "id": "31aa1c5f", + "id": "49418fef", "metadata": { "editable": true }, @@ -3337,7 +3352,7 @@ }, { "cell_type": "markdown", - "id": "72c659c7", + "id": "b7e00c55", "metadata": { "editable": true }, @@ -3354,7 +3369,7 @@ }, { "cell_type": "markdown", - "id": "d9610efd", + "id": "f4d3b6ed", "metadata": { "editable": true }, @@ -3364,7 +3379,7 @@ }, { "cell_type": "markdown", - "id": "ae92d0fb", + "id": "b6ada977", "metadata": { "editable": true }, @@ -3380,7 +3395,7 @@ }, { "cell_type": "markdown", - "id": "6ed29b9d", + "id": "27ecbfef", "metadata": { "editable": true }, @@ -3392,7 +3407,7 @@ }, { "cell_type": "markdown", - "id": "e2bee617", + "id": "fd2fa044", "metadata": { "editable": true }, @@ -3404,7 +3419,7 @@ }, { "cell_type": "markdown", - "id": "d7dc3912", + "id": "9fd99313", "metadata": { "editable": true }, @@ -3416,7 +3431,7 @@ }, { "cell_type": "markdown", - "id": "8a69fc8e", + "id": "3967be3c", "metadata": { "editable": true }, @@ -3426,7 +3441,7 @@ }, { "cell_type": "markdown", - "id": "ad12a058", + "id": "470d79c9", "metadata": { "editable": true }, @@ -3438,7 +3453,7 @@ }, { "cell_type": "markdown", - "id": "aa29301c", + "id": "afb9fa7a", "metadata": { "editable": true }, @@ -3455,7 +3470,7 @@ }, { "cell_type": "markdown", - "id": "73aa8d68", + "id": "23c4c38a", "metadata": { "editable": true }, @@ -3465,7 +3480,7 @@ }, { "cell_type": "markdown", - "id": "abfab134", + "id": "acfa5e70", "metadata": { "editable": true }, @@ -3477,7 +3492,7 @@ }, { "cell_type": "markdown", - "id": "065ca9b3", + "id": "6ca05848", "metadata": { "editable": true }, @@ -3491,7 +3506,7 @@ }, { "cell_type": "markdown", - "id": "20bae180", + "id": "11b8633a", "metadata": { "editable": true }, @@ -3507,7 +3522,7 @@ }, { "cell_type": "markdown", - "id": "8fc1858f", + "id": "82de0646", "metadata": { "editable": true }, @@ -3519,7 +3534,7 @@ }, { "cell_type": "markdown", - "id": "9f6a3eea", + "id": "5b117280", "metadata": { "editable": true }, @@ -3541,7 +3556,7 @@ }, { "cell_type": "markdown", - "id": "e75cd892", + "id": "9e23d93c", "metadata": { "editable": true }, @@ -3553,7 +3568,7 @@ }, { "cell_type": "markdown", - "id": "a54d3f92", + "id": "c66c9d7a", "metadata": { "editable": true }, @@ -3576,7 +3591,7 @@ }, { "cell_type": "markdown", - "id": "ed8ca01d", + "id": "4d55f1d5", "metadata": { "editable": true }, @@ -3592,7 +3607,7 @@ }, { "cell_type": "markdown", - "id": "725d7e60", + "id": "81ccb597", "metadata": { "editable": true }, @@ -3604,7 +3619,7 @@ }, { "cell_type": "markdown", - "id": "ed7fc6fd", + "id": "351e7bd0", "metadata": { "editable": true }, @@ -3628,7 +3643,7 @@ }, { "cell_type": "markdown", - "id": "2bb3f2c4", + "id": "393e6171", "metadata": { "editable": true }, @@ -3640,7 +3655,7 @@ }, { "cell_type": "markdown", - "id": "c676c15d", + "id": "71b2569a", "metadata": { "editable": true }, @@ -3661,7 +3676,7 @@ }, { "cell_type": "markdown", - "id": "aa7f62c4", + "id": "5bc38371", "metadata": { "editable": true }, @@ -3673,7 +3688,7 @@ }, { "cell_type": "markdown", - "id": "665597ac", + "id": "e506906c", "metadata": { "editable": true }, @@ -3692,7 +3707,7 @@ }, { "cell_type": "markdown", - "id": "a40d62e3", + "id": "15884d16", "metadata": { "editable": true }, @@ -3702,7 +3717,7 @@ }, { "cell_type": "markdown", - "id": "faa869e9", + "id": "659ce37c", "metadata": { "editable": true }, @@ -3716,7 +3731,7 @@ }, { "cell_type": "markdown", - "id": "17c8b491", + "id": "81ad3b8d", "metadata": { "editable": true }, @@ -3728,7 +3743,7 @@ }, { "cell_type": "markdown", - "id": "1d5d3c59", + "id": "c80275f0", "metadata": { "editable": true }, @@ -3740,7 +3755,7 @@ }, { "cell_type": "markdown", - "id": "c4b20b4c", + "id": "277ed95a", "metadata": { "editable": true }, @@ -3757,7 +3772,7 @@ }, { "cell_type": "markdown", - "id": "f5c75325", + "id": "b33a94dc", "metadata": { "editable": true }, @@ -3769,7 +3784,7 @@ }, { "cell_type": "markdown", - "id": "95941372", + "id": "fc5ad11b", "metadata": { "editable": true }, @@ -3791,7 +3806,7 @@ }, { "cell_type": "markdown", - "id": "54d3612c", + "id": "f1556cb6", "metadata": { "editable": true }, @@ -3806,7 +3821,7 @@ }, { "cell_type": "markdown", - "id": "5ee0a297", + "id": "26238df7", "metadata": { "editable": true }, @@ -3817,7 +3832,7 @@ { "cell_type": "code", "execution_count": 24, - "id": "685ef9f1", + "id": "014617fe", "metadata": { "collapsed": false, "editable": true @@ -3972,7 +3987,7 @@ }, { "cell_type": "markdown", - "id": "45d98f31", + "id": "9d738f75", "metadata": { "editable": true }, @@ -3987,7 +4002,7 @@ { "cell_type": "code", "execution_count": 25, - "id": "c3101ec8", + "id": "df58a772", "metadata": { "collapsed": false, "editable": true @@ -4156,7 +4171,7 @@ }, { "cell_type": "markdown", - "id": "1efb0b75", + "id": "e9ec5a90", "metadata": { "editable": true }, @@ -4169,7 +4184,7 @@ }, { "cell_type": "markdown", - "id": "4eb288fe", + "id": "2f4cc21b", "metadata": { "editable": true }, @@ -4186,7 +4201,7 @@ }, { "cell_type": "markdown", - "id": "5a5aa11a", + "id": "10d741aa", "metadata": { "editable": true }, @@ -4202,7 +4217,7 @@ }, { "cell_type": "markdown", - "id": "534201f2", + "id": "9372f482", "metadata": { "editable": true }, @@ -4215,7 +4230,7 @@ }, { "cell_type": "markdown", - "id": "c6ef6ceb", + "id": "4e5c33ed", "metadata": { "editable": true }, @@ -4232,7 +4247,7 @@ }, { "cell_type": "markdown", - "id": "816549c2", + "id": "8fb325b6", "metadata": { "editable": true }, @@ -4244,7 +4259,7 @@ }, { "cell_type": "markdown", - "id": "560f46b1", + "id": "5cebac25", "metadata": { "editable": true }, @@ -4271,7 +4286,7 @@ }, { "cell_type": "markdown", - "id": "9b8e47e9", + "id": "339fb0dc", "metadata": { "editable": true }, @@ -4284,7 +4299,7 @@ { "cell_type": "code", "execution_count": 26, - "id": "dccac119", + "id": "73730937", "metadata": { "collapsed": false, "editable": true @@ -4458,7 +4473,7 @@ }, { "cell_type": "markdown", - "id": "a5eb5f7f", + "id": "d6359e47", "metadata": { "editable": true }, @@ -4478,7 +4493,7 @@ }, { "cell_type": "markdown", - "id": "44382a0e", + "id": "f5ada791", "metadata": { "editable": true }, @@ -4493,7 +4508,7 @@ }, { "cell_type": "markdown", - "id": "03f72101", + "id": "6da1597b", "metadata": { "editable": true }, @@ -4507,7 +4522,7 @@ }, { "cell_type": "markdown", - "id": "ad57deb7", + "id": "13fa9fde", "metadata": { "editable": true }, @@ -4523,7 +4538,7 @@ }, { "cell_type": "markdown", - "id": "d3090cfd", + "id": "1ba345dc", "metadata": { "editable": true }, @@ -4533,7 +4548,7 @@ }, { "cell_type": "markdown", - "id": "4518e99b", + "id": "f263a5dc", "metadata": { "editable": true }, @@ -4555,7 +4570,7 @@ }, { "cell_type": "markdown", - "id": "6d828572", + "id": "5ebd4428", "metadata": { "editable": true }, @@ -4569,7 +4584,7 @@ { "cell_type": "code", "execution_count": 27, - "id": "71dfbd8b", + "id": "95a32158", "metadata": { "collapsed": false, "editable": true @@ -4645,7 +4660,7 @@ }, { "cell_type": "markdown", - "id": "e6dedd6b", + "id": "de8093cf", "metadata": { "editable": true }, @@ -4657,7 +4672,7 @@ }, { "cell_type": "markdown", - "id": "15c09ff8", + "id": "905ceb1e", "metadata": { "editable": true }, @@ -4674,7 +4689,7 @@ }, { "cell_type": "markdown", - "id": "8723d0c1", + "id": "e3d5f8a0", "metadata": { "editable": true }, @@ -4686,7 +4701,7 @@ }, { "cell_type": "markdown", - "id": "0442985c", + "id": "52c161b4", "metadata": { "editable": true }, @@ -4701,7 +4716,7 @@ }, { "cell_type": "markdown", - "id": "631c2faf", + "id": "7777097f", "metadata": { "editable": true }, @@ -4713,7 +4728,7 @@ }, { "cell_type": "markdown", - "id": "cb348ed7", + "id": "4bbb70db", "metadata": { "editable": true }, @@ -4725,7 +4740,7 @@ }, { "cell_type": "markdown", - "id": "70758df0", + "id": "48006843", "metadata": { "editable": true }, @@ -4737,7 +4752,7 @@ }, { "cell_type": "markdown", - "id": "7272a9c6", + "id": "8638c014", "metadata": { "editable": true }, @@ -4747,7 +4762,7 @@ }, { "cell_type": "markdown", - "id": "91cf4043", + "id": "27c57849", "metadata": { "editable": true }, @@ -4764,7 +4779,7 @@ }, { "cell_type": "markdown", - "id": "319fc407", + "id": "c391bc33", "metadata": { "editable": true }, @@ -4776,7 +4791,7 @@ }, { "cell_type": "markdown", - "id": "649addfd", + "id": "a3819b93", "metadata": { "editable": true }, @@ -4788,7 +4803,7 @@ }, { "cell_type": "markdown", - "id": "063153ec", + "id": "7b1c2870", "metadata": { "editable": true }, @@ -4798,7 +4813,7 @@ }, { "cell_type": "markdown", - "id": "b71e18cb", + "id": "c77e16fc", "metadata": { "editable": true }, @@ -4810,7 +4825,7 @@ }, { "cell_type": "markdown", - "id": "9973352c", + "id": "fe153456", "metadata": { "editable": true }, @@ -4821,7 +4836,7 @@ { "cell_type": "code", "execution_count": 28, - "id": "1200f869", + "id": "1ad3d48d", "metadata": { "collapsed": false, "editable": true @@ -4982,7 +4997,7 @@ }, { "cell_type": "markdown", - "id": "5c3d897e", + "id": "c40a7203", "metadata": { "editable": true }, @@ -5004,7 +5019,7 @@ }, { "cell_type": "markdown", - "id": "8b8b736c", + "id": "c6fa6ab2", "metadata": { "editable": true }, @@ -5021,7 +5036,7 @@ }, { "cell_type": "markdown", - "id": "81b1c4ab", + "id": "f194e6eb", "metadata": { "editable": true }, @@ -5031,7 +5046,7 @@ }, { "cell_type": "markdown", - "id": "ccc1933f", + "id": "7f05f9b0", "metadata": { "editable": true }, @@ -5046,7 +5061,7 @@ }, { "cell_type": "markdown", - "id": "5a90e2b7", + "id": "770d5cf3", "metadata": { "editable": true }, @@ -5056,7 +5071,7 @@ }, { "cell_type": "markdown", - "id": "f242dc33", + "id": "805cd4c8", "metadata": { "editable": true }, @@ -5071,7 +5086,7 @@ }, { "cell_type": "markdown", - "id": "73402682", + "id": "cdf4faec", "metadata": { "editable": true }, @@ -5082,7 +5097,7 @@ }, { "cell_type": "markdown", - "id": "f4977e37", + "id": "507b9b84", "metadata": { "editable": true }, @@ -5102,7 +5117,7 @@ }, { "cell_type": "markdown", - "id": "ab8e82d6", + "id": "67b2c134", "metadata": { "editable": true }, @@ -5114,7 +5129,7 @@ }, { "cell_type": "markdown", - "id": "98bbe79c", + "id": "30036fd5", "metadata": { "editable": true }, @@ -5151,7 +5166,7 @@ }, { "cell_type": "markdown", - "id": "0e07c010", + "id": "374c2536", "metadata": { "editable": true }, @@ -5161,7 +5176,7 @@ }, { "cell_type": "markdown", - "id": "a74fda57", + "id": "1391a6dd", "metadata": { "editable": true }, @@ -5174,7 +5189,7 @@ { "cell_type": "code", "execution_count": 29, - "id": "649a8941", + "id": "e7f38d7e", "metadata": { "collapsed": false, "editable": true @@ -5375,7 +5390,7 @@ }, { "cell_type": "markdown", - "id": "2a825d47", + "id": "9fc31e49", "metadata": { "editable": true }, @@ -5392,7 +5407,7 @@ }, { "cell_type": "markdown", - "id": "9b3774d9", + "id": "c0928905", "metadata": { "editable": true }, @@ -5409,7 +5424,7 @@ }, { "cell_type": "markdown", - "id": "ca2a3a22", + "id": "7bae33b7", "metadata": { "editable": true }, @@ -5419,7 +5434,7 @@ }, { "cell_type": "markdown", - "id": "e3f99542", + "id": "b43539b4", "metadata": { "editable": true }, @@ -5434,7 +5449,7 @@ }, { "cell_type": "markdown", - "id": "63428621", + "id": "6fc1ca67", "metadata": { "editable": true }, @@ -5448,7 +5463,7 @@ }, { "cell_type": "markdown", - "id": "e402ff81", + "id": "d35a7f13", "metadata": { "editable": true }, @@ -5461,7 +5476,7 @@ }, { "cell_type": "markdown", - "id": "3a249787", + "id": "4cce797b", "metadata": { "editable": true }, @@ -5481,7 +5496,7 @@ }, { "cell_type": "markdown", - "id": "e0340dcd", + "id": "e399151e", "metadata": { "editable": true }, @@ -5493,7 +5508,7 @@ }, { "cell_type": "markdown", - "id": "ebfeaacb", + "id": "67e4d279", "metadata": { "editable": true }, @@ -5505,7 +5520,7 @@ }, { "cell_type": "markdown", - "id": "a05db097", + "id": "fcaa5c92", "metadata": { "editable": true }, @@ -5517,7 +5532,7 @@ }, { "cell_type": "markdown", - "id": "9ec431fb", + "id": "7681fcbc", "metadata": { "editable": true }, @@ -5527,7 +5542,7 @@ }, { "cell_type": "markdown", - "id": "62c43026", + "id": "2657db4f", "metadata": { "editable": true }, @@ -5539,7 +5554,7 @@ }, { "cell_type": "markdown", - "id": "381fcc2a", + "id": "7e50704f", "metadata": { "editable": true }, @@ -5551,7 +5566,7 @@ }, { "cell_type": "markdown", - "id": "a8ff1678", + "id": "b8ecd408", "metadata": { "editable": true }, @@ -5563,7 +5578,7 @@ }, { "cell_type": "markdown", - "id": "cd8aca35", + "id": "4088543f", "metadata": { "editable": true }, @@ -5573,7 +5588,7 @@ }, { "cell_type": "markdown", - "id": "3bad7389", + "id": "ced127ba", "metadata": { "editable": true }, @@ -5589,7 +5604,7 @@ }, { "cell_type": "markdown", - "id": "fe03c00e", + "id": "c9f0f219", "metadata": { "editable": true }, @@ -5599,7 +5614,7 @@ }, { "cell_type": "markdown", - "id": "f7752aff", + "id": "55a10797", "metadata": { "editable": true }, @@ -5611,7 +5626,7 @@ }, { "cell_type": "markdown", - "id": "11081c91", + "id": "718ef592", "metadata": { "editable": true }, @@ -5628,7 +5643,7 @@ }, { "cell_type": "markdown", - "id": "5603660f", + "id": "e9c1ebd6", "metadata": { "editable": true }, @@ -5638,7 +5653,7 @@ }, { "cell_type": "markdown", - "id": "ca7cca9f", + "id": "f900ccf7", "metadata": { "editable": true }, @@ -5654,7 +5669,7 @@ }, { "cell_type": "markdown", - "id": "7ee81419", + "id": "83307dd1", "metadata": { "editable": true }, @@ -5668,7 +5683,7 @@ }, { "cell_type": "markdown", - "id": "a28c8cad", + "id": "11a91a53", "metadata": { "editable": true }, @@ -5687,7 +5702,7 @@ { "cell_type": "code", "execution_count": 30, - "id": "3f52ff40", + "id": "c6626e17", "metadata": { "collapsed": false, "editable": true @@ -5742,7 +5757,7 @@ }, { "cell_type": "markdown", - "id": "1d854f1a", + "id": "9bc068c4", "metadata": { "editable": true }, @@ -5772,7 +5787,7 @@ }, { "cell_type": "markdown", - "id": "2658ed46", + "id": "72dcd8e2", "metadata": { "editable": true }, @@ -5801,7 +5816,7 @@ { "cell_type": "code", "execution_count": 31, - "id": "400fcb9d", + "id": "17e14051", "metadata": { "collapsed": false, "editable": true @@ -5848,7 +5863,7 @@ }, { "cell_type": "markdown", - "id": "dd829371", + "id": "503a302f", "metadata": { "editable": true }, @@ -5874,7 +5889,7 @@ { "cell_type": "code", "execution_count": 32, - "id": "0a98eef4", + "id": "02343bb2", "metadata": { "collapsed": false, "editable": true @@ -6108,7 +6123,7 @@ }, { "cell_type": "markdown", - "id": "c5b1a802", + "id": "61fa3ee3", "metadata": { "editable": true }, @@ -6120,7 +6135,7 @@ }, { "cell_type": "markdown", - "id": "de3d66e0", + "id": "f08ec1b3", "metadata": { "editable": true }, @@ -6132,7 +6147,7 @@ }, { "cell_type": "markdown", - "id": "4cd80ad5", + "id": "aca9df35", "metadata": { "editable": true }, @@ -6144,7 +6159,7 @@ }, { "cell_type": "markdown", - "id": "88fd9ec0", + "id": "c854909b", "metadata": { "editable": true }, @@ -6161,7 +6176,7 @@ }, { "cell_type": "markdown", - "id": "a04931d9", + "id": "a4d855d2", "metadata": { "editable": true }, @@ -6171,7 +6186,7 @@ }, { "cell_type": "markdown", - "id": "537251f6", + "id": "7bcd28e2", "metadata": { "editable": true }, @@ -6183,7 +6198,7 @@ }, { "cell_type": "markdown", - "id": "c9acba2f", + "id": "2c689212", "metadata": { "editable": true }, @@ -6200,7 +6215,7 @@ }, { "cell_type": "markdown", - "id": "997e8a22", + "id": "0bbaf576", "metadata": { "editable": true }, @@ -6211,7 +6226,7 @@ }, { "cell_type": "markdown", - "id": "6db10bba", + "id": "6763059e", "metadata": { "editable": true }, @@ -6231,7 +6246,7 @@ }, { "cell_type": "markdown", - "id": "2191f32f", + "id": "1e65f7b9", "metadata": { "editable": true }, @@ -6241,7 +6256,7 @@ }, { "cell_type": "markdown", - "id": "d306770f", + "id": "e3d81595", "metadata": { "editable": true }, @@ -6267,7 +6282,7 @@ }, { "cell_type": "markdown", - "id": "0c9f3199", + "id": "a75130a3", "metadata": { "editable": true }, @@ -6283,7 +6298,7 @@ }, { "cell_type": "markdown", - "id": "1485b594", + "id": "fae3ec5d", "metadata": { "editable": true }, @@ -6294,7 +6309,7 @@ { "cell_type": "code", "execution_count": 33, - "id": "e10b3ec2", + "id": "c2a73012", "metadata": { "collapsed": false, "editable": true @@ -6525,7 +6540,7 @@ }, { "cell_type": "markdown", - "id": "d51e5284", + "id": "b4f99f14", "metadata": { "editable": true }, diff --git a/doc/src/week41/week41.do.txt b/doc/src/week41/week41.do.txt index f5a262b2a..d8dc65c86 100644 --- a/doc/src/week41/week41.do.txt +++ b/doc/src/week41/week41.do.txt @@ -23,6 +23,13 @@ For a more in depth discussion on neural networks we recommend Goodfellow et al !split ===== Review of the back propagation algorithm ===== +During the last lecture we discussed in detail the back propagation +algorithm. This algorithm is based on a repeated application of the +chain rule. Let us bring back the basic equation and at the same time +link this with the basic mathematics of automatic differentiation. + + + !split ===== Setting up the Back propagation algorithm =====