diff --git a/doc/src/NeuralNet/NeuralNet.do.txt b/doc/src/NeuralNet/NeuralNet.do.txt index 9b24b99d7..6364fec81 100644 --- a/doc/src/NeuralNet/NeuralNet.do.txt +++ b/doc/src/NeuralNet/NeuralNet.do.txt @@ -49,92 +49,113 @@ o neural networks for sequential data such as Recurrent Neural Networks (RNNs), o neural networks for unsupervised learning such as Deep Boltzmann Machines. -In natural science, DNNs and CNNs have already found numerous applications. In -statistical physics, they have been applied to detect phase -transitions in 2D Ising and Potts models, lattice gauge theories, and -different phases of polymers, or solving the Navier-Stokes equation in weather forecasting. -Deep learning has also found interesting applications in quantum -physics. Various quantum phase transitions can be detected and studied -using DNNs and CNNs, +In natural science, DNNs and CNNs have already found numerous +applications. In statistical physics, they have been applied to detect +phase transitions in 2D Ising and Potts models, lattice gauge +theories, and different phases of polymers, or solving the +Navier-Stokes equation in weather forecasting. Deep learning has also +found interesting applications in quantum physics. Various quantum +phase transitions can be detected and studied using DNNs and CNNs, topological phases, and even non-equilibrium many-body localization. Representing quantum states as DNNs quantum state -tomography are among some of the impressive -achievements to reveal the potential of DNNs to facilitate the study -of quantum systems. +tomography are among some of the impressive achievements to reveal the +potential of DNNs to facilitate the study of quantum systems. In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. In lattice quantum chromodynamics, -DNNs have been used to learn action parameters in regions of parameter -space where PCA fails. +gate decompositions with the help of neural. -The applications are not limited to the natural sciences. There is a plethora of applications in essentially all disciplines, from the humanities to life science and medicine. +The applications are not limited to the natural sciences. There is a +plethora of applications in essentially all disciplines, from the +humanities to life science and medicine. !split ===== Neural network types ===== -An artificial neural network (NN), is a computational model that -consists of layers of connected neurons, or *nodes*. It is supposed -to mimic a biological nervous system by letting each neuron interact -with other neurons by sending signals in the form of mathematical -functions between layers. A wide variety of different NNs have been -developed, but most of them consist of an input layer, an output layer -and eventual layers in-between, called *hidden layers*. All layers can -contain an arbitrary number of nodes, and each connection between two -nodes is associated with a weight variable. +An artificial neural network (ANN), is a computational model that +consists of layers of connected neurons, or nodes or units. We will +refer to these interchangeably as units or nodes, and sometimes as +neurons. + +It is supposed to mimic a biological nervous system by letting each +neuron interact with other neurons by sending signals in the form of +mathematical functions between layers. A wide variety of different +ANNs have been developed, but most of them consist of an input layer, +an output layer and eventual layers in-between, called *hidden +layers*. All layers can contain an arbitrary number of nodes, and each +connection between two nodes is associated with a weight variable. Neural networks (also called neural nets) are neural-inspired nonlinear models for supervised learning. As we will see, neural nets can be viewed as natural, more powerful extensions of supervised learning methods such as linear and logistic regression and soft-max -methods. +methods we discussed earlier. !split ===== Feed-forward neural networks ===== -The feed-forward neural network (FFNN) was the first and simplest type of NN devised. In this network, -the information moves in only one direction: forward through the layers. +The feed-forward neural network (FFNN) was the first and simplest type +of ANNs that were devised. In this network, the information moves in +only one direction: forward through the layers. -Nodes are represented by circles, while the arrows display the connections between the nodes, including the -direction of information flow. Additionally, each arrow corresponds to a weight variable, not displayed here. -We observe that each node in a layer is connected to *all* nodes in the subsequent layer, -making this a so-called *fully-connected* FFNN. +Nodes are represented by circles, while the arrows display the +connections between the nodes, including the direction of information +flow. Additionally, each arrow corresponds to a weight variable +(figure to come). We observe that each node in a layer is connected +to *all* nodes in the subsequent layer, making this a so-called +*fully-connected* FFNN. -A different variant of FFNNs are *convolutional neural networks* (CNNs), which have a connectivity pattern -inspired by the animal visual cortex. Individual neurons in the visual cortex only respond to stimuli from -small sub-regions of the visual field, called a receptive field. This makes the neurons well-suited to exploit the strong -spatially local correlation present in natural images. The response of each neuron can be approximated mathematically -as a convolution operation. +!split +===== Convolutional Neural Network ===== -CNNs emulate the behaviour of neurons in the visual cortex by enforcing a *local* connectivity pattern -between nodes of adjacent layers: Each node -in a convolutional layer is connected only to a subset of the nodes in the previous layer, -in contrast to the fully-connected FFNN. -Often, CNNs -consist of several convolutional layers that learn local features of the input, with a fully-connected layer at the end, -which gathers all the local data and produces the outputs. They have wide applications in image and video recognition +A different variant of FFNNs are *convolutional neural networks* +(CNNs), which have a connectivity pattern inspired by the animal +visual cortex. Individual neurons in the visual cortex only respond to +stimuli from small sub-regions of the visual field, called a receptive +field. This makes the neurons well-suited to exploit the strong +spatially local correlation present in natural images. The response of +each neuron can be approximated mathematically as a convolution +operation. (figure to come) + +Convolutional neural networks emulate the behaviour of neurons in the +visual cortex by enforcing a *local* connectivity pattern between +nodes of adjacent layers: Each node in a convolutional layer is +connected only to a subset of the nodes in the previous layer, in +contrast to the fully-connected FFNN. Often, CNNs consist of several +convolutional layers that learn local features of the input, with a +fully-connected layer at the end, which gathers all the local data and +produces the outputs. They have wide applications in image and video +recognition. !split ===== Recurrent neural networks ===== -So far we have only mentioned NNs where information flows in one direction: forward. *Recurrent neural networks* on -the other hand, have connections between nodes that form directed *cycles*. This creates a form of -internal memory which are able to capture information on what has been calculated before; the output is dependent -on the previous computations. Recurrent NNs make use of sequential information by performing the same task for -every element in a sequence, where each element depends on previous elements. An example of such information is -sentences, making recurrent NNs especially well-suited for handwriting and speech recognition. +So far we have only mentioned ANNs where information flows in one +direction: forward. *Recurrent neural networks* on the other hand, +have connections between nodes that form directed *cycles*. This +creates a form of internal memory which are able to capture +information on what has been calculated before; the output is +dependent on the previous computations. Recurrent NNs make use of +sequential information by performing the same task for every element +in a sequence, where each element depends on previous elements. An +example of such information is sentences, making recurrent NNs +especially well-suited for handwriting and speech recognition. !split ===== Other types of networks ===== -There are many other kinds of NNs that have been developed. One type that is specifically designed for interpolation -in multidimensional space is the radial basis function (RBF) network. RBFs are typically made up of three layers: -an input layer, a hidden layer with non-linear radial symmetric activation functions and a linear output layer (''linear'' here -means that each node in the output layer has a linear activation function). The layers are normally fully-connected and -there are no cycles, thus RBFs can be viewed as a type of fully-connected FFNN. They are however usually treated as -a separate type of NN due the unusual activation functions. +There are many other kinds of ANNs that have been developed. One type +that is specifically designed for interpolation in multidimensional +space is the radial basis function (RBF) network. RBFs are typically +made up of three layers: an input layer, a hidden layer with +non-linear radial symmetric activation functions and a linear output +layer (''linear'' here means that each node in the output layer has a +linear activation function). The layers are normally fully-connected +and there are no cycles, thus RBFs can be viewed as a type of +fully-connected FFNN. They are however usually treated as a separate +type of NN due the unusual activation functions. !split ===== Multilayer perceptrons ===== @@ -144,41 +165,34 @@ with three or more layers (an input layer, one or more hidden layers and an output layer) consisting of neurons that have non-linear activation functions. -Such networks are often called *multilayer perceptrons* (MLPs) +Such networks are often called *multilayer perceptrons* (MLPs). !split ===== Why multilayer perceptrons? ===== -According to the *Universal approximation theorem*, a feed-forward neural network with just a single hidden layer containing -a finite number of neurons can approximate a continuous multidimensional function to arbitrary accuracy, -assuming the activation function for the hidden layer is a _non-constant, bounded and monotonically-increasing continuous function_. +According to the *Universal approximation theorem*, a feed-forward +neural network with just a single hidden layer containing a finite +number of neurons can approximate a continuous multidimensional +function to arbitrary accuracy, assuming the activation function for +the hidden layer is a _non-constant, bounded and +monotonically-increasing continuous function_. Note that the requirements on the activation function only applies to the hidden layer, the output nodes are always assumed to be linear, so as to not restrict the range of output values. -We note that this theorem is only applicable to an NN with *one* hidden -layer. Therefore, we can easily construct an NN that employs -activation functions which do not satisfy the above requirements, as -long as we have at least one layer with activation functions that -*do*. Furthermore, although the universal approximation theorem lays -the theoretical foundation for regression with neural networks, it -does not say anything about how things work in practice: A neural -network can still be able to approximate a given function reasonably -well without having the flexibility to fit *all other* functions. - - !split ===== Mathematical model ===== +The output $y$ is produced via the activation function $f$ !bt -\begin{equation} - y = f\left(\sum_{i=1}^n w_ix_i + b_i\right) = f(u) - label{artificialNeuron2} -\end{equation} +\[ + y = f\left(\sum_{i=1}^n w_ix_i + b_i\right) = f(z), +\] !et - +This function receives $x_i$ as inputs. +Here the activation $z=\sum_{i=1}^n w_ix_i$. In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of the neurons in the preceding layer. Furthermore, an MLP is fully-connected, which means that each neuron receives a weighted sum @@ -187,29 +201,34 @@ of the outputs of *all* neurons in the previous layer. !split ===== Mathematical model ===== -First, for each node $i$ in the first hidden layer, we calculate a weighted sum $u_i^1$ of the input coordinates $x_j$, +First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$, !bt -\begin{equation} - u_i^1 = \sum_{j=1}^2 w_{ij}^1 x_j + b_i^1 +\begin{equation} z_i^1 = \sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1 \end{equation} !et -This value is the argument to the activation function $f_1$ of each neuron $i$, -producing the output $y_i^1$ of all neurons in layer 1, + +Here $b_i$ is the so-called bias which is normally needed in +case of zero activation weights or inputs. How to fix the biases and +the weights will be discussed below. The value of $z_i^1$ is the +argument to the activation function $f_i$ of each node $i$, The +variable $M$ stands for all possible inputs to a given node $i$ in the +first layer. We define the output $y_i^1$ of all neurons in layer 1 as !bt \begin{equation} - y_i^1 = f_1(u_i^1) = f_1\left(\sum_{j=1}^2 w_{ij}^1 x_j + b_i^1\right) + y_i^1 = f(z_i^1) = f\left(\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\right) label{outputLayer1} \end{equation} !et where we assume that all nodes in the same layer have identical -activation functions, hence the notation $f_l$ +activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions. +In this case we would identify these functions with a superscript $l$ for the $l$-th layer, !bt \begin{equation} - y_i^l = f_l(u_i^l) = f_l\left(\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\right) + y_i^l = f^l(u_i^l) = f^l\left(\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\right) label{generalLayer} \end{equation} !et @@ -228,17 +247,17 @@ The output of neuron $i$ in layer 2 is thus, !bt \begin{align} - y_i^2 &= f_2\left(\sum_{j=1}^3 w_{ij}^2 y_j^1 + b_i^2\right) \\ - &= f_2\left[\sum_{j=1}^3 w_{ij}^2f_1\left(\sum_{k=1}^2 w_{jk}^1 x_k + b_j^1\right) + b_i^2\right] + y_i^2 &= f^2\left(\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\right) \\ + &= f^2\left[\sum_{j=1}^N w_{ij}^2f^1\left(\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\right) + b_i^2\right] label{outputLayer2} \end{align} !et -where we have substituted $y_m^1$ with. Finally, the NN output yields, +where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads !bt \begin{align} - y_1^3 &= f_3\left(\sum_{j=1}^3 w_{1m}^3 y_j^2 + b_1^3\right) \\ - &= f_3\left[\sum_{j=1}^3 w_{1j}^3 f_2\left(\sum_{k=1}^3 w_{jk}^2 f_1\left(\sum_{m=1}^2 w_{km}^1 x_m + b_k^1\right) + b_j^2\right) + y_i^3 &= f^3\left(\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\right) \\ + &= f_3\left[\sum_{j=1}^3 w_{ij}^3 f^2\left(\sum_{k=1}^3 w_{jk}^2 f^1\left(\sum_{m=1}^2 w_{km}^1 x_m + b_k^1\right) + b_j^2\right) + b_1^3\right] \end{align} !et @@ -251,8 +270,8 @@ layers. The complete functional form is, !bt \begin{align} -&y^{l+1}_1\! = \!f_{l+1}\!\left[\!\sum_{j=1}^{N_l}\! w_{1j}^3 f_l\!\left(\!\sum_{k=1}^{N_{l-1}}\! w_{jk}^2 f_{l-1}\!\left(\! - \dots \!f_1\!\left(\!\sum_{n=1}^{N_0} \!w_{mn}^1 x_n\! + \!b_m^1\!\right) +&y^{l+1}_i\! = \!f^{l+1}\!\left[\!\sum_{j=1}^{N_l}\! w_{ij}^3 f^l\!\left(\!\sum_{k=1}^{N_{l-1}}\! w_{jk}^2 ^_{l-1}\!\left(\! + \dots \!f^1\!\left(\!\sum_{n=1}^{N_0} \!w_{mn}^1 x_n\! + \!b_m^1\!\right) \!\dots \!\right) \!+ \!b_k^2\!\right) \!+ \!b_1^3\!\right] && label{completeNN} @@ -267,19 +286,16 @@ variables are the input values $x_n$. This confirms that an MLP, despite its quite convoluted mathematical form, is nothing more than an analytic function, specifically a -mapping of real-valued vectors $\vec{x} \in \mathbb{R}^n \rightarrow -\vec{y} \in \mathbb{R}^m$. In our example, $n=2$ and -$m=1$. Consequentially, the number of input and output values of the -function we want to fit must be equal to the number of inputs and -outputs of our MLP. +mapping of real-valued vectors $\hat{x} \in \mathbb{R}^n \rightarrow +\hat{y} \in \mathbb{R}^m$. -Furthermore, the flexibility and universality of a MLP can be +Furthermore, the flexibility and universality of an MLP can be illustrated by realizing that the expression is essentially a nested sum of scaled activation functions of the form !bt \begin{equation} - h(x) = c_1 f(c_2 x + c_3) + c_4 + f(x) = c_1 f(c_2 x + c_3) + c_4 \end{equation} !et @@ -291,18 +307,18 @@ flexibility of a neural network. !split === Matrix-vector notation === -We can introduce a more convenient notation for the activations in a NN. +We can introduce a more convenient notation for the activations in an A NN. Additionally, we can represent the biases and activations -as layer-wise column vectors $\vec{b}_l$ and $\vec{y}_l$, so that the $i$-th element of each vector +as layer-wise column vectors $\hat{b}_l$ and $\hat{y}_l$, so that the $i$-th element of each vector is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. -We have that $\mathrm{W}_l$ is a $N_{l-1} \times N_l$ matrix, while $\vec{b}_l$ and $\vec{y}_l$ are $N_l \times 1$ column vectors. -With this notation, the sum in becomes a matrix-vector multiplication, and we can write -the equation for the activations of hidden layer 2 in +We have that $\mathrm{W}_l$ is an $N_{l-1} \times N_l$ matrix, while $\hat{b}_l$ and $\hat{y}_l$ are $N_l \times 1$ column vectors. +With this notation, the sum becomes a matrix-vector multiplication, and we can write +the equation for the activations of hidden layer 2 as !bt \begin{equation} - \vec{y}_2 = f_2(\mathrm{W}_2 \vec{y}_{1} + \vec{b}_{2}) = + \hat{y}_2 = f_2(\mathrm{W}_2 \hat{y}_{1} + \hat{b}_{2}) = f_2\left(\left[\begin{array}{ccc} w^2_{11} &w^2_{12} &w^2_{13} \\ w^2_{21} &w^2_{22} &w^2_{23} \\ @@ -337,7 +353,7 @@ This is not just a convenient and compact notation, but also a useful and intuitive way to think about MLPs: The output is calculated by a series of matrix-vector multiplications and vector additions that are used as input to the activation functions. For each operation -$\mathrm{W}_l \vec{y}_{l-1}$ we move forward one layer. +$\mathrm{W}_l \hat{y}_{l-1}$ we move forward one layer. !split @@ -370,17 +386,15 @@ some kind of non-linearity to the NN to be able to fit non-linear functions Typical examples are the logistic *Sigmoid* !bt -\begin{equation} +\[ f(x) = \frac{1}{1 + e^{-x}}, - label{sigmoidActivationFunction} -\end{equation} +\] !et and the *hyperbolic tangent* function !bt -\begin{equation} +\[ f(x) = \tanh(x) - label{tanhActivationFunction} -\end{equation} +\] !et !split @@ -476,8 +490,8 @@ o The multilayer network structure, or architecture, or topology, consists of an output layer. o The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer. -As a convention it is normal to call a network with a layer of input units, a layer of hidden -units and a layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc. +As a convention it is normal to call a network with one layer of input units, one layer of hidden +units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc. For an MLP there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. Hereafter we will call the various entities of a layer for nodes. @@ -485,7 +499,7 @@ There are also no connections within a single layer. The number of input nodes does not need to equal the number of output nodes. This applies also to the hidden layers. Each layer may have its -own number of nodes. +own number of nodes and activation functions. The hidden layers have their name from the fact that they are not linked to observables and as we will see below when we define the @@ -493,23 +507,28 @@ so-called activation $\hat{z}$, we can think of this as a basis expansion of the original inputs $\hat{x}$. The difference however between neural networks and say linear regression is that now these basis functions (which will correspond to the weights in the network) -are learned from data. This makes an important difference between +are learned from data. This results in an important difference between neural networks and deep learning approaches on one side and methods -like logistic regression or linear regression and their modifications. +like logistic regression or linear regression and their modifications on the other side. !split ===== From one to many layers, the universal approximation theorem ===== -A neural network with only one layer, what we called the simple perceptron, is best suited if we have a standard binary model with clear (linear) boundaries between the -outcomes. As such it could equally well be replaced by standard linear regression or logistic regression. Networks with one or more hidden layers approximate systems with more complex boundaries. +A neural network with only one layer, what we called the simple +perceptron, is best suited if we have a standard binary model with +clear (linear) boundaries between the outcomes. As such it could +equally well be replaced by standard linear regression or logistic +regression. Networks with one or more hidden layers approximate +systems with more complex boundaries. As stated earlier, -an important theorem in studies of neural networks, stated without +an important theorem in studies of neural networks, restated without proof here, is the "universal approximation -theorem":"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf" -states that a feed-forward network with a single hidden layer +theorem":"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf". + +It states that a feed-forward network with a single hidden layer containing a finite number of neurons can approximate continuous functions on compact subsets of real functions. The theorem thus states that simple neural networks can represent a wide variety of @@ -524,26 +543,35 @@ the potential of being universal approximators. _Note: figures will be inserted later!_ -As we have seen now in feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. -The unknowwn quantities are our weights $W_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible. +As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. +The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible. This leads us to the famous "back propagation algorithm":"https://www.nature.com/articles/323533a0". -The questions we want to ask are how do changes in the biases and the weights in our network change the cost function and how can we use the final output to modify the weights? +The questions we want to ask are how do changes in the biases and the +weights in our network change the cost function and how can we use the +final output to modify the weights? + +To derive these equations let us start with a plain regression problem +and define our cost function as -To derive these equations let us start with a plain regression problem and define our cost function as !bt \[ {\cal C}(\hat{W}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2, \] !et -where the $t_i$s are our $n$ targets (the values we want to reproduce), while the outputs of the network after having propagated all inputs $\hat{x}$ are given by $y_i$. -Below we will demonstrate how the basic equations arising from the back propagation algorithm can be modified in order to study classification problems with $C$ classes. + +where the $t_i$s are our $n$ targets (the values we want to +reproduce), while the outputs of the network after having propagated +all inputs $\hat{x}$ are given by $y_i$. Below we will demonstrate +how the basic equations arising from the back propagation algorithm +can be modified in order to study classification problems with $K$ +classes. !split ===== Definitions ===== With our definition of the targets $\hat{t}$, the outputs of the -network $\hat{y}$ and the inputs $\hat{x}$ (see the figure here, to come) we +network $\hat{y}$ and the inputs $\hat{x}$ we define now the activation $z_j^l$ of node/neuron/unit $j$ of the $l$-th layer as a function of the bias, the weights which add up from the previous layer $l-1$ and the forward passes/outputs @@ -555,7 +583,11 @@ $\hat{a}^{l-1}$ from the previous layer as z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_j^{l-1}+b_j^l, \] !et -where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$ represents the total number of nodes/neurons/units of layer $l-1$. The figure here illustrates this equation. We can rewrite this in a more compact form as the matrix-vector products we discussed earlier, + +where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$ +represents the total number of nodes/neurons/units of layer $l-1$. The +figure here illustrates this equation. We can rewrite this in a more +compact form as the matrix-vector products we discussed earlier, !bt \[ @@ -563,8 +595,12 @@ where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$ represents the total \] !et -With the activation function $\hat{z}^l$ we can in turn define the output of layer $l$ as $\hat{a}^l = f(\hat{z}^l)$ where $f$ is our activation function. In the examples here we will use the sigmoid function discussed in our logistic regression lectures and here as well. -It means we have +With the activation function $\hat{z}^l$ we can in turn define the +output of layer $l$ as $\hat{a}^l = f(\hat{z}^l)$ where $f$ is our +activation function. In the examples here we will use the sigmoid +function discussed in our logistic regression lectures and here as +well. We will also use the same activation function $f$ for all layers +and their nodes. It means we have !bt \[ @@ -589,7 +625,7 @@ and \] !et -With our definition of the activation function we have that (note that this functions depends only on $z_j^l$) +With our definition of the activation function we have that (note that this function depends only on $z_j^l$) !bt \[ \frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)). @@ -646,11 +682,24 @@ and using the Hadamard product of two vectors we can write this as \hat{\delta}^L = f'(\hat{z}^L)\circ\frac{\partial {\cal C}}{\partial (\hat{a}L)}. \] !et -This is an important expression. The second term on the right handside measures how fast the cost is changing as a function of the $j$th output activation. -If, for example, the cost function doesn't depend much on a particular output node $j$, then $\delta_j^L$ will be small, which is what we would expect. The first term on the right, measures how fast the activation function $f$ is changing at a given activation value $z_j^L$1. -Notice that everything in (BP1) is easily computed. In particular, we compute zLj while computing the behaviour of the network, and it's only a small additional overhead to compute σ′(zLj). The exact form of ∂C/∂aLj will, of course, depend on the form of the cost function. However, provided the cost function is known there should be little trouble computing ∂C/∂aLj. +This is an important expression. The second term on the right handside +measures how fast the cost is changing as a function of the $j$th +output activation. If, for example, the cost function doesn't depend +much on a particular output node $j$, then $\delta_j^L$ will be small, +which is what we would expect. The first term on the right, measures +how fast the activation function $f$ is changing at a given activation +value $z_j^L$1. +Notice that everything in the above equations is easily computed. +In particular, we compute $z_j^L$ while computing the behaviour of the network, and it iss only a small additional overhead to compute $f′(z^L_j)$. +The exact form of the derivative with respect to the outpuwill, of course, depend on the form of the cost function. +However, provided the cost function is known there should be little trouble computing +!bt +\[ +\frac{\partial {\cal C}}{\partial (a_j^L)} +\] +!et With the definition of $\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely !bt @@ -703,13 +752,26 @@ and !eblock -A nice consequence of Equation (32) is that when the activation ain is small, ain≈0, the gradient term ∂C/∂w will also tend to be small. In this case, we'll say the weight learns slowly, meaning that it's not changing much during gradient descent. In other words, one consequence of (BP4) is that weights output from low-activation neurons learn slowly. +An interesting consequence of the above equations is that when the +activation $a_k^{L-1}$ is small, the gradient term, that is the +derivative of the cost function with respect to the weights, will also +tend to be small. We say then that the weight learns slowly, meaning +that it changes slowly when we minimize the weights via say gradient +descent. In this case we say the system learns slowly. -There are other insights along these lines which can be obtained from (BP1)-(BP4). Let's start by looking at the output layer. Consider the term σ′(zLj) in (BP1). Recall from the graph of the sigmoid function in the last chapter that the σ function becomes very flat when σ(zLj) is approximately 0 or 1. When this occurs we will have σ′(zLj)≈0. And so the lesson is that a weight in the final layer will learn slowly if the output neuron is either low activation (≈0) or high activation (≈1). In this case it's common to say the output neuron has saturated and, as a result, the weight has stopped learning (or is learning slowly). Similar remarks hold also for the biases of output neuron. +Another interesting feature is that is when the activation function, +represented by the sigmoid function here, is rather flat when towards +its end values $0$ and $1$ (see the above Python codes). In these +cases, the derivatives of the activation function will also be close +to zero, meaning again that the gradients will be small and the +network learns slowly again. -We need a fourth equation and we are set. We are going to propagate backwards in order to the determine the weights and biases. In order to so we need to represent -the error in the layer before the final one $L-1$ in terms of the errors in the final output layer. + +We need a fourth equation and we are set. We are going to propagate +backwards in order to the determine the weights and biases. In order +to do so we need to represent the error in the layer before the final +one $L-1$ in terms of the errors in the final output layer. !split ===== Final back propagating equation ===== @@ -741,42 +803,87 @@ we obtain !et This is our final equation. +We are now ready to set up the algorithm for back propagation and learning the weights and biases. + +!split +===== Setting up the Back propagation algorithm ===== -This equation appears complicated, but each element has a nice -interpretation. Suppose we know the error δl+1 at the l+1th -layer. When we apply the transpose weight matrix, (wl+1)T, we can -think intuitively of this as moving the error backward through the -network, giving us some sort of measure of the error at the output of -the lth layer. We then take the Hadamard product ⊙σ′(zl). This moves -the error backward through the activation function in layer l, giving -us the error δl in the weighted input to layer l. -By combining (BP2) with (BP1) we can compute the error δl for any layer in the network. We start by using (BP1) to compute δL, then apply Equation (BP2) to compute δL−1, then Equation (BP2) again to compute δL−2, and so on, all the way back through the network. +The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm: +* Set up the input data $\hat{x}$ and the activations $\hat{z}_1$ of the input layer and compute the activation function and the pertinent outputs $\hat{a}^1$. +* Perform then the feed forward till you reach the output layer and compute all $\hat{z}_l$ of the input layer and compute the activation function and the pertinent outputs $\hat{a}^l$ for $l=2,3,\dots, L$.. +* Compute then the ouput error $\hat{\delta}^L by computing all +!bt +\[ +\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. +\] +!et +* Then compute the back propagate error for each $l=L-1, L-2,\dots, 2$ as +!bt +\[ +\delta_j^l =\sum_k \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l). +\] +!et +* Update the weights and the biases using gradient descent Gradient descent for each $l=L,L−1,\dots,2$ and update the weights and biases according to the rules +!bt +\[ +w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, +\] +!et +!bt +\[ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^L}, +\end{equation} +!et + +The parameter $\eta$ is the learning parameter discussed in connection with the gradient descent methods. +Here it is convenient to use stochastic radient descent with mini-batches with an outer loop that steps through multiple epochs of training. !split -===== Setting up a Multi-layer perceptron model, classification ===== - +===== Setting up a Multi-layer perceptron model for classification ===== +We are now gong to develop an example based on the MNIST data base. This is a classification problem and we need to use our cross-entropy function we discussed +in connection with logistic regression. The cross-entropy defines our cost function for the classificaton problems with neural networks. -In binary classification with two classes (0, 1) we define the logistic/sigmoid function as the probability that a -particular input is in class 0. 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. +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: - -$$ P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp (- \boldsymbol{a}^T \boldsymbol{w}_{out})} ,$$ -$$ P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) ,$$ + +!bt +\[ +P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp (- \boldsymbol{a}^T \boldsymbol{w}_{out})} , +\] +!et +and +!bt +\[ +P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , +\] +!et where $y \in \{0, 1\}$ and $\boldsymbol{\theta}$ represents the weights and biases of our network. - -$$ \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}) .$$ + +!split +===== Defining the cost function ===== +Our cost function is given as (see the Logistic regression lectures) +!bt +\[ +\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}) . +\] +!et This last equality means that we can interpret our **cost** function as a sum over the **loss** function for each point in the dataset $\mathcal{L}_i(\boldsymbol{\theta})$. @@ -785,469 +892,51 @@ than maximizing a negative number. In **multiclass** classification it is common to treat each integer label as a so called **one-hot** vector: -$$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ +$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) ,$$ +$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. +i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. If $\boldsymbol{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th output vector $\boldsymbol{y}_i$. The probability of $\boldsymbol{x}_i$ being in class $c$ will be given by the softmax function: -$$ P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} ,$$ +!bt +\[ +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'})}} , +\] +!et which reduces to the logistic function in the binary case. The likelihood of this $C$-class classifier is now given as: -$$ P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .$$ - +!bt +\[ +P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . +\] +!et Again we take the negative log-likelihood to define our cost function: -$$ \mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n \sum_{c=0}^{C-1} +!bt +\[ +\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n \sum_{c=0}^{C-1} y_{ic} \ln[P(y_{ic} = 1)] = \sum_{i=1}^n -\mathcal{L}_i(\boldsymbol{\theta}) .$$ +\mathcal{L}_i(\boldsymbol{\theta}) . +\] +!et -# Deriving the backpropagation equations - - -Assume that there are $L$ layers in our network with $l = 1,2,...,L$ indexing the layers, including -the output layer and all the hidden layers. -Let $w_{ij}^l$ denote the weight for the connection -from the $i$-th neuron in layer $l - 1$ to the $j$-th neuron in layer $l$. Let $b_{j}^l$ denote the bias of this $j$-th neuron. - -The activation $a_{j}^l$ of the $j$-th neuron in the $l$-th layer is related to the activities of the neurons in the layer $l - 1$ by: - -$$ a_{j}^l = f \left( \sum_i w_{ij}^l a_i^{l-1} + b_j^l \right) = f \left( z_j^l \right) ,$$ - -where $f$ is some activation function. - -The cost function $\mathcal{C}$ depends directly on the activations in the output layer, and indirectly on the activations -in all the lower layers. -Define the error $\Delta_j^L$ of the $j$-th neuron in the $L$-th (final) layer as the change in cost function -with respect to the weighted input $z_j^L$: - -$$ \Delta_j^L = \frac{\partial \mathcal{C}}{\partial z_j^L} .$$ - -Define analogously the error $\Delta_j^l$ of neuron $j$ in the $l$-th layer as the change in cost function with respect to the weighted input -$z_j^l$: - -$$ \Delta_j^l = \frac{\partial \mathcal{C}}{\partial z_j^l} .$$ - -This can also be interpreted as the change in cost function with respect to the bias $b_j^l$: - -$$ \Delta_j^l = \frac{\partial \mathcal{C}}{\partial z_j^l} = \frac{\partial \mathcal{C}}{\partial b_j^l} \frac{\partial b_j^l}{\partial z_j^l} = \frac{\partial \mathcal{C}}{\partial b_j^l} ,$$ - -since $ \partial b_l^j / \partial z_j^l = 1$. - -The error depends on neurons in layer $l$ only through the activation of neurons in layer $l + 1$, so using the chain rule we can write: - -$$ \begin{split} -\Delta_j^l &= \frac{\partial \mathcal{C}}{\partial z_j^l} = \sum_i \frac{\partial \mathcal{C}}{\partial z_i^{l+1}} -\frac{\partial z_i^{l+1}}{\partial z_j^l} \\ - &= \sum_i \Delta_i^{l+1} \frac{\partial z_i^{l+1}}{\partial z_j^l} \\ - &= \sum_i \Delta_i^{l+1} w_{ij}^{l+1} f'(z_j^l) \\ - &= \left( \sum_i \Delta_i^{l+1} w_{ij}^{l+1} \right) f'(z_j^l) \\ -\end{split} \label{1} \tag{1} .$$ - -The sum comes from the fact that any error in neuron $j$ in the $l$-th layer propagates to all the neurons -in the layer $l + 1$, -so we have to sum up these errors. - -This gives us the equations we need to update the weights and biases of our network: - -$$ \frac{\partial \mathcal{C}}{\partial w_{ij}^l} = \frac{\partial \mathcal{C}}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{ij}^l} -= \Delta_j^l a_i^{l-1} \tag{2} .$$ - -$$ \frac{\partial \mathcal{C}}{\partial b_{j}^l} = \Delta_j^l \tag{3} .$$ - -Now, if we have the error of every neuron $j$ at the output layer, $\Delta_j^L$, equation \ref{1} gives us the recipe for calculating the error in the preceding layer until we reach the first hidden layer, and we are done. All we are missing is the error at the output layer: - -$$ \Delta_j^L = \frac{\partial \mathcal{C}}{\partial z_j^L} = \frac{\partial}{\partial z_j^L} \left( - \sum_c y_{c} \log f(z_{c}^L) \right) ,$$ - -where $f$ is the softmax function. -Taking the derivative of each term: - -$$ \frac{\partial \log f(z_c^L)}{\partial z_j^L} = \frac{\partial}{\partial z_j^L} \left( z_c^L - \log \left( \sum_c \exp -\left( z_c^L \right) \right) \right) = \delta_{jc} - f(z_j^L) ,$$ - -where $\delta_{jc}$ is the Kronecker-Delta. -This gives us the final expression we need: - -$$ \begin{split} -\Delta_j^L &= -\sum_c y_c \left( \delta_{jc} - f(z_j^L) \right) \\ - &= -\sum_c y_c \delta_{jc} + \sum_c y_c f(z_j^L) \\ - &= -y_j + f(z_j^L) \sum_c y_c \\ - &= f(z_j^L) - y_j \\ - &= \hat{y}_j - y_j \\ -\end{split} \tag{4} .$$ +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! +We leave it as an exercise in project 2 to derive these equations. -!split -===== Building a code ===== - -!bc pycod -from scipy import optimize - -class Neural_Network(object): - def __init__(self, Lambda=0): - #Define Hyperparameters - self.inputLayerSize = 2 - self.outputLayerSize = 1 - self.hiddenLayerSize = 3 - - #Weights (parameters) - self.W1 = np.random.randn(self.inputLayerSize,self.hiddenLayerSize) - self.W2 = np.random.randn(self.hiddenLayerSize,self.outputLayerSize) - - #Regularization Parameter: - self.Lambda = Lambda - - def forward(self, X): - #Propagate inputs though network - self.z2 = np.dot(X, self.W1) - self.a2 = self.sigmoid(self.z2) - self.z3 = np.dot(self.a2, self.W2) - yHat = self.sigmoid(self.z3) - return yHat - - def sigmoid(self, z): - #Apply sigmoid activation function to scalar, vector, or matrix - return 1/(1+np.exp(-z)) - - def sigmoidPrime(self,z): - #Gradient of sigmoid - return np.exp(-z)/((1+np.exp(-z))**2) - - def costFunction(self, X, y): - #Compute cost for given X,y, use weights already stored in class. - self.yHat = self.forward(X) - J = 0.5*sum((y-self.yHat)**2)/X.shape[0] + (self.Lambda/2)*(np.sum(self.W1**2)+np.sum(self.W2**2)) - return J - - def costFunctionPrime(self, X, y): - #Compute derivative with respect to W and W2 for a given X and y: - self.yHat = self.forward(X) - - delta3 = np.multiply(-(y-self.yHat), self.sigmoidPrime(self.z3)) - #Add gradient of regularization term: - dJdW2 = np.dot(self.a2.T, delta3)/X.shape[0] + self.Lambda*self.W2 - - delta2 = np.dot(delta3, self.W2.T)*self.sigmoidPrime(self.z2) - #Add gradient of regularization term: - dJdW1 = np.dot(X.T, delta2)/X.shape[0] + self.Lambda*self.W1 - - return dJdW1, dJdW2 - - #Helper functions for interacting with other methods/classes - def getParams(self): - #Get W1 and W2 Rolled into vector: - params = np.concatenate((self.W1.ravel(), self.W2.ravel())) - return params - - def setParams(self, params): - #Set W1 and W2 using single parameter vector: - W1_start = 0 - W1_end = self.hiddenLayerSize*self.inputLayerSize - self.W1 = np.reshape(params[W1_start:W1_end], \ - (self.inputLayerSize, self.hiddenLayerSize)) - W2_end = W1_end + self.hiddenLayerSize*self.outputLayerSize - self.W2 = np.reshape(params[W1_end:W2_end], \ - (self.hiddenLayerSize, self.outputLayerSize)) - - def computeGradients(self, X, y): - dJdW1, dJdW2 = self.costFunctionPrime(X, y) - return np.concatenate((dJdW1.ravel(), dJdW2.ravel())) - - -class trainer(object): - def __init__(self, N): - #Make Local reference to network: - self.N = N - - def callbackF(self, params): - self.N.setParams(params) - self.J.append(self.N.costFunction(self.X, self.y)) - self.testJ.append(self.N.costFunction(self.testX, self.testY)) - - def costFunctionWrapper(self, params, X, y): - self.N.setParams(params) - cost = self.N.costFunction(X, y) - grad = self.N.computeGradients(X,y) - return cost, grad - - def train(self, trainX, trainY, testX, testY): - #Make an internal variable for the callback function: - self.X = trainX - self.y = trainY - - self.testX = testX - self.testY = testY - - #Make empty list to store training costs: - self.J = [] - self.testJ = [] - - params0 = self.N.getParams() - - options = {'maxiter': 200, 'disp' : True} - _res = optimize.minimize(self.costFunctionWrapper, params0, jac=True, method='BFGS', \ - args=(trainX, trainY), options=options, callback=self.callbackF) - - self.N.setParams(_res.x) - self.optimizationResults = _res -!ec - - -!split -===== Two-layer Neural Network ===== -!bc pycod -import numpy as np - -#sigmoid -def nonlin(x, deriv=False): - if (deriv==True): - return x*(1-x) - return 1/(1+np.exp(-x)) - -#input data -x=np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]]) - -#output data -y=np.array([0,1,1,0]).T - -#seed random numbers to make calculation -np.random.seed(1) - -#initialize weights with mean=0 -syn0=2*np.random.random((3,4))-1 - -for iter in range(10000): - #forward propogation - l0=x - l1=nonlin(np.dot(l0,syn0)) - l1_error=y-l1 - #multiply error by slope of sigmoid at values of l1 - l1_delta=l1_error*nonlin(l1,True) - #update weights - syn0+=np.dot(l0.T, l1_delta) - -print("Output after training: ",l1 ) -!ec - - -!bc pycod -import numpy as np -import random -class Network(object): - - def _init_(self, sizes): - self.num_layers=len(sizes) - self.sizes=sizes - self.biases=[np.random.randn(y,1) for y in sizes[1:]] - self.weights=[np.random.randn(y,x) for x,y in zip(sizes[:-1], sizes[1:])] - -#sizes is the number of neurons in each layer -#for example, say n_1st_layer=3, n_2nd_layer=3, n_3rd_layer=1, then net=Network([3,3,1]) - -#The biases and weights are initialized randomly, using Gaussian distributions of mean=0, stdev=1 -#z is a vector (or a np.array) - - def feedforward(self,a): - #returns output w/ 'a' as an input - for b, w in zip(self.biases, self.weights): - a=sigmoid(np.dot(w,b)+b) - return a - -#Apply a Stochastic Gradient Descent (SGD) method: - def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None): - """Trains network using batches incorporating SGD. The network will be evaluated against the - test data after each epoch, with partial progress being printed out (this is useful for tracking, - but slows the process.)""" - if test_data: n_test=len(test_data) - n=len(training_data) - for j in xrange(epochs): - random.shuffle(training_data) - mini_batches=[training_data[k:k+mini_batch_size] for k in xrange(o,n,mini_batch_size)] - for mini_batch in mini_batches: - self.update_mini_batch(mini_batch, eta) - if test_data: - print ("Epoch {0}: {1}/{2}".format(j, self.evaluate(test_data), n_test)) - else: - print ("Epoch {0} complete".format(j)) - - - def update_mini_batch(self, mini_batch, eta): - #updates w and b using backpropagation to a single mini batch. eta is the learning rate." - nabla_b=[np.zeros(b.shape) for b in self.biases] - nabla_w=[np.zeros(w.shape) for w in self.weights] - for x,y in mini_batch: - delta_nabla_b, delta_nabla_w=self.backprop(x,y) - nabla_b=[nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] - nabla_w=[nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] - self.weights=[w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)] - self.biases=[b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)] - - def backprop(self, x, y): - """Return a tuple ``(nabla_b, nabla_w)`` representing the - gradient for the cost function C_x. ``nabla_b`` and - ``nabla_w`` are layer-by-layer lists of numpy arrays, similar - to ``self.biases`` and ``self.weights``.""" - nabla_b = [np.zeros(b.shape) for b in self.biases] - nabla_w = [np.zeros(w.shape) for w in self.weights] - # feedforward - activation = x - activations = [x] # list to store all the activations, layer by layer - zs = [] # list to store all the z vectors, layer by layer - for b, w in zip(self.biases, self.weights): - z = np.dot(w, activation)+b - zs.append(z) - activation = sigmoid(z) - activations.append(activation) - # backward pass - delta = self.cost_derivative(activations[-1], y) * \ - sigmoid_prime(zs[-1]) - nabla_b[-1] = delta - nabla_w[-1] = np.dot(delta, activations[-2].transpose()) - # Note that the variable l in the loop below is used a little - # differently to the notation in Chapter 2 of the book. Here, - # l = 1 means the last layer of neurons, l = 2 is the - # second-last layer, and so on. It's a renumbering of the - # scheme in the book, used here to take advantage of the fact - # that Python can use negative indices in lists. - for l in xrange(2, self.num_layers): - z = zs[-l] - sp = sigmoid_prime(z) - delta = np.dot(self.weights[-l+1].transpose(), delta) * sp - nabla_b[-l] = delta - nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) - return (nabla_b, nabla_w) - - def evaluate(self, test_data): - """Return the number of test inputs for which the neural - network outputs the correct result. Note that the neural - network's output is assumed to be the index of whichever - neuron in the final layer has the highest activation.""" - test_results = [(np.argmax(self.feedforward(x)), y) - for (x, y) in test_data] - return sum(int(x == y) for (x, y) in test_results) - - def cost_derivative(self, output_activations, y): - """Return the vector of partial derivatives \partial C_x / - \partial a for the output activations.""" - return (output_activations-y) - - - -#Functions -def sigmoid(z): - return 1.0/(1.0+np.exp(-z)) - -def sigmoid_prime(z): - return sigmoid(z)*(1-sigmoid(z)) - -network=Network() - -!ec - -!bc pycod -# %load neural-networks-and-deep-learning/src/mnist_loader.py -""" -mnist_loader -~~~~~~~~~~~~ - -A library to load the MNIST image data. For details of the data -structures that are returned, see the doc strings for ``load_data`` -and ``load_data_wrapper``. In practice, ``load_data_wrapper`` is the -function usually called by our neural network code. -""" - -#### Libraries -# Standard library -import pickle -import gzip - -# Third-party libraries -import numpy as np - -def load_data(): - """Return the MNIST data as a tuple containing the training data, - the validation data, and the test data. - - The ``training_data`` is returned as a tuple with two entries. - The first entry contains the actual training images. This is a - numpy ndarray with 50,000 entries. Each entry is, in turn, a - numpy ndarray with 784 values, representing the 28 * 28 = 784 - pixels in a single MNIST image. - - The second entry in the ``training_data`` tuple is a numpy ndarray - containing 50,000 entries. Those entries are just the digit - values (0...9) for the corresponding images contained in the first - entry of the tuple. - - The ``validation_data`` and ``test_data`` are similar, except - each contains only 10,000 images. - - This is a nice data format, but for use in neural networks it's - helpful to modify the format of the ``training_data`` a little. - That's done in the wrapper function ``load_data_wrapper()``, see - below. - """ - f = gzip.open('../data/mnist.pkl.gz', 'rb') - training_data, validation_data, test_data = cPickle.load(f) - f.close() - return (training_data, validation_data, test_data) - -def load_data_wrapper(): - """Return a tuple containing ``(training_data, validation_data, - test_data)``. Based on ``load_data``, but the format is more - convenient for use in our implementation of neural networks. - - In particular, ``training_data`` is a list containing 50,000 - 2-tuples ``(x, y)``. ``x`` is a 784-dimensional numpy.ndarray - containing the input image. ``y`` is a 10-dimensional - numpy.ndarray representing the unit vector corresponding to the - correct digit for ``x``. - - ``validation_data`` and ``test_data`` are lists containing 10,000 - 2-tuples ``(x, y)``. In each case, ``x`` is a 784-dimensional - numpy.ndarry containing the input image, and ``y`` is the - corresponding classification, i.e., the digit values (integers) - corresponding to ``x``. - - Obviously, this means we're using slightly different formats for - the training data and the validation / test data. These formats - turn out to be the most convenient for use in our neural network - code.""" - tr_d, va_d, te_d = load_data() - training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]] - training_results = [vectorized_result(y) for y in tr_d[1]] - training_data = zip(training_inputs, training_results) - validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]] - validation_data = zip(validation_inputs, va_d[1]) - test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]] - test_data = zip(test_inputs, te_d[1]) - return (training_data, validation_data, test_data) - -def vectorized_result(j): - """Return a 10-dimensional unit vector with a 1.0 in the jth - position and zeroes elsewhere. This is used to convert a digit - (0...9) into a corresponding desired output from the neural - network.""" - e = np.zeros((10, 1)) - e[j] = 1.0 - return e - -net=network.Network([784,30,30]) -net.SGD(training_data,30,10,3,test_data=test_data) -!ec