diff --git a/doc/src/week42/backup2022.do.txt b/doc/src/week42/backup2022.do.txt new file mode 100644 index 000000000..b1bf3842d --- /dev/null +++ b/doc/src/week42/backup2022.do.txt @@ -0,0 +1,3474 @@ +TITLE: Week 42 Solving differential equations and Convolutional (CNN) +AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +DATE: today + + +!split +===== Plan for week 42 ===== + +!bblock +* Thursday: Solving differential equations with Neural Networks and intro to _Tensorflow_ with examples. + * "Video of lecture":"https://youtu.be/MdYT6uwOkT0" +* Friday: Convolutional Neural Networks. + * "Video of lecture":"https://youtu.be/3bDkrB-E7cU" +* Reading recommendations: + o See lecture notes for week 42 at https://compphysics.github.io/MachineLearning/doc/web/course.html. + o For Tensorflow and Keras, see lecture notes from week 41 + o For neural networks we recommend Goodfellow et al chapters 6 and 7. For CNNs, see Goodfellow et al chapter 9. See also chapter 11 and 12 on practicalities and applications + o Reading suggestions for implementation of CNNs: "Aurelien Geron's chapter 13":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf". +!eblock + + +!bblock Excellent lectures on CNNs and Neural Networks +* "Video on Deep Learning":"https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi" +* "Video on Convolutional Neural Networks from MIT":"https://www.youtube.com/watch?v=iaSUYvmCekI&ab_channel=AlexanderAmini" +* "Video on CNNs from Stanford":"https://www.youtube.com/watch?v=bNb2fEVKeEo&list=PLC1qU-LWwrF64f4QKQT-Vg5Wr4qEE1Zxk&index=6&ab_channel=StanfordUniversitySchoolofEngineering" +!eblock +m + +!bblock And Lecture material on CNNs +* "Lectures from IN5400 spring 2019":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/v19/material/week5/in5400_2019_week5_convolutional_nerual_networks.pdf" +* "Lectures from IN5400 spring 2021":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/v21/lecture-slides/in5400_2021_w5_lecture_convolutions.pdf" +* "See also Michael Nielsen's Lectures":"http://neuralnetworksanddeeplearning.com/chap6.html" +!eblock + + + +!split +===== Using Automatic differentiation ===== +a +In our discussions of ordinary differential equations +we will also study the usage of "Autograd":"https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola" in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from "week 39":"https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html" and the "Autograd documentation":"https://github.com/HIPS/autograd". +t + +!split +===== Back propagation and automatic differentiation ===== + +For more details on the back propagation algorithm and automatic differentiation see +o URL:"https://www.jmlr.org/papers/volume18/17-468/17-468.pdf" +o URL:"https://deepimaging.github.io/lectures/lecture_11_Backpropagation.pdf" +o Slides 12-44 at URL":http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf" + + +!split +===== Solving ODEs with Deep Learning ===== + +!bblock +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. +!eblock + +!bblock Book on solving differential equations with ML methods +"An Introduction to Neural Network Methods for Differential Equations":"https://www.springer.com/gp/book/9789401798150", by Yadav and Kumar. +!eblock + +!bblock Master thesis on applying deep learning to problems in mechanics +"Using Deep Reinforcement Learning for Active Flow Control":"https://www.duo.uio.no/handle/10852/79212", by Marius Holm +!eblock + + + +!bblock Thanks to Kristine Baluka Hein +The lectures on differential equations were developed by Kristine Baluka Hein, now PhD student at IFI. +A great thanks to Kristine. +!eblock + +!split +===== Ordinary Differential Equations ===== + +An ordinary differential equation (ODE) is an equation involving functions having one variable. + +In general, an ordinary differential equation looks like + +!bt +\begin{equation} \label{ode} +f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) = 0 +\end{equation} +!et + +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 (ref{ode}). +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 (ref{ode}), some additional conditions of the function $g(x)$ are typically given +for the solution to be unique. + +!split +===== The trial solution ===== + +Let the trial solution $g_t(x)$ be + +!bt +\begin{equation} + g_t(x) = h_1(x) + h_2(x,N(x,P)) +\end{equation} +!et + + +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. + + +!split +===== Minimization process ===== + +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 (ref{ode}). +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 + +!bt +C\left(x, P\right) = \big(f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right)\big)^2 +!et + +If $N$ inputs are given as a vector $\bm{x}$ with elements $x_i$ for $i = 1,\dots,N$, +the cost function becomes + +!bt +\begin{equation} \label{cost} + C\left(\bm{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} +!et + +The neural net should then find the parameters $P$ that minimizes the cost function in +(ref{cost}) for a set of $N$ training samples $x_i$. + +!split +===== Minimizing the cost function using gradient descent and automatic differentiation ===== + +To perform the minimization using gradient descent, the gradient of $C\left(\bm{x}, P\right)$ is needed. +It might happen so that finding an analytical expression of the gradient of $C(\bm{x}, P)$ from (ref{cost}) gets too messy, depending on which cost function one desires to use. + +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. + + +!split +===== Example: Exponential decay ===== + +An exponential decay of a quantity $g(x)$ is described by the equation + +!bt +\begin{equation} \label{solve_expdec} + g'(x) = -\gamma g(x) +\end{equation} +!et + +with $g(0) = g_0$ for some chosen initial value $g_0$. + +The analytical solution of (ref{solve_expdec}) is + +!bt +\begin{equation} + g(x) = g_0 \exp\left(-\gamma x\right) +\end{equation} +!et + +Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of (ref{solve_expdec}). + + +!split +===== The function to solve for ===== + +The program will use a neural network to solve + +!bt +\begin{equation} \label{solveode} +g'(x) = -\gamma g(x) +\end{equation} +!et + +where $g(0) = g_0$ with $\gamma$ and $g_0$ being some chosen values. + +In this example, $\gamma = 2$ and $g_0 = 10$. + +!split +===== 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 + +!bt +g_t(x, P) = h_1(x) + h_2(x, N(x, P)) +!et + +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. + +!split +===== 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 (ref{solveode}). 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: + +!bt +\begin{equation} \label{trial} +g_t(x, P) = g_0 + x \cdot N(x, P) +\end{equation} +!et + +!split +===== Reformulating the problem ===== + +We wish that our neural network manages to minimize a given cost function. + +A reformulation of out equation, (ref{solveode}), must therefore be done, +such that it describes the problem a neural network can solve for. + +The neural network must find the set of weights and biases $P$ such that the trial solution in (ref{trial}) satisfies (ref{solveode}). + +The trial solution + +!bt +g_t(x, P) = g_0 + x \cdot N(x, P) +!et + +has been chosen such that it already solves the condition $g(0) = g_0$. What remains, is to find $P$ such that + +!bt +\begin{equation} \label{nnmin} +g_t'(x, P) = - \gamma g_t(x, P) +\end{equation} +!et + +is fulfilled as *best as possible*. + +!split +===== More technicalities ===== + +The left hand side and right hand side of (ref{nnmin}) 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: + +!bt +\min_{P}\Big\{ \big(g_t'(x, P) - ( -\gamma g_t(x, P) \big)^2 \Big\} +!et + +(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: + +!bt +\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\} +!et + +for an input value $x$. + +!split +===== More details ===== + +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 + +!bt +\begin{equation} \label{min} +\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} +!et + +Letting $\bm{x}$ be a vector with elements $x_i$ and $C(\bm{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 + +!bt +\min_{P} C(\bm{x}, P) +!et + +In terms of $P_{\text{hidden} }$ and $P_{\text{output} }$, this could also be expressed as + +$$ +\min_{P_{\text{hidden} }, \ P_{\text{output} }} C(\bm{x}, \{P_{\text{hidden} }, P_{\text{output} }\}) +$$ + +!split +===== A possible implementation of a neural network ===== + +For simplicity, it is assumed that the input is an array $\bm{x} = (x_1, \dots, x_N)$ with $N$ elements. It is at these points the neural network should find $P$ such that it fulfills (ref{min}). + +First, the neural network must feed forward the inputs. +This means that $\bm{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} }$. + +!split +===== Technicalities ===== + +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: + +!bt +\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} +!et + +!split +===== Final technicalities I ===== + +The result after weighting the inputs at the $i$-th hidden neuron can be written as a vector: + +!bt +\begin{aligned} +\bm{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} \\ +&= \bm{p}_{i, \text{hidden}}^T X +\end{aligned} +!et + +!split +===== Final technicalities II ===== + +The vector $\bm{p}_{i, \text{hidden}}^T$ constitutes each row in $P_{\text{hidden} }$, which contains the weights for the neural network to minimize according to (ref{min}). + +After having found $\bm{z}_{i}^{\text{hidden}} $ for every $i$-th neuron within the hidden layer, the vector will be sent to an activation function $a_i(\bm{z})$. + +In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron: + +!bt +f(z) = \frac{1}{1 + \exp{(-z)}} +!et + +It is possible to use other activations functions for the hidden layer also. + +The output $\bm{x}_i^{\text{hidden}}$ from each $i$-th hidden neuron is: + +$$ +\bm{x}_i^{\text{hidden} } = f\big( \bm{z}_{i}^{\text{hidden}} \big) +$$ + +The outputs $\bm{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. + +!split +===== Final technicalities III ===== + + +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. + +!bt +\begin{aligned} +z_{1,j}^{\text{output}} & = +\begin{pmatrix} +b_1^{\text{output}} & \bm{w}_1^{\text{output}} +\end{pmatrix} +\begin{pmatrix} +1 \\ +\bm{x}_j^{\text{hidden}} +\end{pmatrix} +\end{aligned} +!et + +!split +===== Final technicalities IV ===== + +Expressing $z_{1,j}^{\text{output}}$ as a vector gives the following way of weighting the inputs from the hidden layer: + +!bt +\bm{z}_{1}^{\text{output}} = +\begin{pmatrix} +b_1^{\text{output}} & \bm{w}_1^{\text{output}} +\end{pmatrix} +\begin{pmatrix} +1 & 1 & \dots & 1 \\ +\bm{x}_1^{\text{hidden}} & \bm{x}_2^{\text{hidden}} & \dots & \bm{x}_N^{\text{hidden}} +\end{pmatrix} +!et + +In this case we seek a continuous range of values since we are approximating a function. This means that after computing $\bm{z}_{1}^{\text{output}}$ the neural network has finished its feed forward step, and $\bm{z}_{1}^{\text{output}}$ is the final output of the network. + +!split +===== Back propagation ===== + +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 + +!bt +C(\bm{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 +!et + +In order to minimize the cost function, an optimization method must be chosen. + +Here, gradient descent with a constant step size has been chosen. + +!split +===== Gradient descent ===== + +The idea of the gradient descent algorithm is to update parameters in +a direction where the cost function decreases goes to a minimum. + +In general, the update of some parameters $\bm{\omega}$ given a cost +function defined by some weights $\bm{\omega}$, $C(\bm{x}, +\bm{\omega})$, goes as follows: + +!bt +\bm{\omega}_{\text{new} } = \bm{\omega} - \lambda \nabla_{\bm{\omega}} C(\bm{x}, \bm{\omega}) +!et + +for a number of iterations or until $ \big|\big| \bm{\omega}_{\text{new} } - \bm{\omega} \big|\big|$ becomes smaller than some given tolerance. + +The value of $\lambda$ decides how large steps the algorithm must take +in the direction of $ \nabla_{\bm{\omega}} C(\bm{x}, \bm{\omega})$. +The notation $\nabla_{\bm{\omega}}$ express the gradient with respect +to the elements in $\bm{\omega}$. + +In our case, we have to minimize the cost function $C(\bm{x}, P)$ with +respect to the two sets of weights and biases, that is for the hidden +layer $P_{\text{hidden} }$ and for the output layer $P_{\text{output} +}$ . + +This means that $P_{\text{hidden} }$ and $P_{\text{output} }$ is updated by + +!bt +\begin{aligned} +P_{\text{hidden},\text{new}} &= P_{\text{hidden}} - \lambda \nabla_{P_{\text{hidden}}} C(\bm{x}, P) \\ +P_{\text{output},\text{new}} &= P_{\text{output}} - \lambda \nabla_{P_{\text{output}}} C(\bm{x}, P) +\end{aligned} +!et + +!split +===== The code for solving the ODE ===== + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +# Assuming one input, hidden, and output layer +def neural_network(params, x): + + # Find the weights (including and biases) for the hidden and output layer. + # Assume that params is a list of parameters for each layer. + # The biases are the first element for each array in params, + # and the weights are the remaning elements in each array in params. + + w_hidden = params[0] + w_output = params[1] + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + ## Hidden layer: + + # Add a row of ones to include bias + x_input = np.concatenate((np.ones((1,num_values)), x_input ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_input) + x_hidden = sigmoid(z_hidden) + + ## Output layer: + + # Include bias: + x_hidden = np.concatenate((np.ones((1,num_values)), x_hidden ), axis = 0) + + z_output = np.matmul(w_output, x_hidden) + x_output = z_output + + return x_output + +# The trial solution using the deep neural network: +def g_trial(x,params, g0 = 10): + return g0 + x*neural_network(params,x) + +# The right side of the ODE: +def g(x, g_trial, gamma = 2): + return -gamma*g_trial + +# The cost function: +def cost_function(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial(x,P) + + # Find the derivative w.r.t x of the neural network + d_net_out = elementwise_grad(neural_network,1)(P,x) + + # Find the derivative w.r.t x of the trial function + d_g_t = elementwise_grad(g_trial,0)(x,P) + + # The right side of the ODE + func = g(x, g_t) + + err_sqr = (d_g_t - func)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum / np.size(err_sqr) + +# Solve the exponential decay ODE using neural network with one input, hidden, and output layer +def solve_ode_neural_network(x, num_neurons_hidden, num_iter, lmb): + ## Set up initial weights and biases + + # For the hidden layer + p0 = npr.randn(num_neurons_hidden, 2 ) + + # For the output layer + p1 = npr.randn(1, num_neurons_hidden + 1 ) # +1 since bias is included + + P = [p0, p1] + + print('Initial cost: %g'%cost_function(P, x)) + + ## Start finding the optimal weights using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_grad = grad(cost_function,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of two arrays; + # one for the gradient w.r.t P_hidden and + # one for the gradient w.r.t P_output + cost_grad = cost_function_grad(P, x) + + P[0] = P[0] - lmb * cost_grad[0] + P[1] = P[1] - lmb * cost_grad[1] + + print('Final cost: %g'%cost_function(P, x)) + + return P + +def g_analytic(x, gamma = 2, g0 = 10): + return g0*np.exp(-gamma*x) + +# Solve the given problem +if __name__ == '__main__': + # Set seed such that the weight are initialized + # with same weights and biases for every run. + npr.seed(15) + + ## Decide the vales of arguments to the function to solve + N = 10 + x = np.linspace(0, 1, N) + + ## Set up the initial parameters + num_hidden_neurons = 10 + num_iter = 10000 + lmb = 0.001 + + # Use the network + P = solve_ode_neural_network(x, num_hidden_neurons, num_iter, lmb) + + # Print the deviation from the trial solution and true solution + res = g_trial(x,P) + res_analytical = g_analytic(x) + + print('Max absolute difference: %g'%np.max(np.abs(res - res_analytical))) + + # Plot the results + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(x, res_analytical) + plt.plot(x, res[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('x') + plt.ylabel('g(x)') + plt.show() +!ec + + +!split +===== The network with one input layer, specified number of hidden layers, and one output layer ===== + +It is also possible to extend the construction of our network into a more general one, allowing the network to contain more than one hidden layers. + +The number of neurons within each hidden layer are given as a list of integers in the program below. + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +# The neural network with one input layer and one output layer, +# but with number of hidden layers specified by the user. +def deep_neural_network(deep_params, x): + # N_hidden is the number of hidden layers + + N_hidden = np.size(deep_params) - 1 # -1 since params consists of + # parameters to all the hidden + # layers AND the output layer. + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + # Due to multiple hidden layers, define a variable referencing to the + # output of the previous layer: + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output + +# The trial solution using the deep neural network: +def g_trial_deep(x,params, g0 = 10): + return g0 + x*deep_neural_network(params, x) + +# The right side of the ODE: +def g(x, g_trial, gamma = 2): + return -gamma*g_trial + +# The same cost function as before, but calls deep_neural_network instead. +def cost_function_deep(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial_deep(x,P) + + # Find the derivative w.r.t x of the neural network + d_net_out = elementwise_grad(deep_neural_network,1)(P,x) + + # Find the derivative w.r.t x of the trial function + d_g_t = elementwise_grad(g_trial_deep,0)(x,P) + + # The right side of the ODE + func = g(x, g_t) + + err_sqr = (d_g_t - func)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum / np.size(err_sqr) + +# Solve the exponential decay ODE using neural network with one input and one output layer, +# but with specified number of hidden layers from the user. +def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb): + # num_hidden_neurons is now a list of number of neurons within each hidden layer + + # The number of elements in the list num_hidden_neurons thus represents + # the number of hidden layers. + + # Find the number of hidden layers: + N_hidden = np.size(num_neurons) + + ## Set up initial weights and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 ) + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: %g'%cost_function_deep(P, x)) + + ## Start finding the optimal weights using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_deep_grad = grad(cost_function_deep,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases + # in the hidden layers and output layers evaluated at x. + cost_deep_grad = cost_function_deep_grad(P, x) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_deep_grad[l] + + print('Final cost: %g'%cost_function_deep(P, x)) + + return P + +def g_analytic(x, gamma = 2, g0 = 10): + return g0*np.exp(-gamma*x) + +# Solve the given problem +if __name__ == '__main__': + npr.seed(15) + + ## Decide the vales of arguments to the function to solve + N = 10 + x = np.linspace(0, 1, N) + + ## Set up the initial parameters + num_hidden_neurons = np.array([10,10]) + num_iter = 10000 + lmb = 0.001 + + P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb) + + res = g_trial_deep(x,P) + res_analytical = g_analytic(x) + + plt.figure(figsize=(10,10)) + + plt.title('Performance of a deep neural network solving an ODE compared to the analytical solution') + plt.plot(x, res_analytical) + plt.plot(x, res[0,:]) + plt.legend(['analytical','dnn']) + plt.ylabel('g(x)') + plt.show() +!ec + + +!split +===== Example: Population growth ===== + +A logistic model of population growth assumes that a population converges toward an equilibrium. +The population growth can be modeled by + +!bt +\begin{equation} \label{log} + g'(t) = \alpha g(t)(A - g(t)) +\end{equation} +!et + +where $g(t)$ is the population density at time $t$, $\alpha > 0$ the growth rate and $A > 0$ is the maximum population number in the environment. +Also, at $t = 0$ the population has the size $g(0) = g_0$, where $g_0$ is some chosen constant. + +In this example, similar network as for the exponential decay using Autograd has been used to solve the equation. However, as the implementation might suffer from e.g numerical instability +and high execution time (this might be more apparent in the examples solving PDEs), +using a library like TensorFlow is recommended. +Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method. + +!split +===== Setting up the problem ===== + +Here, we will model a population $g(t)$ in an environment having carrying capacity $A$. +The population follows the model + +!bt +\begin{equation} \label{solveode_population} +g'(t) = \alpha g(t)(A - g(t)) +\end{equation} +!et + +where $g(0) = g_0$. + +In this example, we let $\alpha = 2$, $A = 1$, and $g_0 = 1.2$. + +!split +===== The trial solution ===== + +We will get a slightly different trial solution, as the boundary conditions are different +compared to the case for exponential decay. + +A possible trial solution satisfying the condition $g(0) = g_0$ could be + +$$ +h_1(t) = g_0 + t \cdot N(t,P) +$$ + +with $N(t,P)$ being the output from the neural network with weights and biases for each layer collected in the set $P$. + +The analytical solution is + +$$ +g(t) = \frac{Ag_0}{g_0 + (A - g_0)\exp(-\alpha A t)} +$$ + +!split +===== The program using Autograd ===== + +The network will be the similar as for the exponential decay example, but with some small modifications for our problem. + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +# Function to get the parameters. +# Done such that one can easily change the paramaters after one's liking. +def get_parameters(): + alpha = 2 + A = 1 + g0 = 1.2 + return alpha, A, g0 + +def deep_neural_network(P, x): + # N_hidden is the number of hidden layers + N_hidden = np.size(P) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + # Due to multiple hidden layers, define a variable referencing to the + # output of the previous layer: + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = P[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = P[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output + + +def cost_function_deep(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial_deep(x,P) + + # Find the derivative w.r.t x of the trial function + d_g_t = elementwise_grad(g_trial_deep,0)(x,P) + + # The right side of the ODE + func = f(x, g_t) + + err_sqr = (d_g_t - func)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum / np.size(err_sqr) + +# The right side of the ODE: +def f(x, g_trial): + alpha,A, g0 = get_parameters() + return alpha*g_trial*(A - g_trial) + +# The trial solution using the deep neural network: +def g_trial_deep(x, params): + alpha,A, g0 = get_parameters() + return g0 + x*deep_neural_network(params,x) + +# The analytical solution: +def g_analytic(t): + alpha,A, g0 = get_parameters() + return A*g0/(g0 + (A - g0)*np.exp(-alpha*A*t)) + +def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb): + # num_hidden_neurons is now a list of number of neurons within each hidden layer + + # Find the number of hidden layers: + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 ) + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: %g'%cost_function_deep(P, x)) + + ## Start finding the optimal weigths using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_deep_grad = grad(cost_function_deep,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases + # in the hidden layers and output layers evaluated at x. + cost_deep_grad = cost_function_deep_grad(P, x) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_deep_grad[l] + + print('Final cost: %g'%cost_function_deep(P, x)) + + return P + +if __name__ == '__main__': + npr.seed(4155) + + ## Decide the vales of arguments to the function to solve + Nt = 10 + T = 1 + t = np.linspace(0,T, Nt) + + ## Set up the initial parameters + num_hidden_neurons = [100, 50, 25] + num_iter = 1000 + lmb = 1e-3 + + P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb) + + g_dnn_ag = g_trial_deep(t,P) + g_analytical = g_analytic(t) + + # Find the maximum absolute difference between the solutons: + diff_ag = np.max(np.abs(g_dnn_ag - g_analytical)) + print("The max absolute difference between the solutions is: %g"%diff_ag) + + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(t, g_analytical) + plt.plot(t, g_dnn_ag[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('t') + plt.ylabel('g(t)') + + plt.show() +!ec + +!split +===== Using forward Euler to solve the ODE ===== + +A straightforward way of solving an ODE numerically, is to use Euler's method. + +Euler's method uses Taylor series to approximate the value at a function $f$ at a step $\Delta x$ from $x$: + +$$ +f(x + \Delta x) \approx f(x) + \Delta x f'(x) +$$ + +In our case, using Euler's method to approximate the value of $g$ at a step $\Delta t$ from $t$ yields + +!bt +\begin{aligned} + g(t + \Delta t) &\approx g(t) + \Delta t g'(t) \\ + &= g(t) + \Delta t \big(\alpha g(t)(A - g(t))\big) +\end{aligned} +!et +along with the condition that $g(0) = g_0$. + +Let $t_i = i \cdot \Delta t$ where $\Delta t = \frac{T}{N_t-1}$ where $T$ is the final time our solver must solve for and $N_t$ the number of values for $t \in [0, T]$ for $i = 0, \dots, N_t-1$. + +For $i \geq 1$, we have that +!bt +\begin{aligned} +t_i &= i\Delta t \\ +&= (i - 1)\Delta t + \Delta t \\ +&= t_{i-1} + \Delta t +\end{aligned} +!et + +Now, if $g_i = g(t_i)$ then + +!bt +\begin{equation} + \begin{aligned} + g_i &= g(t_i) \\ + &= g(t_{i-1} + \Delta t) \\ + &\approx g(t_{i-1}) + \Delta t \big(\alpha g(t_{i-1})(A - g(t_{i-1}))\big) \\ + &= g_{i-1} + \Delta t \big(\alpha g_{i-1}(A - g_{i-1})\big) + \end{aligned} +\end{equation} \label{odenum} +!et +for $i \geq 1$ and $g_0 = g(t_0) = g(0) = g_0$. + +Equation (ref{odenum}) could be implemented in the following way, +extending the program that uses the network using Autograd: + +!bc pycod +# Assume that all function definitions from the example program using Autograd +# are located here. + +if __name__ == '__main__': + npr.seed(4155) + + ## Decide the vales of arguments to the function to solve + Nt = 10 + T = 1 + t = np.linspace(0,T, Nt) + + ## Set up the initial parameters + num_hidden_neurons = [100,50,25] + num_iter = 1000 + lmb = 1e-3 + + P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb) + + g_dnn_ag = g_trial_deep(t,P) + g_analytical = g_analytic(t) + + # Find the maximum absolute difference between the solutons: + diff_ag = np.max(np.abs(g_dnn_ag - g_analytical)) + print("The max absolute difference between the solutions is: %g"%diff_ag) + + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(t, g_analytical) + plt.plot(t, g_dnn_ag[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('t') + plt.ylabel('g(t)') + + ## Find an approximation to the funtion using forward Euler + + alpha, A, g0 = get_parameters() + dt = T/(Nt - 1) + + # Perform forward Euler to solve the ODE + g_euler = np.zeros(Nt) + g_euler[0] = g0 + + for i in range(1,Nt): + g_euler[i] = g_euler[i-1] + dt*(alpha*g_euler[i-1]*(A - g_euler[i-1])) + + # Print the errors done by each method + diff1 = np.max(np.abs(g_euler - g_analytical)) + diff2 = np.max(np.abs(g_dnn_ag[0,:] - g_analytical)) + + print('Max absolute difference between Euler method and analytical: %g'%diff1) + print('Max absolute difference between deep neural network and analytical: %g'%diff2) + + # Plot results + plt.figure(figsize=(10,10)) + + plt.plot(t,g_euler) + plt.plot(t,g_analytical) + plt.plot(t,g_dnn_ag[0,:]) + + plt.legend(['euler','analytical','dnn']) + plt.xlabel('Time t') + plt.ylabel('g(t)') + + plt.show() +!ec + + + +!split +===== Example: Solving the one dimensional Poisson equation ===== + +The Poisson equation for $g(x)$ in one dimension is + +!bt +\begin{equation} \label{poisson} + -g''(x) = f(x) +\end{equation} +!et + +where $f(x)$ is a given function for $x \in (0,1)$. + +The conditions that $g(x)$ is chosen to fulfill, are +!bt +\begin{align*} + g(0) &= 0 \\ + g(1) &= 0 +\end{align*} +!et + +This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used. +The results from the networks can then be compared to the analytical solution. +In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks. + +!split +===== The specific equation to solve for ===== + +Here, the function $g(x)$ to solve for follows the equation + +!bt +-g''(x) = f(x),\qquad x \in (0,1) +!et + +where $f(x)$ is a given function, along with the chosen conditions + +!bt +\begin{aligned} +g(0) = g(1) = 0 +\end{aligned}\label{cond} +!et + +In this example, we consider the case when $f(x) = (3x + x^2)\exp(x)$. + +For this case, a possible trial solution satisfying the conditions could be + +!bt +g_t(x) = x \cdot (1-x) \cdot N(P,x) +!et + +The analytical solution for this problem is + +!bt +g(x) = x(1 - x)\exp(x) +!et + +!split +===== Solving the equation using Autograd ===== + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # N_hidden is the number of hidden layers + N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + # Due to multiple hidden layers, define a variable referencing to the + # output of the previous layer: + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output + +def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb): + # num_hidden_neurons is now a list of number of neurons within each hidden layer + + # Find the number of hidden layers: + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 ) + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: %g'%cost_function_deep(P, x)) + + ## Start finding the optimal weigths using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_deep_grad = grad(cost_function_deep,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases + # in the hidden layers and output layers evaluated at x. + cost_deep_grad = cost_function_deep_grad(P, x) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_deep_grad[l] + + print('Final cost: %g'%cost_function_deep(P, x)) + + return P + +## Set up the cost function specified for this Poisson equation: + +# The right side of the ODE +def f(x): + return (3*x + x**2)*np.exp(x) + +def cost_function_deep(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial_deep(x,P) + + # Find the derivative w.r.t x of the trial function + d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P) + + right_side = f(x) + + err_sqr = (-d2_g_t - right_side)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum/np.size(err_sqr) + +# The trial solution: +def g_trial_deep(x,P): + return x*(1-x)*deep_neural_network(P,x) + +# The analytic solution; +def g_analytic(x): + return x*(1-x)*np.exp(x) + +if __name__ == '__main__': + npr.seed(4155) + + ## Decide the vales of arguments to the function to solve + Nx = 10 + x = np.linspace(0,1, Nx) + + ## Set up the initial parameters + num_hidden_neurons = [200,100] + num_iter = 1000 + lmb = 1e-3 + + P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb) + + g_dnn_ag = g_trial_deep(x,P) + g_analytical = g_analytic(x) + + # Find the maximum absolute difference between the solutons: + max_diff = np.max(np.abs(g_dnn_ag - g_analytical)) + print("The max absolute difference between the solutions is: %g"%max_diff) + + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(x, g_analytical) + plt.plot(x, g_dnn_ag[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('x') + plt.ylabel('g(x)') + plt.show() +!ec + +!split +===== Comparing with a numerical scheme ===== + +The Poisson equation is possible to solve using Taylor series to approximate the second derivative. + +Using Taylor series, the second derivative can be expressed as + +$$ +g''(x) = \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2} + E_{\Delta x}(x) +$$ + +where $\Delta x$ is a small step size and $E_{\Delta x}(x)$ being the error term. + +Looking away from the error terms gives an approximation to the second derivative: + +!bt +\begin{equation} \label{approx} +g''(x) \approx \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2} +\end{equation} +!et + +If $x_i = i \Delta x = x_{i-1} + \Delta x$ and $g_i = g(x_i)$ for $i = 1,\dots N_x - 2$ with $N_x$ being the number of values for $x$, (ref{approx}) becomes + +!bt +\begin{aligned} +g''(x_i) &\approx \frac{g(x_i + \Delta x) - 2g(x_i) + g(x_i -\Delta x)}{\Delta x^2} \\ +&= \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2} +\end{aligned} +!et + +Since we know from our problem that + +!bt +\begin{aligned} +-g''(x) &= f(x) \\ +&= (3x + x^2)\exp(x) +\end{aligned} +!et + +along with the conditions $g(0) = g(1) = 0$, +the following scheme can be used to find an approximate solution for $g(x)$ numerically: + +!bt +\begin{equation} + \begin{aligned} + -\Big( \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2} \Big) &= f(x_i) \\ + -g_{i+1} + 2g_i - g_{i-1} &= \Delta x^2 f(x_i) + \end{aligned} +\end{equation} \label{odesys} +!et + +for $i = 1, \dots, N_x - 2$ where $g_0 = g_{N_x - 1} = 0$ and $f(x_i) = (3x_i + x_i^2)\exp(x_i)$, which is given for our specific problem. + +The equation can be rewritten into a matrix equation: + +!bt +\begin{aligned} +\begin{pmatrix} +2 & -1 & 0 & \dots & 0 \\ +-1 & 2 & -1 & \dots & 0 \\ +\vdots & & \ddots & & \vdots \\ +0 & \dots & -1 & 2 & -1 \\ +0 & \dots & 0 & -1 & 2\\ +\end{pmatrix} +\begin{pmatrix} +g_1 \\ +g_2 \\ +\vdots \\ +g_{N_x - 3} \\ +g_{N_x - 2} +\end{pmatrix} +&= +\Delta x^2 +\begin{pmatrix} +f(x_1) \\ +f(x_2) \\ +\vdots \\ +f(x_{N_x - 3}) \\ +f(x_{N_x - 2}) +\end{pmatrix} \\ +\bm{A}\bm{g} &= \bm{f}, +\end{aligned} +!et + +which makes it possible to solve for the vector $\bm{g}$. + +!split +===== Setting up the code ===== + +We can then compare the result from this numerical scheme with the output from our network using Autograd: + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # N_hidden is the number of hidden layers + N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + # Due to multiple hidden layers, define a variable referencing to the + # output of the previous layer: + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output + +def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb): + # num_hidden_neurons is now a list of number of neurons within each hidden layer + + # Find the number of hidden layers: + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 ) + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: %g'%cost_function_deep(P, x)) + + ## Start finding the optimal weigths using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_deep_grad = grad(cost_function_deep,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases + # in the hidden layers and output layers evaluated at x. + cost_deep_grad = cost_function_deep_grad(P, x) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_deep_grad[l] + + print('Final cost: %g'%cost_function_deep(P, x)) + + return P + +## Set up the cost function specified for this Poisson equation: + +# The right side of the ODE +def f(x): + return (3*x + x**2)*np.exp(x) + +def cost_function_deep(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial_deep(x,P) + + # Find the derivative w.r.t x of the trial function + d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P) + + right_side = f(x) + + err_sqr = (-d2_g_t - right_side)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum/np.size(err_sqr) + +# The trial solution: +def g_trial_deep(x,P): + return x*(1-x)*deep_neural_network(P,x) + +# The analytic solution; +def g_analytic(x): + return x*(1-x)*np.exp(x) + +if __name__ == '__main__': + npr.seed(4155) + + ## Decide the vales of arguments to the function to solve + Nx = 10 + x = np.linspace(0,1, Nx) + + ## Set up the initial parameters + num_hidden_neurons = [200,100] + num_iter = 1000 + lmb = 1e-3 + + P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb) + + g_dnn_ag = g_trial_deep(x,P) + g_analytical = g_analytic(x) + + # Find the maximum absolute difference between the solutons: + + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(x, g_analytical) + plt.plot(x, g_dnn_ag[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('x') + plt.ylabel('g(x)') + + ## Perform the computation using the numerical scheme + + dx = 1/(Nx - 1) + + # Set up the matrix A + A = np.zeros((Nx-2,Nx-2)) + + A[0,0] = 2 + A[0,1] = -1 + + for i in range(1,Nx-3): + A[i,i-1] = -1 + A[i,i] = 2 + A[i,i+1] = -1 + + A[Nx - 3, Nx - 4] = -1 + A[Nx - 3, Nx - 3] = 2 + + # Set up the vector f + f_vec = dx**2 * f(x[1:-1]) + + # Solve the equation + g_res = np.linalg.solve(A,f_vec) + + g_vec = np.zeros(Nx) + g_vec[1:-1] = g_res + + # Print the differences between each method + max_diff1 = np.max(np.abs(g_dnn_ag - g_analytical)) + max_diff2 = np.max(np.abs(g_vec - g_analytical)) + print("The max absolute difference between the analytical solution and DNN Autograd: %g"%max_diff1) + print("The max absolute difference between the analytical solution and numerical scheme: %g"%max_diff2) + + # Plot the results + plt.figure(figsize=(10,10)) + + plt.plot(x,g_vec) + plt.plot(x,g_analytical) + plt.plot(x,g_dnn_ag[0,:]) + + plt.legend(['numerical scheme','analytical','dnn']) + plt.show() + +!ec + + + +!split +===== Partial Differential Equations ===== + +A partial differential equation (PDE) has a solution here the function +is defined by multiple variables. The equation may involve all kinds +of combinations of which variables the function is differentiated with +respect to. + +In general, a partial differential equation for a function $g(x_1,\dots,x_N)$ with $N$ variables may be expressed as + +!bt +\begin{equation} \label{PDE} + f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) = 0 +\end{equation} +!et + +where $f$ is an expression involving all kinds of possible mixed derivatives of $g(x_1,\dots,x_N)$ up to an order $n$. In order for the solution to be unique, some additional conditions must also be given. + +!split +===== Type of problem ===== + +The problem our network must solve for, is similar to the ODE case. +We must have a trial solution $g_t$ at hand. + +For instance, the trial solution could be expressed as +!bt +\begin{align*} + g_t(x_1,\dots,x_N) = h_1(x_1,\dots,x_N) + h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P)) +\end{align*} +!et +where $h_1(x_1,\dots,x_N)$ is a function that ensures $g_t(x_1,\dots,x_N)$ satisfies some given conditions. +The neural network $N(x_1,\dots,x_N,P)$ has weights and biases described by $P$ and $h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P))$ is an expression using the output from the neural network in some way. + +The role of the function $h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P))$, is to ensure that the output of $N(x_1,\dots,x_N,P)$ is zero when $g_t(x_1,\dots,x_N)$ is evaluated at the values of $x_1,\dots,x_N$ where the given conditions must be satisfied. The function $h_1(x_1,\dots,x_N)$ should alone make $g_t(x_1,\dots,x_N)$ satisfy the conditions. + + +!split +===== Network requirements ===== + +The network tries then the minimize the cost function following the +same ideas as described for the ODE case, but now with more than one +variables to consider. The concept still remains the same; find a set +of parameters $P$ such that the expression $f$ in (ref{PDE}) is as +close to zero as possible. + +As for the ODE case, the cost function is the mean squared error that +the network must try to minimize. The cost function for the network to +minimize is + +!bt +\begin{equation*} +C\left(x_1, \dots, x_N, P\right) = \left( f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) \right)^2 +\end{equation*} +!et + +!split +===== More details ===== + +If we let $\bm{x} = \big( x_1, \dots, x_N \big)$ be an array containing the values for $x_1, \dots, x_N$ respectively, the cost function can be reformulated into the following: +!bt +\[ + C\left(\bm{x}, P\right) = f\left( \left( \bm{x}, \frac{\partial g(\bm{x}) }{\partial x_1}, \dots , \frac{\partial g(\bm{x}) }{\partial x_N}, \frac{\partial g(\bm{x}) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\bm{x}) }{\partial x_N^n} \right) \right)^2 +\] +!et + +If we also have $M$ different sets of values for $x_1, \dots, x_N$, that is $\bm{x}_i = \big(x_1^{(i)}, \dots, x_N^{(i)}\big)$ for $i = 1,\dots,M$ being the rows in matrix $X$, the cost function can be generalized into +!bt +\begin{equation*} +C\left(X, P \right) = \sum_{i=1}^M f\left( \left( \bm{x}_i, \frac{\partial g(\bm{x}_i) }{\partial x_1}, \dots , \frac{\partial g(\bm{x}_i) }{\partial x_N}, \frac{\partial g(\bm{x}_i) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\bm{x}_i) }{\partial x_N^n} \right) \right)^2. +\end{equation*} +!et + +!split +===== Example: The diffusion equation ===== + +In one spatial dimension, the equation reads +!bt +\begin{equation*} + \frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2} +\end{equation*} +!et + +where a possible choice of conditions are +!bt +\begin{align*} +g(0,t) &= 0 ,\qquad t \geq 0 \\ +g(1,t) &= 0, \qquad t \geq 0 \\ +g(x,0) &= u(x),\qquad x\in [0,1] +\end{align*} +!et +with $u(x)$ being some given function. + +!split +===== Defining the problem ===== + +For this case, we want to find $g(x,t)$ such that + +!bt +\begin{equation} + \frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2} +\end{equation} \label{diffonedim} +!et + +and + +!bt +\begin{align*} +g(0,t) &= 0 ,\qquad t \geq 0 \\ +g(1,t) &= 0, \qquad t \geq 0 \\ +g(x,0) &= u(x),\qquad x\in [0,1] +\end{align*} +!et +with $u(x) = \sin(\pi x)$. + +First, let us set up the deep neural network. +The deep neural network will follow the same structure as discussed in the examples solving the ODEs. +First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions. + + + +!split +===== Setting up the network using Autograd ===== + +The only change to do here, is to extend our network such that +functions of multiple parameters are correctly handled. In this case +we have two variables in our function to solve for, that is time $t$ +and position $x$. The variables will be represented by a +one-dimensional array in the program. The program will evaluate the +network at each possible pair $(x,t)$, given an array for the desired +$x$-values and $t$-values to approximate the solution at. + +!bc pycod +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # x is now a point and a 1D numpy array; make it a column vector + num_coordinates = np.size(x,0) + x = x.reshape(num_coordinates,-1) + + num_points = np.size(x,1) + + # N_hidden is the number of hidden layers + N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer + + # Assume that the input layer does nothing to the input x + x_input = x + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output[0][0] +!ec + +!split +===== Setting up the network using Autograd; The trial solution ===== + +The cost function must then iterate through the given arrays +containing values for $x$ and $t$, defines a point $(x,t)$ the deep +neural network and the trial solution is evaluated at, and then finds +the Jacobian of the trial solution. + +A possible trial solution for this PDE is + +$$ +g_t(x,t) = h_1(x,t) + x(1-x)tN(x,t,P) +$$ + +with $A(x,t)$ being a function ensuring that $g_t(x,t)$ satisfies our given conditions, and $N(x,t,P)$ being the output from the deep neural network using weights and biases for each layer from $P$. + +To fulfill the conditions, $A(x,t)$ could be: + +$$ +h_1(x,t) = (1-t)\Big(u(x) - \big((1-x)u(0) + x u(1)\big)\Big) = (1-t)u(x) = (1-t)\sin(\pi x) +$$ +since $(0) = u(1) = 0$ and $u(x) = \sin(\pi x)$. + +!split +===== Why the jacobian? ===== + +The Jacobian is used because the program must find the derivative of +the trial solution with respect to $x$ and $t$. + +This gives the necessity of computing the Jacobian matrix, as we want +to evaluate the gradient with respect to $x$ and $t$ (note that the +Jacobian of a scalar-valued multivariate function is simply its +gradient). + +In Autograd, the differentiation is by default done with respect to +the first input argument of your Python function. Since the points is +an array representing $x$ and $t$, the Jacobian is calculated using +the values of $x$ and $t$. + +To find the second derivative with respect to $x$ and $t$, the +Jacobian can be found for the second time. The result is a Hessian +matrix, which is the matrix containing all the possible second order +mixed derivatives of $g(x,t)$. + +!bc pycod +# Set up the trial function: +def u(x): + return np.sin(np.pi*x) + +def g_trial(point,P): + x,t = point + return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point) + +# The right side of the ODE: +def f(point): + return 0. + +# The cost function: +def cost_function(P, x, t): + cost_sum = 0 + + g_t_jacobian_func = jacobian(g_trial) + g_t_hessian_func = hessian(g_trial) + + for x_ in x: + for t_ in t: + point = np.array([x_,t_]) + + g_t = g_trial(point,P) + g_t_jacobian = g_t_jacobian_func(point,P) + g_t_hessian = g_t_hessian_func(point,P) + + g_t_dt = g_t_jacobian[1] + g_t_d2x = g_t_hessian[0][0] + + func = f(point) + + err_sqr = ( (g_t_dt - g_t_d2x) - func)**2 + cost_sum += err_sqr + + return cost_sum +!ec + +!split +===== Setting up the network using Autograd; The full program ===== + +Having set up the network, along with the trial solution and cost function, we can now see how the deep neural network performs by comparing the results to the analytical solution. + +The analytical solution of our problem is + +$$ +g(x,t) = \exp(-\pi^2 t)\sin(\pi x) +$$ + +A possible way to implement a neural network solving the PDE, is given below. +Be aware, though, that it is fairly slow for the parameters used. +A better result is possible, but requires more iterations, and thus longer time to complete. + + +Indeed, the program below is not optimal in its implementation, but rather serves as an example on how to implement and use a neural network to solve a PDE. +Using TensorFlow results in a much better execution time. Try it! + +!bc pycod +import autograd.numpy as np +from autograd import jacobian,hessian,grad +import autograd.numpy.random as npr +from matplotlib import cm +from matplotlib import pyplot as plt +from mpl_toolkits.mplot3d import axes3d + +## Set up the network + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # x is now a point and a 1D numpy array; make it a column vector + num_coordinates = np.size(x,0) + x = x.reshape(num_coordinates,-1) + + num_points = np.size(x,1) + + # N_hidden is the number of hidden layers + N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer + + # Assume that the input layer does nothing to the input x + x_input = x + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output[0][0] + +## Define the trial solution and cost function +def u(x): + return np.sin(np.pi*x) + +def g_trial(point,P): + x,t = point + return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point) + +# The right side of the ODE: +def f(point): + return 0. + +# The cost function: +def cost_function(P, x, t): + cost_sum = 0 + + g_t_jacobian_func = jacobian(g_trial) + g_t_hessian_func = hessian(g_trial) + + for x_ in x: + for t_ in t: + point = np.array([x_,t_]) + + g_t = g_trial(point,P) + g_t_jacobian = g_t_jacobian_func(point,P) + g_t_hessian = g_t_hessian_func(point,P) + + g_t_dt = g_t_jacobian[1] + g_t_d2x = g_t_hessian[0][0] + + func = f(point) + + err_sqr = ( (g_t_dt - g_t_d2x) - func)**2 + cost_sum += err_sqr + + return cost_sum /( np.size(x)*np.size(t) ) + +## For comparison, define the analytical solution +def g_analytic(point): + x,t = point + return np.exp(-np.pi**2*t)*np.sin(np.pi*x) + +## Set up a function for training the network to solve for the equation +def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb): + ## Set up initial weigths and biases + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: ',cost_function(P, x, t)) + + cost_function_grad = grad(cost_function,0) + + # Let the update be done num_iter times + for i in range(num_iter): + cost_grad = cost_function_grad(P, x , t) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_grad[l] + + print('Final cost: ',cost_function(P, x, t)) + + return P + +if __name__ == '__main__': + ### Use the neural network: + npr.seed(15) + + ## Decide the vales of arguments to the function to solve + Nx = 10; Nt = 10 + x = np.linspace(0, 1, Nx) + t = np.linspace(0,1,Nt) + + ## Set up the parameters for the network + num_hidden_neurons = [100, 25] + num_iter = 250 + lmb = 0.01 + + P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb) + + ## Store the results + g_dnn_ag = np.zeros((Nx, Nt)) + G_analytical = np.zeros((Nx, Nt)) + for i,x_ in enumerate(x): + for j, t_ in enumerate(t): + point = np.array([x_, t_]) + g_dnn_ag[i,j] = g_trial(point,P) + + G_analytical[i,j] = g_analytic(point) + + # Find the map difference between the analytical and the computed solution + diff_ag = np.abs(g_dnn_ag - G_analytical) + print('Max absolute difference between the analytical solution and the network: %g'%np.max(diff_ag)) + + ## Plot the solutions in two dimensions, that being in position and time + + T,X = np.meshgrid(t,x) + + fig = plt.figure(figsize=(10,10)) + ax = fig.gca(projection='3d') + ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons)) + s = ax.plot_surface(T,X,g_dnn_ag,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + + fig = plt.figure(figsize=(10,10)) + ax = fig.gca(projection='3d') + ax.set_title('Analytical solution') + s = ax.plot_surface(T,X,G_analytical,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + fig = plt.figure(figsize=(10,10)) + ax = fig.gca(projection='3d') + ax.set_title('Difference') + s = ax.plot_surface(T,X,diff_ag,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + ## Take some slices of the 3D plots just to see the solutions at particular times + indx1 = 0 + indx2 = int(Nt/2) + indx3 = Nt-1 + + t1 = t[indx1] + t2 = t[indx2] + t3 = t[indx3] + + # Slice the results from the DNN + res1 = g_dnn_ag[:,indx1] + res2 = g_dnn_ag[:,indx2] + res3 = g_dnn_ag[:,indx3] + + # Slice the analytical results + res_analytical1 = G_analytical[:,indx1] + res_analytical2 = G_analytical[:,indx2] + res_analytical3 = G_analytical[:,indx3] + + # Plot the slices + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t1) + plt.plot(x, res1) + plt.plot(x,res_analytical1) + plt.legend(['dnn','analytical']) + + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t2) + plt.plot(x, res2) + plt.plot(x,res_analytical2) + plt.legend(['dnn','analytical']) + + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t3) + plt.plot(x, res3) + plt.plot(x,res_analytical3) + plt.legend(['dnn','analytical']) + + plt.show() +!ec + +!split +===== Example: Solving the wave equation with Neural Networks ===== + +The wave equation is +!bt +\begin{equation*} + \frac{\partial^2 g(x,t)}{\partial t^2} = c^2\frac{\partial^2 g(x,t)}{\partial x^2} +\end{equation*} +!et + +with $c$ being the specified wave speed. + +Here, the chosen conditions are +!bt +\begin{align*} + g(0,t) &= 0 \\ + g(1,t) &= 0 \\ + g(x,0) &= u(x) \\ + \frac{\partial g(x,t)}{\partial t} \Big |_{t = 0} &= v(x) +\end{align*} +!et +where $\frac{\partial g(x,t)}{\partial t} \Big |_{t = 0}$ means the derivative of $g(x,t)$ with respect to $t$ is evaluated at $t = 0$, and $u(x)$ and $v(x)$ being given functions. + +!split +===== The problem to solve for ===== + +The wave equation to solve for, is + +!bt +\begin{equation} \label{wave} +\frac{\partial^2 g(x,t)}{\partial t^2} = c^2 \frac{\partial^2 g(x,t)}{\partial x^2} +\end{equation} +!et + +where $c$ is the given wave speed. +The chosen conditions for this equation are + +!bt +\begin{aligned} +g(0,t) &= 0, &t \geq 0 \\ +g(1,t) &= 0, &t \geq 0 \\ +g(x,0) &= u(x), &x\in[0,1] \\ +\frac{\partial g(x,t)}{\partial t}\Big |_{t = 0} &= v(x), &x \in [0,1] +\end{aligned} \label{condwave} +!et + +In this example, let $c = 1$ and $u(x) = \sin(\pi x)$ and $v(x) = -\pi\sin(\pi x)$. + + +!split +===== The trial solution ===== +Setting up the network is done in similar matter as for the example of solving the diffusion equation. +The only things we have to change, is the trial solution such that it satisfies the conditions from (ref{condwave}) and the cost function. + +The trial solution becomes slightly different since we have other conditions than in the example of solving the diffusion equation. Here, a possible trial solution $g_t(x,t)$ is + +$$ +g_t(x,t) = h_1(x,t) + x(1-x)t^2N(x,t,P) +$$ + +where + +$$ +h_1(x,t) = (1-t^2)u(x) + tv(x) +$$ + +Note that this trial solution satisfies the conditions only if $u(0) = v(0) = u(1) = v(1) = 0$, which is the case in this example. + +!split +===== The analytical solution ===== + +The analytical solution for our specific problem, is + +$$ +g(x,t) = \sin(\pi x)\cos(\pi t) - \sin(\pi x)\sin(\pi t) +$$ + +!split +===== Solving the wave equation - the full program using Autograd ===== + +!bc pycod +import autograd.numpy as np +from autograd import hessian,grad +import autograd.numpy.random as npr +from matplotlib import cm +from matplotlib import pyplot as plt +from mpl_toolkits.mplot3d import axes3d + +## Set up the trial function: +def u(x): + return np.sin(np.pi*x) + +def v(x): + return -np.pi*np.sin(np.pi*x) + +def h1(point): + x,t = point + return (1 - t**2)*u(x) + t*v(x) + +def g_trial(point,P): + x,t = point + return h1(point) + x*(1-x)*t**2*deep_neural_network(P,point) + +## Define the cost function +def cost_function(P, x, t): + cost_sum = 0 + + g_t_hessian_func = hessian(g_trial) + + for x_ in x: + for t_ in t: + point = np.array([x_,t_]) + + g_t_hessian = g_t_hessian_func(point,P) + + g_t_d2x = g_t_hessian[0][0] + g_t_d2t = g_t_hessian[1][1] + + err_sqr = ( (g_t_d2t - g_t_d2x) )**2 + cost_sum += err_sqr + + return cost_sum / (np.size(t) * np.size(x)) + +## The neural network +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # x is now a point and a 1D numpy array; make it a column vector + num_coordinates = np.size(x,0) + x = x.reshape(num_coordinates,-1) + + num_points = np.size(x,1) + + # N_hidden is the number of hidden layers + N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer + + # Assume that the input layer does nothing to the input x + x_input = x + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output[0][0] + +## The analytical solution +def g_analytic(point): + x,t = point + return np.sin(np.pi*x)*np.cos(np.pi*t) - np.sin(np.pi*x)*np.sin(np.pi*t) + +def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb): + ## Set up initial weigths and biases + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: ',cost_function(P, x, t)) + + cost_function_grad = grad(cost_function,0) + + # Let the update be done num_iter times + for i in range(num_iter): + cost_grad = cost_function_grad(P, x , t) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_grad[l] + + + print('Final cost: ',cost_function(P, x, t)) + + return P + +if __name__ == '__main__': + ### Use the neural network: + npr.seed(15) + + ## Decide the vales of arguments to the function to solve + Nx = 10; Nt = 10 + x = np.linspace(0, 1, Nx) + t = np.linspace(0,1,Nt) + + ## Set up the parameters for the network + num_hidden_neurons = [50,20] + num_iter = 1000 + lmb = 0.01 + + P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb) + + ## Store the results + res = np.zeros((Nx, Nt)) + res_analytical = np.zeros((Nx, Nt)) + for i,x_ in enumerate(x): + for j, t_ in enumerate(t): + point = np.array([x_, t_]) + res[i,j] = g_trial(point,P) + + res_analytical[i,j] = g_analytic(point) + + diff = np.abs(res - res_analytical) + print("Max difference between analytical and solution from nn: %g"%np.max(diff)) + + ## Plot the solutions in two dimensions, that being in position and time + + T,X = np.meshgrid(t,x) + + fig = plt.figure(figsize=(10,10)) + ax = fig.gca(projection='3d') + ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons)) + s = ax.plot_surface(T,X,res,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + + fig = plt.figure(figsize=(10,10)) + ax = fig.gca(projection='3d') + ax.set_title('Analytical solution') + s = ax.plot_surface(T,X,res_analytical,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + + fig = plt.figure(figsize=(10,10)) + ax = fig.gca(projection='3d') + ax.set_title('Difference') + s = ax.plot_surface(T,X,diff,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + ## Take some slices of the 3D plots just to see the solutions at particular times + indx1 = 0 + indx2 = int(Nt/2) + indx3 = Nt-1 + + t1 = t[indx1] + t2 = t[indx2] + t3 = t[indx3] + + # Slice the results from the DNN + res1 = res[:,indx1] + res2 = res[:,indx2] + res3 = res[:,indx3] + + # Slice the analytical results + res_analytical1 = res_analytical[:,indx1] + res_analytical2 = res_analytical[:,indx2] + res_analytical3 = res_analytical[:,indx3] + + # Plot the slices + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t1) + plt.plot(x, res1) + plt.plot(x,res_analytical1) + plt.legend(['dnn','analytical']) + + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t2) + plt.plot(x, res2) + plt.plot(x,res_analytical2) + plt.legend(['dnn','analytical']) + + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t3) + plt.plot(x, res3) + plt.plot(x,res_analytical3) + plt.legend(['dnn','analytical']) + + plt.show() +!ec + +!split +===== Resources on differential equations and deep learning ===== + +o "Artificial neural networks for solving ordinary and partial differential equations by I.E. Lagaris et al":"https://pdfs.semanticscholar.org/d061/df393e0e8fbfd0ea24976458b7d42419040d.pdf" +o "Neural networks for solving differential equations by A. Honchar":"https://becominghuman.ai/neural-networks-for-solving-differential-equations-fa230ac5e04c" +o "Solving differential equations using neural networks by M.M Chiaramonte and M. Kiener":"http://cs229.stanford.edu/proj2013/ChiaramonteKiener-SolvingDifferentialEquationsUsingNeuralNetworks.pdf" +o "Introduction to Partial Differential Equations by A. Tveito, R. Winther":"https://www.springer.com/us/book/9783540225515" + + + + + + + + + +!split +===== Convolutional Neural Networks (recognizing images) ===== + + +Convolutional neural networks (CNNs) were developed during the last +decade of the previous century, with a focus on character recognition +tasks. Nowadays, CNNs are a central element in the spectacular success +of deep learning methods. The success in for example image +classifications have made them a central tool for most machine +learning practitioners. + +CNNs are very similar to ordinary Neural Networks. +They are made up of neurons that have learnable weights and +biases. Each neuron receives some inputs, performs a dot product and +optionally follows it with a non-linearity. The whole network still +expresses a single differentiable score function: from the raw image +pixels on one end to class scores at the other. And they still have a +loss function (for example Softmax) on the last (fully-connected) layer +and all the tips/tricks we developed for learning regular Neural +Networks still apply (back propagation, gradient descent etc etc). + +!split +===== What is the Difference ===== + +_CNN architectures make the explicit assumption that +the inputs are images, which allows us to encode certain properties +into the architecture. These then make the forward function more +efficient to implement and vastly reduce the amount of parameters in +the network._ + +Here we provide only a superficial overview, for the more interested, we recommend highly the course +"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" +and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/". + +Another good read is the article here URL:"https://arxiv.org/pdf/1603.07285.pdf". + + + + +!split +===== Neural Networks vs CNNs ===== + +Neural networks are defined as _affine transformations_, that is +a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an +output (to which a bias vector is usually added before passing the result +through a nonlinear activation function). This is applicable to any type of input, be it an +image, a sound clip or an unordered collection of features: whatever their +dimensionality, their representation can always be flattened into a vector +before the transformation. + + +!split +===== Why CNNS for images, sound files, medical images from CT scans etc? ===== + +However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic +structure. More formally, they share these important properties: +* They are stored as multi-dimensional arrays (think of the pixels of a figure) . +* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip). +* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track). + +These properties are not exploited when an affine transformation is applied; in +fact, all the axes are treated in the same way and the topological information +is not taken into account. Still, taking advantage of the implicit structure of +the data may prove very handy in solving some tasks, like computer vision and +speech recognition, and in these cases it would be best to preserve it. This is +where discrete convolutions come into play. + +A discrete convolution is a linear transformation that preserves this notion of +ordering. It is sparse (only a few input units contribute to a given output +unit) and reuses parameters (the same weights are applied to multiple locations +in the input). + + + + +!split +===== Regular NNs don’t scale well to full images ===== + +As an example, consider +an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a +single fully-connected neuron in a first hidden layer of a regular +Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still +seems manageable, but clearly this fully-connected structure does not +scale to larger images. For example, an image of more respectable +size, say $200\times 200\times 3$, would lead to neurons that have +$200\times 200\times 3 = 120,000$ weights. + +We could have +several such neurons, and the parameters would add up quickly! Clearly, +this full connectivity is wasteful and the huge number of parameters +would quickly lead to possible overfitting. + +FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network. + +!split +===== 3D volumes of neurons ===== + +Convolutional Neural Networks take advantage of the fact that the +input consists of images and they constrain the architecture in a more +sensible way. + +In particular, unlike a regular Neural Network, the +layers of a CNN have neurons arranged in 3 dimensions: width, +height, depth. (Note that the word depth here refers to the third +dimension of an activation volume, not to the depth of a full Neural +Network, which can refer to the total number of layers in a network.) + +To understand it better, the above example of an image +with an input volume of +activations has dimensions $32\times 32\times 3$ (width, height, +depth respectively). + +The neurons in a layer will +only be connected to a small region of the layer before it, instead of +all of the neurons in a fully-connected manner. Moreover, the final +output layer could for this specific image have dimensions $1\times 1 \times 10$, +because by the +end of the CNN architecture we will reduce the full image into a +single vector of class scores, arranged along the depth +dimension. + +FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). + + + +!split +===== Layers used to build CNNs ===== + + +A simple CNN is a sequence of layers, and every layer of a CNN +transforms one volume of activations to another through a +differentiable function. We use three main types of layers to build +CNN architectures: Convolutional Layer, Pooling Layer, and +Fully-Connected Layer (exactly as seen in regular Neural Networks). We +will stack these layers to form a full CNN architecture. + +A simple CNN for image classification could have the architecture: + +* _INPUT_ ($32\times 32 \times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B. +* _CONV_ (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters. +* _RELU_ layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\times 32\times 12]$). +* _POOL_ (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$. +* _FC_ (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\times 1\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume. + + +!split +===== Transforming images ===== + +CNNs transform the original image layer by layer from the original +pixel values to the final class scores. + +Observe that some layers contain +parameters and other don’t. In particular, the CNN layers perform +transformations that are a function of not only the activations in the +input volume, but also of the parameters (the weights and biases of +the neurons). On the other hand, the RELU/POOL layers will implement a +fixed function. The parameters in the CONV/FC layers will be trained +with gradient descent so that the class scores that the CNN computes +are consistent with the labels in the training set for each image. + + +!split +===== CNNs in brief ===== + +In summary: + +* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores) +* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular) +* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function +* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t) +* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t) + +For more material on convolutional networks, we strongly recommend +the course +"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" +and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/" which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). "Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs":"http://neuralnetworksanddeeplearning.com/chap6.html". + +The textbook by Goodfellow et al, see chapter 9 contains an in depth discussion as well. + +!split +===== Key Idea ===== + +A dense neural network is representd by an affine operation (like matrix-matrix multiplication) where all parameters are included. + +The key idea in CNNs for say imaging is that in images neighbor pixels tend to be related! So we connect +only neighboring neurons in the input instead of connecting all with the first hidden layer. + +We say we perform a filtering (convolution is the mathematical operation). + + +!split +===== Mathematics of CNNs ===== + +The mathematics of CNNs is based on the mathematical operation of +_convolution_. In mathematics (in particular in functional analysis), +convolution is represented by mathematical operation (integration, +summation etc) on two function in order to produce a third function +that expresses how the shape of one gets modified by the other. +Convolution has a plethora of applications in a variety of disciplines, spanning from statistics to signal processing, computer vision, solutions of differential equations,linear algebra, engineering, and yes, machine learning. + +Mathematically, convolution is defined as follows (one-dimensional example): +Let us define a continuous function $y(t)$ given by +!bt +\[ +y(t) = \int x(a) w(t-a) da, +\] +!et +where $x(a)$ represents a so-called input and $w(t-a)$ is normally called the weight function or kernel. + +The above integral is written in a more compact form as +!bt +\[ +y(t) = \left(x * w\right)(t). +\] +!et + +The discretized version reads +!bt +\[ +y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a). +\] +!et +Computing the inverse of the above convolution operations is known as deconvolution. + +How can we use this? And what does it mean? Let us study some familiar examples first. + + +!split +===== Convolution Examples: Polynomial multiplication ===== + +We have already met such an example in project 1 when we tried to set +up the design matrix for a two-dimensional function. This was an +example of polynomial multiplication. Let us recast such a problem in terms of the convolution operation. +Let us look a the following polynomials to second and third order, respectively: +!bt +\[ +p(t) = \alpha_0+\alpha_1 t+\alpha_2 t^2, +\] +!et +and +!bt +\[ +s(t) = \beta_0+\beta_1 t+\beta_2 t^2+\beta_3 t^3. +\] +!et + +The polynomial multiplication gives us a new polynomial of degree $5$ +!bt +\[ +z(t) = \delta_0+\delta_1 t+\delta_2 t^2+\delta_3 t^3+\delta_4 t^4+\delta_5 t^5. +\] +!et + +!split +===== Efficient Polynomial Multiplication ===== + +Computing polynomial products can be implemented efficiently if we rewrite the more brute force multiplications using convolution. +We note first that the new coefficients are given as + +!bt +\begin{split} +\delta_0=&\alpha_0\beta_0\\ +\delta_1=&\alpha_1\beta_0+\alpha_1\beta_0\\ +\delta_2=&\alpha_0\beta_2+\alpha_1\beta_1+\alpha_2\beta_0\\ +\delta_3=&\alpha_1\beta_2+\alpha_2\beta_1+\alpha_0\beta_3\\ +\delta_4=&\alpha_2\beta_2+\alpha_1\beta_3\\ +\delta_5=&\alpha_2\beta_3.\\ +\end{split} +!et + + +We note that $\alpha_i=0$ except for $i\in \left\{0,1,2\right\}$ and $\beta_i=0$ except for $i\in\left\{0,1,2,3\right\}$. + +We can then rewrite the coefficients $\delta_j$ using a discrete convolution as +!bt +\[ +\delta_j = \sum_{i=-\infty}^{i=\infty}\alpha_i\beta_{j-i}=(\alpha * \beta)_j, +\] +!et +or as a double sum with restriction $l=i+j$ +!bt +\[ +\delta_l = \sum_{ij}\alpha_i\beta_{j}. +\] +!et + +Do you see a potential drawback with these equations? + +!split +===== A more efficient way of coding the above Convolution ===== + +Since we only have a finite number of $\alpha$ and $\beta$ values +which are non-zero, we can rewrite the above convolution expressions +as a matrix-vector multiplication + +!bt +\[ +\bm{\delta}=\begin{bmatrix}\alpha_0 & 0 & 0 & 0 \\ + \alpha_1 & \alpha_0 & 0 & 0 \\ + \alpha_2 & \alpha_1 & \alpha_0 & 0 \\ + 0 & \alpha_2 & \alpha_1 & \alpha_0 \\ + 0 & 0 & \alpha_2 & \alpha_1 \\ + 0 & 0 & 0 & \alpha_2 + \end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}. +\] +!et + +The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding $\beta$ and a vector holding $\alpha$. +In this case we have +!bt +\[ +\bm{\delta}=\begin{bmatrix}\beta_0 & 0 & 0 \\ + \beta_1 & \beta_0 & 0 \\ + \beta_2 & \beta_1 & \beta_0 \\ + \beta_3 & \beta_2 & \beta_1 \\ + 0 & \beta_3 & \beta_2 \\ + 0 & 0 & \beta_3 + \end{bmatrix}\begin{bmatrix} \alpha_0 \\ \alpha_1 \\ \alpha_2\end{bmatrix}. +\] +!et + +Note that the use of these matrices is for mathematical purposes only and not implementation purposes. +When implementing the above equation we do not encode (and allocate memory) the matrices explicitely. +We rather code the convolutions in the minimal memory footprint that they require. + +Does the number of floating point operations change here when we use the commutative property? + +!split +===== Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms) ===== + +For problems with so-called harmonic oscillations, given by for example the following differential equation +!bt +\[ +m\frac{d^2x}{dt^2}+\eta\frac{dx}{dt}+x(t)=F(t), +\] +!et +where $F(t)$ is an applied external force acting on the system (often called a driving force), one can use the theory of Fourier transformations to find the solutions of this type of equations. + +If one has several driving forces, $F(t)=\sum_n F_n(t)$, one can find +the particular solution to each $F_n$, $x_{pn}(t)$, and the particular +solution for the entire driving force is then given by a series like + +!bt +\begin{equation} +x_p(t)=\sum_nx_{pn}(t). +\end{equation} +!et + +!split +===== Principle of Superposition ===== + +This is known as the principle of superposition. It only applies when +the homogenous equation is linear. If there were an anharmonic term +such as $x^3$ in the homogenous equation, then when one summed various +solutions, $x=(\sum_n x_n)^2$, one would get cross +terms. Superposition is especially useful when $F(t)$ can be written +as a sum of sinusoidal terms, because the solutions for each +sinusoidal (sine or cosine) term is analytic. + +Driving forces are often periodic, even when they are not +sinusoidal. Periodicity implies that for some time $\tau$ + +!bt +\begin{eqnarray} +F(t+\tau)=F(t). +\end{eqnarray} +!et + +One example of a non-sinusoidal periodic force is a square wave. Many +components in electric circuits are non-linear, e.g. diodes, which +makes many wave forms non-sinusoidal even when the circuits are being +driven by purely sinusoidal sources. + +!split +===== Simple Code Example ===== + +The code here shows a typical example of such a square wave generated using the functionality included in the _scipy_ Python package. We have used a period of $\tau=0.2$. + +!bc pycod +import numpy as np +import math +from scipy import signal +import matplotlib.pyplot as plt + +# number of points +n = 500 +# start and final times +t0 = 0.0 +tn = 1.0 +# Period +t = np.linspace(t0, tn, n, endpoint=False) +SqrSignal = np.zeros(n) +SqrSignal = 1.0+signal.square(2*np.pi*5*t) +plt.plot(t, SqrSignal) +plt.ylim(-0.5, 2.5) +plt.show() +!ec + + +For the sinusoidal example the +period is $\tau=2\pi/\omega$. However, higher harmonics can also +satisfy the periodicity requirement. In general, any force that +satisfies the periodicity requirement can be expressed as a sum over +harmonics, + +!bt +\begin{equation} +F(t)=\frac{f_0}{2}+\sum_{n>0} f_n\cos(2n\pi t/\tau)+g_n\sin(2n\pi t/\tau). +\end{equation} +!et + +!split +===== Wrapping up Fourier transforms ===== + +We can write down the answer for +$x_{pn}(t)$, by substituting $f_n/m$ or $g_n/m$ for $F_0/m$. By +writing each factor $2n\pi t/\tau$ as $n\omega t$, with $\omega\equiv +2\pi/\tau$, + +!bt +\begin{equation} +label{eq:fourierdef1} +F(t)=\frac{f_0}{2}+\sum_{n>0}f_n\cos(n\omega t)+g_n\sin(n\omega t). +\end{equation} +!et + +The solutions for $x(t)$ then come from replacing $\omega$ with +$n\omega$ for each term in the particular solution, + +!bt +\begin{eqnarray} +x_p(t)&=&\frac{f_0}{2k}+\sum_{n>0} \alpha_n\cos(n\omega t-\delta_n)+\beta_n\sin(n\omega t-\delta_n),\\ +\nonumber +\alpha_n&=&\frac{f_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\ +\nonumber +\beta_n&=&\frac{g_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\ +\nonumber +\delta_n&=&\tan^{-1}\left(\frac{2\beta n\omega}{\omega_0^2-n^2\omega^2}\right). +\end{eqnarray} +!et + +!split +===== Finding the Coefficients ===== + +Because the forces have been applied for a long time, any non-zero +damping eliminates the homogenous parts of the solution, so one need +only consider the particular solution for each $n$. + +The problem is considered solved if one can find expressions for the +coefficients $f_n$ and $g_n$, even though the solutions are expressed +as an infinite sum. The coefficients can be extracted from the +function $F(t)$ by + +!bt +\begin{eqnarray} +label{eq:fourierdef2} +f_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\cos(2n\pi t/\tau),\\ +\nonumber +g_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\sin(2n\pi t/\tau). +\end{eqnarray} +!et + +To check the consistency of these expressions and to verify +Eq. (ref{eq:fourierdef2}), one can insert the expansion of $F(t)$ in +Eq. (ref{eq:fourierdef1}) into the expression for the coefficients in +Eq. (ref{eq:fourierdef2}) and see whether + +!bt +\begin{eqnarray} +f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~\left\{ +\frac{f_0}{2}+\sum_{m>0}f_m\cos(m\omega t)+g_m\sin(m\omega t) +\right\}\cos(n\omega t). +\end{eqnarray} +!et + +Immediately, one can throw away all the terms with $g_m$ because they +convolute an even and an odd function. The term with $f_0/2$ +disappears because $\cos(n\omega t)$ is equally positive and negative +over the interval and will integrate to zero. For all the terms +$f_m\cos(m\omega t)$ appearing in the sum, one can use angle addition +formulas to see that $\cos(m\omega t)\cos(n\omega +t)=(1/2)(\cos[(m+n)\omega t]+\cos[(m-n)\omega t]$. This will integrate +to zero unless $m=n$. In that case the $m=n$ term gives + +!bt +\begin{equation} +\int_{-\tau/2}^{\tau/2}dt~\cos^2(m\omega t)=\frac{\tau}{2}, +\end{equation} +!et + +and + +!bt +\begin{eqnarray} +f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~f_n/2\\ +\nonumber +&=&f_n~\checkmark. +\end{eqnarray} +!et + +The same method can be used to check for the consistency of $g_n$. + + + +!split +===== Final words on Fourier Transforms ===== + +The code here uses the Fourier series applied to a +square wave signal. The code here +visualizes the various approximations given by Fourier series compared +with a square wave with period $T=0.2$ (dimensionless time), width $0.1$ and max value of the force $F=2$. We +see that when we increase the number of components in the Fourier +series, the Fourier series approximation gets closer and closer to the +square wave signal. + +!bc pycod +import numpy as np +import math +from scipy import signal +import matplotlib.pyplot as plt + +# number of points +n = 500 +# start and final times +t0 = 0.0 +tn = 1.0 +# Period +T =0.2 +# Max value of square signal +Fmax= 2.0 +# Width of signal +Width = 0.1 +t = np.linspace(t0, tn, n, endpoint=False) +SqrSignal = np.zeros(n) +FourierSeriesSignal = np.zeros(n) +SqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T) +a0 = Fmax*Width/T +FourierSeriesSignal = a0 +Factor = 2.0*Fmax/np.pi +for i in range(1,500): + FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T) +plt.plot(t, SqrSignal) +plt.plot(t, FourierSeriesSignal) +plt.ylim(-0.5, 2.5) +plt.show() +!ec + + +!split +===== Two-dimensional Objects ===== + +We often use convolutions over more than one dimension at a time. If +we have a two-dimensional image $I$ as input, we can have a _filter_ +defined by a two-dimensional _kernel_ $K$. This leads to an output $S$ + +!bt +\[ +S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(m,n)K(i-m,j-n). +\] +!et + +Convolution is a commutatitave process, which means we can rewrite this equation as +!bt +\[ +S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i-m,j-n)K(m,n). +\] +!et + +Normally the latter is more straightforward to implement in a machine elarning library since there is less variation in the range of values of $m$ and $n$. + +!split +===== Cross-Correlation ===== + + + +Many deep learning libraries implement cross-correlation instead of convolution +!bt +\[ +S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i+m,j-+)K(m,n). +\] +!et + + +!split +===== More on Dimensionalities ===== + +In feilds like signal processing (and imaging as well), one designs +so-called filters. These filters are defined by the convolutions and +are often hand-crafted. One may specify filters for smoothing, edge +detection, frequency reshaping, and similar operations. However with +neural networks the idea is to automatically learn the filters and use +many of them in conjunction with non-linear operations (activation +functions). + +As an example consider a neural network operating on sound sequence +data. Assume that we an input vector $\bm{x}$ of length $d=10^6$. We +construct then a neural network with onle hidden layer only with +$10^4$ nodes. This means that we will have a weight matrix with +$10^4\times 10^6=10^{10}$ weights to be determined, together with $10^4$ biases. + +Assume furthermore that we have an output layer which is meant to train whether the sound sequence represents a human voice (true) or something else (false). +It means that we have only one output node. But since this output node connects to $10^4$ nodes in the hidden layer, there are in total $10^4$ weights to be determined for the output layer, plus one bias. In total we have + +!bt +\[ +\mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \approx 10^{10}, +\] +!et +that is ten billion parameters to determine. + + +!split +===== Further Dimensionality Remarks ===== + +In today’s architecture one can train such neural networks, however +this is a huge number of parameters for the task at hand. In general, +it is a very wasteful and inefficient use of dense matrices as +parameters. Just as importantly, such trained network parameters are +very specific for the type of input data on which they were trained +and the network is not likely to generalize easily to variations in +the input. + + +The main principles that justify convolutions is locality of +information and repetion of patterns within the signal. Sound samples +of the input in adjacent spots are much more likely to affect each +other than those that are very far away. Similarly, sounds are +repeated in multiple times in the signal. While slightly simplistic, +reasoning about such a sound example demonstrates this. The same +principles then apply to images and other similar data. + + +!split +===== CNNs in more detail, Lecture from IN5400 ===== + +* "Lectures from IN5400 spring 2019":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/v19/material/week5/in5400_2019_week5_convolutional_nerual_networks.pdf" + + +!split +===== CNNs in more detail, building convolutional neural networks in Tensorflow and Keras ===== + + +As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. + +As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the _convolutional_ and _pooling_ layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). + + +!split +===== Setting it up ===== + +It means that to represent the entire +dataset of images, we require a 4D matrix or _tensor_. This tensor has the dimensions: +!bt +\[ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +\] +!et + +!split +===== The MNIST dataset again ===== + +The MNIST dataset consists of grayscale images with a pixel size of +$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each +neuron in the first hidden layer. + +If we were to analyze images of size $128\times 128$ we would require +$128 \times 128 = 16384$ weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size $128\times 128$ for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights $= 49152$ are required for every +single neuron in the first hidden layer. + + +!split +===== Strong correlations ===== + +Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. + +Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a "receptive":"https://en.wikipedia.org/wiki/Receptive_field". + + +!split +===== Layers of a CNN ===== +The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. + +A _convolution_ is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as _filters_. + + +Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the _Rectified Linear (ReLu)_ function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a _pooling layer_, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. + + +!split +===== Systematic reduction ===== + +By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. + + +!split +===== Prerequisites: Collect and pre-process data ===== +!bc pycod +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn import datasets + + +# ensure the same random numbers appear every time +np.random.seed(0) + +# display images in notebook +%matplotlib inline +plt.rcParams['figure.figsize'] = (12,12) + + +# download MNIST dataset +digits = datasets.load_digits() + +# define inputs and labels +inputs = digits.images +labels = digits.target + +# RGB images have a depth of 3 +# our images are grayscale so they should have a depth of 1 +inputs = inputs[:,:,:,np.newaxis] + +print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape)) +print("labels = (n_inputs) = " + str(labels.shape)) + + +# choose some random images to display +n_inputs = len(inputs) +indices = np.arange(n_inputs) +random_indices = np.random.choice(indices, size=5) + +for i, image in enumerate(digits.images[random_indices]): + plt.subplot(1, 5, i+1) + plt.axis('off') + plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') + plt.title("Label: %d" % digits.target[random_indices[i]]) +plt.show() +!ec + + +!split +===== Importing Keras and Tensorflow ===== +!bc pycod +from tensorflow.keras import datasets, layers, models +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 tensorflow.keras import Conv2D +#from tensorflow.keras import MaxPooling2D +#from tensorflow.keras import Flatten + +from sklearn.model_selection import train_test_split + +# representation of labels +labels = to_categorical(labels) + +# split into train and test data +# 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) +!ec + +!split +===== Running with Keras ===== + +!bc pycod +def create_convolutional_neural_network_keras(input_shape, receptive_field, + n_filters, n_neurons_connected, n_categories, + eta, lmbd): + model = Sequential() + model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same', + activation='relu', kernel_regularizer=regularizers.l2(lmbd))) + model.add(layers.MaxPooling2D(pool_size=(2, 2))) + model.add(layers.Flatten()) + model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd))) + model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd))) + + sgd = optimizers.SGD(lr=eta) + model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) + + return model + +epochs = 100 +batch_size = 100 +input_shape = X_train.shape[1:4] +receptive_field = 3 +n_filters = 10 +n_neurons_connected = 50 +n_categories = 10 + +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +!ec + +!split +===== Final part ===== + +!bc pycod +CNN_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): + CNN = create_convolutional_neural_network_keras(input_shape, receptive_field, + n_filters, n_neurons_connected, n_categories, + eta, lmbd) + CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) + scores = CNN.evaluate(X_test, Y_test) + + CNN_keras[i][j] = CNN + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Test accuracy: %.3f" % scores[1]) + print() +!ec + +!split +===== Final visualization ===== + +!bc pycod +# 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)): + CNN = CNN_keras[i][j] + + train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1] + test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1] + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Test Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() +!ec + + + +!split +===== The CIFAR01 data set ===== + +The CIFAR10 dataset contains 60,000 color images in 10 classes, with +6,000 images in each class. The dataset is divided into 50,000 +training images and 10,000 testing images. The classes are mutually +exclusive and there is no overlap between them. + +!bc pycod +import tensorflow as tf + +from tensorflow.keras import datasets, layers, models +import matplotlib.pyplot as plt + +# We import the data set +(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data() + +# Normalize pixel values to be between 0 and 1 by dividing by 255. +train_images, test_images = train_images / 255.0, test_images / 255.0 + +!ec + + + +!split +===== Verifying the data set ===== + +To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image. + +!bc pycod +class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', + 'dog', 'frog', 'horse', 'ship', 'truck'] +​ +plt.figure(figsize=(10,10)) +for i in range(25): + plt.subplot(5,5,i+1) + plt.xticks([]) + plt.yticks([]) + plt.grid(False) + plt.imshow(train_images[i], cmap=plt.cm.binary) + # The CIFAR labels happen to be arrays, + # which is why you need the extra index + plt.xlabel(class_names[train_labels[i][0]]) +plt.show() +!ec + +!split +===== Set up the model ===== + +The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers. + +As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer. + +!bc pycod +model = models.Sequential() +model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3))) +model.add(layers.MaxPooling2D((2, 2))) +model.add(layers.Conv2D(64, (3, 3), activation='relu')) +model.add(layers.MaxPooling2D((2, 2))) +model.add(layers.Conv2D(64, (3, 3), activation='relu')) + +# Let's display the architecture of our model so far. + +model.summary() +!ec + +You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer. + + + + +!split +===== Add Dense layers on top ===== + +To complete our model, you will feed the last output tensor from the +convolutional base (of shape (4, 4, 64)) into one or more Dense layers +to perform classification. Dense layers take vectors as input (which +are 1D), while the current output is a 3D tensor. First, you will +flatten (or unroll) the 3D output to 1D, then add one or more Dense +layers on top. CIFAR has 10 output classes, so you use a final Dense +layer with 10 outputs and a softmax activation. + +!bc pycod +model.add(layers.Flatten()) +model.add(layers.Dense(64, activation='relu')) +model.add(layers.Dense(10)) +Here's the complete architecture of our model. + +model.summary() +!ec +As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers. + +!split +===== Compile and train the model ===== + +!bc pycod +model.compile(optimizer='adam', + loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), + metrics=['accuracy']) +​ +history = model.fit(train_images, train_labels, epochs=10, + validation_data=(test_images, test_labels)) + +!ec + + +!split +===== Finally, evaluate the model ===== + +!bc pycod +plt.plot(history.history['accuracy'], label='accuracy') +plt.plot(history.history['val_accuracy'], label = 'val_accuracy') +plt.xlabel('Epoch') +plt.ylabel('Accuracy') +plt.ylim([0.5, 1]) +plt.legend(loc='lower right') + +test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) + +print(test_acc) + +!ec + + + + + + + diff --git a/doc/src/week42/backweek41.do.txt b/doc/src/week42/backweek41.do.txt new file mode 100644 index 000000000..e4fe80e29 --- /dev/null +++ b/doc/src/week42/backweek41.do.txt @@ -0,0 +1,1965 @@ +TITLE: Week 41 Constructing a Neural Network code, Tensor flow and start Convolutional Neural Networks +AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University +DATE: Week 41 + + +!split +===== Plan for week 41 ===== + +* Building our own Feed-forward Neural Network and discussion of project 2. +* Playing around with our own Feed-forward Neural Network and introduction to TensorFlow. Solving differential equations with neural networks. +" +Reading suggestions: These notes, "Aurelien Geron's chapters 10-11":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf". +For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. Bishop's chapter 5 on Neural Networks is an additional good read. + +!split +===== Videos on Neural Networks ===== + +* "Video on Neural Networks":"https://www.youtube.com/watch?v=CqOfi41LfDw" + +* "Video on the back propagation algorithm":"https://www.youtube.com/watch?v=Ilg3gGewQ5U" + +I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at URL:"http://neuralnetworksanddeeplearning.com/chap4.html". + + + +!split +===== 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 ===== + + + +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. + +!bblock +First, we set up the input data $\bm{x}$ and the activations +$\bm{z}_1$ of the input layer and compute the activation function and +the pertinent outputs $\bm{a}^1$. +!eblock + +!bblock +Secondly, we perform then the feed forward till we reach the output +layer and compute all $\bm{z}_l$ of the input layer and compute the +activation function and the pertinent outputs $\bm{a}^l$ for +$l=2,3,\dots,L$. +!eblock + +!bblock +Thereafter we compute the ouput error $\bm{\delta}^L$ by computing all +!bt +\[ +\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. +\] +!et +!eblock + +!bblock +Then we compute the back propagate error for each $l=L-1,L-2,\dots,2$ as +!bt +\[ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l). +\] +!et +!eblock + +!bblock +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 +!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}=b_j^l-\eta \delta_j^l, +\] +!et +!eblock + +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. + + + + +!split +===== Setting up a Multi-layer perceptron model for classification ===== + +We are now gong to develop an example based on the MNIST data +base. This is a classification problem and we need to use our +cross-entropy function we discussed in connection with logistic +regression. The cross-entropy defines our cost function for the +classificaton problems with neural networks. + +In binary classification with two classes $(0, 1)$ we define the +logistic/sigmoid function as the probability that a particular input +is in class $0$ or $1$. This is possible because the logistic +function takes any input from the real numbers and inputs a number +between 0 and 1, and can therefore be interpreted as a probability. It +also has other nice properties, such as a derivative that is simple to +calculate. + +For an input $\boldsymbol{a}$ from the hidden layer, the probability that the input $\boldsymbol{x}$ +is in class 0 or 1 is just. We let $\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$ +represents our activation values $z$. We have +!bt +\[ +P(y = 0 \mid \bm{x}, \bm{\theta}) = \frac{1}{1 + \exp{(- \bm{x}})} , +\] +!et +and +!bt +\[ +P(y = 1 \mid \bm{x}, \bm{\theta}) = 1 - P(y = 0 \mid \bm{x}, \bm{\theta}) , +\] +!et + +where $y \in \{0, 1\}$ and $\bm{\theta}$ represents the weights and biases +of our network. + + +!split +===== Defining the cost function ===== + +Our cost function is given as (see the Logistic regression lectures) +!bt +\[ +\mathcal{C}(\bm{\theta}) = - \ln P(\mathcal{D} \mid \bm{\theta}) = - \sum_{i=1}^n +y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\bm{\theta}) . +\] +!et + +This last equality means that we can interpret our *cost* function as a sum over the *loss* function +for each point in the dataset $\mathcal{L}_i(\bm{\theta})$. +The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather +than maximizing a negative number. + +In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: + +$y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and + + +$y = 1 \quad \rightarrow \quad \bm{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ + + +i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. + +If $\bm{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th +output vector $\bm{y}_i$. +The probability of $\bm{x}_i$ being in class $c$ will be given by the softmax function: + +!bt +\[ +P(y_{ic} = 1 \mid \bm{x}_i, \bm{\theta}) = \frac{\exp{((\bm{a}_i^{hidden})^T \bm{w}_c)}} +{\sum_{c'=0}^{C-1} \exp{((\bm{a}_i^{hidden})^T \bm{w}_{c'})}} , +\] +!et + +which reduces to the logistic function in the binary case. +The likelihood of this $C$-class classifier +is now given as: + +!bt +\[ +P(\mathcal{D} \mid \bm{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . +\] +!et +Again we take the negative log-likelihood to define our cost function: + +!bt +\[ +\mathcal{C}(\bm{\theta}) = - \log{P(\mathcal{D} \mid \bm{\theta})}. +\] +!et +See the logistic regression lectures for a full definition of the cost function. + +The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before! + +!split +===== Example: binary classification problem ===== + +As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\beta$ as +!bt +\[ +\mathcal{C}(\bm{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\bm{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\bm{\beta})}\right), +\] +!et +where we had defined the logistic (sigmoid) function +!bt +\[ +p(y_i =1\vert x_i,\bm{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, +\] +!et +and +!bt +\[ +p(y_i =0\vert x_i,\bm{\beta})=1-p(y_i =1\vert x_i,\bm{\beta}). +\] +!et +The parameters $\bm{\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. + +Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. +We have then +!bt +\[ +a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, +\] +!et +with +!bt +\[ +z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, +\] +!et +where the superscript $l-1$ indicates that these are the outputs from layer $l-1$. +Our cost function at the final layer $l=L$ is now +!bt +\[ +\mathcal{C}(\bm{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), +\] +!et +where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get +!bt +\[ +\frac{\partial \mathcal{C}(\bm{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. +\] +!et +In case we use another activation function than the logistic one, we need to evaluate other derivatives. + + +!split +===== The Softmax function ===== +In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need +!bt +\[ +\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = +\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. +\] +!et +For the Softmax function we have +!bt +\[ +f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. +\] +!et +Its derivative with respect to $z_j^l$ gives +!bt +\[ +\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), +\] +!et +which in case of the simply binary model reduces to having $i=j$. + +!split +===== Developing a code for doing neural networks with back propagation ===== + + +One can identify a set of key steps when using neural networks to solve supervised learning problems: + +o Collect and pre-process data +o Define model and architecture +o Choose cost function and optimizer +o Train the model +o Evaluate model performance on test data +o Adjust hyperparameters (if necessary, network architecture) + +!split +===== Collect and pre-process data ===== + +Here we will be using the MNIST dataset, which is readily available through the _scikit-learn_ +package. You may also find it for example "here":"http://yann.lecun.com/exdb/mnist/". +The *MNIST* (Modified National Institute of Standards and Technology) database is a large database +of handwritten digits that is commonly used for training various image processing systems. +The MNIST dataset consists of 70 000 images of size $28\times 28$ pixels, each labeled from 0 to 9. +The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\times 8$ collected and processed from this database. + +To feed data into a feed-forward neural network we need to represent +the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each +row represents an *input*, in this case a handwritten digit, and +each column represents a *feature*, in this case a pixel. The +correct answers, also known as *labels* or *targets* are +represented as a 1D array of integers +$Y = (n_{inputs}) = (5, 3, 1, 8,...)$. + +As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from +measurements of height (in m) +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: + +$$ X = \begin{bmatrix} +1.85 & 81\\ +1.71 & 65\\ +1.95 & 103\\ +1.55 & 42\\ +1.63 & 56 +\end{bmatrix} ,$$ + +and the targets would be: + +$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ + +Since each input image is a 2D matrix, we need to flatten the image +(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a +design/feature matrix. This means we lose all spatial information in the +image, such as locality and translational invariance. More complicated +architectures such as Convolutional Neural Networks can take advantage +of such information, and are most commonly applied when analyzing +images. + + +!bc pycod +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn import datasets + + +# ensure the same random numbers appear every time +np.random.seed(0) + +# display images in notebook +%matplotlib inline +plt.rcParams['figure.figsize'] = (12,12) + + +# download MNIST dataset +digits = datasets.load_digits() + +# define inputs and labels +inputs = digits.images +labels = digits.target + +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) +print("labels = (n_inputs) = " + str(labels.shape)) + + +# flatten the image +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 +n_inputs = len(inputs) +inputs = inputs.reshape(n_inputs, -1) +print("X = (n_inputs, n_features) = " + str(inputs.shape)) + + +# choose some random images to display +indices = np.arange(n_inputs) +random_indices = np.random.choice(indices, size=5) + +for i, image in enumerate(digits.images[random_indices]): + plt.subplot(1, 5, i+1) + plt.axis('off') + plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') + plt.title("Label: %d" % digits.target[random_indices[i]]) +plt.show() +!ec + +!split +===== Train and test datasets ===== + +Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. + +We will reserve $80 \%$ of our dataset for training and $20 \%$ for testing. + +It is important that the train and test datasets are drawn randomly from our dataset, to ensure +no bias in the sampling. +Say you are taking measurements of weather data to predict the weather in the coming 5 days. +You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data +collected from 12.00 to 24.00. + + +!bc pycod +from sklearn.model_selection import train_test_split + +# one-liner from scikit-learn library +train_size = 0.8 +test_size = 1 - train_size +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, + test_size=test_size) + +# equivalently in numpy +def train_test_split_numpy(inputs, labels, train_size, test_size): + n_inputs = len(inputs) + inputs_shuffled = inputs.copy() + labels_shuffled = labels.copy() + + np.random.shuffle(inputs_shuffled) + np.random.shuffle(labels_shuffled) + + train_end = int(n_inputs*train_size) + X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] + Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] + + return X_train, X_test, Y_train, Y_test + +#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size) + +print("Number of training images: " + str(len(X_train))) +print("Number of test images: " + str(len(X_test))) +!ec + +!split +===== Define model and architecture ===== + +Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have + +$$ z = \sum_{i=1}^n w_i a_i ,$$ + +$$ y = f(z) ,$$ + +where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer +and $w_i$ is the weight to input $i$. +The activation of the neurons in the input layer is just the features (e.g. a pixel value). + +The simplest activation function for a neuron is the *Heaviside* function: + +$$ f(z) = +\begin{cases} +1, & z > 0\\ +0, & \text{otherwise} +\end{cases} +$$ + +A feed-forward neural network with this activation is known as a *perceptron*. +For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. +This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), +and we call these architectures *multiclass perceptrons*. + +However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and +Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. + +Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). +We will be using the sigmoid function $\sigma(x)$: + +$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$ + +which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions. + +!split +===== Layers ===== + +* Input +Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. + +* Hidden layer +We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. +Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. + +* Output +If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, +which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. + +For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. + +Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: + +$$ P(\text{class $j$} \mid \text{input $\bm{a}$}) = \frac{\exp{(\bm{a}^T \bm{w}_j)}} +{\sum_{c=0}^{9} \exp{(\bm{a}^T \bm{w}_c)}} ,$$ + +i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\bm{a}$, with $\bm{w}_j$ the weights of neuron $j$ to the inputs. +The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. +The exponent is just the weighted sum of inputs as before: + +$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ + +Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 +weights to the output layer. + +!split +===== Weights and biases ===== + +Typically weights are initialized with small values distributed around zero, drawn from a uniform +or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. + +Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range +of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: + +$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ + +The bias weights $\bm{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle. +!bc pycod +# building our neural network + +n_inputs, n_features = X_train.shape +n_hidden_neurons = 50 +n_categories = 10 + +# we make the weights normally distributed using numpy.random.randn + +# weights and bias in the hidden layer +hidden_weights = np.random.randn(n_features, n_hidden_neurons) +hidden_bias = np.zeros(n_hidden_neurons) + 0.01 + +# weights and bias in the output layer +output_weights = np.random.randn(n_hidden_neurons, n_categories) +output_bias = np.zeros(n_categories) + 0.01 +!ec + +!split +===== Feed-forward pass ===== + +Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. +For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: + +$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ + +this is then passed through our activation function + +$$ a_{j}^{l} = f(z_{j}^{l}) .$$ + +We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: + +$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ + +Finally we calculate the output of neuron $j$ in the output layer using the softmax function: + +$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} +{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ + +!split +===== Matrix multiplications ===== + +Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden +layer have the dimensions +$W_{hidden} = (n_{features}, n_{hidden})$, +we can easily feed the network all our training data in one go by taking the matrix product + +$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ + +and obtain a matrix that holds the weighted sum of inputs to the hidden layer +for each input image and each hidden neuron. +We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: + +$$ \bm{z}^{l} = \bm{X} \bm{W}^{l} + \bm{b}^{l} ,$$ + +meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. +This is then passed through the activation: + +$$ \bm{a}^{l} = f(\bm{z}^l) .$$ + +This is fed to the output layer: + +$$ \bm{z}^{L} = \bm{a}^{L} \bm{W}^{L} + \bm{b}^{L} .$$ + +Finally we receive our output values for each image and each category by passing it through the softmax function: + +$$ output = softmax (\bm{z}^{L}) = (n_{inputs}, n_{categories}) .$$ + + +!bc pycod +# setup the feed-forward pass, subscript h = hidden layer + +def sigmoid(x): + return 1/(1 + np.exp(-x)) + +def feed_forward(X): + # weighted sum of inputs to the hidden layer + z_h = np.matmul(X, hidden_weights) + hidden_bias + # activation in the hidden layer + a_h = sigmoid(z_h) + + # weighted sum of inputs to the output layer + z_o = np.matmul(a_h, output_weights) + output_bias + # softmax output + # axis 0 holds each input and axis 1 the probabilities of each category + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + return probabilities + +probabilities = feed_forward(X_train) +print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape)) +print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0])) +print("probabilities sum up to: " + str(probabilities[0].sum())) +print() + +# we obtain a prediction by taking the class with the highest likelihood +def predict(X): + probabilities = feed_forward(X) + return np.argmax(probabilities, axis=1) + +predictions = predict(X_train) +print("predictions = (n_inputs) = " + str(predictions.shape)) +print("prediction for image 0: " + str(predictions[0])) +print("correct label for image 0: " + str(Y_train[0])) +!ec + +!split +===== Choose cost function and optimizer ===== + +To measure how well our neural network is doing we need to introduce a cost function. +We will call the function that gives the error of a single sample output the *loss* function, and the function +that gives the total error of our network across all samples the *cost* function. +A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. + +In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: + +$$ y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ + + +$$ y = 1 \quad \rightarrow \quad \bm{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ + + +i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. + +Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. +We define the cost function $\mathcal{C}$ as a sum over the cross-entropy loss for each point $\bm{x}_i$ in the dataset. + +In the one-hot representation only one of the terms in the loss function is non-zero, namely the +probability of the correct category $c'$ +(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong +you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\bm{\theta}$ represents the parameters of our network, i.e. all the weights and biases. + + +!split +===== Optimizing the cost function ===== + +The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent +is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. +Each parameter $\theta$ is iteratively adjusted according to the rule + +$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ + +where $\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. +This update can be repeated for any number of iterations, or until we are satisfied with the result. + +A simple and effective improvement is a variant called *Batch Gradient Descent*. +Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient +on a subset of the data called a *minibatch*. +If there are $N$ data points and we have a minibatch size of $M$, the total number of batches +is $N/M$. +We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: + +$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ + +i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. + +This has two important benefits: +o Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. +o It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. + +The various optmization methods, with codes and algorithms, are discussed in our lectures on "Gradient descent approaches":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". + +!split +===== Regularization ===== + +It is common to add an extra term to the cost function, proportional +to the size of the weights. This is equivalent to constraining the +size of the weights, so that they do not grow out of control. +Constraining the size of the weights means that the weights cannot +grow arbitrarily large to fit the training data, and in this way +reduces *overfitting*. + +We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: + +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \bm{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ + +i.e. we sum up all the weights squared. The factor $\lambda$ is known as a regularization parameter. + + +In order to train the model, we need to calculate the derivative of +the cost function with respect to every bias and weight in the +network. In total our network has $(64 + 1)\times 50=3250$ weights in +the hidden layer and $(50 + 1)\times 10=510$ weights to the output +layer ($+1$ for the bias), and the gradient must be calculated for +every parameter. We use the *backpropagation* algorithm discussed +above. This is a clever use of the chain rule that allows us to +calculate the gradient efficently. + + +!split +===== Matrix multiplication ===== + +To more efficently train our network these equations are implemented using matrix operations. +The error in the output layer is calculated simply as, with $\bm{t}$ being our targets, + +$$ \delta_L = \bm{t} - \bm{y} = (n_{inputs}, n_{categories}) .$$ + +The gradient for the output weights is calculated as + +$$ \nabla W_{L} = \bm{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ + +where $\bm{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. +Since we are going backwards we have to transpose the activation matrix. + +The gradient with respect to the output bias is then + +$$ \nabla \bm{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ + +The error in the hidden layer is + +$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ + +where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean +that we are summing up the products for each neuron in the output layer. The symbol $\circ$ denotes +the *Hadamard product*, meaning element-wise multiplication. + +This again gives us the gradients in the hidden layer: + +$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ + +$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ + + +!bc pycod +# to categorical turns our integer vector into a onehot representation +from sklearn.metrics import accuracy_score + +# one-hot in numpy +def to_categorical_numpy(integer_vector): + n_inputs = len(integer_vector) + n_categories = np.max(integer_vector) + 1 + onehot_vector = np.zeros((n_inputs, n_categories)) + onehot_vector[range(n_inputs), integer_vector] = 1 + + return onehot_vector + +#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test) +Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test) + +def feed_forward_train(X): + # weighted sum of inputs to the hidden layer + z_h = np.matmul(X, hidden_weights) + hidden_bias + # activation in the hidden layer + a_h = sigmoid(z_h) + + # weighted sum of inputs to the output layer + z_o = np.matmul(a_h, output_weights) + output_bias + # softmax output + # axis 0 holds each input and axis 1 the probabilities of each category + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + # for backpropagation need activations in hidden and output layers + return a_h, probabilities + +def backpropagation(X, Y): + a_h, probabilities = feed_forward_train(X) + + # error in the output layer + error_output = probabilities - Y + # error in the hidden layer + error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h) + + # gradients for the output layer + output_weights_gradient = np.matmul(a_h.T, error_output) + output_bias_gradient = np.sum(error_output, axis=0) + + # gradient for the hidden layer + hidden_weights_gradient = np.matmul(X.T, error_hidden) + hidden_bias_gradient = np.sum(error_hidden, axis=0) + + return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient + +print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) + +eta = 0.01 +lmbd = 0.01 +for i in range(1000): + # calculate gradients + dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot) + + # regularization term gradients + dWo += lmbd * output_weights + dWh += lmbd * hidden_weights + + # update weights and biases + output_weights -= eta * dWo + output_bias -= eta * dBo + hidden_weights -= eta * dWh + hidden_bias -= eta * dBh + +print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) +!ec + +!split +===== Improving performance ===== + +As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. +In order to obtain a network that does something useful, we will have to do a bit more work. + +The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\lambda = 10^{-6},...,10^{-0}$. + +Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period +going through the entire dataset ($n/M$ batches) an *epoch*. + +If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. +Andrew Ng goes through some of these considerations in this "video":"https://youtu.be/F1ka6a13S9I". You can find a summary of the video "here":"https://kevinzakka.github.io/2016/09/26/applying-deep-learning/". + +!split +===== Full object-oriented implementation ===== + +It is very natural to think of the network as an object, with specific instances of the network +being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. + + +!bc pycod +class NeuralNetwork: + def __init__( + self, + X_data, + Y_data, + n_hidden_neurons=50, + n_categories=10, + epochs=10, + batch_size=100, + eta=0.1, + lmbd=0.0): + + self.X_data_full = X_data + self.Y_data_full = Y_data + + self.n_inputs = X_data.shape[0] + self.n_features = X_data.shape[1] + self.n_hidden_neurons = n_hidden_neurons + self.n_categories = n_categories + + self.epochs = epochs + self.batch_size = batch_size + self.iterations = self.n_inputs // self.batch_size + self.eta = eta + self.lmbd = lmbd + + self.create_biases_and_weights() + + def create_biases_and_weights(self): + self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons) + self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01 + + self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories) + self.output_bias = np.zeros(self.n_categories) + 0.01 + + def feed_forward(self): + # feed-forward for training + self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias + self.a_h = sigmoid(self.z_h) + + self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias + + exp_term = np.exp(self.z_o) + self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + def feed_forward_out(self, X): + # feed-forward for output + z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias + a_h = sigmoid(z_h) + + z_o = np.matmul(a_h, self.output_weights) + self.output_bias + + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + return probabilities + + def backpropagation(self): + error_output = self.probabilities - self.Y_data + error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h) + + self.output_weights_gradient = np.matmul(self.a_h.T, error_output) + self.output_bias_gradient = np.sum(error_output, axis=0) + + self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden) + self.hidden_bias_gradient = np.sum(error_hidden, axis=0) + + if self.lmbd > 0.0: + self.output_weights_gradient += self.lmbd * self.output_weights + self.hidden_weights_gradient += self.lmbd * self.hidden_weights + + self.output_weights -= self.eta * self.output_weights_gradient + self.output_bias -= self.eta * self.output_bias_gradient + self.hidden_weights -= self.eta * self.hidden_weights_gradient + self.hidden_bias -= self.eta * self.hidden_bias_gradient + + def predict(self, X): + probabilities = self.feed_forward_out(X) + return np.argmax(probabilities, axis=1) + + def predict_probabilities(self, X): + probabilities = self.feed_forward_out(X) + return probabilities + + def train(self): + data_indices = np.arange(self.n_inputs) + + for i in range(self.epochs): + for j in range(self.iterations): + # pick datapoints with replacement + chosen_datapoints = np.random.choice( + data_indices, size=self.batch_size, replace=False + ) + + # minibatch training data + self.X_data = self.X_data_full[chosen_datapoints] + self.Y_data = self.Y_data_full[chosen_datapoints] + + self.feed_forward() + self.backpropagation() +!ec + +!split +===== Evaluate model performance on test data ===== + +To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. +We measure the performance of the network using the *accuracy* score. +The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. + +$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ + +where $I$ is the indicator function, $1$ if $\tilde{y}_i = y_i$ and $0$ otherwise. + + +!bc pycod +epochs = 100 +batch_size = 100 + +dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, + n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) +dnn.train() +test_predict = dnn.predict(X_test) + +# accuracy score from scikit library +print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) + +# equivalent in numpy +def accuracy_score_numpy(Y_test, Y_pred): + return np.sum(Y_test == Y_pred) / len(Y_test) + +#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict)) +!ec + +!split +===== Adjust hyperparameters ===== + +We now perform a grid search to find the optimal hyperparameters for the network. +Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\%$ ($2\%$ error rate). + +!bc pycod +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +# store the models for later use +DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +# grid search +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, + n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) + dnn.train() + + DNN_numpy[i][j] = dnn + + test_predict = dnn.predict(X_test) + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) + print() +!ec + +!split +===== Visualization ===== + +!bc pycod +# visual representation of grid search +# uses seaborn heatmap, you can also do this with matplotlib imshow +import seaborn as sns + +sns.set() + +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) + +for i in range(len(eta_vals)): + for j in range(len(lmbd_vals)): + dnn = DNN_numpy[i][j] + + train_pred = dnn.predict(X_train) + test_pred = dnn.predict(X_test) + + train_accuracy[i][j] = accuracy_score(Y_train, train_pred) + test_accuracy[i][j] = accuracy_score(Y_test, test_pred) + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Test Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() +!ec + +!split +===== scikit-learn implementation ===== + +_scikit-learn_ focuses more +on traditional machine learning methods, such as regression, +clustering, decision trees, etc. As such, it has only two types of +neural networks: Multi Layer Perceptron outputting continuous values, +*MPLRegressor*, and Multi Layer Perceptron outputting labels, +*MLPClassifier*. We will see how simple it is to use these classes. + +_scikit-learn_ implements a few improvements from our neural network, +such as early stopping, a varying learning rate, different +optimization methods, etc. We would therefore expect a better +performance overall. + +!bc pycod +from sklearn.neural_network import MLPClassifier +# store models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, Y_train) + + DNN_scikit[i][j] = dnn + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Accuracy score on test set: ", dnn.score(X_test, Y_test)) + print() +!ec + + +!split +===== Visualization ===== +!bc pycod +# optional +# visual representation of grid search +# uses seaborn heatmap, could probably do this in matplotlib +import seaborn as sns + +sns.set() + +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) + +for i in range(len(eta_vals)): + for j in range(len(lmbd_vals)): + dnn = DNN_scikit[i][j] + + train_pred = dnn.predict(X_train) + test_pred = dnn.predict(X_test) + + train_accuracy[i][j] = accuracy_score(Y_train, train_pred) + test_accuracy[i][j] = accuracy_score(Y_test, test_pred) + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Test Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() +!ec + + +!split +===== Testing our code for the XOR, OR and AND gates ===== + +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$: + +|---------------------| +| $x_1$ | $x_2$ | $y$ | +|---------------------| +| 0 | 0 | 0 | +| 0 | 1 | 1 | +| 1 | 0 | 1 | +| 1 | 1 | 1 | +|---------------------| + +!split +===== The AND and XOR Gates ===== + +The AND gate is defined as + +|---------------------| +| $x_1$ | $x_2$ | $y$ | +|---------------------| +| 0 | 0 | 0 | +| 0 | 1 | 0 | +| 1 | 0 | 0 | +| 1 | 1 | 1 | +|---------------------| + +And finally we have the XOR gate + +|---------------------| +| $x_1$ | $x_2$ | $y$ | +|---------------------| +| 0 | 0 | 0 | +| 0 | 1 | 1 | +| 1 | 0 | 1 | +| 1 | 1 | 0 | +|---------------------| + +!split +===== Representing the Data Sets ===== + +Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads + +!bt +\bm{X}=\begin{bmatrix} 0 & 0 \\ + 0 & 1 \\ + 1 & 0 \\ + 1 & 1 \end{bmatrix}, +!et + +while the vector of outputs is $\bm{y}^T=[0,1,1,0]$ for the XOR gate, $\bm{y}^T=[0,0,0,1]$ for the AND gate and $\bm{y}^T=[0,1,1,1]$ for the OR gate. + +!split +===== Setting up the Neural Network ===== + +We define first our design matrix and the various output vectors for the different gates. + +!bc pycod +""" +Simple code that tests XOR, OR and AND gates with linear regression +""" + +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn import datasets + +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) + +!ec + +Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above. + +!split +===== The Code using Scikit-Learn ===== + +!bc pycod +# 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() + +!ec + + +!split +===== Building neural networks in Tensorflow and Keras ===== + +Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. + +In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. + +!split +===== Tensorflow ===== + +Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. + +Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. + +"Tensorflow uses":"https://www.tensorflow.org/guide/graphs" so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph* +to represent your model, and then create a Tensorflow *session* to run the graph. + +In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. + +To install tensorflow on Unix/Linux systems, use pip as +!bc pycod +pip3 install tensorflow +!ec +and/or if you use _anaconda_, just write (or install from the graphical user interface) +(current release of CPU-only TensorFlow) +!bc pycod +conda create -n tf tensorflow +conda activate tf +!ec +To install the current release of GPU TensorFlow +!bc pycod +conda create -n tf-gpu tensorflow-gpu +conda activate tf-gpu +!ec + +!split +===== Using Keras ===== + +Keras is a high level "neural network":"https://en.wikipedia.org/wiki/Application_programming_interface" +that supports Tensorflow, CTNK and Theano as backends. +If you have Anaconda installed you may run the following command +!bc pycod +conda install keras +!ec +You can look up the "instructions here":"https://keras.io/" for more information. + +We will to a large extent use _keras_ in this course. + +!split +===== Collect and pre-process data ===== + +Let us look again at the MINST data set. + +!bc pycod +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +import tensorflow as tf +from sklearn import datasets + + +# ensure the same random numbers appear every time +np.random.seed(0) + +# display images in notebook +%matplotlib inline +plt.rcParams['figure.figsize'] = (12,12) + + +# download MNIST dataset +digits = datasets.load_digits() + +# define inputs and labels +inputs = digits.images +labels = digits.target + +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) +print("labels = (n_inputs) = " + str(labels.shape)) + + +# flatten the image +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 +n_inputs = len(inputs) +inputs = inputs.reshape(n_inputs, -1) +print("X = (n_inputs, n_features) = " + str(inputs.shape)) + + +# choose some random images to display +indices = np.arange(n_inputs) +random_indices = np.random.choice(indices, size=5) + +for i, image in enumerate(digits.images[random_indices]): + plt.subplot(1, 5, i+1) + plt.axis('off') + plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') + plt.title("Label: %d" % digits.target[random_indices[i]]) +plt.show() +!ec + +!bc pycod +from tensorflow.keras.layers import Input +from tensorflow.keras.models import Sequential #This allows appending layers to existing models +from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer +from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop) +from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2) +from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function + +from sklearn.model_selection import train_test_split + +# one-hot representation of labels +labels = to_categorical(labels) + +# split into train and test data +train_size = 0.8 +test_size = 1 - train_size +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, + test_size=test_size) +!ec + + + +!bc pycod + +epochs = 100 +batch_size = 100 +n_neurons_layer1 = 100 +n_neurons_layer2 = 50 +n_categories = 10 +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd): + model = Sequential() + model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd))) + model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd))) + model.add(Dense(n_categories, activation='softmax')) + + sgd = optimizers.SGD(lr=eta) + model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) + + return model +!ec + +!bc pycod +DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, + eta=eta, lmbd=lmbd) + DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) + scores = DNN.evaluate(X_test, Y_test) + + DNN_keras[i][j] = DNN + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Test accuracy: %.3f" % scores[1]) + print() +!ec + + + +!bc pycod +# optional +# visual representation of grid search +# uses seaborn heatmap, could probably do this in matplotlib +import seaborn as sns + +sns.set() + +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) + +for i in range(len(eta_vals)): + for j in range(len(lmbd_vals)): + DNN = DNN_keras[i][j] + + train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1] + test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1] + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Test Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() +!ec + + + +!split +===== The Breast Cancer Data, now with Keras ===== + +!bc pycod + +import tensorflow as tf +from tensorflow.keras.layers import Input +from tensorflow.keras.models import Sequential #This allows appending layers to existing models +from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer +from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop) +from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2) +from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function +import numpy as np +import matplotlib.pyplot as plt +import seaborn as sns +from sklearn.model_selection import train_test_split as splitter +from sklearn.datasets import load_breast_cancer +import pickle +import os + + +"""Load breast cancer dataset""" + +np.random.seed(0) #create same seed for random number every time + +cancer=load_breast_cancer() #Download breast cancer dataset + +inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters) +outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant) +labels=cancer.feature_names[0:30] + +print('The content of the breast cancer dataset is:') #Print information about the datasets +print(labels) +print('-------------------------') +print("inputs = " + str(inputs.shape)) +print("outputs = " + str(outputs.shape)) +print("labels = "+ str(labels.shape)) + +x=inputs #Reassign the Feature and Label matrices to other variables +y=outputs + +#%% + +# Visualisation of dataset (for correlation analysis) + +plt.figure() +plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral) +plt.xlabel('Mean radius',fontweight='bold') +plt.ylabel('Mean perimeter',fontweight='bold') +plt.show() + +plt.figure() +plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral) +plt.xlabel('Mean compactness',fontweight='bold') +plt.ylabel('Mean concavity',fontweight='bold') +plt.show() + + +plt.figure() +plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) +plt.xlabel('Mean radius',fontweight='bold') +plt.ylabel('Mean texture',fontweight='bold') +plt.show() + +plt.figure() +plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) +plt.xlabel('Mean perimeter',fontweight='bold') +plt.ylabel('Mean compactness',fontweight='bold') +plt.show() + + +# Generate training and testing datasets + +#Select features relevant to classification (texture,perimeter,compactness and symmetery) +#and add to input matrix + +temp1=np.reshape(x[:,1],(len(x[:,1]),1)) +temp2=np.reshape(x[:,2],(len(x[:,2]),1)) +X=np.hstack((temp1,temp2)) +temp=np.reshape(x[:,5],(len(x[:,5]),1)) +X=np.hstack((X,temp)) +temp=np.reshape(x[:,8],(len(x[:,8]),1)) +X=np.hstack((X,temp)) + +X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing + +y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy +y_test=to_categorical(y_test) + +del temp1,temp2,temp + +# %% + +# Define tunable parameters" + +eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser) +lamda=0.01 #Define hyperparameter +n_layers=2 #Define number of hidden layers in the model +n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer +epochs=100 #Number of reiterations over the input data +batch_size=100 #Number of samples per gradient update + +# %% + +"""Define function to return Deep Neural Network model""" + +def NN_model(inputsize,n_layers,n_neuron,eta,lamda): + model=Sequential() + for i in range(n_layers): #Run loop to add hidden layers to the model + if (i==0): #First layer requires input dimensions + model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize)) + else: #Subsequent layers are capable of automatic shape inferencing + model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda))) + model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob) + sgd=optimizers.SGD(lr=eta) + model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy']) + return model + + +Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function +Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for + +for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate + for j in range(len(eta)): #accuracy scores + DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda) + DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1) + Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1] + Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1] + + +def plot_data(x,y,data,title=None): + + # plot results + fontsize=16 + + + fig = plt.figure() + ax = fig.add_subplot(111) + cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1) + + cbar=fig.colorbar(cax) + cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize) + cbar.set_ticks([0,.2,.4,0.6,0.8,1.0]) + cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%']) + + # put text on matrix elements + for i, x_val in enumerate(np.arange(len(x))): + for j, y_val in enumerate(np.arange(len(y))): + c = "${0:.1f}\\%$".format( 100*data[j,i]) + ax.text(x_val, y_val, c, va='center', ha='center') + + # convert axis vaues to to string labels + x=[str(i) for i in x] + y=[str(i) for i in y] + + + ax.set_xticklabels(['']+x) + ax.set_yticklabels(['']+y) + + ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize) + ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize) + if title is not None: + ax.set_title(title) + + plt.tight_layout() + + plt.show() + +plot_data(eta,n_neuron,Train_accuracy, 'training') +plot_data(eta,n_neuron,Test_accuracy, 'testing') + +!ec + + + + + + +!split +===== Fine-tuning neural network hyperparameters ===== + +The flexibility of neural networks is also one of their main +drawbacks: there are many hyperparameters to tweak. Not only can you +use any imaginable network topology (how neurons/nodes are interconnected), +but even in a simple FFNN you can change the number of layers, the +number of neurons per layer, the type of activation function to use in +each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you +know what combination of hyperparameters is the best for your task? + +* You can use grid search with cross-validation to find the right hyperparameters. + +However,since there are many hyperparameters to tune, and since +training a neural network on a large dataset takes a lot of time, you +will only be able to explore a tiny part of the hyperparameter space. + + +* You can use randomized search. +* Or use tools like "Oscar":"http://oscar.calldesk.ai/", which implements more complex algorithms to help you find a good set of hyperparameters quickly. + +!split +===== Hidden layers ===== + + + +For many problems you can start with just one or two hidden layers and it will work just fine. +For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a +few hundred neurons. +You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of +neurons, in roughly the same amount of training time. + +For more complex problems, you can gradually +ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such +as large image classification or speech recognition, typically require networks with dozens of layers +and they need a huge amount +of training data. However, you will rarely have to train such networks from scratch: it is much more +common to reuse parts of a pretrained state-of-the-art network that performs a similar task. + + + + +!split +===== Which activation function should I use? ===== + +The Back propagation algorithm we derived above works by going from +the output layer to the input layer, propagating the error gradient on +the way. Once the algorithm has computed the gradient of the cost +function with regards to each parameter in the network, it uses these +gradients to update each parameter with a Gradient Descent (GD) step. + + +Unfortunately for us, the gradients often get smaller and smaller as the +algorithm progresses down to the first hidden layers. As a result, the +GD update leaves the lower layer connection weights +virtually unchanged, and training never converges to a good +solution. This is known in the literature as +_the vanishing gradients problem_. + +In other cases, the opposite can happen, namely the the gradients can grow bigger and +bigger. The result is that many of the layers get large updates of the +weights the +algorithm diverges. This is the _exploding gradients problem_, which is +mostly encountered in recurrent neural networks. More generally, deep +neural networks suffer from unstable gradients, different layers may +learn at widely different speeds + + + +!split +===== Is the Logistic activation function (Sigmoid) our choice? ===== + +Although this unfortunate behavior has been empirically observed for +quite a while (it was one of the reasons why deep neural networks were +mostly abandoned for a long time), it is only around 2010 that +significant progress was made in understanding it. + +A paper titled "Understanding the Difficulty of Training Deep +Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio":"http://proceedings.mlr.press/v9/glorot10a.html" found that +the problems with the popular logistic +sigmoid activation function and the weight initialization technique +that was most popular at the time, namely random initialization using +a normal distribution with a mean of 0 and a standard deviation of +1. + +They showed that with this activation function and this +initialization scheme, the variance of the outputs of each layer is +much greater than the variance of its inputs. Going forward in the +network, the variance keeps increasing after each layer until the +activation function saturates at the top layers. This is actually made +worse by the fact that the logistic function has a mean of 0.5, not 0 +(the hyperbolic tangent function has a mean of 0 and behaves slightly +better than the logistic function in deep networks). + + +!split +===== The derivative of the Logistic funtion ===== + +Looking at the logistic activation function, when inputs become large +(negative or positive), the function saturates at 0 or 1, with a +derivative extremely close to 0. Thus when backpropagation kicks in, +it has virtually no gradient to propagate back through the network, +and what little gradient exists keeps getting diluted as +backpropagation progresses down through the top layers, so there is +really nothing left for the lower layers. + +In their paper, Glorot and Bengio propose a way to significantly +alleviate this problem. We need the signal to flow properly in both +directions: in the forward direction when making predictions, and in +the reverse direction when backpropagating gradients. We don’t want +the signal to die out, nor do we want it to explode and saturate. For +the signal to flow properly, the authors argue that we need the +variance of the outputs of each layer to be equal to the variance of +its inputs, and we also need the gradients to have equal variance +before and after flowing through a layer in the reverse direction. + + + +One of the insights in the 2010 paper by Glorot and Bengio was that +the vanishing/exploding gradients problems were in part due to a poor +choice of activation function. Until then most people had assumed that +if Nature had chosen to use roughly sigmoid activation functions in +biological neurons, they must be an excellent choice. But it turns out +that other activation functions behave much better in deep neural +networks, in particular the ReLU activation function, mostly because +it does not saturate for positive values (and also because it is quite +fast to compute). + + +!split +===== The RELU function family ===== + +The ReLU activation function suffers from a problem known as the dying +ReLUs: during training, some neurons effectively die, meaning they +stop outputting anything other than 0. + +In some cases, you may find that half of your network’s neurons are +dead, especially if you used a large learning rate. During training, +if a neuron’s weights get updated such that the weighted sum of the +neuron’s inputs is negative, it will start outputting 0. When this +happen, the neuron is unlikely to come back to life since the gradient +of the ReLU function is 0 when its input is negative. + +To solve this problem, nowadays practitioners use a variant of the ReLU +function, such as the leaky ReLU discussed above or the so-called +exponential linear unit (ELU) function + + +!bt +\[ +ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. +\] +!et + +!split +===== Which activation function should we use? ===== + +In general it seems that the ELU activation function is better than +the leaky ReLU function (and its variants), which is better than +ReLU. ReLU performs better than $\tanh$ which in turn performs better +than the logistic function. + +If runtime +performance is an issue, then you may opt for the leaky ReLU function over the +ELU function If you don’t +want to tweak yet another hyperparameter, you may just use the default +$\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have +spare time and computing power, you can use cross-validation or +bootstrap to evaluate other activation functions. + + +!split +===== More on activation functions, output layers ===== + +In most cases you can use the ReLU activation function in the hidden layers (or one of its variants). + +It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck. + +_For the output layer:_ + +* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive). +* For regression tasks, you can simply use no activation function at all. + + + + +!split +===== Batch Normalization ===== + +Batch Normalization +aims to address the vanishing/exploding gradients problems, and more generally the problem that the +distribution of each layer’s inputs changes during training, as the parameters of the previous layers change. + +The technique consists of adding an operation in the model just before the activation function of each +layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new +parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model +learn the optimal scale and mean of the inputs for each layer. +In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and +standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current +mini-batch, from this the name batch normalization. + +!split +===== Dropout ===== + +It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but +excluding the output neurons) has a probability $p$ of being temporarily dropped out, meaning it will be +entirely ignored during this training step, but it may be active during the next step. + +The +hyperparameter $p$ is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore. + It is viewed as one of the most popular regularization techniques. + +!split +===== Gradient Clipping ===== + +A popular technique to lessen the exploding gradients problem is to simply clip the gradients during +backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural +networks). + +This technique is called Gradient Clipping. + +In general however, Batch +Normalization is preferred. + +!split +===== A very nice website on Neural Networks ===== + +You may find this "website":"https://playground.tensorflow.org/#activation=tanh&batchSize=10&dataset=circle®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=4,2&seed=0.29243&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false" very useful. + +!split +===== A top-down perspective on Neural networks ===== + + +The first thing we would like to do is divide the data into two or three +parts. A training set, a validation or dev (development) set, and a +test set. The test set is the data on which we want to make +predictions. The dev set is a subset of the training data we use to +check how well we are doing out-of-sample, after training the model on +the training dataset. We use the validation error as a proxy for the +test error in order to make tweaks to our model. It is crucial that we +do not use any of the test data to train the algorithm. This is a +cardinal sin in ML. Then: + + +* Estimate optimal error rate + +* Minimize underfitting (bias) on training data set. + +* Make sure you are not overfitting. + +If the validation and test sets are drawn from the same distributions, +then a good performance on the validation set should lead to similarly +good performance on the test set. + +However, sometimes +the training data and test data differ in subtle ways because, for +example, they are collected using slightly different methods, or +because it is cheaper to collect data in one way versus another. In +this case, there can be a mismatch between the training and test +data. This can lead to the neural network overfitting these small +differences between the test and training sets, and a poor performance +on the test set despite having a good performance on the validation +set. To rectify this, Andrew Ng suggests making two validation or dev +sets, one constructed from the training data and one constructed from +the test data. The difference between the performance of the algorithm +on these two validation sets quantifies the train-test mismatch. This +can serve as another important diagnostic when using DNNs for +supervised learning. + +!split +===== Limitations of supervised learning with deep networks ===== + +Like all statistical methods, supervised learning using neural +networks has important limitations. This is especially important when +one seeks to apply these methods, especially to physics problems. Like +all tools, DNNs are not a universal solution. Often, the same or +better performance on a task can be achieved by using a few +hand-engineered features (or even a collection of random +features). + +Here we list some of the important limitations of supervised neural network based models. + + + +* _Need labeled data_. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images). +* _Supervised neural networks are extremely data intensive._ DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs. +* _Homogeneous data._ Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e.~some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types. +* _Many problems are not about prediction._ In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science. + +Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems. + + + diff --git a/doc/src/week42/exercisesweek42.do.txt b/doc/src/week42/exercisesweek42.do.txt new file mode 100644 index 000000000..0c5446b98 --- /dev/null +++ b/doc/src/week42/exercisesweek42.do.txt @@ -0,0 +1,781 @@ +TITLE: Exercises week 41 +AUTHOR: October 9-13, 2023 +DATE: Deadline is Sunday October 15 at midnight + + +======= Overarching aims of the exercises this week ======= + +The aim of the exercises this week is to get started with implementing +gradient methods of relevance for project 2. This exercise will also +be continued next week with the addition of automatic differentation. +Everything you develop here will be used in project 2. + +In order to get started, we will now replace in our standard ordinary +least squares (OLS) and Ridge regression codes (from project 1) the +matrix inversion algorithm with our own gradient descent (GD) and SGD +codes. You can use the Franke function or the terrain data from +project 1. _However, we recommend using a simpler function like_ +$f(x)=a_0+a_1x+a_2x^2$ or higher-order one-dimensional polynomials. +You can obviously test your final codes against for example the Franke +function. Automatic differentiation will be discussed next week. + +You should include in your analysis of the GD and SGD codes the following elements +o A plain gradient descent with a fixed learning rate (you will need to tune it) using the analytical expression of the gradients +o Add momentum to the plain GD code and compare convergence with a fixed learning rate (you may need to tune the learning rate), again using the analytical expression of the gradients. +o Repeat these steps for stochastic gradient descent with mini batches and a given number of epochs. Use a tunable learning rate as discussed in the lectures from week 39. Discuss the results as functions of the various parameters (size of batches, number of epochs etc) +o Implement the Adagrad method in order to tune the learning rate. Do this with and without momentum for plain gradient descent and SGD. +o Add RMSprop and Adam to your library of methods for tuning the learning rate. +The lecture notes from weeks 39 and 40 contain more information and code examples. Feel free to use these examples. + +In summary, you should +perform an analysis of the results for OLS and Ridge regression as +function of the chosen learning rates, the number of mini-batches and +epochs as well as algorithm for scaling the learning rate. You can +also compare your own results with those that can be obtained using +for example _Scikit-Learn_'s various SGD options. Discuss your +results. For Ridge regression you need now to study the results as functions of the hyper-parameter $\lambda$ and +the learning rate $\eta$. Discuss your results. + +You will need your SGD code for the setup of the Neural Network and +Logistic Regression codes. You will find the Python "Seaborn +package":"https://seaborn.pydata.org/generated/seaborn.heatmap.html" +useful when plotting the results as function of the learning rate +$\eta$ and the hyper-parameter $\lambda$ when you use Ridge +regression. + +We recommend reading chapter 8 on optimization from the textbook of "Goodfellow, Bengio and Courville":"https://www.deeplearningbook.org/". This chapter contains many useful insights and discussions on the optimization part of machine learning. + + +======= Code examples from week 39 and 40 ======= + + + + +===== Code with a Number of Minibatches which varies, analytical gradient ===== + +In the code here we vary the number of mini-batches. +!bc pycode +# Importing various packages +from math import exp, sqrt +from random import random, seed +import numpy as np +import matplotlib.pyplot as plt + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 + + +for iter in range(Niterations): + gradients = 2.0/n*X.T @ ((X @ theta)-y) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +t0, t1 = 5, 50 + +def learning_schedule(t): + return t0/(t+t1) + +theta = np.random.randn(2,1) + +for epoch in range(n_epochs): +# Can you figure out a better way of setting up the contributions to each batch? + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi) + eta = learning_schedule(epoch*m+i) + theta = theta - eta*gradients +print("theta from own sdg") +print(theta) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') +plt.show() + +!ec + + + +In the above code, we have use replacement in setting up the +mini-batches. The discussion +"here":"https://sebastianraschka.com/faq/docs/sgd-methods.html" may be +useful. + + + +===== Momentum based GD ===== + +The stochastic gradient descent (SGD) is almost always used with a +*momentum* or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows + +!bt +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\end{align} +!et + +where we have introduced a momentum parameter $\gamma$, with +$0\le\gamma\le 1$, and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that $\mathbf{v}_t$ is a +running average of recently encountered gradients and +$(1-\gamma)^{-1}$ sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +$\gamma=0$, this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is + +!bt +\[ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +\] +!et +where we have defined $\Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1}$. + +===== Algorithms and codes for Adagrad, RMSprop and Adam ===== + +The algorithms we have implemented are well described in the text by "Goodfellow, Bengio and Courville, chapter 8":"https://www.deeplearningbook.org/contents/optimization.html". + +The codes which implement these algorithms are discussed after our presentation of automatic differentiation. + + + +===== Practical tips ===== + +* _Randomize the data when making mini-batches_. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented. + +* _Transform your inputs_. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case. + +* _Monitor the out-of-sample performance._ Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings. + +* _Adaptive optimization methods don't always have good generalization._ Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications. + +Geron's text, see chapter 11, has several interesting discussions. + +===== Using Automatic differentation with OLS ===== + +We conclude the part on optmization by showing how we can make codes +for linear regression and logistic regression using _autograd_. The +first example shows results with ordinary leats squares. + +!bc pycod +# Using Autograd to calculate gradients for OLS +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +def CostOLS(beta): + return (1.0/n)*np.sum((y-X @ beta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 +# define the gradient +training_gradient = grad(CostOLS) + +for iter in range(Niterations): + gradients = training_gradient(theta) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') +plt.show() + +!ec + + + +===== Same code but now with momentum gradient descent ===== +!bc pycod +# Using Autograd to calculate gradients for OLS +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +def CostOLS(beta): + return (1.0/n)*np.sum((y-X @ beta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x#+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 30 + +# define the gradient +training_gradient = grad(CostOLS) + +for iter in range(Niterations): + gradients = training_gradient(theta) + theta -= eta*gradients + print(iter,gradients[0],gradients[1]) +print("theta from own gd") +print(theta) + +# Now improve with momentum gradient descent +change = 0.0 +delta_momentum = 0.3 +for iter in range(Niterations): + # calculate gradient + gradients = training_gradient(theta) + # calculate update + new_change = eta*gradients+delta_momentum*change + # take a step + theta -= new_change + # save the change + change = new_change + print(iter,gradients[0],gradients[1]) +print("theta from own gd wth momentum") +print(theta) + +!ec + + +===== But noen of these can compete with Newton's method ===== + +!bc pycod +# Using Newton's method +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +def CostOLS(beta): + return (1.0/n)*np.sum((y-X @ beta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(beta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +# Note that here the Hessian does not depend on the parameters beta +invH = np.linalg.pinv(H) +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +beta = np.random.randn(2,1) +Niterations = 5 + +# define the gradient +training_gradient = grad(CostOLS) + +for iter in range(Niterations): + gradients = training_gradient(beta) + beta -= invH @ gradients + print(iter,gradients[0],gradients[1]) +print("beta from own Newton code") +print(beta) +!ec + + + +===== Including Stochastic Gradient Descent with Autograd ===== +In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using _autograd_. + +!bc pycod +# Using Autograd to calculate gradients using SGD +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) + +for iter in range(Niterations): + gradients = (1.0/n)*training_gradient(y, X, theta) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') +plt.show() + +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +t0, t1 = 5, 50 +def learning_schedule(t): + return t0/(t+t1) + +theta = np.random.randn(2,1) + +for epoch in range(n_epochs): +# Can you figure out a better way of setting up the contributions to each batch? + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + eta = learning_schedule(epoch*m+i) + theta = theta - eta*gradients +print("theta from own sdg") +print(theta) + + +!ec + + + +===== Same code but now with momentum gradient descent ===== +!bc pycod +# Using Autograd to calculate gradients using SGD +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 100 + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) + +for iter in range(Niterations): + gradients = (1.0/n)*training_gradient(y, X, theta) + theta -= eta*gradients +print("theta from own gd") +print(theta) + + +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +t0, t1 = 5, 50 +def learning_schedule(t): + return t0/(t+t1) + +theta = np.random.randn(2,1) + +change = 0.0 +delta_momentum = 0.3 + +for epoch in range(n_epochs): + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + eta = learning_schedule(epoch*m+i) + # calculate update + new_change = eta*gradients+delta_momentum*change + # take a step + theta -= new_change + # save the change + change = new_change +print("theta from own sdg with momentum") +print(theta) +!ec + +===== AdaGrad algorithm, taken from "Goodfellow et al":"https://www.deeplearningbook.org/contents/optimization.html" ===== + +FIGURE: [figures/adagrad.png, width=600 frac=0.8] + +===== Similar (second order function now) problem but now with AdaGrad ===== +!bc pycod +# Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 1000 +x = np.random.rand(n,1) +y = 2.0+3*x +4*x*x + +X = np.c_[np.ones((n,1)), x, x*x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) + + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) +# Define parameters for Stochastic Gradient Descent +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +# Guess for unknown parameters theta +theta = np.random.randn(3,1) + +# Value for learning rate +eta = 0.01 +# Including AdaGrad parameter to avoid possible division by zero +delta = 1e-8 +for epoch in range(n_epochs): + Giter = 0.0 + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + Giter += gradients*gradients + update = gradients*eta/(delta+np.sqrt(Giter)) + theta -= update +print("theta from own AdaGrad") +print(theta) + + +!ec + +Running this code we note an almost perfect agreement with the results from matrix inversion. + +===== RMSProp algorithm, taken from "Goodfellow et al":"https://www.deeplearningbook.org/contents/optimization.html" ===== + +FIGURE: [figures/rmsprop.png, width=600 frac=0.8] + + +===== RMSprop for adaptive learning rate with Stochastic Gradient Descent ===== +!bc pycod +# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 1000 +x = np.random.rand(n,1) +y = 2.0+3*x +4*x*x# +np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x, x*x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) + + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) +# Define parameters for Stochastic Gradient Descent +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +# Guess for unknown parameters theta +theta = np.random.randn(3,1) + +# Value for learning rate +eta = 0.01 +# Value for parameter rho +rho = 0.99 +# Including AdaGrad parameter to avoid possible division by zero +delta = 1e-8 +for epoch in range(n_epochs): + Giter = 0.0 + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + # Accumulated gradient + # Scaling with rho the new and the previous results + Giter = (rho*Giter+(1-rho)*gradients*gradients) + # Taking the diagonal only and inverting + update = gradients*eta/(delta+np.sqrt(Giter)) + # Hadamard product + theta -= update +print("theta from own RMSprop") +print(theta) +!ec + +===== ADAM algorithm, taken from "Goodfellow et al":"https://www.deeplearningbook.org/contents/optimization.html" ===== + +FIGURE: [figures/adam.png, width=600 frac=0.8] + + +===== And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf" ===== + +!bc pycod +# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 1000 +x = np.random.rand(n,1) +y = 2.0+3*x +4*x*x# +np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x, x*x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) + + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) +# Define parameters for Stochastic Gradient Descent +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +# Guess for unknown parameters theta +theta = np.random.randn(3,1) + +# Value for learning rate +eta = 0.01 +# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980 +beta1 = 0.9 +beta2 = 0.999 +# Including AdaGrad parameter to avoid possible division by zero +delta = 1e-7 +iter = 0 +for epoch in range(n_epochs): + first_moment = 0.0 + second_moment = 0.0 + iter += 1 + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + # Computing moments first + first_moment = beta1*first_moment + (1-beta1)*gradients + second_moment = beta2*second_moment+(1-beta2)*gradients*gradients + first_term = first_moment/(1.0-beta1**iter) + second_term = second_moment/(1.0-beta2**iter) + # Scaling with rho the new and the previous results + update = eta*first_term/(np.sqrt(second_term)+delta) + theta -= update +print("theta from own ADAM") +print(theta) +!ec + +===== Introducing "JAX":"https://jax.readthedocs.io/en/latest/" ===== + +Presently, instead of using _autograd_, we recommend using "JAX":"https://jax.readthedocs.io/en/latest/" + +_JAX_ is Autograd and "XLA (Accelerated Linear Algebra))":"https://www.tensorflow.org/xla", +brought together for high-performance numerical computing and machine learning research. +It provides composable transformations of Python+NumPy programs: differentiate, vectorize, parallelize, Just-In-Time compile to GPU/TPU, and more. + +=== Getting started with Jax, note the way we import numpy === +!bc pycod +import jax +import jax.numpy as jnp +import numpy as np +import matplotlib.pyplot as plt + +from jax import grad as jax_grad +!ec + + +=== A warm-up example === + +!bc pycod +def function(x): + return x**2 + +def analytical_gradient(x): + return 2*x + +def gradient_descent(starting_point, learning_rate, num_iterations, solver="analytical"): + x = starting_point + trajectory_x = [x] + trajectory_y = [function(x)] + + if solver == "analytical": + grad = analytical_gradient + elif solver == "jax": + grad = jax_grad(function) + x = jnp.float64(x) + learning_rate = jnp.float64(learning_rate) + + for _ in range(num_iterations): + + x = x - learning_rate * grad(x) + trajectory_x.append(x) + trajectory_y.append(function(x)) + + return trajectory_x, trajectory_y + +x = np.linspace(-5, 5, 100) +plt.plot(x, function(x), label="f(x)") + +descent_x, descent_y = gradient_descent(5, 0.1, 10, solver="analytical") +jax_descend_x, jax_descend_y = gradient_descent(5, 0.1, 10, solver="jax") + +plt.plot(descent_x, descent_y, label="Gradient descent", marker="o") +plt.plot(jax_descend_x, jax_descend_y, label="JAX", marker="x") +!ec + +=== A more advanced example === + +!bc pycod +backend = np + +def function(x): + return x*backend.sin(x**2 + 1) + +def analytical_gradient(x): + return backend.sin(x**2 + 1) + 2*x**2*backend.cos(x**2 + 1) + + +x = np.linspace(-5, 5, 100) +plt.plot(x, function(x), label="f(x)") + +descent_x, descent_y = gradient_descent(1, 0.01, 300, solver="analytical") + +# Change the backend to JAX +backend = jnp +jax_descend_x, jax_descend_y = gradient_descent(1, 0.01, 300, solver="jax") + +plt.scatter(descent_x, descent_y, label="Gradient descent", marker="v", s=10, color="red") +plt.scatter(jax_descend_x, jax_descend_y, label="JAX", marker="x", s=5, color="black") +!ec + diff --git a/doc/src/week42/week41.do.txt b/doc/src/week42/week41.do.txt new file mode 100644 index 000000000..b412b1c46 --- /dev/null +++ b/doc/src/week42/week41.do.txt @@ -0,0 +1,2338 @@ +TITLE: Week 41 Neural networks and constructing a neural network code +AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University +DATE: Week 41 + + +!split +===== Plan for week 41 ===== + + +!bblock Material for the active learning sessions on Tuesday and Wednesday + * Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation + * One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code + * Discussion of project 2 + * Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent +!eblock + +!bblock Material for the lecture on Thursday October 12, 2023 + * Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model. + * Building our own Feed-forward Neural Network + * "Video of lecture notes":"https://youtu.be/5-RRTO9uDvI" + * "Whiteboard notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesOct12.pdf" + * Readings and Videos: + * These lecture notes + * For neural networks we recommend Goodfellow et al chapter 6. + * "Neural Networks demystified":"https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" + * "Building Neural Networks from scratch":"https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex" + * "Video on Neural Networks":"https://www.youtube.com/watch?v=CqOfi41LfDw" + * "Video on the back propagation algorithm":"https://www.youtube.com/watch?v=Ilg3gGewQ5U" +I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at URL:"http://neuralnetworksanddeeplearning.com/chap4.html". +!eblock + + + +!split +===== Lecture Thursday October 12 ===== + +!split +===== Introduction to Neural networks ===== + +Artificial neural networks are computational systems that can learn to +perform tasks by considering examples, generally without being +programmed with any task-specific rules. It is supposed to mimic a +biological system, wherein neurons interact by sending signals in the +form of mathematical functions between layers. All layers can contain +an arbitrary number of neurons, and each connection is represented by +a weight variable. + + +!split +===== Artificial neurons ===== + +The field of artificial neural networks has a long history of +development, and is closely connected with the advancement of computer +science and computers in general. A model of artificial neurons was +first developed by McCulloch and Pitts in 1943 to study signal +processing in the brain and has later been refined by others. The +general idea is to mimic neural networks in the human brain, which is +composed of billions of neurons that communicate with each other by +sending electrical signals. Each neuron accumulates its incoming +signals, which must exceed an activation threshold to yield an +output. If the threshold is not overcome, the neuron remains inactive, +i.e. has zero output. + +This behaviour has inspired a simple mathematical model for an artificial neuron. + +!bt +\begin{equation} + y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u) + label{artificialNeuron} +\end{equation} +!et +Here, the output $y$ of the neuron is the value of its activation function, which have as input +a weighted sum of signals $x_i, \dots ,x_n$ received by $n$ other neurons. + +Conceptually, it is helpful to divide neural networks into four +categories: +o general purpose neural networks for supervised learning, +o neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs), +o neural networks for sequential data such as Recurrent Neural Networks (RNNs), and +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, +topological phases, and even non-equilibrium many-body +localization. Representing quantum states as DNNs quantum state +tomography are among some of the impressive achievements to reveal the +potential of DNNs to facilitate the study of quantum systems. + +In quantum information theory, it has been shown that one can perform +gate decompositions with the help of neural. + +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 (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 we discussed earlier. + + +!split +===== Feed-forward neural networks ===== + +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 +(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. + + + +!split +===== Convolutional Neural Network ===== + +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 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 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 ===== + +One uses often so-called fully-connected feed-forward neural networks +with three or more layers (an input layer, one or more hidden layers +and an output layer) consisting of neurons that have non-linear +activation functions. + +Such networks are often called *multilayer perceptrons* (MLPs). + +!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_. + +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. + + +!split +===== Illustration of a single perceptron model and a multi-perceptron model ===== + +FIGURE: [figures/nns.png, width=600 frac=0.8] In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer. + + +!split +===== Examples of XOR, OR and AND gates ===== + + + +Let us first try to fit various gates using standard linear +regression. The gates we are thinking of are the classical XOR, OR and +AND gates, well-known elements in computer science. The tables here +show how we can set up the inputs $x_1$ and $x_2$ in order to yield a +specific target $y_i$. + + + + +!bc pycod +""" +Simple code that tests XOR, OR and AND gates with linear regression +""" + +import numpy as np +# Design matrix +X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64) +print(f"The X.TX matrix:{X.T @ X}") +Xinv = np.linalg.pinv(X.T @ X) +print(f"The invers of X.TX matrix:{Xinv}") + +# The XOR gate +yXOR = np.array( [ 0, 1 ,1, 0]) +ThetaXOR = Xinv @ X.T @ yXOR +print(f"The values of theta for the XOR gate:{ThetaXOR}") +print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}") + + +# The OR gate +yOR = np.array( [ 0, 1 ,1, 1]) +ThetaOR = Xinv @ X.T @ yOR +print(f"The values of theta for the OR gate:{ThetaOR}") +print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}") + + +# The OR gate +yAND = np.array( [ 0, 0 ,0, 1]) +ThetaAND = Xinv @ X.T @ yAND +print(f"The values of theta for the AND gate:{ThetaAND}") +print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}") +!ec + +What is happening here? + +!split +===== Does Logistic Regression do a better Job? ===== + +!bc pycod +""" +Simple code that tests XOR and OR gates with linear regression +and logistic regression +""" + +import matplotlib.pyplot as plt +from sklearn.linear_model import LogisticRegression +import numpy as np + +# Design matrix +X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64) +print(f"The X.TX matrix:{X.T @ X}") +Xinv = np.linalg.pinv(X.T @ X) +print(f"The invers of X.TX matrix:{Xinv}") + +# The XOR gate +yXOR = np.array( [ 0, 1 ,1, 0]) +ThetaXOR = Xinv @ X.T @ yXOR +print(f"The values of theta for the XOR gate:{ThetaXOR}") +print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}") + + +# The OR gate +yOR = np.array( [ 0, 1 ,1, 1]) +ThetaOR = Xinv @ X.T @ yOR +print(f"The values of theta for the OR gate:{ThetaOR}") +print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}") + + +# The OR gate +yAND = np.array( [ 0, 0 ,0, 1]) +ThetaAND = Xinv @ X.T @ yAND +print(f"The values of theta for the AND gate:{ThetaAND}") +print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}") + +# Now we change to logistic regression + + +# Logistic Regression +logreg = LogisticRegression() +logreg.fit(X, yOR) +print("Test set accuracy with Logistic Regression for OR gate: {:.2f}".format(logreg.score(X,yOR))) + +logreg.fit(X, yXOR) +print("Test set accuracy with Logistic Regression for XOR gate: {:.2f}".format(logreg.score(X,yXOR))) + + +logreg.fit(X, yAND) +print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND))) +!ec + +Not exactly impressive, but somewhat better. + +!split +===== Adding Neural Networks ===== + +!bc pycod + +# and now neural networks with Scikit-Learn and the XOR + +from sklearn.neural_network import MLPClassifier +from sklearn.datasets import make_classification +X, yXOR = make_classification(n_samples=100, random_state=1) +FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR) +FFNN.predict_proba(X) +print(f"Test set accuracy with Feed Forward Neural Network for XOR gate:{FFNN.score(X, yXOR)}") + +!ec + + + +!split +===== Mathematical model ===== + +The output $y$ is produced via the activation function $f$ +!bt +\[ + 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+b_i)$. +In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of +the neurons in the preceding layer. Furthermore, an MLP is +fully-connected, which means that each neuron receives a weighted sum +of the outputs of *all* neurons in the previous layer. + +!split +===== Mathematical model ===== + +First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$, + +!bt +\begin{equation} z_i^1 = \sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1 +\end{equation} +!et + +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(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$. 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) + label{generalLayer} +\end{equation} +!et + +where $N_l$ is the number of nodes in layer $l$. When the output of +all the nodes in the first hidden layer are computed, the values of +the subsequent layer can be calculated and so forth until the output +is obtained. + + + +!split +===== Mathematical model ===== + +The output of neuron $i$ in layer 2 is thus, + +!bt +\begin{align} + 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_k^1$ with the inputs $x_k$. Finally, the ANN output reads + +!bt +\begin{align} + 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} w_{ij}^3 f^2\left(\sum_{k} w_{jk}^2 f^1\left(\sum_{m} w_{km}^1 x_m + b_k^1\right) + b_j^2\right) + + b_1^3\right] +\end{align} +!et + +!split +===== Mathematical model ===== + +We can generalize this expression to an MLP with $l$ hidden +layers. The complete functional form is, + +!bt +\begin{align} +&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}^{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} +\end{align} +!et + +which illustrates a basic property of MLPs: The only independent +variables are the input values $x_n$. + +!split +===== Mathematical model ===== + +This confirms that an MLP, despite its quite convoluted mathematical +form, is nothing more than an analytic function, specifically a +mapping of real-valued vectors $\hat{x} \in \mathbb{R}^n \rightarrow +\hat{y} \in \mathbb{R}^m$. + +Furthermore, the flexibility and universality of an MLP can be +illustrated by realizing that the expression is essentially a nested +sum of scaled activation functions of the form + +!bt +\begin{equation} + f(x) = c_1 f(c_2 x + c_3) + c_4 +\end{equation} +!et + +where the parameters $c_i$ are weights and biases. By adjusting these +parameters, the activation functions can be shifted up and down or +left and right, change slope or be rescaled which is the key to the +flexibility of a neural network. + +!split +=== Matrix-vector notation === + +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 $\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 an $N_{l-1} \times N_l$ matrix, while $\hat{b}_l$ and $\hat{y}_l$ are $N_l \times 1$ column vectors. +With this notation, the sum becomes a matrix-vector multiplication, and we can write +the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as +!bt +\begin{equation} + \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} \\ + w^2_{31} &w^2_{32} &w^2_{33} \\ + \end{array} \right] \cdot + \left[\begin{array}{c} + y^1_1 \\ + y^1_2 \\ + y^1_3 \\ + \end{array}\right] + + \left[\begin{array}{c} + b^2_1 \\ + b^2_2 \\ + b^2_3 \\ + \end{array}\right]\right). +\end{equation} +!et + +!split +=== Matrix-vector notation and activation === + +The activation of node $i$ in layer 2 is + +!bt +\begin{equation} + y^2_i = f_2\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\Bigr) = + f_2\left(\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\right). +\end{equation} +!et + +This is not just a convenient and compact notation, but also a useful +and intuitive way to think about MLPs: The output is calculated by a +series of matrix-vector multiplications and vector additions that are +used as input to the activation functions. For each operation +$\mathrm{W}_l \hat{y}_{l-1}$ we move forward one layer. + + +!split +=== Activation functions === + + +A property that characterizes a neural network, other than its +connectivity, is the choice of activation function(s). As described +in, the following restrictions are imposed on an activation function +for a FFNN to fulfill the universal approximation theorem + + * Non-constant + + * Bounded + + * Monotonically-increasing + + * Continuous + +!split +=== Activation functions, Logistic and Hyperbolic ones === + +The second requirement excludes all linear functions. Furthermore, in +a MLP with only linear activation functions, each layer simply +performs a linear transformation of its inputs. + +Regardless of the number of layers, the output of the NN will be +nothing but a linear function of the inputs. Thus we need to introduce +some kind of non-linearity to the NN to be able to fit non-linear +functions Typical examples are the logistic *Sigmoid* + +!bt +\[ + f(x) = \frac{1}{1 + e^{-x}}, +\] +!et +and the *hyperbolic tangent* function +!bt +\[ + f(x) = \tanh(x) +\] +!et + +!split +=== Relevance === + +The *sigmoid* function are more biologically plausible because the +output of inactive neurons are zero. Such activation function are +called *one-sided*. However, it has been shown that the hyperbolic +tangent performs better than the sigmoid for training MLPs. has +become the most popular for *deep neural networks* + +!bc pycod +"""The sigmoid function (or the logistic curve) is a +function that takes any real number, z, and outputs a number (0,1). +It is useful in neural networks for assigning weights on a relative scale. +The value z is the weighted sum of parameters involved in the learning algorithm.""" + +import numpy +import matplotlib.pyplot as plt +import math as mt + +z = numpy.arange(-5, 5, .1) +sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z))) +sigma = sigma_fn(z) + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.plot(z, sigma) +ax.set_ylim([-0.1, 1.1]) +ax.set_xlim([-5,5]) +ax.grid(True) +ax.set_xlabel('z') +ax.set_title('sigmoid function') + +plt.show() + +"""Step Function""" +z = numpy.arange(-5, 5, .02) +step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0) +step = step_fn(z) + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.plot(z, step) +ax.set_ylim([-0.5, 1.5]) +ax.set_xlim([-5,5]) +ax.grid(True) +ax.set_xlabel('z') +ax.set_title('step function') + +plt.show() + +"""Sine Function""" +z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1) +t = numpy.sin(z) + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.plot(z, t) +ax.set_ylim([-1.0, 1.0]) +ax.set_xlim([-2*mt.pi,2*mt.pi]) +ax.grid(True) +ax.set_xlabel('z') +ax.set_title('sine function') + +plt.show() + +"""Plots a graph of the squashing function used by a rectified linear +unit""" +z = numpy.arange(-2, 2, .1) +zero = numpy.zeros(len(z)) +y = numpy.max([zero, z], axis=0) + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.plot(z, y) +ax.set_ylim([-2.0, 2.0]) +ax.set_xlim([-2.0, 2.0]) +ax.grid(True) +ax.set_xlabel('z') +ax.set_title('Rectified linear unit') + +plt.show() +!ec + + + +!split +===== The multilayer perceptron (MLP) ===== + +The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of +o A neural network with one or more layers of nodes between the input and the output nodes. +o The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one 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 one layer of input units, one layer of hidden +units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc. + +For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. +Hereafter we will call the various entities of a layer for nodes. +There are also no connections within a single layer. + +The number of input nodes does not need to equal the number of output +nodes. This applies also to the hidden layers. Each layer may have its +own number of nodes and activation functions. + +The hidden layers have their name from the fact that they are not +linked to observables and as we will see below when we define the +so-called activation $\hat{z}$, we can think of this as a basis +expansion of the original inputs $\hat{x}$. The difference however +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 results in an important difference between +neural networks and deep learning approaches on one side and methods +like logistic regression or linear regression and their modifications on the other side. + + +!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. + +As stated earlier, +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". + +It states that a feed-forward network with a single hidden layer +containing a finite number of neurons can approximate continuous +functions on compact subsets of real functions. The theorem thus +states that simple neural networks can represent a wide variety of +interesting functions when given appropriate parameters. It is the +multilayer feedforward architecture itself which gives neural networks +the potential of being universal approximators. + + +!split +===== Deriving the back propagation code for a multilayer perceptron model ===== + + + +As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. +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? + +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 $K$ +classes. + +!split +===== Definitions ===== + +With our definition of the targets $\hat{t}$, the outputs of the +network $\hat{y}$ and the inputs $\hat{x}$ we +define now the activation $z_j^l$ of node/neuron/unit $j$ of the +$l$-th layer as a function of the bias, the weights which add up from +the previous layer $l-1$ and the forward passes/outputs +$\hat{a}^{l-1}$ from the previous layer as + + +!bt +\[ +z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{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, + +!bt +\[ +\hat{z}^l = \left(\hat{W}^l\right)^T\hat{a}^{l-1}+\hat{b}^l. +\] +!et + +With the activation values $\hat{z}^l$ we can in turn define the +output of layer $l$ as $\hat{a}^l = f(\hat{z}^l)$ where $f$ is our +activation function. In the examples here we will use the sigmoid +function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers +and their nodes. It means we have + +!bt +\[ +a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. +\] +!et + + +!split +===== Derivatives and the chain rule ===== + +From the definition of the activation $z_j^l$ we have +!bt +\[ +\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, +\] +!et +and +!bt +\[ +\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. +\] +!et + +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)). +\] +!et + + +!split +===== Derivative of the cost function ===== + +With these definitions we can now compute the derivative of the cost function in terms of the weights. + +Let us specialize to the output layer $l=L$. Our cost function is +!bt +\[ +{\cal C}(\hat{W^L}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - t_i\right)^2, +\] +!et +The derivative of this function with respect to the weights is + +!bt +\[ +\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}}, +\] +!et +The last partial derivative can easily be computed and reads (by applying the chain rule) +!bt +\[ +\frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1}, +\] +!et + + + +!split +===== Bringing it together, first back propagation equation ===== + +We have thus +!bt +\[ +\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)a_j^L(1-a_j^L)a_k^{L-1}, +\] +!et + +Defining +!bt +\[ +\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - t_j\right) = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, +\] +!et +and using the Hadamard product of two vectors we can write this as +!bt +\[ +\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 function is changing as a function of the $j$th +output activation. If, for example, the cost function doesn't depend +much on a particular output node $j$, then $\delta_j^L$ will be small, +which is what we would expect. The first term on the right, measures +how fast the activation function $f$ is changing at a given activation +value $z_j^L$. + +Notice that everything in the above equations is easily computed. In +particular, we compute $z_j^L$ while computing the behaviour of the +network, and it is only a small additional overhead to compute +$f'(z^L_j)$. The exact form of the derivative with respect to the +output depends on the form of the cost function. +However, provided the cost function is known there should be little +trouble in calculating + +!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 +\[ +\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}. +\] +!et + +!split +===== Derivatives in terms of $z_j^L$ ===== + +It is also easy to see that our previous equation can be written as + +!bt +\[ +\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, +\] +!et +which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely +!bt +\[ +\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, +\] +!et +That is, the error $\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias. +!split +===== Bringing it together ===== + +We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are + +!bblock The starting equations + +!bt +\begin{equation} +\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}, +\end{equation} +!et +and +!bt +\begin{equation} +\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, +\end{equation} +!et +and + +!bt +\begin{equation} +\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}, +\end{equation} +!et +!eblock + + +An interesting consequence of the above equations is that when the +activation $a_k^{L-1}$ is small, the gradient term, that is the +derivative of the cost function with respect to the weights, will also +tend to be small. We say then that the weight learns slowly, meaning +that it changes slowly when we minimize the weights via say gradient +descent. In this case we say the system learns slowly. + +Another interesting feature is that is when the activation function, +represented by the sigmoid function here, is rather flat when we move towards +its end values $0$ and $1$ (see the above Python codes). In these +cases, the derivatives of the activation function will also be close +to zero, meaning again that the gradients will be small and the +network learns slowly again. + + + +We need a fourth equation and we are set. We are going to propagate +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 ===== + +We have that (replacing $L$ with a general layer $l$) +!bt +\[ +\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. +\] +!et +We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have + +!bt +\[ +\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, +\] +!et +and recalling that +!bt +\[ +z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, +\] +!et +with $M_l$ being the number of nodes in layer $l$, we obtain +!bt +\[ +\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l), +\] +!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 ===== + + + +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. + +!bblock +First, we set up the input data $\hat{x}$ and the activations +$\hat{z}_1$ of the input layer and compute the activation function and +the pertinent outputs $\hat{a}^1$. +!eblock + +!bblock +Secondly, we perform then the feed forward till we reach the output +layer and compute all $\hat{z}_l$ of the input layer and compute the +activation function and the pertinent outputs $\hat{a}^l$ for +$l=2,3,\dots,L$. +!eblock + +!bblock +Thereafter we compute 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 +!eblock + +!bblock +Then we compute the back propagate error for each $l=L-1,L-2,\dots,2$ as +!bt +\[ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l). +\] +!et +!eblock + +!bblock +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 +!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}=b_j^l-\eta \delta_j^l, +\] +!et +!eblock + +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. + + +!split +===== Setting up the Back propagation algorithm ===== + + + +The four equations above provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm. + +!bblock +First, we set up the input data $\bm{x}$ and the activations +$\bm{z}_1$ of the input layer and compute the activation function and +the pertinent outputs $\bm{a}^1$. +!eblock + +!bblock +Secondly, we perform then the feed forward till we reach the output +layer and compute all $\bm{z}_l$ of the input layer and compute the +activation function and the pertinent outputs $\bm{a}^l$ for +$l=2,3,\dots,L$. +!eblock + +!bblock +Thereafter we compute the ouput error $\bm{\delta}^L$ by computing all +!bt +\[ +\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. +\] +!et +!eblock + +!bblock +Then we compute the back propagate error for each $l=L-1,L-2,\dots,2$ as +!bt +\[ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l). +\] +!et +!eblock + +!bblock +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 +!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}=b_j^l-\eta \delta_j^l, +\] +!et +!eblock + +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. + + + + + + + + +!split +===== Setting up the Back propagation algorithm ===== + + + +The four equations derived discussed above provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm. + +!bblock +First, we set up the input data $\bm{x}$ and the activations +$\bm{z}_1$ of the input layer and compute the activation function and +the pertinent outputs $\bm{a}^1$. +!eblock + +!bblock +Secondly, we perform then the feed forward till we reach the output +layer and compute all $\bm{z}_l$ of the input layer and compute the +activation function and the pertinent outputs $\bm{a}^l$ for +$l=2,3,\dots,L$. +!eblock + +!bblock +Thereafter we compute the ouput error $\bm{\delta}^L$ by computing all +!bt +\[ +\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. +\] +!et +!eblock + +!bblock +Then we compute the back propagate error for each $l=L-1,L-2,\dots,2$ as +!bt +\[ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l). +\] +!et +!eblock + +!bblock +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 +!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}=b_j^l-\eta \delta_j^l, +\] +!et +!eblock + +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. + + + + +!split +===== Setting up a Multi-layer perceptron model for classification ===== + +We are now gong to develop an example based on the MNIST data +base. This is a classification problem and we need to use our +cross-entropy function we discussed in connection with logistic +regression. The cross-entropy defines our cost function for the +classificaton problems with neural networks. + +In binary classification with two classes $(0, 1)$ we define the +logistic/sigmoid function as the probability that a particular input +is in class $0$ or $1$. This is possible because the logistic +function takes any input from the real numbers and inputs a number +between 0 and 1, and can therefore be interpreted as a probability. It +also has other nice properties, such as a derivative that is simple to +calculate. + +For an input $\boldsymbol{a}$ from the hidden layer, the probability that the input $\boldsymbol{x}$ +is in class 0 or 1 is just. We let $\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$ +represents our activation values $z$. We have +!bt +\[ +P(y = 0 \mid \bm{x}, \bm{\theta}) = \frac{1}{1 + \exp{(- \bm{x}})} , +\] +!et +and +!bt +\[ +P(y = 1 \mid \bm{x}, \bm{\theta}) = 1 - P(y = 0 \mid \bm{x}, \bm{\theta}) , +\] +!et + +where $y \in \{0, 1\}$ and $\bm{\theta}$ represents the weights and biases +of our network. + + +!split +===== Defining the cost function ===== + +Our cost function is given as (see the Logistic regression lectures) +!bt +\[ +\mathcal{C}(\bm{\theta}) = - \ln P(\mathcal{D} \mid \bm{\theta}) = - \sum_{i=1}^n +y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\bm{\theta}) . +\] +!et + +This last equality means that we can interpret our *cost* function as a sum over the *loss* function +for each point in the dataset $\mathcal{L}_i(\bm{\theta})$. +The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather +than maximizing a negative number. + +In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: + +$y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and + + +$y = 1 \quad \rightarrow \quad \bm{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ + + +i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. + +If $\bm{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th +output vector $\bm{y}_i$. +The probability of $\bm{x}_i$ being in class $c$ will be given by the softmax function: + +!bt +\[ +P(y_{ic} = 1 \mid \bm{x}_i, \bm{\theta}) = \frac{\exp{((\bm{a}_i^{hidden})^T \bm{w}_c)}} +{\sum_{c'=0}^{C-1} \exp{((\bm{a}_i^{hidden})^T \bm{w}_{c'})}} , +\] +!et + +which reduces to the logistic function in the binary case. +The likelihood of this $C$-class classifier +is now given as: + +!bt +\[ +P(\mathcal{D} \mid \bm{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . +\] +!et +Again we take the negative log-likelihood to define our cost function: + +!bt +\[ +\mathcal{C}(\bm{\theta}) = - \log{P(\mathcal{D} \mid \bm{\theta})}. +\] +!et +See the logistic regression lectures for a full definition of the cost function. + +The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before! + +!split +===== Example: binary classification problem ===== + +As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\beta$ as +!bt +\[ +\mathcal{C}(\bm{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\bm{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\bm{\beta})}\right), +\] +!et +where we had defined the logistic (sigmoid) function +!bt +\[ +p(y_i =1\vert x_i,\bm{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, +\] +!et +and +!bt +\[ +p(y_i =0\vert x_i,\bm{\beta})=1-p(y_i =1\vert x_i,\bm{\beta}). +\] +!et +The parameters $\bm{\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. + +Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. +We have then +!bt +\[ +a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, +\] +!et +with +!bt +\[ +z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, +\] +!et +where the superscript $l-1$ indicates that these are the outputs from layer $l-1$. +Our cost function at the final layer $l=L$ is now +!bt +\[ +\mathcal{C}(\bm{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), +\] +!et +where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get +!bt +\[ +\frac{\partial \mathcal{C}(\bm{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. +\] +!et +In case we use another activation function than the logistic one, we need to evaluate other derivatives. + + +!split +===== The Softmax function ===== +In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need +!bt +\[ +\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = +\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. +\] +!et +For the Softmax function we have +!bt +\[ +f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. +\] +!et +Its derivative with respect to $z_j^l$ gives +!bt +\[ +\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), +\] +!et +which in case of the simply binary model reduces to having $i=j$. + +!split +===== Developing a code for doing neural networks with back propagation ===== + + +One can identify a set of key steps when using neural networks to solve supervised learning problems: + +o Collect and pre-process data +o Define model and architecture +o Choose cost function and optimizer +o Train the model +o Evaluate model performance on test data +o Adjust hyperparameters (if necessary, network architecture) + +!split +===== Collect and pre-process data ===== + +Here we will be using the MNIST dataset, which is readily available through the _scikit-learn_ +package. You may also find it for example "here":"http://yann.lecun.com/exdb/mnist/". +The *MNIST* (Modified National Institute of Standards and Technology) database is a large database +of handwritten digits that is commonly used for training various image processing systems. +The MNIST dataset consists of 70 000 images of size $28\times 28$ pixels, each labeled from 0 to 9. +The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\times 8$ collected and processed from this database. + +To feed data into a feed-forward neural network we need to represent +the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each +row represents an *input*, in this case a handwritten digit, and +each column represents a *feature*, in this case a pixel. The +correct answers, also known as *labels* or *targets* are +represented as a 1D array of integers +$Y = (n_{inputs}) = (5, 3, 1, 8,...)$. + +As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from +measurements of height (in m) +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: + +$$ X = \begin{bmatrix} +1.85 & 81\\ +1.71 & 65\\ +1.95 & 103\\ +1.55 & 42\\ +1.63 & 56 +\end{bmatrix} ,$$ + +and the targets would be: + +$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ + +Since each input image is a 2D matrix, we need to flatten the image +(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a +design/feature matrix. This means we lose all spatial information in the +image, such as locality and translational invariance. More complicated +architectures such as Convolutional Neural Networks can take advantage +of such information, and are most commonly applied when analyzing +images. + + +!bc pycod +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn import datasets + + +# ensure the same random numbers appear every time +np.random.seed(0) + +# display images in notebook +%matplotlib inline +plt.rcParams['figure.figsize'] = (12,12) + + +# download MNIST dataset +digits = datasets.load_digits() + +# define inputs and labels +inputs = digits.images +labels = digits.target + +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) +print("labels = (n_inputs) = " + str(labels.shape)) + + +# flatten the image +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 +n_inputs = len(inputs) +inputs = inputs.reshape(n_inputs, -1) +print("X = (n_inputs, n_features) = " + str(inputs.shape)) + + +# choose some random images to display +indices = np.arange(n_inputs) +random_indices = np.random.choice(indices, size=5) + +for i, image in enumerate(digits.images[random_indices]): + plt.subplot(1, 5, i+1) + plt.axis('off') + plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') + plt.title("Label: %d" % digits.target[random_indices[i]]) +plt.show() +!ec + +!split +===== Train and test datasets ===== + +Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. + +We will reserve $80 \%$ of our dataset for training and $20 \%$ for testing. + +It is important that the train and test datasets are drawn randomly from our dataset, to ensure +no bias in the sampling. +Say you are taking measurements of weather data to predict the weather in the coming 5 days. +You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data +collected from 12.00 to 24.00. + + +!bc pycod +from sklearn.model_selection import train_test_split + +# one-liner from scikit-learn library +train_size = 0.8 +test_size = 1 - train_size +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, + test_size=test_size) + +# equivalently in numpy +def train_test_split_numpy(inputs, labels, train_size, test_size): + n_inputs = len(inputs) + inputs_shuffled = inputs.copy() + labels_shuffled = labels.copy() + + np.random.shuffle(inputs_shuffled) + np.random.shuffle(labels_shuffled) + + train_end = int(n_inputs*train_size) + X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] + Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] + + return X_train, X_test, Y_train, Y_test + +#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size) + +print("Number of training images: " + str(len(X_train))) +print("Number of test images: " + str(len(X_test))) +!ec + +!split +===== Define model and architecture ===== + +Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have + +$$ z = \sum_{i=1}^n w_i a_i ,$$ + +$$ y = f(z) ,$$ + +where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer +and $w_i$ is the weight to input $i$. +The activation of the neurons in the input layer is just the features (e.g. a pixel value). + +The simplest activation function for a neuron is the *Heaviside* function: + +$$ f(z) = +\begin{cases} +1, & z > 0\\ +0, & \text{otherwise} +\end{cases} +$$ + +A feed-forward neural network with this activation is known as a *perceptron*. +For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. +This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), +and we call these architectures *multiclass perceptrons*. + +However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and +Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. + +Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). +We will be using the sigmoid function $\sigma(x)$: + +$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$ + +which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions. + +!split +===== Layers ===== + +* Input +Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. + +* Hidden layer +We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. +Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. + +* Output +If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, +which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. + +For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. + +Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: + +$$ P(\text{class $j$} \mid \text{input $\bm{a}$}) = \frac{\exp{(\bm{a}^T \bm{w}_j)}} +{\sum_{c=0}^{9} \exp{(\bm{a}^T \bm{w}_c)}} ,$$ + +i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\bm{a}$, with $\bm{w}_j$ the weights of neuron $j$ to the inputs. +The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. +The exponent is just the weighted sum of inputs as before: + +$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ + +Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 +weights to the output layer. + +!split +===== Weights and biases ===== + +Typically weights are initialized with small values distributed around zero, drawn from a uniform +or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. + +Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range +of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: + +$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ + +The bias weights $\bm{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle. +!bc pycod +# building our neural network + +n_inputs, n_features = X_train.shape +n_hidden_neurons = 50 +n_categories = 10 + +# we make the weights normally distributed using numpy.random.randn + +# weights and bias in the hidden layer +hidden_weights = np.random.randn(n_features, n_hidden_neurons) +hidden_bias = np.zeros(n_hidden_neurons) + 0.01 + +# weights and bias in the output layer +output_weights = np.random.randn(n_hidden_neurons, n_categories) +output_bias = np.zeros(n_categories) + 0.01 +!ec + +!split +===== Feed-forward pass ===== + +Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. +For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: + +$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ + +this is then passed through our activation function + +$$ a_{j}^{l} = f(z_{j}^{l}) .$$ + +We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: + +$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ + +Finally we calculate the output of neuron $j$ in the output layer using the softmax function: + +$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} +{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ + +!split +===== Matrix multiplications ===== + +Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden +layer have the dimensions +$W_{hidden} = (n_{features}, n_{hidden})$, +we can easily feed the network all our training data in one go by taking the matrix product + +$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ + +and obtain a matrix that holds the weighted sum of inputs to the hidden layer +for each input image and each hidden neuron. +We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: + +$$ \bm{z}^{l} = \bm{X} \bm{W}^{l} + \bm{b}^{l} ,$$ + +meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. +This is then passed through the activation: + +$$ \bm{a}^{l} = f(\bm{z}^l) .$$ + +This is fed to the output layer: + +$$ \bm{z}^{L} = \bm{a}^{L} \bm{W}^{L} + \bm{b}^{L} .$$ + +Finally we receive our output values for each image and each category by passing it through the softmax function: + +$$ output = softmax (\bm{z}^{L}) = (n_{inputs}, n_{categories}) .$$ + + +!bc pycod +# setup the feed-forward pass, subscript h = hidden layer + +def sigmoid(x): + return 1/(1 + np.exp(-x)) + +def feed_forward(X): + # weighted sum of inputs to the hidden layer + z_h = np.matmul(X, hidden_weights) + hidden_bias + # activation in the hidden layer + a_h = sigmoid(z_h) + + # weighted sum of inputs to the output layer + z_o = np.matmul(a_h, output_weights) + output_bias + # softmax output + # axis 0 holds each input and axis 1 the probabilities of each category + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + return probabilities + +probabilities = feed_forward(X_train) +print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape)) +print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0])) +print("probabilities sum up to: " + str(probabilities[0].sum())) +print() + +# we obtain a prediction by taking the class with the highest likelihood +def predict(X): + probabilities = feed_forward(X) + return np.argmax(probabilities, axis=1) + +predictions = predict(X_train) +print("predictions = (n_inputs) = " + str(predictions.shape)) +print("prediction for image 0: " + str(predictions[0])) +print("correct label for image 0: " + str(Y_train[0])) +!ec + +!split +===== Choose cost function and optimizer ===== + +To measure how well our neural network is doing we need to introduce a cost function. +We will call the function that gives the error of a single sample output the *loss* function, and the function +that gives the total error of our network across all samples the *cost* function. +A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. + +In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: + +$$ y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ + + +$$ y = 1 \quad \rightarrow \quad \bm{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ + + +i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. + +Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. +We define the cost function $\mathcal{C}$ as a sum over the cross-entropy loss for each point $\bm{x}_i$ in the dataset. + +In the one-hot representation only one of the terms in the loss function is non-zero, namely the +probability of the correct category $c'$ +(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong +you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\bm{\theta}$ represents the parameters of our network, i.e. all the weights and biases. + + +!split +===== Optimizing the cost function ===== + +The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent +is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. +Each parameter $\theta$ is iteratively adjusted according to the rule + +$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ + +where $\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. +This update can be repeated for any number of iterations, or until we are satisfied with the result. + +A simple and effective improvement is a variant called *Batch Gradient Descent*. +Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient +on a subset of the data called a *minibatch*. +If there are $N$ data points and we have a minibatch size of $M$, the total number of batches +is $N/M$. +We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: + +$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ + +i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. + +This has two important benefits: +o Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. +o It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. + +The various optmization methods, with codes and algorithms, are discussed in our lectures on "Gradient descent approaches":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". + +!split +===== Regularization ===== + +It is common to add an extra term to the cost function, proportional +to the size of the weights. This is equivalent to constraining the +size of the weights, so that they do not grow out of control. +Constraining the size of the weights means that the weights cannot +grow arbitrarily large to fit the training data, and in this way +reduces *overfitting*. + +We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: + +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \bm{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ + +i.e. we sum up all the weights squared. The factor $\lambda$ is known as a regularization parameter. + + +In order to train the model, we need to calculate the derivative of +the cost function with respect to every bias and weight in the +network. In total our network has $(64 + 1)\times 50=3250$ weights in +the hidden layer and $(50 + 1)\times 10=510$ weights to the output +layer ($+1$ for the bias), and the gradient must be calculated for +every parameter. We use the *backpropagation* algorithm discussed +above. This is a clever use of the chain rule that allows us to +calculate the gradient efficently. + + +!split +===== Matrix multiplication ===== + +To more efficently train our network these equations are implemented using matrix operations. +The error in the output layer is calculated simply as, with $\bm{t}$ being our targets, + +$$ \delta_L = \bm{t} - \bm{y} = (n_{inputs}, n_{categories}) .$$ + +The gradient for the output weights is calculated as + +$$ \nabla W_{L} = \bm{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ + +where $\bm{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. +Since we are going backwards we have to transpose the activation matrix. + +The gradient with respect to the output bias is then + +$$ \nabla \bm{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ + +The error in the hidden layer is + +$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ + +where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean +that we are summing up the products for each neuron in the output layer. The symbol $\circ$ denotes +the *Hadamard product*, meaning element-wise multiplication. + +This again gives us the gradients in the hidden layer: + +$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ + +$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ + + +!bc pycod +# to categorical turns our integer vector into a onehot representation +from sklearn.metrics import accuracy_score + +# one-hot in numpy +def to_categorical_numpy(integer_vector): + n_inputs = len(integer_vector) + n_categories = np.max(integer_vector) + 1 + onehot_vector = np.zeros((n_inputs, n_categories)) + onehot_vector[range(n_inputs), integer_vector] = 1 + + return onehot_vector + +#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test) +Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test) + +def feed_forward_train(X): + # weighted sum of inputs to the hidden layer + z_h = np.matmul(X, hidden_weights) + hidden_bias + # activation in the hidden layer + a_h = sigmoid(z_h) + + # weighted sum of inputs to the output layer + z_o = np.matmul(a_h, output_weights) + output_bias + # softmax output + # axis 0 holds each input and axis 1 the probabilities of each category + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + # for backpropagation need activations in hidden and output layers + return a_h, probabilities + +def backpropagation(X, Y): + a_h, probabilities = feed_forward_train(X) + + # error in the output layer + error_output = probabilities - Y + # error in the hidden layer + error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h) + + # gradients for the output layer + output_weights_gradient = np.matmul(a_h.T, error_output) + output_bias_gradient = np.sum(error_output, axis=0) + + # gradient for the hidden layer + hidden_weights_gradient = np.matmul(X.T, error_hidden) + hidden_bias_gradient = np.sum(error_hidden, axis=0) + + return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient + +print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) + +eta = 0.01 +lmbd = 0.01 +for i in range(1000): + # calculate gradients + dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot) + + # regularization term gradients + dWo += lmbd * output_weights + dWh += lmbd * hidden_weights + + # update weights and biases + output_weights -= eta * dWo + output_bias -= eta * dBo + hidden_weights -= eta * dWh + hidden_bias -= eta * dBh + +print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) +!ec + +!split +===== Improving performance ===== + +As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. +In order to obtain a network that does something useful, we will have to do a bit more work. + +The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\lambda = 10^{-6},...,10^{-0}$. + +Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period +going through the entire dataset ($n/M$ batches) an *epoch*. + +If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. +Andrew Ng goes through some of these considerations in this "video":"https://youtu.be/F1ka6a13S9I". You can find a summary of the video "here":"https://kevinzakka.github.io/2016/09/26/applying-deep-learning/". + +!split +===== Full object-oriented implementation ===== + +It is very natural to think of the network as an object, with specific instances of the network +being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. + + +!bc pycod +class NeuralNetwork: + def __init__( + self, + X_data, + Y_data, + n_hidden_neurons=50, + n_categories=10, + epochs=10, + batch_size=100, + eta=0.1, + lmbd=0.0): + + self.X_data_full = X_data + self.Y_data_full = Y_data + + self.n_inputs = X_data.shape[0] + self.n_features = X_data.shape[1] + self.n_hidden_neurons = n_hidden_neurons + self.n_categories = n_categories + + self.epochs = epochs + self.batch_size = batch_size + self.iterations = self.n_inputs // self.batch_size + self.eta = eta + self.lmbd = lmbd + + self.create_biases_and_weights() + + def create_biases_and_weights(self): + self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons) + self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01 + + self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories) + self.output_bias = np.zeros(self.n_categories) + 0.01 + + def feed_forward(self): + # feed-forward for training + self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias + self.a_h = sigmoid(self.z_h) + + self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias + + exp_term = np.exp(self.z_o) + self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + def feed_forward_out(self, X): + # feed-forward for output + z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias + a_h = sigmoid(z_h) + + z_o = np.matmul(a_h, self.output_weights) + self.output_bias + + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + return probabilities + + def backpropagation(self): + error_output = self.probabilities - self.Y_data + error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h) + + self.output_weights_gradient = np.matmul(self.a_h.T, error_output) + self.output_bias_gradient = np.sum(error_output, axis=0) + + self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden) + self.hidden_bias_gradient = np.sum(error_hidden, axis=0) + + if self.lmbd > 0.0: + self.output_weights_gradient += self.lmbd * self.output_weights + self.hidden_weights_gradient += self.lmbd * self.hidden_weights + + self.output_weights -= self.eta * self.output_weights_gradient + self.output_bias -= self.eta * self.output_bias_gradient + self.hidden_weights -= self.eta * self.hidden_weights_gradient + self.hidden_bias -= self.eta * self.hidden_bias_gradient + + def predict(self, X): + probabilities = self.feed_forward_out(X) + return np.argmax(probabilities, axis=1) + + def predict_probabilities(self, X): + probabilities = self.feed_forward_out(X) + return probabilities + + def train(self): + data_indices = np.arange(self.n_inputs) + + for i in range(self.epochs): + for j in range(self.iterations): + # pick datapoints with replacement + chosen_datapoints = np.random.choice( + data_indices, size=self.batch_size, replace=False + ) + + # minibatch training data + self.X_data = self.X_data_full[chosen_datapoints] + self.Y_data = self.Y_data_full[chosen_datapoints] + + self.feed_forward() + self.backpropagation() +!ec + +!split +===== Evaluate model performance on test data ===== + +To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. +We measure the performance of the network using the *accuracy* score. +The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. + +$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ + +where $I$ is the indicator function, $1$ if $\tilde{y}_i = y_i$ and $0$ otherwise. + + +!bc pycod +epochs = 100 +batch_size = 100 + +dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, + n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) +dnn.train() +test_predict = dnn.predict(X_test) + +# accuracy score from scikit library +print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) + +# equivalent in numpy +def accuracy_score_numpy(Y_test, Y_pred): + return np.sum(Y_test == Y_pred) / len(Y_test) + +#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict)) +!ec + +!split +===== Adjust hyperparameters ===== + +We now perform a grid search to find the optimal hyperparameters for the network. +Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\%$ ($2\%$ error rate). + +!bc pycod +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +# store the models for later use +DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +# grid search +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, + n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) + dnn.train() + + DNN_numpy[i][j] = dnn + + test_predict = dnn.predict(X_test) + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) + print() +!ec + +!split +===== Visualization ===== + +!bc pycod +# visual representation of grid search +# uses seaborn heatmap, you can also do this with matplotlib imshow +import seaborn as sns + +sns.set() + +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) + +for i in range(len(eta_vals)): + for j in range(len(lmbd_vals)): + dnn = DNN_numpy[i][j] + + train_pred = dnn.predict(X_train) + test_pred = dnn.predict(X_test) + + train_accuracy[i][j] = accuracy_score(Y_train, train_pred) + test_accuracy[i][j] = accuracy_score(Y_test, test_pred) + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Test Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() +!ec + +!split +===== scikit-learn implementation ===== + +_scikit-learn_ focuses more +on traditional machine learning methods, such as regression, +clustering, decision trees, etc. As such, it has only two types of +neural networks: Multi Layer Perceptron outputting continuous values, +*MPLRegressor*, and Multi Layer Perceptron outputting labels, +*MLPClassifier*. We will see how simple it is to use these classes. + +_scikit-learn_ implements a few improvements from our neural network, +such as early stopping, a varying learning rate, different +optimization methods, etc. We would therefore expect a better +performance overall. + +!bc pycod +from sklearn.neural_network import MLPClassifier +# store models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, Y_train) + + DNN_scikit[i][j] = dnn + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Accuracy score on test set: ", dnn.score(X_test, Y_test)) + print() +!ec + + +!split +===== Visualization ===== +!bc pycod +# optional +# visual representation of grid search +# uses seaborn heatmap, could probably do this in matplotlib +import seaborn as sns + +sns.set() + +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) + +for i in range(len(eta_vals)): + for j in range(len(lmbd_vals)): + dnn = DNN_scikit[i][j] + + train_pred = dnn.predict(X_train) + test_pred = dnn.predict(X_test) + + train_accuracy[i][j] = accuracy_score(Y_train, train_pred) + test_accuracy[i][j] = accuracy_score(Y_test, test_pred) + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Test Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() +!ec + + +!split +===== Testing our code for the XOR, OR and AND gates ===== + +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$: + +|---------------------| +| $x_1$ | $x_2$ | $y$ | +|---------------------| +| 0 | 0 | 0 | +| 0 | 1 | 1 | +| 1 | 0 | 1 | +| 1 | 1 | 1 | +|---------------------| + +!split +===== The AND and XOR Gates ===== + +The AND gate is defined as + +|---------------------| +| $x_1$ | $x_2$ | $y$ | +|---------------------| +| 0 | 0 | 0 | +| 0 | 1 | 0 | +| 1 | 0 | 0 | +| 1 | 1 | 1 | +|---------------------| + +And finally we have the XOR gate + +|---------------------| +| $x_1$ | $x_2$ | $y$ | +|---------------------| +| 0 | 0 | 0 | +| 0 | 1 | 1 | +| 1 | 0 | 1 | +| 1 | 1 | 0 | +|---------------------| + +!split +===== Representing the Data Sets ===== + +Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads + +!bt +\bm{X}=\begin{bmatrix} 0 & 0 \\ + 0 & 1 \\ + 1 & 0 \\ + 1 & 1 \end{bmatrix}, +!et + +while the vector of outputs is $\bm{y}^T=[0,1,1,0]$ for the XOR gate, $\bm{y}^T=[0,0,0,1]$ for the AND gate and $\bm{y}^T=[0,1,1,1]$ for the OR gate. + +!split +===== Setting up the Neural Network ===== + +We define first our design matrix and the various output vectors for the different gates. + +!bc pycod +""" +Simple code that tests XOR, OR and AND gates with linear regression +""" + +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn import datasets + +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) + +!ec + +Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above. + +!split +===== The Code using Scikit-Learn ===== + +!bc pycod +# 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() + +!ec + + + + + + + + +