From f16d3eefc4aca1020bb4479e85ed0b015a222ad7 Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Mon, 23 Oct 2023 06:20:12 +0200 Subject: [PATCH] updating --- doc/src/week43/backup2022.do.txt | 3474 +++++++++++++++ doc/src/week43/exercisesweek43.do.txt | 35 + doc/src/week43/week42.do.txt | 1976 +++++++++ doc/src/week43/week43.do.txt | 5668 +++++++++++++++++-------- 4 files changed, 9349 insertions(+), 1804 deletions(-) create mode 100644 doc/src/week43/backup2022.do.txt create mode 100644 doc/src/week43/exercisesweek43.do.txt create mode 100644 doc/src/week43/week42.do.txt diff --git a/doc/src/week43/backup2022.do.txt b/doc/src/week43/backup2022.do.txt new file mode 100644 index 000000000..b1bf3842d --- /dev/null +++ b/doc/src/week43/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/week43/exercisesweek43.do.txt b/doc/src/week43/exercisesweek43.do.txt new file mode 100644 index 000000000..19348228d --- /dev/null +++ b/doc/src/week43/exercisesweek43.do.txt @@ -0,0 +1,35 @@ +TITLE: Exercises week 42 +AUTHOR: October 9-13, 2023 +DATE: Deadline is Sunday October 22 at midnight + +You can hand in the exercises from week 41 and week 42 as one exercise and get a total score of two additional points. + +======= 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. The exercise this week is a simple +continuation from the previous 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 automatic differentiation. Compare this with the analytical expression of the gradients you obtained last week. Feel free to use _Autograd_ as Python package or _JAX_. You can use the examples form last week. +o Add momentum to the plain GD code and compare convergence with a fixed learning rate (you may need to tune the learning rate). Compare this with the analytical expression of the gradients you obtained last week. +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 using automatic differentiation.. +o Add RMSprop and Adam to your library of methods for tuning the learning rate. Again using automatic differentiation. + +The lecture notes from weeks 39 and 40 contain more information and code examples. Feel free to use these examples. + + +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. + + diff --git a/doc/src/week43/week42.do.txt b/doc/src/week43/week42.do.txt new file mode 100644 index 000000000..a0618bbe5 --- /dev/null +++ b/doc/src/week43/week42.do.txt @@ -0,0 +1,1976 @@ +TITLE: Week 42 Constructing a Neural Network code with introduction to Tensor flow +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: October 16-20, 2023 + + + +!split +===== Plan for week 42 ===== + +!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 from the previous week but now with inclusion of automatic differentiation + * Discussion of project 2 + * "See video on automatic differentiation from last year":"https://www.youtube.com/watch?v=cWCebuNKrA8". This video will be updated before Tuesday. +!eblock + +!bblock Material for the lecture on Thursday October 12, 2023 + * Building our own Feed-forward Neural Network and discussion of project 2 + * Readings and Videos: + * These lecture notes + * "Video of lecture":"https://youtu.be/0q5-PhovchQ" + * "Whiteboard notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesOct19.pdf" + * "Aurelien Geron's chapters 10-11":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf" + * For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. + * "Neural Networks demystified":"https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" + * "Building Neural Networks from scratch":"https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex" + * "Video on Neural Networks":"https://www.youtube.com/watch?v=CqOfi41LfDw" + * "Video on the back propagation algorithm":"https://www.youtube.com/watch?v=Ilg3gGewQ5U" +I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at URL:"http://neuralnetworksanddeeplearning.com/chap4.html". +!eblock + + + +!split +===== Lecture Thursday October 19 ===== + + +!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/week43/week43.do.txt b/doc/src/week43/week43.do.txt index 1c8513984..fd1243bd6 100644 --- a/doc/src/week43/week43.do.txt +++ b/doc/src/week43/week43.do.txt @@ -1,556 +1,296 @@ -TITLE: Week 43: Deep Learning: Convolutional Neural Networks and Recurrent 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 National Superconducting Cyclotron Laboratory, Michigan State University +TITLE: Week 43: Deep Learning: Constructing a Neural Network code and solving differential equations +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: today !split ===== Plans for week 43 ===== -* Thursday: Convolutional Neural Networks (CNN) - * "Video of lecture":"https://youtu.be/Hm6Ay5DS6o0" -* Friday: Recurrent Neural Networks (RNN) - * "Video of lecture":"https://youtu.be/JHfgQ77fpqs" +!bblock Material for the active learning sessions on Tuesday and Wednesday + * Exercise on writing your own neural network code, application to the OR and XOR gates + * The exercises this week will be continued next week as well + * Discussion of project 2 +!eblock - -!bblock Excellent lectures on CNNs and RNNs -* "Video on Convolutional Neural Networks from MIT":"https://www.youtube.com/watch?v=iaSUYvmCekI&ab_channel=AlexanderAmini" -* "Video on Recurrent Neural Networks from MIT":"https://www.youtube.com/watch?v=SEnXr6v2ifU&ab_channel=AlexanderAmini" -* "Video on Deep Learning":"https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi" -!eblock - -!bblock More resources -* "IN5400 at UiO Lecture":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/v20/material/week10/in5400_2020_week10_recurrent_neural_network.pdf" -* "CS231 at Stanford Lecture":"https://www.youtube.com/watch?v=6niqTuYFZLQ&list=PLzUTmXVwsnXod6WNdg57Yc3zFx_f-RYsq&index=10&ab_channel=StanfordUniversitySchoolofEngineering" +!bblock Material for the lecture on Thursday October 26, 2023 + * Building our own Feed-forward Neural Network and discussion of project 2 + * Readings and Videos: + * These lecture notes + * "Aurelien Geron's chapters 10-11":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf" + * For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. + * "Neural Networks demystified":"https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" + * "Building Neural Networks from scratch":"https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex" + * "Video on Neural Networks":"https://www.youtube.com/watch?v=CqOfi41LfDw" + * "Video on the back propagation algorithm":"https://www.youtube.com/watch?v=Ilg3gGewQ5U" +I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at URL:"http://neuralnetworksanddeeplearning.com/chap4.html". !eblock -!split -===== Reading Recommendations ===== - -!bblock CNN readings -o "Goodfellow, Bengio, Courville, chapter 9":"https://www.deeplearningbook.org/contents/convnets.html" -o We will follow to a large extent the "lectures from CS231 at Stanford":"http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture5.pdf" -o "Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs":"http://neuralnetworksanddeeplearning.com/chap6.html". -!eblock - - -!bblock RNN readings -o "Goodfellow et al":"https://www.deeplearningbook.org/contents/rnn.html", chapter 10 on Recurrent NNs, chapters 11 and 12 on various practicalities around deep learning are also recommended. -o "Lectures from CS231 at Stanford":"http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture10.pdf" -o Aurelien Geron, chapter 14 on RNNs. -!eblock - !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). +===== Material for exercises week 43 and week 44 ===== !split -===== What is the Difference ===== +===== Writing our first neural network code, Testing our code for the OR and XOR gates ===== -_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._ +During week 41, 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 -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). - - +===== Lecture Thursday October 26 ===== !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_0\beta_1\\ -\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 -===== 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 ===== +===== Developing a code for doing neural networks with back propagation ===== +We repeat some of the elements discussed last week. -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. +One can identify a set of key steps when using neural networks to solve supervised learning problems: -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). - +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 -===== 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 +===== Collect and pre-process data ===== -!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. +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. - -!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". +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,...)$. - -!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. +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. + -!split -===== Prerequisites: Collect and pre-process data ===== !bc pycod # import necessary packages import numpy as np @@ -573,16 +313,18 @@ digits = datasets.load_digits() 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("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) print("labels = (n_inputs) = " + str(labels.shape)) -# choose some random images to display +# 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) @@ -594,92 +336,688 @@ for i, image in enumerate(digits.images[random_indices]): 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 +===== 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 -# 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) + +# 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 -===== Running with Keras ===== +!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 -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 +# building our neural network -epochs = 100 -batch_size = 100 -input_shape = X_train.shape[1:4] -receptive_field = 3 -n_filters = 10 -n_neurons_connected = 50 +n_inputs, n_features = X_train.shape +n_hidden_neurons = 50 n_categories = 10 -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) +# 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 -===== Final part ===== +===== 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 -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 +# 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 -===== Final visualization ===== +===== 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 @@ -691,10 +1029,13 @@ 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] + dnn = DNN_scikit[i][j] + + train_pred = dnn.predict(X_train) + test_pred = dnn.predict(X_test) - train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1] - test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1] + 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)) @@ -715,1403 +1056,3122 @@ plt.show() !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 - +===== 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 -===== 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. - +===== 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 -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() +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 -===== 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. - +===== 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 -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() +conda install keras !ec +You can look up the "instructions here":"https://keras.io/" for more information. -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. - - - +We will to a large extent use _keras_ in this course. !split -===== Add Dense layers on top ===== +===== Collect and pre-process data ===== -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. +Let us look again at the MINST data set. !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 - - -!split -===== Recurrent neural networks: Overarching view ===== - -Till now our focus has been, including convolutional neural networks -as well, on feedforward neural networks. The output or the activations -flow only in one direction, from the input layer to the output layer. - -A recurrent neural network (RNN) looks very much like a feedforward -neural network, except that it also has connections pointing -backward. - -RNNs are used to analyze time series data such as stock prices, and -tell you when to buy or sell. In autonomous driving systems, they can -anticipate car trajectories and help avoid accidents. More generally, -they can work on sequences of arbitrary lengths, rather than on -fixed-sized inputs like all the nets we have discussed so far. For -example, they can take sentences, documents, or audio samples as -input, making them extremely useful for natural language processing -systems such as automatic translation and speech-to-text. - - -!split -===== Set up of an RNN ===== - -See handwritten notes for week 43 and "Lectures from CS231 at Stanford":"http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture10.pdf" - -!split -===== A simple example ===== - -!bc pycod -# Start importing packages -import pandas as pd +# import necessary packages import numpy as np import matplotlib.pyplot as plt import tensorflow as tf -from tensorflow.keras import datasets, layers, models +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 Model, Sequential -from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU -from tensorflow.keras import optimizers -from tensorflow.keras import regularizers -from tensorflow.keras.utils import to_categorical +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 -# convert into dataset matrix -def convertToMatrix(data, step): - X, Y =[], [] - for i in range(len(data)-step): - d=i+step - X.append(data[i:d,]) - Y.append(data[d,]) - return np.array(X), np.array(Y) +from sklearn.model_selection import train_test_split -step = 4 -N = 1000 -Tp = 800 +# one-hot representation of labels +labels = to_categorical(labels) -t=np.arange(0,N) -x=np.sin(0.02*t)+2*np.random.rand(N) -df = pd.DataFrame(x) -df.head() +# 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 -plt.plot(df) + + +!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() -values=df.values -train,test = values[0:Tp,:], values[Tp:N,:] +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: -# add step elements into train and test -test = np.append(test,np.repeat(test[-1,],step)) -train = np.append(train,np.repeat(train[-1,],step)) -trainX,trainY =convertToMatrix(train,step) -testX,testY =convertToMatrix(test,step) -trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1])) -testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1])) +* Estimate optimal error rate -model = Sequential() -model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu")) -model.add(Dense(8, activation="relu")) -model.add(Dense(1)) -model.compile(loss='mean_squared_error', optimizer='rmsprop') -model.summary() -model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2) -trainPredict = model.predict(trainX) -testPredict= model.predict(testX) -predicted=np.concatenate((trainPredict,testPredict),axis=0) +* Minimize underfitting (bias) on training data set. -trainScore = model.evaluate(trainX, trainY, verbose=0) -print(trainScore) +* 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. -df = pd.DataFrame(x) -pred = pd.DataFrame(predicted) -plt.plot(df,c="b") -plt.plot(pred,c="r") -plt.show() -!ec +* _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. + + +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 -===== An extrapolation example ===== +===== Plan for week 42 ===== -The following code provides an example of how recurrent neural -networks can be used to extrapolate to unknown values of physics data -sets. Specifically, the data sets used in this program come from -a quantum mechanical many-body calculation of energies as functions of the number of particles. +!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 -!bc pycod -# For matrices and calculations -import numpy as np -# For machine learning (backend for keras) -import tensorflow as tf -# User-friendly machine learning library -# Front end for TensorFlow -import tensorflow.keras -# Different methods from Keras needed to create an RNN -# This is not necessary but it shortened function calls -# that need to be used in the code. -from tensorflow.keras import datasets, layers, models -from tensorflow.keras.layers import Input -from tensorflow.keras import regularizers -from tensorflow.keras.models import Model, Sequential -from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU -# For timing the code -from timeit import default_timer as timer -# For plotting -import matplotlib.pyplot as plt - - -# The data set -datatype='VaryDimension' -X_tot = np.arange(2, 42, 2) -y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846, - -0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, - -1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767]) - -!ec !split -===== Formatting the Data ===== - -The way the recurrent neural networks are trained in this program -differs from how machine learning algorithms are usually trained. -Typically a machine learning algorithm is trained by learning the -relationship between the $x$ data and the $y$ data. In this program, the -recurrent neural network will be trained to recognize the relationship -in a sequence of $y$ values. This is type of data formatting is -typically used for time series forecasting, but it can also be used in any -extrapolation (time series forecasting is just a specific type of -extrapolation along the time axis). This method of data formatting -does not use the $x$ data and assumes that the $y$ data are evenly spaced. - -For a standard machine learning algorithm, the training data has the -form of $(x,y)$ so the machine learning algorithm learns to associate a -$y$ value with a given $x$ value. This is useful when the test data has $x$ -values within the same range as the training data. However, for this -application, the x values of the test data are outside of the x values -of the training data and the traditional method of training a machine -learning algorithm does not work as well. For this reason, the -recurrent neural network is trained on sequences of y values of the -form $((y1, y2), y3)$, so that the network is concerned with learning -the pattern of the y data and not the relation between the x and y -data. As long as the pattern of y data outside of the training region -stays relatively stable compared to what was inside the training -region, this method of training can produce accurate extrapolations to -y values far removed from the training data set. - - -# -# The idea behind formatting the data in this way comes from [this resource](https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/) and [this one](https://fairyonice.github.io/Understand-Keras%27s-RNN-behind-the-scenes-with-a-sin-wave-example.html). -# -# The following method takes in a y data set and formats it so the "x data" are of the form (y1, y2) and the "y data" are of the form y3, with extra brackets added in to make the resulting arrays compatable with both Keras and Tensorflow. -# -# Note: Using a sequence length of two is not required for time series forecasting so any lenght of sequence could be used (for example instead of ((y1, y2) y3) you could change the length of sequence to be 4 and the resulting data points would have the form ((y1, y2, y3, y4), y5)). While the following method can be used to create a data set of any sequence length, the remainder of the code expects the length of sequence to be 2. This is because the data sets are very small and the higher the lenght of the sequence the less resulting data points. - -!bc pycod -# FORMAT_DATA -def format_data(data, length_of_sequence = 2): - """ - Inputs: - data(a numpy array): the data that will be the inputs to the recurrent neural - network - length_of_sequence (an int): the number of elements in one iteration of the - sequence patter. For a function approximator use length_of_sequence = 2. - Returns: - rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its - dimensions are length of data - length of sequence, length of sequence, - dimnsion of data - rnn_output (a numpy array): the training data for the neural network - Formats data to be used in a recurrent neural network. - """ - - X, Y = [], [] - for i in range(len(data)-length_of_sequence): - # Get the next length_of_sequence elements - a = data[i:i+length_of_sequence] - # Get the element that immediately follows that - b = data[i+length_of_sequence] - # Reshape so that each data point is contained in its own array - a = np.reshape (a, (len(a), 1)) - X.append(a) - Y.append(b) - rnn_input = np.array(X) - rnn_output = np.array(Y) - - return rnn_input, rnn_output - - -# ## Defining the Recurrent Neural Network Using Keras -# -# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer. - -def rnn(length_of_sequences, batch_size = None, stateful = False): - """ - Inputs: - length_of_sequences (an int): the number of y values in "x data". This is determined - when the data is formatted - batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. - stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. - Returns: - model (a Keras model): The recurrent neural network that is built and compiled by this - method - Builds and compiles a recurrent neural network with one hidden layer and returns the model. - """ - # Number of neurons in the input and output layers - in_out_neurons = 1 - # Number of neurons in the hidden layer - hidden_neurons = 200 - # Define the input layer - inp = Input(batch_shape=(batch_size, - length_of_sequences, - in_out_neurons)) - # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to - # the network immediately after the input layer - rnn = SimpleRNN(hidden_neurons, - return_sequences=False, - stateful = stateful, - name="RNN")(inp) - # Define the output layer as a dense neural network layer (standard neural network layer) - #and add it to the network immediately after the hidden layer. - dens = Dense(in_out_neurons,name="dense")(rnn) - # Create the machine learning model starting with the input layer and ending with the - # output layer - model = Model(inputs=[inp],outputs=[dens]) - # Compile the machine learning model using the mean squared error function as the loss - # function and an Adams optimizer. - model.compile(loss="mean_squared_error", optimizer="adam") - return model - -!ec +===== 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 -===== Predicting New Points With A Trained Recurrent Neural Network ===== +===== 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 -def test_rnn (x1, y_test, plot_min, plot_max): - """ - Inputs: - x1 (a list or numpy array): The complete x component of the data set - y_test (a list or numpy array): The complete y component of the data set - plot_min (an int or float): the smallest x value used in the training data - plot_max (an int or float): the largest x valye used in the training data - Returns: - None. - Uses a trained recurrent neural network model to predict future points in the - series. Computes the MSE of the predicted data set from the true data set, saves - the predicted data set to a csv file, and plots the predicted and true data sets w - while also displaying the data range used for training. - """ - # Add the training data as the first dim points in the predicted data array as these - # are known values. - y_pred = y_test[:dim].tolist() - # Generate the first input to the trained recurrent neural network using the last two - # points of the training data. Based on how the network was trained this means that it - # will predict the first point in the data set after the training data. All of the - # brackets are necessary for Tensorflow. - next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]]) - # Save the very last point in the training data set. This will be used later. - last = [y_test[dim-1]] +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt - # Iterate until the complete data set is created. - for i in range (dim, len(y_test)): - # Predict the next point in the data set using the previous two points. - next = model.predict(next_input) - # Append just the number of the predicted data set - y_pred.append(next[0][0]) - # Create the input that will be used to predict the next data point in the data set. - next_input = np.array([[last, next[0]]], dtype=np.float64) - last = next +def sigmoid(z): + return 1/(1 + np.exp(-z)) - # Print the mean squared error between the known data set and the predicted data set. - print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean()) - # Save the predicted data set as a csv file for later use - name = datatype + 'Predicted'+str(dim)+'.csv' - np.savetxt(name, y_pred, delimiter=',') - # Plot the known data set and the predicted data set. The red box represents the region that was used - # for the training data. - fig, ax = plt.subplots() - ax.plot(x1, y_test, label="true", linewidth=3) - ax.plot(x1, y_pred, 'g-.',label="predicted", linewidth=4) - ax.legend() - # Created a red region to represent the points used in the training data. - ax.axvspan(plot_min, plot_max, alpha=0.25, color='red') +# 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() - -# Check to make sure the data set is complete -assert len(X_tot) == len(y_tot) - -# This is the number of points that will be used in as the training data -dim=12 - -# Separate the training data from the whole data set -X_train = X_tot[:dim] -y_train = y_tot[:dim] - - -# Generate the training data for the RNN, using a sequence of 2 -rnn_input, rnn_training = format_data(y_train, 2) - - -# Create a recurrent neural network in Keras and produce a summary of the -# machine learning model -model = rnn(length_of_sequences = rnn_input.shape[1]) -model.summary() - -# Start the timer. Want to time training+testing -start = timer() -# Fit the model using the training data genenerated above using 150 training iterations and a 5% -# validation split. Setting verbose to True prints information about each training iteration. -hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, - verbose=True,validation_split=0.05) - -for label in ["loss","val_loss"]: - plt.plot(hist.history[label],label=label) - -plt.ylabel("loss") -plt.xlabel("epoch") -plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) -plt.legend() -plt.show() - -# Use the trained neural network to predict more points of the data set -test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) -# Stop the timer and calculate the total time needed. -end = timer() -print('Time: ', end-start) !ec + !split -===== Other Things to Try ===== +===== 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. -Changing the size of the recurrent neural network and its parameters -can drastically change the results you get from the model. The below -code takes the simple recurrent neural network from above and adds a -second hidden layer, changes the number of neurons in the hidden -layer, and explicitly declares the activation function of the hidden -layers to be a sigmoid function. The loss function and optimizer can -also be changed but are kept the same as the above network. These -parameters can be tuned to provide the optimal result from the -network. For some ideas on how to improve the performance of a -"recurrent neural network":"https://danijar.com/tips-for-training-recurrent-neural-networks". +The number of neurons within each hidden layer are given as a list of integers in the program below. !bc pycod -def rnn_2layers(length_of_sequences, batch_size = None, stateful = False): - """ - Inputs: - length_of_sequences (an int): the number of y values in "x data". This is determined - when the data is formatted - batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. - stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. - Returns: - model (a Keras model): The recurrent neural network that is built and compiled by this - method - Builds and compiles a recurrent neural network with two hidden layers and returns the model. - """ - # Number of neurons in the input and output layers - in_out_neurons = 1 - # Number of neurons in the hidden layer, increased from the first network - hidden_neurons = 500 - # Define the input layer - inp = Input(batch_shape=(batch_size, - length_of_sequences, - in_out_neurons)) - # Create two hidden layers instead of one hidden layer. Explicitly set the activation - # function to be the sigmoid function (the default value is hyperbolic tangent) - rnn1 = SimpleRNN(hidden_neurons, - return_sequences=True, # This needs to be True if another hidden layer is to follow - stateful = stateful, activation = 'sigmoid', - name="RNN1")(inp) - rnn2 = SimpleRNN(hidden_neurons, - return_sequences=False, activation = 'sigmoid', - stateful = stateful, - name="RNN2")(rnn1) - # Define the output layer as a dense neural network layer (standard neural network layer) - #and add it to the network immediately after the hidden layer. - dens = Dense(in_out_neurons,name="dense")(rnn2) - # Create the machine learning model starting with the input layer and ending with the - # output layer - model = Model(inputs=[inp],outputs=[dens]) - # Compile the machine learning model using the mean squared error function as the loss - # function and an Adams optimizer. - model.compile(loss="mean_squared_error", optimizer="adam") - return model +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt -# Check to make sure the data set is complete -assert len(X_tot) == len(y_tot) +def sigmoid(z): + return 1/(1 + np.exp(-z)) -# This is the number of points that will be used in as the training data -dim=12 +# 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 -# Separate the training data from the whole data set -X_train = X_tot[:dim] -y_train = y_tot[:dim] + 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) -# Generate the training data for the RNN, using a sequence of 2 -rnn_input, rnn_training = format_data(y_train, 2) + # 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 -# Create a recurrent neural network in Keras and produce a summary of the -# machine learning model -model = rnn_2layers(length_of_sequences = 2) -model.summary() + ## Hidden layers: -# Start the timer. Want to time training+testing -start = timer() -# Fit the model using the training data genenerated above using 150 training iterations and a 5% -# validation split. Setting verbose to True prints information about each training iteration. -hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, - verbose=True,validation_split=0.05) + 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) -# This section plots the training loss and the validation loss as a function of training iteration. -# This is not required for analyzing the couple cluster data but can help determine if the network is -# being overtrained. -for label in ["loss","val_loss"]: - plt.plot(hist.history[label],label=label) + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) -plt.ylabel("loss") -plt.xlabel("epoch") -plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) -plt.legend() -plt.show() + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden -# Use the trained neural network to predict more points of the data set -test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) -# Stop the timer and calculate the total time needed. -end = timer() -print('Time: ', end-start) -!ec + ## Output layer: -!split -===== Other Types of Recurrent Neural Networks ===== + # Get the weights and bias for this layer + w_output = deep_params[-1] -Besides a simple recurrent neural network layer, there are two other -commonly used types of recurrent neural network layers: Long Short -Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short -introduction to these layers see URL:"https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b" -and URL:"https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b". + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) -The first network created below is similar to the previous network, -but it replaces the SimpleRNN layers with LSTM layers. The second -network below has two hidden layers made up of GRUs, which are -preceeded by two dense (feeddorward) neural network layers. These -dense layers "preprocess" the data before it reaches the recurrent -layers. This architecture has been shown to improve the performance -of recurrent neural networks (see the link above and also -URL:"https://arxiv.org/pdf/1807.02857.pdf". + z_output = np.matmul(w_output, x_prev) + x_output = z_output -!bc pycod -def lstm_2layers(length_of_sequences, batch_size = None, stateful = False): - """ - Inputs: - length_of_sequences (an int): the number of y values in "x data". This is determined - when the data is formatted - batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. - stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. - Returns: - model (a Keras model): The recurrent neural network that is built and compiled by this - method - Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model. - """ - # Number of neurons on the input/output layer and the number of neurons in the hidden layer - in_out_neurons = 1 - hidden_neurons = 250 - # Input Layer - inp = Input(batch_shape=(batch_size, - length_of_sequences, - in_out_neurons)) - # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers) - rnn= LSTM(hidden_neurons, - return_sequences=True, - stateful = stateful, - name="RNN", use_bias=True, activation='tanh')(inp) - rnn1 = LSTM(hidden_neurons, - return_sequences=False, - stateful = stateful, - name="RNN1", use_bias=True, activation='tanh')(rnn) - # Output layer - dens = Dense(in_out_neurons,name="dense")(rnn1) - # Define the midel - model = Model(inputs=[inp],outputs=[dens]) - # Compile the model - model.compile(loss='mean_squared_error', optimizer='adam') - # Return the model - return model + return x_output -def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False): - """ - Inputs: - length_of_sequences (an int): the number of y values in "x data". This is determined - when the data is formatted - batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. - stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. - Returns: - model (a Keras model): The recurrent neural network that is built and compiled by this - method - Builds and compiles a recurrent neural network with four hidden layers (two dense followed by - two GRU layers) and returns the model. - """ - # Number of neurons on the input/output layers and hidden layers - in_out_neurons = 1 - hidden_neurons = 250 - # Input layer - inp = Input(batch_shape=(batch_size, - length_of_sequences, - in_out_neurons)) - # Hidden Dense (feedforward) layers - dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp) - dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn) - # Hidden GRU layers - rnn1 = GRU(hidden_neurons, - return_sequences=True, - stateful = stateful, - name="RNN1", use_bias=True)(dnn1) - rnn = GRU(hidden_neurons, - return_sequences=False, - stateful = stateful, - name="RNN", use_bias=True)(rnn1) - # Output layer - dens = Dense(in_out_neurons,name="dense")(rnn) - # Define the model - model = Model(inputs=[inp],outputs=[dens]) - # Compile the mdoel - model.compile(loss='mean_squared_error', optimizer='adam') - # Return the model - return model +# The trial solution using the deep neural network: +def g_trial_deep(x,params, g0 = 10): + return g0 + x*deep_neural_network(params, x) -# Check to make sure the data set is complete -assert len(X_tot) == len(y_tot) +# The right side of the ODE: +def g(x, g_trial, gamma = 2): + return -gamma*g_trial -# This is the number of points that will be used in as the training data -dim=12 +# The same cost function as before, but calls deep_neural_network instead. +def cost_function_deep(P, x): -# Separate the training data from the whole data set -X_train = X_tot[:dim] -y_train = y_tot[:dim] + # 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) -# Generate the training data for the RNN, using a sequence of 2 -rnn_input, rnn_training = format_data(y_train, 2) + # 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) -# Create a recurrent neural network in Keras and produce a summary of the -# machine learning model -# Change the method name to reflect which network you want to use -model = dnn2_gru2(length_of_sequences = 2) -model.summary() + err_sqr = (d_g_t - func)**2 + cost_sum = np.sum(err_sqr) -# Start the timer. Want to time training+testing -start = timer() -# Fit the model using the training data genenerated above using 150 training iterations and a 5% -# validation split. Setting verbose to True prints information about each training iteration. -hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, - verbose=True,validation_split=0.05) + 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 -# This section plots the training loss and the validation loss as a function of training iteration. -# This is not required for analyzing the couple cluster data but can help determine if the network is -# being overtrained. -for label in ["loss","val_loss"]: - plt.plot(hist.history[label],label=label) + # The number of elements in the list num_hidden_neurons thus represents + # the number of hidden layers. -plt.ylabel("loss") -plt.xlabel("epoch") -plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) -plt.legend() -plt.show() + # Find the number of hidden layers: + N_hidden = np.size(num_neurons) -# Use the trained neural network to predict more points of the data set -test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) -# Stop the timer and calculate the total time needed. -end = timer() -print('Time: ', end-start) + ## Set up initial weights and biases + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer -# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data) -# -# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation. + 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 -# Check to make sure the data set is complete -assert len(X_tot) == len(y_tot) + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included -# This is the number of points that will be used in as the training data -dim=12 + print('Initial cost: %g'%cost_function_deep(P, x)) -# Separate the training data from the whole data set -X_train = X_tot[:dim] -y_train = y_tot[:dim] + ## Start finding the optimal weights using gradient descent -# Reshape the data for Keras specifications -X_train = X_train.reshape((dim, 1)) -y_train = y_train.reshape((dim, 1)) + # 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) -# Create a recurrent neural network in Keras and produce a summary of the -# machine learning model -# Set the sequence length to 1 for regular data formatting -model = rnn(length_of_sequences = 1) -model.summary() + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_deep_grad[l] -# Start the timer. Want to time training+testing -start = timer() -# Fit the model using the training data genenerated above using 150 training iterations and a 5% -# validation split. Setting verbose to True prints information about each training iteration. -hist = model.fit(X_train, y_train, batch_size=None, epochs=150, - verbose=True,validation_split=0.05) + print('Final cost: %g'%cost_function_deep(P, x)) + return P -# This section plots the training loss and the validation loss as a function of training iteration. -# This is not required for analyzing the couple cluster data but can help determine if the network is -# being overtrained. -for label in ["loss","val_loss"]: - plt.plot(hist.history[label],label=label) +def g_analytic(x, gamma = 2, g0 = 10): + return g0*np.exp(-gamma*x) -plt.ylabel("loss") -plt.xlabel("epoch") -plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) -plt.legend() -plt.show() +# Solve the given problem +if __name__ == '__main__': + npr.seed(15) -# Use the trained neural network to predict the remaining data points -X_pred = X_tot[dim:] -X_pred = X_pred.reshape((len(X_pred), 1)) -y_model = model.predict(X_pred) -y_pred = np.concatenate((y_tot[:dim], y_model.flatten())) + ## Decide the vales of arguments to the function to solve + N = 10 + x = np.linspace(0, 1, N) -# Plot the known data set and the predicted data set. The red box represents the region that was used -# for the training data. -fig, ax = plt.subplots() -ax.plot(X_tot, y_tot, label="true", linewidth=3) -ax.plot(X_tot, y_pred, 'g-.',label="predicted", linewidth=4) -ax.legend() -# Created a red region to represent the points used in the training data. -ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red') -plt.show() + ## Set up the initial parameters + num_hidden_neurons = np.array([10,10]) + num_iter = 10000 + lmb = 0.001 -# Stop the timer and calculate the total time needed. -end = timer() -print('Time: ', end-start) + 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 -===== Generative Models ===== +===== Example: Population growth ===== -_Generative models_ describe a class of statistical models that are a contrast -to _discriminative models_. Informally we say that generative models can -generate new data instances while discriminative models discriminate between -different kinds of data instances. A generative model could generate new photos -of animals that look like 'real' animals while a discriminative model could tell -a dog from a cat. More formally, given a data set $x$ and a set of labels / -targets $y$. Generative models capture the joint probability $p(x, y)$, or -just $p(x)$ if there are no labels, while discriminative models capture the -conditional probability $p(y | x)$. Discriminative models generally try to draw -boundaries in the data space (often high dimensional), while generative models -try to model how data is placed throughout the space. +A logistic model of population growth assumes that a population converges toward an equilibrium. +The population growth can be modeled by -_Note_: this material is thanks to Linus Ekstrøm. - -!split -===== Generative Adversarial Networks ===== - -_Generative Adversarial Networks_ are a type of unsupervised machine learning -algorithm proposed by "Goodfellow et. al": "https://arxiv.org/pdf/1406.2661.pdf" -in 2014 (short and good article). - -The simplest formulation of -the model is based on a game theoretic approach, *zero sum game*, where we pit -two neural networks against one another. We define two rival networks, one -generator $g$, and one discriminator $d$. The generator directly produces -samples !bt -\begin{equation} - x = g(z; \theta^{(g)}) +\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 -===== Discriminator ===== -The discriminator attempts to distinguish between samples drawn from the -training data and samples drawn from the generator. In other words, it tries to -tell the difference between the fake data produced by $g$ and the actual data -samples we want to do prediction on. The discriminator outputs a probability -value given by +===== 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} - d(x; \theta^{(d)}) +\begin{equation} \label{solveode_population} +g'(t) = \alpha g(t)(A - g(t)) \end{equation} !et -indicating the probability that $x$ is a real training example rather than a -fake sample the generator has generated. The simplest way to formulate the -learning process in a generative adversarial network is a zero-sum game, in -which a function - -!bt -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) -\end{equation} -!et - -determines the reward for the discriminator, while the generator gets the -conjugate reward - -!bt -\begin{equation} - -v(\theta^{(g)}, \theta^{(d)}) -\end{equation} -!et +where $g(0) = g_0$. +In this example, we let $\alpha = 2$, $A = 1$, and $g_0 = 1.2$. !split -===== Learning Process ===== +===== The trial solution ===== -During learning both of the networks maximize their own reward function, so that -the generator gets better and better at tricking the discriminator, while the -discriminator gets better and better at telling the difference between the fake -and real data. The generator and discriminator alternate on which one trains at -one time (i.e. for one epoch). In other words, we keep the generator constant -and train the discriminator, then we keep the discriminator constant to train -the generator and repeat. It is this back and forth dynamic which lets GANs -tackle otherwise intractable generative problems. As the generator improves with - training, the discriminator's performance gets worse because it cannot easily - tell the difference between real and fake. If the generator ends up succeeding - perfectly, the the discriminator will do no better than random guessing i.e. - 50\%. This progression in the training poses a problem for the convergence - criteria for GANs. The discriminator feedback gets less meaningful over time, - if we continue training after this point then the generator is effectively - training on junk data which can undo the learning up to that point. Therefore, - we stop training when the discriminator starts outputting $1/2$ everywhere. +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 -===== More about the Learning Process ===== +===== The program using Autograd ===== -At convergence we have - -!bt -\begin{equation} - g^* = \underset{g}{\mathrm{argmin}}\hspace{2pt} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\end{equation} -!et -The default choice for $v$ is -!bt -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) = \mathbb{E}_{x\sim p_\mathrm{data}}\log d(x) - + \mathbb{E}_{x\sim p_\mathrm{model}} - \log (1 - d(x)) -\end{equation} -!et -The main motivation for the design of GANs is that the learning process requires -neither approximate inference (variational autoencoders for example) nor -approximation of a partition function. In the case where -!bt -\begin{equation} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\end{equation} -!et -is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is -asymptotically consistent -( "Seth Lloyd on QuGANs": "https://arxiv.org/pdf/1804.09139.pdf" ). - -!split -===== Additional References ===== -This is in -general not the case and it is possible to get situations where the training -process never converges because the generator and discriminator chase one -another around in the parameter space indefinitely. A much deeper discussion on -the currently open research problem of GAN convergence is available -"here": "https://www.deeplearningbook.org/contents/generative_models.html". To -anyone interested in learning more about GANs it is a highly recommended read. -Direct quote: "In this best-performing formulation, the generator aims to -increase the log probability that the discriminator makes a mistake, rather than -aiming to decrease the log probability that the discriminator makes the correct -prediction." "Another interesting read": "https://arxiv.org/abs/1701.00160" - - -!split -===== Writing Our First Generative Adversarial Network ===== -Let us now move on to actually implementing a GAN in tensorflow. We will study -the performance of our GAN on the MNIST dataset. This code is based on and -adapted from the -"google tutorial": "https://www.tensorflow.org/tutorials/generative/dcgan" - -First we import our libraries +The network will be the similar as for the exponential decay example, but with some small modifications for our problem. !bc pycod -import os -import time -import numpy as np -import tensorflow as tf -import matplotlib.pyplot as plt -from tensorflow.keras import layers -from tensorflow.keras.utils import plot_model -!ec - -Next we define our hyperparameters and import our data the usual way - -!bc pycod -BUFFER_SIZE = 60000 -BATCH_SIZE = 256 -EPOCHS = 30 - -data = tf.keras.datasets.mnist.load_data() -(train_images, train_labels), (test_images, test_labels) = data -train_images = np.reshape(train_images, (train_images.shape[0], - 28, - 28, - 1)).astype('float32') - -# we normalize between -1 and 1 -train_images = (train_images - 127.5) / 127.5 -training_dataset = tf.data.Dataset.from_tensor_slices( - train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE) -!ec - -!split -===== MNIST and GANs ===== - -Let's have a quick look - -!bc pycod -plt.imshow(train_images[0], cmap='Greys') -plt.show() -!ec - -Now we define our two models. This is where the 'magic' happens. There are a -huge amount of possible formulations for both models. A lot of engineering and -trial and error can be done here to try to produce better performing models. For -more advanced GANs this is by far the step where you can 'make or break' a -model. - -We start with the generator. As stated in the introductory text the generator -$g$ upsamples from a random sample to the shape of what we want to predict. In -our case we are trying to predict MNIST images ($28\times 28$ pixels). - -!bc pycod -def generator_model(): - """ - The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to - produce an image from a random seed. We start with a Dense layer taking this - random sample as an input and subsequently upsample through multiple - convolutional layers. - """ - - # we define our model - model = tf.keras.Sequential() - - - # adding our input layer. Dense means that every neuron is connected and - # the input shape is the shape of our random noise. The units need to match - # in some sense the upsampling strides to reach our desired output shape. - # we are using 100 random numbers as our seed - model.add(layers.Dense(units=7*7*BATCH_SIZE, - use_bias=False, - input_shape=(100, ))) - # we normalize the output form the Dense layer - model.add(layers.BatchNormalization()) - # and add an activation function to our 'layer'. LeakyReLU avoids vanishing - # gradient problem - model.add(layers.LeakyReLU()) - model.add(layers.Reshape((7, 7, BATCH_SIZE))) - assert model.output_shape == (None, 7, 7, BATCH_SIZE) - # even though we just added four keras layers we think of everything above - # as 'one' layer - - # next we add our upscaling convolutional layers - model.add(layers.Conv2DTranspose(filters=128, - kernel_size=(5, 5), - strides=(1, 1), - padding='same', - use_bias=False)) - model.add(layers.BatchNormalization()) - model.add(layers.LeakyReLU()) - assert model.output_shape == (None, 7, 7, 128) - - model.add(layers.Conv2DTranspose(filters=64, - kernel_size=(5, 5), - strides=(2, 2), - padding='same', - use_bias=False)) - model.add(layers.BatchNormalization()) - model.add(layers.LeakyReLU()) - assert model.output_shape == (None, 14, 14, 64) - - model.add(layers.Conv2DTranspose(filters=1, - kernel_size=(5, 5), - strides=(2, 2), - padding='same', - use_bias=False, - activation='tanh')) - assert model.output_shape == (None, 28, 28, 1) - - return model - -!ec - -And there we have our 'simple' generator model. Now we move on to defining our -discriminator model $d$, which is a convolutional neural network based image -classifier. - -!bc pycod -def discriminator_model(): - """ - The discriminator is a convolutional neural network based image classifier - """ - - # we define our model - model = tf.keras.Sequential() - model.add(layers.Conv2D(filters=64, - kernel_size=(5, 5), - strides=(2, 2), - padding='same', - input_shape=[28, 28, 1])) - model.add(layers.LeakyReLU()) - # adding a dropout layer as you do in conv-nets - model.add(layers.Dropout(0.3)) - - - model.add(layers.Conv2D(filters=128, - kernel_size=(5, 5), - strides=(2, 2), - padding='same')) - model.add(layers.LeakyReLU()) - # adding a dropout layer as you do in conv-nets - model.add(layers.Dropout(0.3)) - - model.add(layers.Flatten()) - model.add(layers.Dense(1)) - - return model -!ec - -!split -===== Other Models ===== -Let us take a look at our models. _Note_: double click images for bigger view. - -!bc pycod -generator = generator_model() -plot_model(generator, show_shapes=True, rankdir='LR') -!ec - -!bc pycod -discriminator = discriminator_model() -plot_model(discriminator, show_shapes=True, rankdir='LR') -!ec - -Next we need a few helper objects we will use in training - -!bc pycod -cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True) -generator_optimizer = tf.keras.optimizers.Adam(1e-4) -discriminator_optimizer = tf.keras.optimizers.Adam(1e-4) -!ec - -The first object, *cross_entropy* is our loss function and the two others are -our optimizers. Notice we use the same learning rate for both $g$ and $d$. This -is because they need to improve their accuracy at approximately equal speeds to -get convergence (not necessarily exactly equal). Now we define our loss -functions - -!bc pycod -def generator_loss(fake_output): - loss = cross_entropy(tf.ones_like(fake_output), fake_output) - - return loss -!ec - -!bc pycod -def discriminator_loss(real_output, fake_output): - real_loss = cross_entropy(tf.ones_like(real_output), real_output) - fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output) - total_loss = real_loss + fake_loss - - return total_loss -!ec - -Next we define a kind of seed to help us compare the learning process over -multiple training epochs. - -!bc pycod -noise_dimension = 100 -n_examples_to_generate = 16 -seed_images = tf.random.normal([n_examples_to_generate, noise_dimension]) -!ec - -!split -===== Training Step ===== - -Now we have everything we need to define our training step, which we will apply -for every step in our training loop. Notice the @tf.function flag signifying -that the function is tensorflow 'compiled'. Removing this flag doubles the -computation time. - -!bc pycod -@tf.function -def train_step(images): - noise = tf.random.normal([BATCH_SIZE, noise_dimension]) - - with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: - generated_images = generator(noise, training=True) - - real_output = discriminator(images, training=True) - fake_output = discriminator(generated_images, training=True) - - gen_loss = generator_loss(fake_output) - disc_loss = discriminator_loss(real_output, fake_output) - - gradients_of_generator = gen_tape.gradient(gen_loss, - generator.trainable_variables) - gradients_of_discriminator = disc_tape.gradient(disc_loss, - discriminator.trainable_variables) - generator_optimizer.apply_gradients(zip(gradients_of_generator, - generator.trainable_variables)) - discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, - discriminator.trainable_variables)) +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt - return gen_loss, disc_loss -!ec +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 -Next we define a helper function to produce an output over our training epochs -to see the predictive progression of our generator model. _Note_: I am including -this code here, but comment it out in the training loop. -!bc pycod -def generate_and_save_images(model, epoch, test_input): - # we're making inferences here - predictions = model(test_input, training=False) +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 - fig = plt.figure(figsize=(4, 4)) - - for i in range(predictions.shape[0]): - plt.subplot(4, 4, i+1) - plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray') - plt.axis('off') - - plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png') - plt.close() - #plt.show() -!ec + # 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 -!split -===== Checkpoints ===== -Setting up checkpoints to periodically save our model during training so that -everything is not lost even if the program were to somehow terminate while -training. - -!bc pycod -# Setting up checkpoints to save model during training -checkpoint_dir = './training_checkpoints' -checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt') -checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer, - discriminator_optimizer=discriminator_optimizer, - generator=generator, - discriminator=discriminator) -!ec - -Now we define our training loop + # Due to multiple hidden layers, define a variable referencing to the + # output of the previous layer: + x_prev = x_input -!bc pycod -def train(dataset, epochs): - generator_loss_list = [] - discriminator_loss_list = [] + ## Hidden layers: - for epoch in range(epochs): - start = time.time() + 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] - for image_batch in dataset: - gen_loss, disc_loss = train_step(image_batch) - generator_loss_list.append(gen_loss.numpy()) - discriminator_loss_list.append(disc_loss.numpy()) + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0) - #generate_and_save_images(generator, epoch + 1, seed_images) - - if (epoch + 1) % 15 == 0: - checkpoint.save(file_prefix=checkpoint_prefix) - - print(f'Time for epoch {epoch} is {time.time() - start}') + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) - #generate_and_save_images(generator, epochs, seed_images) - - loss_file = './data/lossfile.txt' - with open(loss_file, 'w') as outfile: - outfile.write(str(generator_loss_list)) - outfile.write('\n') - outfile.write('\n') - outfile.write(str(discriminator_loss_list)) - outfile.write('\n') - outfile.write('\n') -!ec + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + ## Output layer: -To train simply call this function. _Warning_: this might take a long time so -there is a folder of a pretrained network already included in the repository. + # Get the weights and bias for this layer + w_output = P[-1] -!bc pycod -train(train_dataset, EPOCHS) -!ec + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) -And here is the result of training our model for 100 epochs + z_output = np.matmul(w_output, x_prev) + x_output = z_output -MOVIE: [images_from_seed_images/generation.gif] + return x_output -Now to avoid having to train and everything, which will take a while depending -on your computer setup we now load in the model which produced the above gif. - -!bc pycod -checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir)) -restored_generator = checkpoint.generator -restored_discriminator = checkpoint.discriminator -print(restored_generator) -print(restored_discriminator) -!ec +def cost_function_deep(P, x): + # Evaluate the trial function with the current parameters P + g_t = g_trial_deep(x,P) -!split -===== Exploring the Latent Space ===== + # Find the derivative w.r.t x of the trial function + d_g_t = elementwise_grad(g_trial_deep,0)(x,P) -We have successfully loaded in our latest model. Let us now play around a bit -and see what kind of things we can learn about this model. Our generator takes -an array of 100 numbers. One idea can be to try to systematically change our -input. Let us try and see what we get + # The right side of the ODE + func = f(x, g_t) -!bc pycod -def generate_latent_points(number=100, scale_means=1, scale_stds=1): - latent_dim = 100 - means = scale_means * tf.linspace(-1, 1, num=latent_dim) - stds = scale_stds * tf.linspace(-1, 1, num=latent_dim) - latent_space_value_range = tf.random.normal([number, latent_dim], - means, - stds, - dtype=tf.float64) + err_sqr = (d_g_t - func)**2 + cost_sum = np.sum(err_sqr) - return latent_space_value_range + return cost_sum / np.size(err_sqr) -def generate_images(latent_points): - # notice we set training to false because we are making inferences - generated_images = restored_generator.predict(latent_points) +# The right side of the ODE: +def f(x, g_trial): + alpha,A, g0 = get_parameters() + return alpha*g_trial*(A - g_trial) - return generated_images -!ec +# 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) -!bc pycod -def plot_result(generated_images, number=100): - # obviously this assumes sqrt number is an int - fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)), - figsize=(10, 10)) +# The analytical solution: +def g_analytic(t): + alpha,A, g0 = get_parameters() + return A*g0/(g0 + (A - g0)*np.exp(-alpha*A*t)) - for i in range(int(np.sqrt(number))): - for j in range(int(np.sqrt(number))): - axs[i, j].imshow(generated_images[i*j], cmap='Greys') - axs[i, j].axis('off') +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 -generated_images = generate_images(generate_latent_points()) -plot_result(generated_images) +# 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 -===== Getting Results ===== -We see that the generator generates images that look like MNIST -numbers: $1, 4, 7, 9$. Let's try to tweak it a bit more to see if we are able -to generate a similar plot where we generate every MNIST number. Let us now try -to 'move' a bit around in the latent space. _Note_: decrease the plot number if -these following cells take too long to run on your computer. +===== Comparing with a numerical scheme ===== -!bc pycod -plot_number = 225 +The Poisson equation is possible to solve using Taylor series to approximate the second derivative. -generated_images = generate_images(generate_latent_points(number=plot_number, - scale_means=5, - scale_stds=1)) -plot_result(generated_images, number=plot_number) +Using Taylor series, the second derivative can be expressed as -generated_images = generate_images(generate_latent_points(number=plot_number, - scale_means=-5, - scale_stds=1)) -plot_result(generated_images, number=plot_number) +$$ +g''(x) = \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2} + E_{\Delta x}(x) +$$ -generated_images = generate_images(generate_latent_points(number=plot_number, - scale_means=1, - scale_stds=5)) -plot_result(generated_images, number=plot_number) -!ec +where $\Delta x$ is a small step size and $E_{\Delta x}(x)$ being the error term. -Again, we have found something interesting. *Moving* around using our means -takes us from digit to digit, while *moving* around using our standard -deviations seem to increase the number of different digits! In the last image -above, we can barely make out every MNIST digit. Let us make on last plot using -this information by upping the standard deviation of our Gaussian noises. +Looking away from the error terms gives an approximation to the second derivative: -!bc pycod -plot_number = 400 -generated_images = generate_images(generate_latent_points(number=plot_number, - scale_means=1, - scale_stds=10)) -plot_result(generated_images, number=plot_number) -!ec -A pretty cool result! We see that our generator indeed has learned a -distribution which qualitatively looks a whole lot like the MNIST dataset. +!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 -===== Interpolating Between MNIST Digits ===== -Another interesting way to explore the latent space of our generator model is by -interpolating between the MNIST digits. This section is largely based on -"this excellent blogpost": "https://machinelearningmastery.com/how-to-interpolate-and-perform-vector-arithmetic-with-faces-using-a-generative-adversarial-network/" -by Jason Brownlee. +===== Setting up the code ===== -So let us start by defining a function to interpolate between two points in the -latent space. +We can then compare the result from this numerical scheme with the output from our network using Autograd: !bc pycod -def interpolation(point_1, point_2, n_steps=10): - ratios = np.linspace(0, 1, num=n_steps) - vectors = [] - for i, ratio in enumerate(ratios): - vectors.append(((1.0 - ratio) * point_1 + ratio * point_2)) +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt - return tf.stack(vectors) -!ec +def sigmoid(z): + return 1/(1 + np.exp(-z)) -Now we have all we need to do our interpolation analysis. +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 -!bc pycod -plot_number = 100 -latent_points = generate_latent_points(number=plot_number) -results = None -for i in range(0, 2*np.sqrt(plot_number), 2): - interpolated = interpolation(latent_points[i], latent_points[i+1]) - generated_images = generate_images(interpolated) + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) - if results is None: - results = generated_images - else: - results = tf.stack((results, generated_images)) + # 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() -plot_results(results, plot_number) !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"