Files
FYS-STK4155/doc/pub/week43/ipynb/week43.ipynb
T
Morten Hjorth-Jensen b488e11a06 notes oct 29
2020-10-29 14:15:54 +01:00

4447 lines
192 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- dom:TITLE: Week 43: Solving Differential Equations with Deep Learning and Dimensionality Reduction methods -->\n",
"# Week 43: Solving Differential Equations with Deep Learning and Dimensionality Reduction methods\n",
"<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->\n",
"<!-- Author: --> \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
"Date: **Oct 26, 2020**\n",
"\n",
"Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
"\n",
"\n",
"## Plans for week 43\n",
"\n",
"* Thursday: Wrapping up Recurrent Neural Networks and solving differential equations. [Video of Lecture October 22](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureOctober22.mp4?vrtx=view-as-webpage)\n",
"\n",
"* Friday: Principal Component Analysis and Dimensionality Reduction. [Video of Lecture October 23](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureOctober23.mp4?vrtx=view-as-webpage)\n",
"\n",
"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 40](https://compphysics.github.io/MachineLearning/doc/pub/week40/html/week40.html) and the [Autograd documentation](https://github.com/HIPS/autograd).\n",
"\n",
"## Recurrent Neural Networks\n",
"\n",
"[Overview video](https://www.youtube.com/watch?v=SEnXr6v2ifU&ab_channel=AlexanderAmini).\n",
"See also lecture on Thursday October 22 and examples from [week 42](https://compphysics.github.io/MachineLearning/doc/pub/week42/html/week42.html).\n",
"\n",
"[IN5400 at UiO Lecture](https://www.uio.no/studier/emner/matnat/ifi/IN5400/v20/material/week10/in5400_2020_week10_recurrent_neural_network.pdf)\n",
"\n",
"[CS231 at Stanford Lecture](https://www.youtube.com/watch?v=6niqTuYFZLQ&list=PLzUTmXVwsnXod6WNdg57Yc3zFx_f-RYsq&index=10&ab_channel=StanfordUniversitySchoolofEngineering)\n",
"\n",
"## Solving ODEs with Deep Learning\n",
"\n",
"The Universal Approximation Theorem states that a neural network can\n",
"approximate any function at a single hidden layer along with one input\n",
"and output layer to any given precision. \n",
"\n",
"\n",
"## Ordinary Differential Equations\n",
"\n",
"An ordinary differential equation (ODE) is an equation involving functions having one variable.\n",
"\n",
"In general, an ordinary differential equation looks like"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"ode\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{ode} \\tag{1}\n",
"f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right) = 0\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $g(x)$ is the function to find, and $g^{(n)}(x)$ is the $n$-th derivative of $g(x)$.\n",
"\n",
"The $f\\left(x, g(x), g'(x), g''(x), \\, \\dots \\, , g^{(n)}(x)\\right)$ is just a way to write that there is an expression involving $x$ and $g(x), \\ g'(x), \\ g''(x), \\, \\dots \\, , \\text{ and } g^{(n)}(x)$ on the left side of the equality sign in ([1](#ode)).\n",
"The highest order of derivative, that is the value of $n$, determines to the order of the equation.\n",
"The equation is referred to as a $n$-th order ODE.\n",
"Along with ([1](#ode)), some additional conditions of the function $g(x)$ are typically given\n",
"for the solution to be unique.\n",
"\n",
"## The trial solution\n",
"\n",
"Let the trial solution $g_t(x)$ be"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"_auto1\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
"\tg_t(x) = h_1(x) + h_2(x,N(x,P))\n",
"\\label{_auto1} \\tag{2}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $h_1(x)$ is a function that makes $g_t(x)$ satisfy a given set\n",
"of conditions, $N(x,P)$ a neural network with weights and biases\n",
"described by $P$ and $h_2(x, N(x,P))$ some expression involving the\n",
"neural network. The role of the function $h_2(x, N(x,P))$, is to\n",
"ensure that the output from $N(x,P)$ is zero when $g_t(x)$ is\n",
"evaluated at the values of $x$ where the given conditions must be\n",
"satisfied. The function $h_1(x)$ should alone make $g_t(x)$ satisfy\n",
"the conditions.\n",
"\n",
"But what about the network $N(x,P)$?\n",
"\n",
"\n",
"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.\n",
"\n",
"\n",
"## Minimization process\n",
"\n",
"For the minimization to be defined, we need to have a cost function at hand to minimize.\n",
"\n",
"It is given that $f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right)$ should be equal to zero in ([1](#ode)).\n",
"We can choose to consider the mean squared error as the cost function for an input $x$.\n",
"Since we are looking at one input, the cost function is just $f$ squared.\n",
"The cost function $c\\left(x, P \\right)$ can therefore be expressed as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C\\left(x, P\\right) = \\big(f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right)\\big)^2\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If $N$ inputs are given as a vector $\\boldsymbol{x}$ with elements $x_i$ for $i = 1,\\dots,N$,\n",
"the cost function becomes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"cost\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{cost} \\tag{3}\n",
"\tC\\left(\\boldsymbol{x}, P\\right) = \\frac{1}{N} \\sum_{i=1}^N \\big(f\\left(x_i, \\, g(x_i), \\, g'(x_i), \\, g''(x_i), \\, \\dots \\, , \\, g^{(n)}(x_i)\\right)\\big)^2\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The neural net should then find the parameters $P$ that minimizes the cost function in\n",
"([3](#cost)) for a set of $N$ training samples $x_i$.\n",
"\n",
"## Minimizing the cost function using gradient descent and automatic differentiation\n",
"\n",
"To perform the minimization using gradient descent, the gradient of $C\\left(\\boldsymbol{x}, P\\right)$ is needed.\n",
"It might happen so that finding an analytical expression of the gradient of $C(\\boldsymbol{x}, P)$ from ([3](#cost)) gets too messy, depending on which cost function one desires to use.\n",
"\n",
"Luckily, there exists libraries that makes the job for us through automatic differentiation.\n",
"Automatic differentiation is a method of finding the derivatives numerically with very high precision.\n",
"\n",
"\n",
"## Example: Exponential decay\n",
"\n",
"An exponential decay of a quantity $g(x)$ is described by the equation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"solve_expdec\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{solve_expdec} \\tag{4}\n",
" g'(x) = -\\gamma g(x)\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with $g(0) = g_0$ for some chosen initial value $g_0$.\n",
"\n",
"The analytical solution of ([4](#solve_expdec)) is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"_auto2\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
" g(x) = g_0 \\exp\\left(-\\gamma x\\right)\n",
"\\label{_auto2} \\tag{5}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of ([4](#solve_expdec)).\n",
"\n",
"\n",
"## The function to solve for\n",
"\n",
"The program will use a neural network to solve"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"solveode\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{solveode} \\tag{6}\n",
"g'(x) = -\\gamma g(x)\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $g(0) = g_0$ with $\\gamma$ and $g_0$ being some chosen values.\n",
"\n",
"In this example, $\\gamma = 2$ and $g_0 = 10$.\n",
"\n",
"## The trial solution\n",
"To begin with, a trial solution $g_t(t)$ must be chosen. A general trial solution for ordinary differential equations could be"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"g_t(x, P) = h_1(x) + h_2(x, N(x, P))\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"## Setup of Network\n",
"\n",
"In this network, there are no weights and bias at the input layer, so $P = \\{ P_{\\text{hidden}}, P_{\\text{output}} \\}$.\n",
"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.\n",
"\n",
"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.\n",
"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.\n",
"\n",
"Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron.\n",
"\n",
"It is given that $g(0) = g_0$. The trial solution must fulfill this condition to be a proper solution of ([6](#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:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"trial\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{trial} \\tag{7}\n",
"g_t(x, P) = g_0 + x \\cdot N(x, P)\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reformulating the problem\n",
"\n",
"We wish that our neural network manages to minimize a given cost function.\n",
"\n",
"A reformulation of out equation, ([6](#solveode)), must therefore be done,\n",
"such that it describes the problem a neural network can solve for.\n",
"\n",
"The neural network must find the set of weights and biases $P$ such that the trial solution in ([7](#trial)) satisfies ([6](#solveode)).\n",
"\n",
"The trial solution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"g_t(x, P) = g_0 + x \\cdot N(x, P)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"has been chosen such that it already solves the condition $g(0) = g_0$. What remains, is to find $P$ such that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"nnmin\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{nnmin} \\tag{8}\n",
"g_t'(x, P) = - \\gamma g_t(x, P)\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"is fulfilled as *best as possible*.\n",
"\n",
"## More technicalities\n",
"\n",
"The left hand side and right hand side of ([8](#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.\n",
"This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero.\n",
"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.\n",
"\n",
"This gives the following cost function our neural network must solve for:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\min_{P}\\Big\\{ \\big(g_t'(x, P) - ( -\\gamma g_t(x, P) \\big)^2 \\Big\\}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(the notation $\\min_{P}\\{ f(x, P) \\}$ means that we desire to find $P$ that yields the minimum of $f(x, P)$)\n",
"\n",
"or, in terms of weights and biases for the hidden and output layer in our network:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\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\\}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"for an input value $x$.\n",
"\n",
"## More details\n",
"\n",
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"min\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{min} \\tag{9}\n",
"\\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\\}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Letting $\\boldsymbol{x}$ be a vector with elements $x_i$ and $C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2$ denote the cost function, the minimization problem that our network must solve, becomes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\min_{P} C(\\boldsymbol{x}, P)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In terms of $P_{\\text{hidden} }$ and $P_{\\text{output} }$, this could also be expressed as\n",
"\n",
"$$\n",
"\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }} C(\\boldsymbol{x}, \\{P_{\\text{hidden} }, P_{\\text{output} }\\})\n",
"$$\n",
"\n",
"## A possible implementation of a neural network\n",
"\n",
"For simplicity, it is assumed that the input is an array $\\boldsymbol{x} = (x_1, \\dots, x_N)$ with $N$ elements. It is at these points the neural network should find $P$ such that it fulfills ([9](#min)).\n",
"\n",
"First, the neural network must feed forward the inputs.\n",
"This means that $\\boldsymbol{x}s$ must be passed through an input layer, a hidden layer and a output layer. The input layer in this case, does not need to process the data any further.\n",
"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} }$.\n",
"\n",
"## Technicalities\n",
"\n",
"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:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{aligned}\n",
"z_{i,j}^{\\text{hidden}} &= b_i^{\\text{hidden}} + w_i^{\\text{hidden}}x_j \\\\\n",
"&=\n",
"\\begin{pmatrix}\n",
"b_i^{\\text{hidden}} & w_i^{\\text{hidden}}\n",
"\\end{pmatrix}\n",
"\\begin{pmatrix}\n",
"1 \\\\\n",
"x_j\n",
"\\end{pmatrix}\n",
"\\end{aligned}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Final technicalities I\n",
"\n",
"The result after weighting the inputs at the $i$-th hidden neuron can be written as a vector:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{aligned}\n",
"\\boldsymbol{z}_{i}^{\\text{hidden}} &= \\Big( b_i^{\\text{hidden}} + w_i^{\\text{hidden}}x_1 , \\ b_i^{\\text{hidden}} + w_i^{\\text{hidden}} x_2, \\ \\dots \\, , \\ b_i^{\\text{hidden}} + w_i^{\\text{hidden}} x_N\\Big) \\\\\n",
"&=\n",
"\\begin{pmatrix}\n",
" b_i^{\\text{hidden}} & w_i^{\\text{hidden}}\n",
"\\end{pmatrix}\n",
"\\begin{pmatrix}\n",
"1 & 1 & \\dots & 1 \\\\\n",
"x_1 & x_2 & \\dots & x_N\n",
"\\end{pmatrix} \\\\\n",
"&= \\boldsymbol{p}_{i, \\text{hidden}}^T X\n",
"\\end{aligned}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Final technicalities II\n",
"\n",
"The vector $\\boldsymbol{p}_{i, \\text{hidden}}^T$ constitutes each row in $P_{\\text{hidden} }$, which contains the weights for the neural network to minimize according to ([9](#min)).\n",
"\n",
"After having found $\\boldsymbol{z}_{i}^{\\text{hidden}} $ for every $i$-th neuron within the hidden layer, the vector will be sent to an activation function $a_i(\\boldsymbol{z})$.\n",
"\n",
"In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"f(z) = \\frac{1}{1 + \\exp{(-z)}}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is possible to use other activations functions for the hidden layer also.\n",
"\n",
"The output $\\boldsymbol{x}_i^{\\text{hidden}}$ from each $i$-th hidden neuron is:\n",
"\n",
"$$\n",
"\\boldsymbol{x}_i^{\\text{hidden} } = f\\big( \\boldsymbol{z}_{i}^{\\text{hidden}} \\big)\n",
"$$\n",
"\n",
"The outputs $\\boldsymbol{x}_i^{\\text{hidden} } $ are then sent to the output layer.\n",
"\n",
"The output layer consists of one neuron in this case, and combines the\n",
"output from each of the neurons in the hidden layers. The output layer\n",
"combines the results from the hidden layer using some weights $w_i^{\\text{output}}$\n",
"and biases $b_i^{\\text{output}}$. In this case,\n",
"it is assumes that the number of neurons in the output layer is one.\n",
"\n",
"## Final technicalities III\n",
"\n",
"\n",
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{aligned}\n",
"z_{1,j}^{\\text{output}} & =\n",
"\\begin{pmatrix}\n",
"b_1^{\\text{output}} & \\boldsymbol{w}_1^{\\text{output}}\n",
"\\end{pmatrix}\n",
"\\begin{pmatrix}\n",
"1 \\\\\n",
"\\boldsymbol{x}_j^{\\text{hidden}}\n",
"\\end{pmatrix}\n",
"\\end{aligned}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Final technicalities IV\n",
"\n",
"Expressing $z_{1,j}^{\\text{output}}$ as a vector gives the following way of weighting the inputs from the hidden layer:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{z}_{1}^{\\text{output}} =\n",
"\\begin{pmatrix}\n",
"b_1^{\\text{output}} & \\boldsymbol{w}_1^{\\text{output}}\n",
"\\end{pmatrix}\n",
"\\begin{pmatrix}\n",
"1 & 1 & \\dots & 1 \\\\\n",
"\\boldsymbol{x}_1^{\\text{hidden}} & \\boldsymbol{x}_2^{\\text{hidden}} & \\dots & \\boldsymbol{x}_N^{\\text{hidden}}\n",
"\\end{pmatrix}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this case we seek a continuous range of values since we are approximating a function. This means that after computing $\\boldsymbol{z}_{1}^{\\text{output}}$ the neural network has finished its feed forward step, and $\\boldsymbol{z}_{1}^{\\text{output}}$ is the final output of the network.\n",
"\n",
"## Back propagation\n",
"\n",
"The next step is to decide how the parameters should be changed such that they minimize the cost function.\n",
"\n",
"The chosen cost function for this problem is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In order to minimize the cost function, an optimization method must be chosen.\n",
"\n",
"Here, gradient descent with a constant step size has been chosen.\n",
"\n",
"## Gradient descent\n",
"\n",
"The idea of the gradient descent algorithm is to update parameters in\n",
"a direction where the cost function decreases goes to a minimum.\n",
"\n",
"In general, the update of some parameters $\\boldsymbol{\\omega}$ given a cost\n",
"function defined by some weights $\\boldsymbol{\\omega}$, $C(\\boldsymbol{x},\n",
"\\boldsymbol{\\omega})$, goes as follows:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{\\omega}_{\\text{new} } = \\boldsymbol{\\omega} - \\lambda \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"for a number of iterations or until $ \\big|\\big| \\boldsymbol{\\omega}_{\\text{new} } - \\boldsymbol{\\omega} \\big|\\big|$ becomes smaller than some given tolerance.\n",
"\n",
"The value of $\\lambda$ decides how large steps the algorithm must take\n",
"in the direction of $ \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})$.\n",
"The notation $\\nabla_{\\boldsymbol{\\omega}}$ express the gradient with respect\n",
"to the elements in $\\boldsymbol{\\omega}$.\n",
"\n",
"In our case, we have to minimize the cost function $C(\\boldsymbol{x}, P)$ with\n",
"respect to the two sets of weights and biases, that is for the hidden\n",
"layer $P_{\\text{hidden} }$ and for the output layer $P_{\\text{output}\n",
"}$ .\n",
"\n",
"This means that $P_{\\text{hidden} }$ and $P_{\\text{output} }$ is updated by"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{aligned}\n",
"P_{\\text{hidden},\\text{new}} &= P_{\\text{hidden}} - \\lambda \\nabla_{P_{\\text{hidden}}} C(\\boldsymbol{x}, P) \\\\\n",
"P_{\\text{output},\\text{new}} &= P_{\\text{output}} - \\lambda \\nabla_{P_{\\text{output}}} C(\\boldsymbol{x}, P)\n",
"\\end{aligned}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The code for solving the ODE"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"import autograd.numpy as np\n",
"from autograd import grad, elementwise_grad\n",
"import autograd.numpy.random as npr\n",
"from matplotlib import pyplot as plt\n",
"\n",
"def sigmoid(z):\n",
" return 1/(1 + np.exp(-z))\n",
"\n",
"# Assuming one input, hidden, and output layer\n",
"def neural_network(params, x):\n",
"\n",
" # Find the weights (including and biases) for the hidden and output layer.\n",
" # Assume that params is a list of parameters for each layer.\n",
" # The biases are the first element for each array in params,\n",
" # and the weights are the remaning elements in each array in params.\n",
"\n",
" w_hidden = params[0]\n",
" w_output = params[1]\n",
"\n",
" # Assumes input x being an one-dimensional array\n",
" num_values = np.size(x)\n",
" x = x.reshape(-1, num_values)\n",
"\n",
" # Assume that the input layer does nothing to the input x\n",
" x_input = x\n",
"\n",
" ## Hidden layer:\n",
"\n",
" # Add a row of ones to include bias\n",
" x_input = np.concatenate((np.ones((1,num_values)), x_input ), axis = 0)\n",
"\n",
" z_hidden = np.matmul(w_hidden, x_input)\n",
" x_hidden = sigmoid(z_hidden)\n",
"\n",
" ## Output layer:\n",
"\n",
" # Include bias:\n",
" x_hidden = np.concatenate((np.ones((1,num_values)), x_hidden ), axis = 0)\n",
"\n",
" z_output = np.matmul(w_output, x_hidden)\n",
" x_output = z_output\n",
"\n",
" return x_output\n",
"\n",
"# The trial solution using the deep neural network:\n",
"def g_trial(x,params, g0 = 10):\n",
" return g0 + x*neural_network(params,x)\n",
"\n",
"# The right side of the ODE:\n",
"def g(x, g_trial, gamma = 2):\n",
" return -gamma*g_trial\n",
"\n",
"# The cost function:\n",
"def cost_function(P, x):\n",
"\n",
" # Evaluate the trial function with the current parameters P\n",
" g_t = g_trial(x,P)\n",
"\n",
" # Find the derivative w.r.t x of the neural network\n",
" d_net_out = elementwise_grad(neural_network,1)(P,x)\n",
"\n",
" # Find the derivative w.r.t x of the trial function\n",
" d_g_t = elementwise_grad(g_trial,0)(x,P)\n",
"\n",
" # The right side of the ODE\n",
" func = g(x, g_t)\n",
"\n",
" err_sqr = (d_g_t - func)**2\n",
" cost_sum = np.sum(err_sqr)\n",
"\n",
" return cost_sum / np.size(err_sqr)\n",
"\n",
"# Solve the exponential decay ODE using neural network with one input, hidden, and output layer\n",
"def solve_ode_neural_network(x, num_neurons_hidden, num_iter, lmb):\n",
" ## Set up initial weights and biases\n",
"\n",
" # For the hidden layer\n",
" p0 = npr.randn(num_neurons_hidden, 2 )\n",
"\n",
" # For the output layer\n",
" p1 = npr.randn(1, num_neurons_hidden + 1 ) # +1 since bias is included\n",
"\n",
" P = [p0, p1]\n",
"\n",
" print('Initial cost: %g'%cost_function(P, x))\n",
"\n",
" ## Start finding the optimal weights using gradient descent\n",
"\n",
" # Find the Python function that represents the gradient of the cost function\n",
" # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
" cost_function_grad = grad(cost_function,0)\n",
"\n",
" # Let the update be done num_iter times\n",
" for i in range(num_iter):\n",
" # Evaluate the gradient at the current weights and biases in P.\n",
" # The cost_grad consist now of two arrays;\n",
" # one for the gradient w.r.t P_hidden and\n",
" # one for the gradient w.r.t P_output\n",
" cost_grad = cost_function_grad(P, x)\n",
"\n",
" P[0] = P[0] - lmb * cost_grad[0]\n",
" P[1] = P[1] - lmb * cost_grad[1]\n",
"\n",
" print('Final cost: %g'%cost_function(P, x))\n",
"\n",
" return P\n",
"\n",
"def g_analytic(x, gamma = 2, g0 = 10):\n",
" return g0*np.exp(-gamma*x)\n",
"\n",
"# Solve the given problem\n",
"if __name__ == '__main__':\n",
" # Set seed such that the weight are initialized\n",
" # with same weights and biases for every run.\n",
" npr.seed(15)\n",
"\n",
" ## Decide the vales of arguments to the function to solve\n",
" N = 10\n",
" x = np.linspace(0, 1, N)\n",
"\n",
" ## Set up the initial parameters\n",
" num_hidden_neurons = 10\n",
" num_iter = 10000\n",
" lmb = 0.001\n",
"\n",
" # Use the network\n",
" P = solve_ode_neural_network(x, num_hidden_neurons, num_iter, lmb)\n",
"\n",
" # Print the deviation from the trial solution and true solution\n",
" res = g_trial(x,P)\n",
" res_analytical = g_analytic(x)\n",
"\n",
" print('Max absolute difference: %g'%np.max(np.abs(res - res_analytical)))\n",
"\n",
" # Plot the results\n",
" plt.figure(figsize=(10,10))\n",
"\n",
" plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
" plt.plot(x, res_analytical)\n",
" plt.plot(x, res[0,:])\n",
" plt.legend(['analytical','nn'])\n",
" plt.xlabel('x')\n",
" plt.ylabel('g(x)')\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The network with one input layer, specified number of hidden layers, and one output layer\n",
"\n",
"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.\n",
"\n",
"The number of neurons within each hidden layer are given as a list of integers in the program below."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad, elementwise_grad\n",
"import autograd.numpy.random as npr\n",
"from matplotlib import pyplot as plt\n",
"\n",
"def sigmoid(z):\n",
" return 1/(1 + np.exp(-z))\n",
"\n",
"# The neural network with one input layer and one output layer,\n",
"# but with number of hidden layers specified by the user.\n",
"def deep_neural_network(deep_params, x):\n",
" # N_hidden is the number of hidden layers\n",
"\n",
" N_hidden = np.size(deep_params) - 1 # -1 since params consists of\n",
" # parameters to all the hidden\n",
" # layers AND the output layer.\n",
"\n",
" # Assumes input x being an one-dimensional array\n",
" num_values = np.size(x)\n",
" x = x.reshape(-1, num_values)\n",
"\n",
" # Assume that the input layer does nothing to the input x\n",
" x_input = x\n",
"\n",
" # Due to multiple hidden layers, define a variable referencing to the\n",
" # output of the previous layer:\n",
" x_prev = x_input\n",
"\n",
" ## Hidden layers:\n",
"\n",
" for l in range(N_hidden):\n",
" # From the list of parameters P; find the correct weigths and bias for this layer\n",
" w_hidden = deep_params[l]\n",
"\n",
" # Add a row of ones to include bias\n",
" x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n",
"\n",
" z_hidden = np.matmul(w_hidden, x_prev)\n",
" x_hidden = sigmoid(z_hidden)\n",
"\n",
" # Update x_prev such that next layer can use the output from this layer\n",
" x_prev = x_hidden\n",
"\n",
" ## Output layer:\n",
"\n",
" # Get the weights and bias for this layer\n",
" w_output = deep_params[-1]\n",
"\n",
" # Include bias:\n",
" x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n",
"\n",
" z_output = np.matmul(w_output, x_prev)\n",
" x_output = z_output\n",
"\n",
" return x_output\n",
"\n",
"# The trial solution using the deep neural network:\n",
"def g_trial_deep(x,params, g0 = 10):\n",
" return g0 + x*deep_neural_network(params, x)\n",
"\n",
"# The right side of the ODE:\n",
"def g(x, g_trial, gamma = 2):\n",
" return -gamma*g_trial\n",
"\n",
"# The same cost function as before, but calls deep_neural_network instead.\n",
"def cost_function_deep(P, x):\n",
"\n",
" # Evaluate the trial function with the current parameters P\n",
" g_t = g_trial_deep(x,P)\n",
"\n",
" # Find the derivative w.r.t x of the neural network\n",
" d_net_out = elementwise_grad(deep_neural_network,1)(P,x)\n",
"\n",
" # Find the derivative w.r.t x of the trial function\n",
" d_g_t = elementwise_grad(g_trial_deep,0)(x,P)\n",
"\n",
" # The right side of the ODE\n",
" func = g(x, g_t)\n",
"\n",
" err_sqr = (d_g_t - func)**2\n",
" cost_sum = np.sum(err_sqr)\n",
"\n",
" return cost_sum / np.size(err_sqr)\n",
"\n",
"# Solve the exponential decay ODE using neural network with one input and one output layer,\n",
"# but with specified number of hidden layers from the user.\n",
"def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n",
" # num_hidden_neurons is now a list of number of neurons within each hidden layer\n",
"\n",
" # The number of elements in the list num_hidden_neurons thus represents\n",
" # the number of hidden layers.\n",
"\n",
" # Find the number of hidden layers:\n",
" N_hidden = np.size(num_neurons)\n",
"\n",
" ## Set up initial weights and biases\n",
"\n",
" # Initialize the list of parameters:\n",
" P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
"\n",
" P[0] = npr.randn(num_neurons[0], 2 )\n",
" for l in range(1,N_hidden):\n",
" P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
"\n",
" # For the output layer\n",
" P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
"\n",
" print('Initial cost: %g'%cost_function_deep(P, x))\n",
"\n",
" ## Start finding the optimal weights using gradient descent\n",
"\n",
" # Find the Python function that represents the gradient of the cost function\n",
" # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
" cost_function_deep_grad = grad(cost_function_deep,0)\n",
"\n",
" # Let the update be done num_iter times\n",
" for i in range(num_iter):\n",
" # Evaluate the gradient at the current weights and biases in P.\n",
" # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n",
" # in the hidden layers and output layers evaluated at x.\n",
" cost_deep_grad = cost_function_deep_grad(P, x)\n",
"\n",
" for l in range(N_hidden+1):\n",
" P[l] = P[l] - lmb * cost_deep_grad[l]\n",
"\n",
" print('Final cost: %g'%cost_function_deep(P, x))\n",
"\n",
" return P\n",
"\n",
"def g_analytic(x, gamma = 2, g0 = 10):\n",
" return g0*np.exp(-gamma*x)\n",
"\n",
"# Solve the given problem\n",
"if __name__ == '__main__':\n",
" npr.seed(15)\n",
"\n",
" ## Decide the vales of arguments to the function to solve\n",
" N = 10\n",
" x = np.linspace(0, 1, N)\n",
"\n",
" ## Set up the initial parameters\n",
" num_hidden_neurons = np.array([10,10])\n",
" num_iter = 10000\n",
" lmb = 0.001\n",
"\n",
" P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n",
"\n",
" res = g_trial_deep(x,P)\n",
" res_analytical = g_analytic(x)\n",
"\n",
" plt.figure(figsize=(10,10))\n",
"\n",
" plt.title('Performance of a deep neural network solving an ODE compared to the analytical solution')\n",
" plt.plot(x, res_analytical)\n",
" plt.plot(x, res[0,:])\n",
" plt.legend(['analytical','dnn'])\n",
" plt.ylabel('g(x)')\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example: Population growth\n",
"\n",
"A logistic model of population growth assumes that a population converges toward an equilibrium.\n",
"The population growth can be modeled by"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"log\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{log} \\tag{10}\n",
"\tg'(t) = \\alpha g(t)(A - g(t))\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"Also, at $t = 0$ the population has the size $g(0) = g_0$, where $g_0$ is some chosen constant.\n",
"\n",
"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\n",
"and high execution time (this might be more apparent in the examples solving PDEs),\n",
"using a library like TensorFlow is recommended.\n",
"Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method.\n",
"\n",
"## Setting up the problem\n",
"\n",
"Here, we will model a population $g(t)$ in an environment having carrying capacity $A$.\n",
"The population follows the model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"solveode_population\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{solveode_population} \\tag{11}\n",
"g'(t) = \\alpha g(t)(A - g(t))\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $g(0) = g_0$.\n",
"\n",
"In this example, we let $\\alpha = 2$, $A = 1$, and $g_0 = 1.2$.\n",
"\n",
"## The trial solution\n",
"\n",
"We will get a slightly different trial solution, as the boundary conditions are different\n",
"compared to the case for exponential decay.\n",
"\n",
"A possible trial solution satisfying the condition $g(0) = g_0$ could be\n",
"\n",
"$$\n",
"h_1(t) = g_0 + t \\cdot N(t,P)\n",
"$$\n",
"\n",
"with $N(t,P)$ being the output from the neural network with weights and biases for each layer collected in the set $P$.\n",
"\n",
"The analytical solution is\n",
"\n",
"$$\n",
"g(t) = \\frac{Ag_0}{g_0 + (A - g_0)\\exp(-\\alpha A t)}\n",
"$$\n",
"\n",
"## The program using Autograd\n",
"\n",
"The network will be the similar as for the exponential decay example, but with some small modifications for our problem."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad, elementwise_grad\n",
"import autograd.numpy.random as npr\n",
"from matplotlib import pyplot as plt\n",
"\n",
"def sigmoid(z):\n",
" return 1/(1 + np.exp(-z))\n",
"\n",
"# Function to get the parameters.\n",
"# Done such that one can easily change the paramaters after one's liking.\n",
"def get_parameters():\n",
" alpha = 2\n",
" A = 1\n",
" g0 = 1.2\n",
" return alpha, A, g0\n",
"\n",
"def deep_neural_network(P, x):\n",
" # N_hidden is the number of hidden layers\n",
" N_hidden = np.size(P) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
"\n",
" # Assumes input x being an one-dimensional array\n",
" num_values = np.size(x)\n",
" x = x.reshape(-1, num_values)\n",
"\n",
" # Assume that the input layer does nothing to the input x\n",
" x_input = x\n",
"\n",
" # Due to multiple hidden layers, define a variable referencing to the\n",
" # output of the previous layer:\n",
" x_prev = x_input\n",
"\n",
" ## Hidden layers:\n",
"\n",
" for l in range(N_hidden):\n",
" # From the list of parameters P; find the correct weigths and bias for this layer\n",
" w_hidden = P[l]\n",
"\n",
" # Add a row of ones to include bias\n",
" x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n",
"\n",
" z_hidden = np.matmul(w_hidden, x_prev)\n",
" x_hidden = sigmoid(z_hidden)\n",
"\n",
" # Update x_prev such that next layer can use the output from this layer\n",
" x_prev = x_hidden\n",
"\n",
" ## Output layer:\n",
"\n",
" # Get the weights and bias for this layer\n",
" w_output = P[-1]\n",
"\n",
" # Include bias:\n",
" x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n",
"\n",
" z_output = np.matmul(w_output, x_prev)\n",
" x_output = z_output\n",
"\n",
" return x_output\n",
"\n",
"\n",
"def cost_function_deep(P, x):\n",
"\n",
" # Evaluate the trial function with the current parameters P\n",
" g_t = g_trial_deep(x,P)\n",
"\n",
" # Find the derivative w.r.t x of the trial function\n",
" d_g_t = elementwise_grad(g_trial_deep,0)(x,P)\n",
"\n",
" # The right side of the ODE\n",
" func = f(x, g_t)\n",
"\n",
" err_sqr = (d_g_t - func)**2\n",
" cost_sum = np.sum(err_sqr)\n",
"\n",
" return cost_sum / np.size(err_sqr)\n",
"\n",
"# The right side of the ODE:\n",
"def f(x, g_trial):\n",
" alpha,A, g0 = get_parameters()\n",
" return alpha*g_trial*(A - g_trial)\n",
"\n",
"# The trial solution using the deep neural network:\n",
"def g_trial_deep(x, params):\n",
" alpha,A, g0 = get_parameters()\n",
" return g0 + x*deep_neural_network(params,x)\n",
"\n",
"# The analytical solution:\n",
"def g_analytic(t):\n",
" alpha,A, g0 = get_parameters()\n",
" return A*g0/(g0 + (A - g0)*np.exp(-alpha*A*t))\n",
"\n",
"def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n",
" # num_hidden_neurons is now a list of number of neurons within each hidden layer\n",
"\n",
" # Find the number of hidden layers:\n",
" N_hidden = np.size(num_neurons)\n",
"\n",
" ## Set up initial weigths and biases\n",
"\n",
" # Initialize the list of parameters:\n",
" P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
"\n",
" P[0] = npr.randn(num_neurons[0], 2 )\n",
" for l in range(1,N_hidden):\n",
" P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
"\n",
" # For the output layer\n",
" P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
"\n",
" print('Initial cost: %g'%cost_function_deep(P, x))\n",
"\n",
" ## Start finding the optimal weigths using gradient descent\n",
"\n",
" # Find the Python function that represents the gradient of the cost function\n",
" # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
" cost_function_deep_grad = grad(cost_function_deep,0)\n",
"\n",
" # Let the update be done num_iter times\n",
" for i in range(num_iter):\n",
" # Evaluate the gradient at the current weights and biases in P.\n",
" # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n",
" # in the hidden layers and output layers evaluated at x.\n",
" cost_deep_grad = cost_function_deep_grad(P, x)\n",
"\n",
" for l in range(N_hidden+1):\n",
" P[l] = P[l] - lmb * cost_deep_grad[l]\n",
"\n",
" print('Final cost: %g'%cost_function_deep(P, x))\n",
"\n",
" return P\n",
"\n",
"if __name__ == '__main__':\n",
" npr.seed(4155)\n",
"\n",
" ## Decide the vales of arguments to the function to solve\n",
" Nt = 10\n",
" T = 1\n",
" t = np.linspace(0,T, Nt)\n",
"\n",
" ## Set up the initial parameters\n",
" num_hidden_neurons = [100, 50, 25]\n",
" num_iter = 1000\n",
" lmb = 1e-3\n",
"\n",
" P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)\n",
"\n",
" g_dnn_ag = g_trial_deep(t,P)\n",
" g_analytical = g_analytic(t)\n",
"\n",
" # Find the maximum absolute difference between the solutons:\n",
" diff_ag = np.max(np.abs(g_dnn_ag - g_analytical))\n",
" print(\"The max absolute difference between the solutions is: %g\"%diff_ag)\n",
"\n",
" plt.figure(figsize=(10,10))\n",
"\n",
" plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
" plt.plot(t, g_analytical)\n",
" plt.plot(t, g_dnn_ag[0,:])\n",
" plt.legend(['analytical','nn'])\n",
" plt.xlabel('t')\n",
" plt.ylabel('g(t)')\n",
"\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using forward Euler to solve the ODE\n",
"\n",
"A straightforward way of solving an ODE numerically, is to use Euler's method.\n",
"\n",
"Euler's method uses Taylor series to approximate the value at a function $f$ at a step $\\Delta x$ from $x$:\n",
"\n",
"$$\n",
"f(x + \\Delta x) \\approx f(x) + \\Delta x f'(x)\n",
"$$\n",
"\n",
"In our case, using Euler's method to approximate the value of $g$ at a step $\\Delta t$ from $t$ yields"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{aligned}\n",
" g(t + \\Delta t) &\\approx g(t) + \\Delta t g'(t) \\\\\n",
" &= g(t) + \\Delta t \\big(\\alpha g(t)(A - g(t))\\big)\n",
"\\end{aligned}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"along with the condition that $g(0) = g_0$.\n",
"\n",
"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$.\n",
"\n",
"For $i \\geq 1$, we have that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{aligned}\n",
"t_i &= i\\Delta t \\\\\n",
"&= (i - 1)\\Delta t + \\Delta t \\\\\n",
"&= t_{i-1} + \\Delta t\n",
"\\end{aligned}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, if $g_i = g(t_i)$ then"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"odenum\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
" \\begin{aligned}\n",
" g_i &= g(t_i) \\\\\n",
" &= g(t_{i-1} + \\Delta t) \\\\\n",
" &\\approx g(t_{i-1}) + \\Delta t \\big(\\alpha g(t_{i-1})(A - g(t_{i-1}))\\big) \\\\\n",
" &= g_{i-1} + \\Delta t \\big(\\alpha g_{i-1}(A - g_{i-1})\\big)\n",
" \\end{aligned}\n",
"\\end{equation} \\label{odenum} \\tag{12}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"for $i \\geq 1$ and $g_0 = g(t_0) = g(0) = g_0$.\n",
"\n",
"Equation ([12](#odenum)) could be implemented in the following way,\n",
"extending the program that uses the network using Autograd:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# Assume that all function definitions from the example program using Autograd\n",
"# are located here.\n",
"\n",
"if __name__ == '__main__':\n",
" npr.seed(4155)\n",
"\n",
" ## Decide the vales of arguments to the function to solve\n",
" Nt = 10\n",
" T = 1\n",
" t = np.linspace(0,T, Nt)\n",
"\n",
" ## Set up the initial parameters\n",
" num_hidden_neurons = [100,50,25]\n",
" num_iter = 1000\n",
" lmb = 1e-3\n",
"\n",
" P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)\n",
"\n",
" g_dnn_ag = g_trial_deep(t,P)\n",
" g_analytical = g_analytic(t)\n",
"\n",
" # Find the maximum absolute difference between the solutons:\n",
" diff_ag = np.max(np.abs(g_dnn_ag - g_analytical))\n",
" print(\"The max absolute difference between the solutions is: %g\"%diff_ag)\n",
"\n",
" plt.figure(figsize=(10,10))\n",
"\n",
" plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
" plt.plot(t, g_analytical)\n",
" plt.plot(t, g_dnn_ag[0,:])\n",
" plt.legend(['analytical','nn'])\n",
" plt.xlabel('t')\n",
" plt.ylabel('g(t)')\n",
"\n",
" ## Find an approximation to the funtion using forward Euler\n",
"\n",
" alpha, A, g0 = get_parameters()\n",
" dt = T/(Nt - 1)\n",
"\n",
" # Perform forward Euler to solve the ODE\n",
" g_euler = np.zeros(Nt)\n",
" g_euler[0] = g0\n",
"\n",
" for i in range(1,Nt):\n",
" g_euler[i] = g_euler[i-1] + dt*(alpha*g_euler[i-1]*(A - g_euler[i-1]))\n",
"\n",
" # Print the errors done by each method\n",
" diff1 = np.max(np.abs(g_euler - g_analytical))\n",
" diff2 = np.max(np.abs(g_dnn_ag[0,:] - g_analytical))\n",
"\n",
" print('Max absolute difference between Euler method and analytical: %g'%diff1)\n",
" print('Max absolute difference between deep neural network and analytical: %g'%diff2)\n",
"\n",
" # Plot results\n",
" plt.figure(figsize=(10,10))\n",
"\n",
" plt.plot(t,g_euler)\n",
" plt.plot(t,g_analytical)\n",
" plt.plot(t,g_dnn_ag[0,:])\n",
"\n",
" plt.legend(['euler','analytical','dnn'])\n",
" plt.xlabel('Time t')\n",
" plt.ylabel('g(t)')\n",
"\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example: Solving the one dimensional Poisson equation\n",
"\n",
"The Poisson equation for $g(x)$ in one dimension is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"poisson\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{poisson} \\tag{13}\n",
" -g''(x) = f(x)\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $f(x)$ is a given function for $x \\in (0,1)$.\n",
"\n",
"The conditions that $g(x)$ is chosen to fulfill, are"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
" g(0) &= 0 \\\\\n",
" g(1) &= 0\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used.\n",
"The results from the networks can then be compared to the analytical solution.\n",
"In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks.\n",
"\n",
"## The specific equation to solve for\n",
"\n",
"Here, the function $g(x)$ to solve for follows the equation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"-g''(x) = f(x),\\qquad x \\in (0,1)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $f(x)$ is a given function, along with the chosen conditions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"cond\"></div>\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"g(0) = g(1) = 0\n",
"\\end{aligned}\\label{cond} \\tag{14}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this example, we consider the case when $f(x) = (3x + x^2)\\exp(x)$.\n",
"\n",
"For this case, a possible trial solution satisfying the conditions could be"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"g_t(x) = x \\cdot (1-x) \\cdot N(P,x)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The analytical solution for this problem is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"g(x) = x(1 - x)\\exp(x)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Solving the equation using Autograd"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad, elementwise_grad\n",
"import autograd.numpy.random as npr\n",
"from matplotlib import pyplot as plt\n",
"\n",
"def sigmoid(z):\n",
" return 1/(1 + np.exp(-z))\n",
"\n",
"def deep_neural_network(deep_params, x):\n",
" # N_hidden is the number of hidden layers\n",
" N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
"\n",
" # Assumes input x being an one-dimensional array\n",
" num_values = np.size(x)\n",
" x = x.reshape(-1, num_values)\n",
"\n",
" # Assume that the input layer does nothing to the input x\n",
" x_input = x\n",
"\n",
" # Due to multiple hidden layers, define a variable referencing to the\n",
" # output of the previous layer:\n",
" x_prev = x_input\n",
"\n",
" ## Hidden layers:\n",
"\n",
" for l in range(N_hidden):\n",
" # From the list of parameters P; find the correct weigths and bias for this layer\n",
" w_hidden = deep_params[l]\n",
"\n",
" # Add a row of ones to include bias\n",
" x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n",
"\n",
" z_hidden = np.matmul(w_hidden, x_prev)\n",
" x_hidden = sigmoid(z_hidden)\n",
"\n",
" # Update x_prev such that next layer can use the output from this layer\n",
" x_prev = x_hidden\n",
"\n",
" ## Output layer:\n",
"\n",
" # Get the weights and bias for this layer\n",
" w_output = deep_params[-1]\n",
"\n",
" # Include bias:\n",
" x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n",
"\n",
" z_output = np.matmul(w_output, x_prev)\n",
" x_output = z_output\n",
"\n",
" return x_output\n",
"\n",
"def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n",
" # num_hidden_neurons is now a list of number of neurons within each hidden layer\n",
"\n",
" # Find the number of hidden layers:\n",
" N_hidden = np.size(num_neurons)\n",
"\n",
" ## Set up initial weigths and biases\n",
"\n",
" # Initialize the list of parameters:\n",
" P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
"\n",
" P[0] = npr.randn(num_neurons[0], 2 )\n",
" for l in range(1,N_hidden):\n",
" P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
"\n",
" # For the output layer\n",
" P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
"\n",
" print('Initial cost: %g'%cost_function_deep(P, x))\n",
"\n",
" ## Start finding the optimal weigths using gradient descent\n",
"\n",
" # Find the Python function that represents the gradient of the cost function\n",
" # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
" cost_function_deep_grad = grad(cost_function_deep,0)\n",
"\n",
" # Let the update be done num_iter times\n",
" for i in range(num_iter):\n",
" # Evaluate the gradient at the current weights and biases in P.\n",
" # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n",
" # in the hidden layers and output layers evaluated at x.\n",
" cost_deep_grad = cost_function_deep_grad(P, x)\n",
"\n",
" for l in range(N_hidden+1):\n",
" P[l] = P[l] - lmb * cost_deep_grad[l]\n",
"\n",
" print('Final cost: %g'%cost_function_deep(P, x))\n",
"\n",
" return P\n",
"\n",
"## Set up the cost function specified for this Poisson equation:\n",
"\n",
"# The right side of the ODE\n",
"def f(x):\n",
" return (3*x + x**2)*np.exp(x)\n",
"\n",
"def cost_function_deep(P, x):\n",
"\n",
" # Evaluate the trial function with the current parameters P\n",
" g_t = g_trial_deep(x,P)\n",
"\n",
" # Find the derivative w.r.t x of the trial function\n",
" d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P)\n",
"\n",
" right_side = f(x)\n",
"\n",
" err_sqr = (-d2_g_t - right_side)**2\n",
" cost_sum = np.sum(err_sqr)\n",
"\n",
" return cost_sum/np.size(err_sqr)\n",
"\n",
"# The trial solution:\n",
"def g_trial_deep(x,P):\n",
" return x*(1-x)*deep_neural_network(P,x)\n",
"\n",
"# The analytic solution;\n",
"def g_analytic(x):\n",
" return x*(1-x)*np.exp(x)\n",
"\n",
"if __name__ == '__main__':\n",
" npr.seed(4155)\n",
"\n",
" ## Decide the vales of arguments to the function to solve\n",
" Nx = 10\n",
" x = np.linspace(0,1, Nx)\n",
"\n",
" ## Set up the initial parameters\n",
" num_hidden_neurons = [200,100]\n",
" num_iter = 1000\n",
" lmb = 1e-3\n",
"\n",
" P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n",
"\n",
" g_dnn_ag = g_trial_deep(x,P)\n",
" g_analytical = g_analytic(x)\n",
"\n",
" # Find the maximum absolute difference between the solutons:\n",
" max_diff = np.max(np.abs(g_dnn_ag - g_analytical))\n",
" print(\"The max absolute difference between the solutions is: %g\"%max_diff)\n",
"\n",
" plt.figure(figsize=(10,10))\n",
"\n",
" plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
" plt.plot(x, g_analytical)\n",
" plt.plot(x, g_dnn_ag[0,:])\n",
" plt.legend(['analytical','nn'])\n",
" plt.xlabel('x')\n",
" plt.ylabel('g(x)')\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comparing with a numerical scheme\n",
"\n",
"The Poisson equation is possible to solve using Taylor series to approximate the second derivative.\n",
"\n",
"Using Taylor series, the second derivative can be expressed as\n",
"\n",
"$$\n",
"g''(x) = \\frac{g(x + \\Delta x) - 2g(x) + g(x-\\Delta x)}{\\Delta x^2} + E_{\\Delta x}(x)\n",
"$$\n",
"\n",
"where $\\Delta x$ is a small step size and $E_{\\Delta x}(x)$ being the error term.\n",
"\n",
"Looking away from the error terms gives an approximation to the second derivative:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"approx\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{approx} \\tag{15}\n",
"g''(x) \\approx \\frac{g(x + \\Delta x) - 2g(x) + g(x-\\Delta x)}{\\Delta x^2}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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$, ([15](#approx)) becomes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{aligned}\n",
"g''(x_i) &\\approx \\frac{g(x_i + \\Delta x) - 2g(x_i) + g(x_i -\\Delta x)}{\\Delta x^2} \\\\\n",
"&= \\frac{g_{i+1} - 2g_i + g_{i-1}}{\\Delta x^2}\n",
"\\end{aligned}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since we know from our problem that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{aligned}\n",
"-g''(x) &= f(x) \\\\\n",
"&= (3x + x^2)\\exp(x)\n",
"\\end{aligned}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"along with the conditions $g(0) = g(1) = 0$,\n",
"the following scheme can be used to find an approximate solution for $g(x)$ numerically:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"odesys\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
" \\begin{aligned}\n",
" -\\Big( \\frac{g_{i+1} - 2g_i + g_{i-1}}{\\Delta x^2} \\Big) &= f(x_i) \\\\\n",
" -g_{i+1} + 2g_i - g_{i-1} &= \\Delta x^2 f(x_i)\n",
" \\end{aligned}\n",
"\\end{equation} \\label{odesys} \\tag{16}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"The equation can be rewritten into a matrix equation:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{aligned}\n",
"\\begin{pmatrix}\n",
"2 & -1 & 0 & \\dots & 0 \\\\\n",
"-1 & 2 & -1 & \\dots & 0 \\\\\n",
"\\vdots & & \\ddots & & \\vdots \\\\\n",
"0 & \\dots & -1 & 2 & -1 \\\\\n",
"0 & \\dots & 0 & -1 & 2\\\\\n",
"\\end{pmatrix}\n",
"\\begin{pmatrix}\n",
"g_1 \\\\\n",
"g_2 \\\\\n",
"\\vdots \\\\\n",
"g_{N_x - 3} \\\\\n",
"g_{N_x - 2}\n",
"\\end{pmatrix}\n",
"&=\n",
"\\Delta x^2\n",
"\\begin{pmatrix}\n",
"f(x_1) \\\\\n",
"f(x_2) \\\\\n",
"\\vdots \\\\\n",
"f(x_{N_x - 3}) \\\\\n",
"f(x_{N_x - 2})\n",
"\\end{pmatrix} \\\\\n",
"\\boldsymbol{A}\\boldsymbol{g} &= \\boldsymbol{f},\n",
"\\end{aligned}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which makes it possible to solve for the vector $\\boldsymbol{g}$.\n",
"\n",
"## Setting up the code\n",
"\n",
"We can then compare the result from this numerical scheme with the output from our network using Autograd:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import grad, elementwise_grad\n",
"import autograd.numpy.random as npr\n",
"from matplotlib import pyplot as plt\n",
"\n",
"def sigmoid(z):\n",
" return 1/(1 + np.exp(-z))\n",
"\n",
"def deep_neural_network(deep_params, x):\n",
" # N_hidden is the number of hidden layers\n",
" N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
"\n",
" # Assumes input x being an one-dimensional array\n",
" num_values = np.size(x)\n",
" x = x.reshape(-1, num_values)\n",
"\n",
" # Assume that the input layer does nothing to the input x\n",
" x_input = x\n",
"\n",
" # Due to multiple hidden layers, define a variable referencing to the\n",
" # output of the previous layer:\n",
" x_prev = x_input\n",
"\n",
" ## Hidden layers:\n",
"\n",
" for l in range(N_hidden):\n",
" # From the list of parameters P; find the correct weigths and bias for this layer\n",
" w_hidden = deep_params[l]\n",
"\n",
" # Add a row of ones to include bias\n",
" x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n",
"\n",
" z_hidden = np.matmul(w_hidden, x_prev)\n",
" x_hidden = sigmoid(z_hidden)\n",
"\n",
" # Update x_prev such that next layer can use the output from this layer\n",
" x_prev = x_hidden\n",
"\n",
" ## Output layer:\n",
"\n",
" # Get the weights and bias for this layer\n",
" w_output = deep_params[-1]\n",
"\n",
" # Include bias:\n",
" x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n",
"\n",
" z_output = np.matmul(w_output, x_prev)\n",
" x_output = z_output\n",
"\n",
" return x_output\n",
"\n",
"def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n",
" # num_hidden_neurons is now a list of number of neurons within each hidden layer\n",
"\n",
" # Find the number of hidden layers:\n",
" N_hidden = np.size(num_neurons)\n",
"\n",
" ## Set up initial weigths and biases\n",
"\n",
" # Initialize the list of parameters:\n",
" P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
"\n",
" P[0] = npr.randn(num_neurons[0], 2 )\n",
" for l in range(1,N_hidden):\n",
" P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
"\n",
" # For the output layer\n",
" P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
"\n",
" print('Initial cost: %g'%cost_function_deep(P, x))\n",
"\n",
" ## Start finding the optimal weigths using gradient descent\n",
"\n",
" # Find the Python function that represents the gradient of the cost function\n",
" # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
" cost_function_deep_grad = grad(cost_function_deep,0)\n",
"\n",
" # Let the update be done num_iter times\n",
" for i in range(num_iter):\n",
" # Evaluate the gradient at the current weights and biases in P.\n",
" # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n",
" # in the hidden layers and output layers evaluated at x.\n",
" cost_deep_grad = cost_function_deep_grad(P, x)\n",
"\n",
" for l in range(N_hidden+1):\n",
" P[l] = P[l] - lmb * cost_deep_grad[l]\n",
"\n",
" print('Final cost: %g'%cost_function_deep(P, x))\n",
"\n",
" return P\n",
"\n",
"## Set up the cost function specified for this Poisson equation:\n",
"\n",
"# The right side of the ODE\n",
"def f(x):\n",
" return (3*x + x**2)*np.exp(x)\n",
"\n",
"def cost_function_deep(P, x):\n",
"\n",
" # Evaluate the trial function with the current parameters P\n",
" g_t = g_trial_deep(x,P)\n",
"\n",
" # Find the derivative w.r.t x of the trial function\n",
" d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P)\n",
"\n",
" right_side = f(x)\n",
"\n",
" err_sqr = (-d2_g_t - right_side)**2\n",
" cost_sum = np.sum(err_sqr)\n",
"\n",
" return cost_sum/np.size(err_sqr)\n",
"\n",
"# The trial solution:\n",
"def g_trial_deep(x,P):\n",
" return x*(1-x)*deep_neural_network(P,x)\n",
"\n",
"# The analytic solution;\n",
"def g_analytic(x):\n",
" return x*(1-x)*np.exp(x)\n",
"\n",
"if __name__ == '__main__':\n",
" npr.seed(4155)\n",
"\n",
" ## Decide the vales of arguments to the function to solve\n",
" Nx = 10\n",
" x = np.linspace(0,1, Nx)\n",
"\n",
" ## Set up the initial parameters\n",
" num_hidden_neurons = [200,100]\n",
" num_iter = 1000\n",
" lmb = 1e-3\n",
"\n",
" P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n",
"\n",
" g_dnn_ag = g_trial_deep(x,P)\n",
" g_analytical = g_analytic(x)\n",
"\n",
" # Find the maximum absolute difference between the solutons:\n",
"\n",
" plt.figure(figsize=(10,10))\n",
"\n",
" plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
" plt.plot(x, g_analytical)\n",
" plt.plot(x, g_dnn_ag[0,:])\n",
" plt.legend(['analytical','nn'])\n",
" plt.xlabel('x')\n",
" plt.ylabel('g(x)')\n",
"\n",
" ## Perform the computation using the numerical scheme\n",
"\n",
" dx = 1/(Nx - 1)\n",
"\n",
" # Set up the matrix A\n",
" A = np.zeros((Nx-2,Nx-2))\n",
"\n",
" A[0,0] = 2\n",
" A[0,1] = -1\n",
"\n",
" for i in range(1,Nx-3):\n",
" A[i,i-1] = -1\n",
" A[i,i] = 2\n",
" A[i,i+1] = -1\n",
"\n",
" A[Nx - 3, Nx - 4] = -1\n",
" A[Nx - 3, Nx - 3] = 2\n",
"\n",
" # Set up the vector f\n",
" f_vec = dx**2 * f(x[1:-1])\n",
"\n",
" # Solve the equation\n",
" g_res = np.linalg.solve(A,f_vec)\n",
"\n",
" g_vec = np.zeros(Nx)\n",
" g_vec[1:-1] = g_res\n",
"\n",
" # Print the differences between each method\n",
" max_diff1 = np.max(np.abs(g_dnn_ag - g_analytical))\n",
" max_diff2 = np.max(np.abs(g_vec - g_analytical))\n",
" print(\"The max absolute difference between the analytical solution and DNN Autograd: %g\"%max_diff1)\n",
" print(\"The max absolute difference between the analytical solution and numerical scheme: %g\"%max_diff2)\n",
"\n",
" # Plot the results\n",
" plt.figure(figsize=(10,10))\n",
"\n",
" plt.plot(x,g_vec)\n",
" plt.plot(x,g_analytical)\n",
" plt.plot(x,g_dnn_ag[0,:])\n",
"\n",
" plt.legend(['numerical scheme','analytical','dnn'])\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Partial Differential Equations\n",
"\n",
"A partial differential equation (PDE) has a solution here the function\n",
"is defined by multiple variables. The equation may involve all kinds\n",
"of combinations of which variables the function is differentiated with\n",
"respect to.\n",
"\n",
"In general, a partial differential equation for a function $g(x_1,\\dots,x_N)$ with $N$ variables may be expressed as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"PDE\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{PDE} \\tag{17}\n",
" 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\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"## Type of problem\n",
"\n",
"The problem our network must solve for, is similar to the ODE case.\n",
"We must have a trial solution $g_t$ at hand.\n",
"\n",
"For instance, the trial solution could be expressed as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
" 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))\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $h_1(x_1,\\dots,x_N)$ is a function that ensures $g_t(x_1,\\dots,x_N)$ satisfies some given conditions.\n",
"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.\n",
"\n",
"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.\n",
"\n",
"\n",
"## Network requirements\n",
"\n",
"The network tries then the minimize the cost function following the\n",
"same ideas as described for the ODE case, but now with more than one\n",
"variables to consider. The concept still remains the same; find a set\n",
"of parameters $P$ such that the expression $f$ in ([17](#PDE)) is as\n",
"close to zero as possible.\n",
"\n",
"As for the ODE case, the cost function is the mean squared error that\n",
"the network must try to minimize. The cost function for the network to\n",
"minimize is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"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\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## More details\n",
"\n",
"If we let $\\boldsymbol{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:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C\\left(\\boldsymbol{x}, P\\right) = f\\left( \\left( \\boldsymbol{x}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}) }{\\partial x_N^n} \\right) \\right)^2\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we also have $M$ different sets of values for $x_1, \\dots, x_N$, that is $\\boldsymbol{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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C\\left(X, P \\right) = \\sum_{i=1}^M f\\left( \\left( \\boldsymbol{x}_i, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}_i) }{\\partial x_N^n} \\right) \\right)^2.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example: The diffusion equation\n",
"\n",
"In one spatial dimension, the equation reads"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where a possible choice of conditions are"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"g(0,t) &= 0 ,\\qquad t \\geq 0 \\\\\n",
"g(1,t) &= 0, \\qquad t \\geq 0 \\\\\n",
"g(x,0) &= u(x),\\qquad x\\in [0,1]\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with $u(x)$ being some given function.\n",
"\n",
"## Defining the problem\n",
"\n",
"For this case, we want to find $g(x,t)$ such that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"diffonedim\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
" \\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n",
"\\end{equation} \\label{diffonedim} \\tag{18}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"g(0,t) &= 0 ,\\qquad t \\geq 0 \\\\\n",
"g(1,t) &= 0, \\qquad t \\geq 0 \\\\\n",
"g(x,0) &= u(x),\\qquad x\\in [0,1]\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with $u(x) = \\sin(\\pi x)$.\n",
"\n",
"First, let us set up the deep neural network.\n",
"The deep neural network will follow the same structure as discussed in the examples solving the ODEs.\n",
"First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions.\n",
"\n",
"\n",
"\n",
"## Setting up the network using Autograd\n",
"\n",
"The only change to do here, is to extend our network such that\n",
"functions of multiple parameters are correctly handled. In this case\n",
"we have two variables in our function to solve for, that is time $t$\n",
"and position $x$. The variables will be represented by a\n",
"one-dimensional array in the program. The program will evaluate the\n",
"network at each possible pair $(x,t)$, given an array for the desired\n",
"$x$-values and $t$-values to approximate the solution at."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"def sigmoid(z):\n",
" return 1/(1 + np.exp(-z))\n",
"\n",
"def deep_neural_network(deep_params, x):\n",
" # x is now a point and a 1D numpy array; make it a column vector\n",
" num_coordinates = np.size(x,0)\n",
" x = x.reshape(num_coordinates,-1)\n",
"\n",
" num_points = np.size(x,1)\n",
"\n",
" # N_hidden is the number of hidden layers\n",
" N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
"\n",
" # Assume that the input layer does nothing to the input x\n",
" x_input = x\n",
" x_prev = x_input\n",
"\n",
" ## Hidden layers:\n",
"\n",
" for l in range(N_hidden):\n",
" # From the list of parameters P; find the correct weigths and bias for this layer\n",
" w_hidden = deep_params[l]\n",
"\n",
" # Add a row of ones to include bias\n",
" x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n",
"\n",
" z_hidden = np.matmul(w_hidden, x_prev)\n",
" x_hidden = sigmoid(z_hidden)\n",
"\n",
" # Update x_prev such that next layer can use the output from this layer\n",
" x_prev = x_hidden\n",
"\n",
" ## Output layer:\n",
"\n",
" # Get the weights and bias for this layer\n",
" w_output = deep_params[-1]\n",
"\n",
" # Include bias:\n",
" x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n",
"\n",
" z_output = np.matmul(w_output, x_prev)\n",
" x_output = z_output\n",
"\n",
" return x_output[0][0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setting up the network using Autograd; The trial solution\n",
"\n",
"The cost function must then iterate through the given arrays\n",
"containing values for $x$ and $t$, defines a point $(x,t)$ the deep\n",
"neural network and the trial solution is evaluated at, and then finds\n",
"the Jacobian of the trial solution.\n",
"\n",
"A possible trial solution for this PDE is\n",
"\n",
"$$\n",
"g_t(x,t) = h_1(x,t) + x(1-x)tN(x,t,P)\n",
"$$\n",
"\n",
"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$.\n",
"\n",
"To fulfill the conditions, $A(x,t)$ could be:\n",
"\n",
"$$\n",
"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)\n",
"$$\n",
"since $(0) = u(1) = 0$ and $u(x) = \\sin(\\pi x)$.\n",
"\n",
"## Why the jacobian?\n",
"\n",
"The Jacobian is used because the program must find the derivative of\n",
"the trial solution with respect to $x$ and $t$.\n",
"\n",
"This gives the necessity of computing the Jacobian matrix, as we want\n",
"to evaluate the gradient with respect to $x$ and $t$ (note that the\n",
"Jacobian of a scalar-valued multivariate function is simply its\n",
"gradient).\n",
"\n",
"In Autograd, the differentiation is by default done with respect to\n",
"the first input argument of your Python function. Since the points is\n",
"an array representing $x$ and $t$, the Jacobian is calculated using\n",
"the values of $x$ and $t$.\n",
"\n",
"To find the second derivative with respect to $x$ and $t$, the\n",
"Jacobian can be found for the second time. The result is a Hessian\n",
"matrix, which is the matrix containing all the possible second order\n",
"mixed derivatives of $g(x,t)$."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"# Set up the trial function:\n",
"def u(x):\n",
" return np.sin(np.pi*x)\n",
"\n",
"def g_trial(point,P):\n",
" x,t = point\n",
" return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point)\n",
"\n",
"# The right side of the ODE:\n",
"def f(point):\n",
" return 0.\n",
"\n",
"# The cost function:\n",
"def cost_function(P, x, t):\n",
" cost_sum = 0\n",
"\n",
" g_t_jacobian_func = jacobian(g_trial)\n",
" g_t_hessian_func = hessian(g_trial)\n",
"\n",
" for x_ in x:\n",
" for t_ in t:\n",
" point = np.array([x_,t_])\n",
"\n",
" g_t = g_trial(point,P)\n",
" g_t_jacobian = g_t_jacobian_func(point,P)\n",
" g_t_hessian = g_t_hessian_func(point,P)\n",
"\n",
" g_t_dt = g_t_jacobian[1]\n",
" g_t_d2x = g_t_hessian[0][0]\n",
"\n",
" func = f(point)\n",
"\n",
" err_sqr = ( (g_t_dt - g_t_d2x) - func)**2\n",
" cost_sum += err_sqr\n",
"\n",
" return cost_sum"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setting up the network using Autograd; The full program\n",
"\n",
"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.\n",
"\n",
"The analytical solution of our problem is\n",
"\n",
"$$\n",
"g(x,t) = \\exp(-\\pi^2 t)\\sin(\\pi x)\n",
"$$\n",
"\n",
"A possible way to implement a neural network solving the PDE, is given below.\n",
"Be aware, though, that it is fairly slow for the parameters used.\n",
"A better result is possible, but requires more iterations, and thus longer time to complete.\n",
"\n",
"\n",
"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.\n",
"Using TensorFlow results in a much better execution time. Try it!"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import jacobian,hessian,grad\n",
"import autograd.numpy.random as npr\n",
"from matplotlib import cm\n",
"from matplotlib import pyplot as plt\n",
"from mpl_toolkits.mplot3d import axes3d\n",
"\n",
"## Set up the network\n",
"\n",
"def sigmoid(z):\n",
" return 1/(1 + np.exp(-z))\n",
"\n",
"def deep_neural_network(deep_params, x):\n",
" # x is now a point and a 1D numpy array; make it a column vector\n",
" num_coordinates = np.size(x,0)\n",
" x = x.reshape(num_coordinates,-1)\n",
"\n",
" num_points = np.size(x,1)\n",
"\n",
" # N_hidden is the number of hidden layers\n",
" N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
"\n",
" # Assume that the input layer does nothing to the input x\n",
" x_input = x\n",
" x_prev = x_input\n",
"\n",
" ## Hidden layers:\n",
"\n",
" for l in range(N_hidden):\n",
" # From the list of parameters P; find the correct weigths and bias for this layer\n",
" w_hidden = deep_params[l]\n",
"\n",
" # Add a row of ones to include bias\n",
" x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n",
"\n",
" z_hidden = np.matmul(w_hidden, x_prev)\n",
" x_hidden = sigmoid(z_hidden)\n",
"\n",
" # Update x_prev such that next layer can use the output from this layer\n",
" x_prev = x_hidden\n",
"\n",
" ## Output layer:\n",
"\n",
" # Get the weights and bias for this layer\n",
" w_output = deep_params[-1]\n",
"\n",
" # Include bias:\n",
" x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n",
"\n",
" z_output = np.matmul(w_output, x_prev)\n",
" x_output = z_output\n",
"\n",
" return x_output[0][0]\n",
"\n",
"## Define the trial solution and cost function\n",
"def u(x):\n",
" return np.sin(np.pi*x)\n",
"\n",
"def g_trial(point,P):\n",
" x,t = point\n",
" return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point)\n",
"\n",
"# The right side of the ODE:\n",
"def f(point):\n",
" return 0.\n",
"\n",
"# The cost function:\n",
"def cost_function(P, x, t):\n",
" cost_sum = 0\n",
"\n",
" g_t_jacobian_func = jacobian(g_trial)\n",
" g_t_hessian_func = hessian(g_trial)\n",
"\n",
" for x_ in x:\n",
" for t_ in t:\n",
" point = np.array([x_,t_])\n",
"\n",
" g_t = g_trial(point,P)\n",
" g_t_jacobian = g_t_jacobian_func(point,P)\n",
" g_t_hessian = g_t_hessian_func(point,P)\n",
"\n",
" g_t_dt = g_t_jacobian[1]\n",
" g_t_d2x = g_t_hessian[0][0]\n",
"\n",
" func = f(point)\n",
"\n",
" err_sqr = ( (g_t_dt - g_t_d2x) - func)**2\n",
" cost_sum += err_sqr\n",
"\n",
" return cost_sum /( np.size(x)*np.size(t) )\n",
"\n",
"## For comparison, define the analytical solution\n",
"def g_analytic(point):\n",
" x,t = point\n",
" return np.exp(-np.pi**2*t)*np.sin(np.pi*x)\n",
"\n",
"## Set up a function for training the network to solve for the equation\n",
"def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb):\n",
" ## Set up initial weigths and biases\n",
" N_hidden = np.size(num_neurons)\n",
"\n",
" ## Set up initial weigths and biases\n",
"\n",
" # Initialize the list of parameters:\n",
" P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
"\n",
" P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias\n",
" for l in range(1,N_hidden):\n",
" P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
"\n",
" # For the output layer\n",
" P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
"\n",
" print('Initial cost: ',cost_function(P, x, t))\n",
"\n",
" cost_function_grad = grad(cost_function,0)\n",
"\n",
" # Let the update be done num_iter times\n",
" for i in range(num_iter):\n",
" cost_grad = cost_function_grad(P, x , t)\n",
"\n",
" for l in range(N_hidden+1):\n",
" P[l] = P[l] - lmb * cost_grad[l]\n",
"\n",
" print('Final cost: ',cost_function(P, x, t))\n",
"\n",
" return P\n",
"\n",
"if __name__ == '__main__':\n",
" ### Use the neural network:\n",
" npr.seed(15)\n",
"\n",
" ## Decide the vales of arguments to the function to solve\n",
" Nx = 10; Nt = 10\n",
" x = np.linspace(0, 1, Nx)\n",
" t = np.linspace(0,1,Nt)\n",
"\n",
" ## Set up the parameters for the network\n",
" num_hidden_neurons = [100, 25]\n",
" num_iter = 250\n",
" lmb = 0.01\n",
"\n",
" P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)\n",
"\n",
" ## Store the results\n",
" g_dnn_ag = np.zeros((Nx, Nt))\n",
" G_analytical = np.zeros((Nx, Nt))\n",
" for i,x_ in enumerate(x):\n",
" for j, t_ in enumerate(t):\n",
" point = np.array([x_, t_])\n",
" g_dnn_ag[i,j] = g_trial(point,P)\n",
"\n",
" G_analytical[i,j] = g_analytic(point)\n",
"\n",
" # Find the map difference between the analytical and the computed solution\n",
" diff_ag = np.abs(g_dnn_ag - G_analytical)\n",
" print('Max absolute difference between the analytical solution and the network: %g'%np.max(diff_ag))\n",
"\n",
" ## Plot the solutions in two dimensions, that being in position and time\n",
"\n",
" T,X = np.meshgrid(t,x)\n",
"\n",
" fig = plt.figure(figsize=(10,10))\n",
" ax = fig.gca(projection='3d')\n",
" ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n",
" s = ax.plot_surface(T,X,g_dnn_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
" ax.set_xlabel('Time $t$')\n",
" ax.set_ylabel('Position $x$');\n",
"\n",
"\n",
" fig = plt.figure(figsize=(10,10))\n",
" ax = fig.gca(projection='3d')\n",
" ax.set_title('Analytical solution')\n",
" s = ax.plot_surface(T,X,G_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
" ax.set_xlabel('Time $t$')\n",
" ax.set_ylabel('Position $x$');\n",
"\n",
" fig = plt.figure(figsize=(10,10))\n",
" ax = fig.gca(projection='3d')\n",
" ax.set_title('Difference')\n",
" s = ax.plot_surface(T,X,diff_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
" ax.set_xlabel('Time $t$')\n",
" ax.set_ylabel('Position $x$');\n",
"\n",
" ## Take some slices of the 3D plots just to see the solutions at particular times\n",
" indx1 = 0\n",
" indx2 = int(Nt/2)\n",
" indx3 = Nt-1\n",
"\n",
" t1 = t[indx1]\n",
" t2 = t[indx2]\n",
" t3 = t[indx3]\n",
"\n",
" # Slice the results from the DNN\n",
" res1 = g_dnn_ag[:,indx1]\n",
" res2 = g_dnn_ag[:,indx2]\n",
" res3 = g_dnn_ag[:,indx3]\n",
"\n",
" # Slice the analytical results\n",
" res_analytical1 = G_analytical[:,indx1]\n",
" res_analytical2 = G_analytical[:,indx2]\n",
" res_analytical3 = G_analytical[:,indx3]\n",
"\n",
" # Plot the slices\n",
" plt.figure(figsize=(10,10))\n",
" plt.title(\"Computed solutions at time = %g\"%t1)\n",
" plt.plot(x, res1)\n",
" plt.plot(x,res_analytical1)\n",
" plt.legend(['dnn','analytical'])\n",
"\n",
" plt.figure(figsize=(10,10))\n",
" plt.title(\"Computed solutions at time = %g\"%t2)\n",
" plt.plot(x, res2)\n",
" plt.plot(x,res_analytical2)\n",
" plt.legend(['dnn','analytical'])\n",
"\n",
" plt.figure(figsize=(10,10))\n",
" plt.title(\"Computed solutions at time = %g\"%t3)\n",
" plt.plot(x, res3)\n",
" plt.plot(x,res_analytical3)\n",
" plt.legend(['dnn','analytical'])\n",
"\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example: Solving the wave equation with Neural Networks\n",
"\n",
"The wave equation is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2\\frac{\\partial^2 g(x,t)}{\\partial x^2}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with $c$ being the specified wave speed.\n",
"\n",
"Here, the chosen conditions are"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"\tg(0,t) &= 0 \\\\\n",
"\tg(1,t) &= 0 \\\\\n",
"\tg(x,0) &= u(x) \\\\\n",
"\t\\frac{\\partial g(x,t)}{\\partial t} \\Big |_{t = 0} &= v(x)\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"## The problem to solve for\n",
"\n",
"The wave equation to solve for, is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"wave\"></div>\n",
"\n",
"$$\n",
"\\begin{equation} \\label{wave} \\tag{19}\n",
"\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2 \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $c$ is the given wave speed.\n",
"The chosen conditions for this equation are"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"condwave\"></div>\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"g(0,t) &= 0, &t \\geq 0 \\\\\n",
"g(1,t) &= 0, &t \\geq 0 \\\\\n",
"g(x,0) &= u(x), &x\\in[0,1] \\\\\n",
"\\frac{\\partial g(x,t)}{\\partial t}\\Big |_{t = 0} &= v(x), &x \\in [0,1]\n",
"\\end{aligned} \\label{condwave} \\tag{20}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this example, let $c = 1$ and $u(x) = \\sin(\\pi x)$ and $v(x) = -\\pi\\sin(\\pi x)$.\n",
"\n",
"\n",
"## The trial solution\n",
"Setting up the network is done in similar matter as for the example of solving the diffusion equation.\n",
"The only things we have to change, is the trial solution such that it satisfies the conditions from ([20](#condwave)) and the cost function.\n",
"\n",
"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\n",
"\n",
"$$\n",
"g_t(x,t) = h_1(x,t) + x(1-x)t^2N(x,t,P)\n",
"$$\n",
"\n",
"where\n",
"\n",
"$$\n",
"h_1(x,t) = (1-t^2)u(x) + tv(x)\n",
"$$\n",
"\n",
"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.\n",
"\n",
"## The analytical solution\n",
"\n",
"The analytical solution for our specific problem, is\n",
"\n",
"$$\n",
"g(x,t) = \\sin(\\pi x)\\cos(\\pi t) - \\sin(\\pi x)\\sin(\\pi t)\n",
"$$\n",
"\n",
"## Solving the wave equation - the full program using Autograd"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"import autograd.numpy as np\n",
"from autograd import hessian,grad\n",
"import autograd.numpy.random as npr\n",
"from matplotlib import cm\n",
"from matplotlib import pyplot as plt\n",
"from mpl_toolkits.mplot3d import axes3d\n",
"\n",
"## Set up the trial function:\n",
"def u(x):\n",
" return np.sin(np.pi*x)\n",
"\n",
"def v(x):\n",
" return -np.pi*np.sin(np.pi*x)\n",
"\n",
"def h1(point):\n",
" x,t = point\n",
" return (1 - t**2)*u(x) + t*v(x)\n",
"\n",
"def g_trial(point,P):\n",
" x,t = point\n",
" return h1(point) + x*(1-x)*t**2*deep_neural_network(P,point)\n",
"\n",
"## Define the cost function\n",
"def cost_function(P, x, t):\n",
" cost_sum = 0\n",
"\n",
" g_t_hessian_func = hessian(g_trial)\n",
"\n",
" for x_ in x:\n",
" for t_ in t:\n",
" point = np.array([x_,t_])\n",
"\n",
" g_t_hessian = g_t_hessian_func(point,P)\n",
"\n",
" g_t_d2x = g_t_hessian[0][0]\n",
" g_t_d2t = g_t_hessian[1][1]\n",
"\n",
" err_sqr = ( (g_t_d2t - g_t_d2x) )**2\n",
" cost_sum += err_sqr\n",
"\n",
" return cost_sum / (np.size(t) * np.size(x))\n",
"\n",
"## The neural network\n",
"def sigmoid(z):\n",
" return 1/(1 + np.exp(-z))\n",
"\n",
"def deep_neural_network(deep_params, x):\n",
" # x is now a point and a 1D numpy array; make it a column vector\n",
" num_coordinates = np.size(x,0)\n",
" x = x.reshape(num_coordinates,-1)\n",
"\n",
" num_points = np.size(x,1)\n",
"\n",
" # N_hidden is the number of hidden layers\n",
" N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
"\n",
" # Assume that the input layer does nothing to the input x\n",
" x_input = x\n",
" x_prev = x_input\n",
"\n",
" ## Hidden layers:\n",
"\n",
" for l in range(N_hidden):\n",
" # From the list of parameters P; find the correct weigths and bias for this layer\n",
" w_hidden = deep_params[l]\n",
"\n",
" # Add a row of ones to include bias\n",
" x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n",
"\n",
" z_hidden = np.matmul(w_hidden, x_prev)\n",
" x_hidden = sigmoid(z_hidden)\n",
"\n",
" # Update x_prev such that next layer can use the output from this layer\n",
" x_prev = x_hidden\n",
"\n",
" ## Output layer:\n",
"\n",
" # Get the weights and bias for this layer\n",
" w_output = deep_params[-1]\n",
"\n",
" # Include bias:\n",
" x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n",
"\n",
" z_output = np.matmul(w_output, x_prev)\n",
" x_output = z_output\n",
"\n",
" return x_output[0][0]\n",
"\n",
"## The analytical solution\n",
"def g_analytic(point):\n",
" x,t = point\n",
" return np.sin(np.pi*x)*np.cos(np.pi*t) - np.sin(np.pi*x)*np.sin(np.pi*t)\n",
"\n",
"def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb):\n",
" ## Set up initial weigths and biases\n",
" N_hidden = np.size(num_neurons)\n",
"\n",
" ## Set up initial weigths and biases\n",
"\n",
" # Initialize the list of parameters:\n",
" P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
"\n",
" P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias\n",
" for l in range(1,N_hidden):\n",
" P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
"\n",
" # For the output layer\n",
" P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
"\n",
" print('Initial cost: ',cost_function(P, x, t))\n",
"\n",
" cost_function_grad = grad(cost_function,0)\n",
"\n",
" # Let the update be done num_iter times\n",
" for i in range(num_iter):\n",
" cost_grad = cost_function_grad(P, x , t)\n",
"\n",
" for l in range(N_hidden+1):\n",
" P[l] = P[l] - lmb * cost_grad[l]\n",
"\n",
"\n",
" print('Final cost: ',cost_function(P, x, t))\n",
"\n",
" return P\n",
"\n",
"if __name__ == '__main__':\n",
" ### Use the neural network:\n",
" npr.seed(15)\n",
"\n",
" ## Decide the vales of arguments to the function to solve\n",
" Nx = 10; Nt = 10\n",
" x = np.linspace(0, 1, Nx)\n",
" t = np.linspace(0,1,Nt)\n",
"\n",
" ## Set up the parameters for the network\n",
" num_hidden_neurons = [50,20]\n",
" num_iter = 1000\n",
" lmb = 0.01\n",
"\n",
" P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)\n",
"\n",
" ## Store the results\n",
" res = np.zeros((Nx, Nt))\n",
" res_analytical = np.zeros((Nx, Nt))\n",
" for i,x_ in enumerate(x):\n",
" for j, t_ in enumerate(t):\n",
" point = np.array([x_, t_])\n",
" res[i,j] = g_trial(point,P)\n",
"\n",
" res_analytical[i,j] = g_analytic(point)\n",
"\n",
" diff = np.abs(res - res_analytical)\n",
" print(\"Max difference between analytical and solution from nn: %g\"%np.max(diff))\n",
"\n",
" ## Plot the solutions in two dimensions, that being in position and time\n",
"\n",
" T,X = np.meshgrid(t,x)\n",
"\n",
" fig = plt.figure(figsize=(10,10))\n",
" ax = fig.gca(projection='3d')\n",
" ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n",
" s = ax.plot_surface(T,X,res,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
" ax.set_xlabel('Time $t$')\n",
" ax.set_ylabel('Position $x$');\n",
"\n",
"\n",
" fig = plt.figure(figsize=(10,10))\n",
" ax = fig.gca(projection='3d')\n",
" ax.set_title('Analytical solution')\n",
" s = ax.plot_surface(T,X,res_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
" ax.set_xlabel('Time $t$')\n",
" ax.set_ylabel('Position $x$');\n",
"\n",
"\n",
" fig = plt.figure(figsize=(10,10))\n",
" ax = fig.gca(projection='3d')\n",
" ax.set_title('Difference')\n",
" s = ax.plot_surface(T,X,diff,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
" ax.set_xlabel('Time $t$')\n",
" ax.set_ylabel('Position $x$');\n",
"\n",
" ## Take some slices of the 3D plots just to see the solutions at particular times\n",
" indx1 = 0\n",
" indx2 = int(Nt/2)\n",
" indx3 = Nt-1\n",
"\n",
" t1 = t[indx1]\n",
" t2 = t[indx2]\n",
" t3 = t[indx3]\n",
"\n",
" # Slice the results from the DNN\n",
" res1 = res[:,indx1]\n",
" res2 = res[:,indx2]\n",
" res3 = res[:,indx3]\n",
"\n",
" # Slice the analytical results\n",
" res_analytical1 = res_analytical[:,indx1]\n",
" res_analytical2 = res_analytical[:,indx2]\n",
" res_analytical3 = res_analytical[:,indx3]\n",
"\n",
" # Plot the slices\n",
" plt.figure(figsize=(10,10))\n",
" plt.title(\"Computed solutions at time = %g\"%t1)\n",
" plt.plot(x, res1)\n",
" plt.plot(x,res_analytical1)\n",
" plt.legend(['dnn','analytical'])\n",
"\n",
" plt.figure(figsize=(10,10))\n",
" plt.title(\"Computed solutions at time = %g\"%t2)\n",
" plt.plot(x, res2)\n",
" plt.plot(x,res_analytical2)\n",
" plt.legend(['dnn','analytical'])\n",
"\n",
" plt.figure(figsize=(10,10))\n",
" plt.title(\"Computed solutions at time = %g\"%t3)\n",
" plt.plot(x, res3)\n",
" plt.plot(x,res_analytical3)\n",
" plt.legend(['dnn','analytical'])\n",
"\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Resources on differential equations and deep learning\n",
"\n",
"1. [Artificial neural networks for solving ordinary and partial differential equations by I.E. Lagaris et al](https://pdfs.semanticscholar.org/d061/df393e0e8fbfd0ea24976458b7d42419040d.pdf)\n",
"\n",
"2. [Neural networks for solving differential equations by A. Honchar](https://becominghuman.ai/neural-networks-for-solving-differential-equations-fa230ac5e04c)\n",
"\n",
"3. [Solving differential equations using neural networks by M.M Chiaramonte and M. Kiener](http://cs229.stanford.edu/proj2013/ChiaramonteKiener-SolvingDifferentialEquationsUsingNeuralNetworks.pdf)\n",
"\n",
"4. [Introduction to Partial Differential Equations by A. Tveito, R. Winther](https://www.springer.com/us/book/9783540225515)\n",
"\n",
"## Friday, Principal Component Analysis\n",
"\n",
"[Overview video](https://www.youtube.com/watch?v=fkf4IBRSeEc&ab_channel=SteveBrunton)\n",
"\n",
"## Basic ideas of the Principal Component Analysis (PCA)\n",
"\n",
"The principal component analysis deals with the problem of fitting a\n",
"low-dimensional affine subspace $S$ of dimension $d$ much smaller than\n",
"the total dimension $D$ of the problem at hand (our data\n",
"set). Mathematically it can be formulated as a statistical problem or\n",
"a geometric problem. In our discussion of the theorem for the\n",
"classical PCA, we will stay with a statistical approach. \n",
"Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable.\n",
"\n",
"We have a data set defined by a design/feature matrix $\\boldsymbol{X}$ (see below for its definition) \n",
"* Each data point is determined by $p$ extrinsic (measurement) variables\n",
"\n",
"* We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data?\n",
"\n",
"* If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. \n",
"\n",
"A good read is for example [Vidal, Ma and Sastry](https://www.springer.com/gp/book/9780387878102).\n",
"\n",
"\n",
"## Introducing the Covariance and Correlation functions\n",
"\n",
"Before we discuss the PCA theorem, we need to remind ourselves about\n",
"the definition of the covariance and the correlation function. These are quantities \n",
"\n",
"Suppose we have defined two vectors\n",
"$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
" \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
" \\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where for example"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With this definition and recalling that the variance is defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we can rewrite the covariance matrix as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
" \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
" \\end{bmatrix}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The covariance takes values between zero and infinity and may thus\n",
"lead to problems with loss of numerical precision for particularly\n",
"large values. It is common to scale the covariance matrix by\n",
"introducing instead the correlation matrix defined via the so-called\n",
"correlation function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
"\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
"can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
"and $\\boldsymbol{y}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
" \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
" \\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above example this is the function we constructed using **pandas**.\n",
"\n",
"## Correlation Function and Design/Feature Matrix\n",
"\n",
"In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
"we defined the design/feature matrix $\\boldsymbol{X}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix}\n",
"x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
"x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
"x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
"\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
"x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
"x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
"\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
"entries $n$ being the row elements.\n",
"We can rewrite the design/feature matrix in terms of its column vectors as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with a given vector"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With these definitions, we can now rewrite our $2\\times 2$\n",
"correaltion/covariance matrix in terms of a moe general design/feature\n",
"matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
"covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
"\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
"\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n",
"\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and the correlation matrix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
"1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
"\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n",
"\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Covariance Matrix Examples\n",
"\n",
"\n",
"The Numpy function **np.cov** calculates the covariance elements using\n",
"the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
"the exact mean values. The following simple function uses the\n",
"**np.vstack** function which takes each vector of dimension $1\\times n$\n",
"and produces a $2\\times n$ matrix $\\boldsymbol{W}$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n",
" x_1 & y_1 \\\\\n",
" x_2 & y_2\\\\\n",
" \\dots & \\dots \\\\\n",
" x_{n-2} & y_{n-2}\\\\\n",
" x_{n-1} & y_{n-1} & \n",
" \\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which in turn is converted into into the $2\\times 2$ covariance matrix\n",
"$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
"the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
"function **np.mean(x)**. We can also extract the eigenvalues of the\n",
"covariance matrix through the **np.linalg.eig()** function."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"# Importing various packages\n",
"import numpy as np\n",
"n = 100\n",
"x = np.random.normal(size=n)\n",
"print(np.mean(x))\n",
"y = 4+3*x+np.random.normal(size=n)\n",
"print(np.mean(y))\n",
"W = np.vstack((x, y))\n",
"C = np.cov(W)\n",
"print(C)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Correlation Matrix\n",
"\n",
"The previous example can be converted into the correlation matrix by\n",
"simply scaling the matrix elements with the variances. We should also\n",
"subtract the mean values for each column. This leads to the following\n",
"code which sets up the correlations matrix for the previous example in\n",
"a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"n = 100\n",
"# define two vectors \n",
"x = np.random.random(size=n)\n",
"y = 4+3*x+np.random.normal(size=n)\n",
"#scaling the x and y vectors \n",
"x = x - np.mean(x)\n",
"y = y - np.mean(y)\n",
"variance_x = np.sum(x@x)/n\n",
"variance_y = np.sum(y@y)/n\n",
"print(variance_x)\n",
"print(variance_y)\n",
"cov_xy = np.sum(x@y)/n\n",
"cov_xx = np.sum(x@x)/n\n",
"cov_yy = np.sum(y@y)/n\n",
"C = np.zeros((2,2))\n",
"C[0,0]= cov_xx/variance_x\n",
"C[1,1]= cov_yy/variance_y\n",
"C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
"C[1,0]= C[0,1]\n",
"print(C)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that the matrix elements along the diagonal are one as they\n",
"should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
"this matrix we easily see that it is a positive definite matrix.\n",
"\n",
"The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
"\n",
"## Correlation Matrix with Pandas\n",
"\n",
"We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"n = 10\n",
"x = np.random.normal(size=n)\n",
"x = x - np.mean(x)\n",
"y = 4+3*x+np.random.normal(size=n)\n",
"y = y - np.mean(y)\n",
"X = (np.vstack((x, y))).T\n",
"print(X)\n",
"Xpd = pd.DataFrame(X)\n",
"print(Xpd)\n",
"correlation_matrix = Xpd.corr()\n",
"print(correlation_matrix)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We expand this model to the Franke function discussed above.\n",
"\n",
"## Correlation Matrix with Pandas and the Franke function"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"# Common imports\n",
"import numpy as np\n",
"import pandas as pd\n",
"\n",
"\n",
"def FrankeFunction(x,y):\n",
"\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
"\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
"\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
"\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
"\treturn term1 + term2 + term3 + term4\n",
"\n",
"\n",
"def create_X(x, y, n ):\n",
"\tif len(x.shape) > 1:\n",
"\t\tx = np.ravel(x)\n",
"\t\ty = np.ravel(y)\n",
"\n",
"\tN = len(x)\n",
"\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
"\tX = np.ones((N,l))\n",
"\n",
"\tfor i in range(1,n+1):\n",
"\t\tq = int((i)*(i+1)/2)\n",
"\t\tfor k in range(i+1):\n",
"\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
"\n",
"\treturn X\n",
"\n",
"\n",
"# Making meshgrid of datapoints and compute Franke's function\n",
"n = 4\n",
"N = 100\n",
"x = np.sort(np.random.uniform(0, 1, N))\n",
"y = np.sort(np.random.uniform(0, 1, N))\n",
"z = FrankeFunction(x, y)\n",
"X = create_X(x, y, n=n) \n",
"\n",
"Xpd = pd.DataFrame(X)\n",
"# subtract the mean values and set up the covariance matrix\n",
"Xpd = Xpd - Xpd.mean()\n",
"covariance_matrix = Xpd.cov()\n",
"print(covariance_matrix)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We note here that the covariance is zero for the first rows and\n",
"columns since all matrix elements in the design matrix were set to one\n",
"(we are fitting the function in terms of a polynomial of degree $n$). We would however not include the intercept\n",
"and wee can simply\n",
"drop these elements and construct a correlation\n",
"matrix without them. \n",
"\n",
"\n",
"## Rewriting the Covariance and/or Correlation Matrix\n",
"\n",
"We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix}\n",
"x_{00} & x_{01}\\\\\n",
"x_{10} & x_{11}\\\\\n",
"\\end{bmatrix}=\\begin{bmatrix}\n",
"\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
"\\end{bmatrix}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we then compute the expectation value"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
"x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n",
"x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n",
"\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which is just"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n",
" \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
" \\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
"\n",
"It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
"\n",
"\n",
"## Towards the PCA theorem\n",
"\n",
"We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\\boldsymbol{S}$.\n",
"These matrices are defined as $\\boldsymbol{S}\\in {\\mathbb{R}}^{p\\times p}$ and obey the orthogonality requirements $\\boldsymbol{S}\\boldsymbol{S}^T=\\boldsymbol{S}^T\\boldsymbol{S}=\\boldsymbol{I}$. The matrix can be written out in terms of the column vectors $\\boldsymbol{s}_i$ as $\\boldsymbol{S}=[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$ and $\\boldsymbol{s}_i \\in {\\mathbb{R}}^{p}$.\n",
"\n",
"Assume also that there is a transformation $\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}=\\boldsymbol{C}[\\boldsymbol{y}]$ such that the new matrix $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal with elements $[\\lambda_0,\\lambda_1,\\lambda_2,\\dots,\\lambda_{p-1}]$. \n",
"\n",
"That is we have"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{y}] = \\mathbb{E}[\\boldsymbol{S}^T\\boldsymbol{X}^T\\boldsymbol{X}T\\boldsymbol{S}]=\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"since the matrix $\\boldsymbol{S}$ is not a data dependent matrix. Multiplying with $\\boldsymbol{S}$ from the left we have"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{y}] = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and since $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{S}_i\\lambda_i = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}_i.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is\n",
"$\\lambda_0 > \\lambda_1 > \\dots > \\lambda_{p-1}$. \n",
"\n",
"\n",
"The eigenvalues tell us then how much we need to stretch the\n",
"corresponding eigenvectors. Dimensions with large eigenvalues have\n",
"thus large variations (large variance) and define therefore useful\n",
"dimensions. The data points are more spread out in the direction of\n",
"these eigenvectors. Smaller eigenvalues mean on the other hand that\n",
"the corresponding eigenvectors are shrunk accordingly and the data\n",
"points are tightly bunched together and there is not much variation in\n",
"these specific directions. Hopefully then we could leave it out\n",
"dimensions where the eigenvalues are very small. If $p$ is very large,\n",
"we could then aim at reducing $p$ to $l << p$ and handle only $l$\n",
"features/predictors.\n",
"\n",
"## The Algorithm before theorem\n",
"\n",
"Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. \n",
"* Set up the datapoints for the design/feature matrix $\\boldsymbol{X}$ with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ referring to the column numbers and the entries $n$ being the row elements."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix}\n",
"x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
"x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
"x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
"\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
"x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
"x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
"\\end{bmatrix},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Center the data by subtracting the mean value for each column. This leads to a new matrix $\\boldsymbol{X}\\rightarrow \\overline{\\boldsymbol{X}}$.\n",
"\n",
"* Compute then the covariance/correlation matrix $\\mathbb{E}[\\overline{\\boldsymbol{X}}^T\\overline{\\boldsymbol{X}}]$.\n",
"\n",
"* Find the eigenpairs of $\\boldsymbol{C}$ with eigenvalues $[\\lambda_0,\\lambda_1,\\dots,\\lambda_{p-1}]$ and eigenvectors $[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$.\n",
"\n",
"* Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.\n",
"\n",
"* Keep only those $l$ eigenvalues larger than a selected threshold value, discarding thus $p-l$ features since we expect small variations in the data here.\n",
"\n",
"## Writing our own PCA code\n",
"\n",
"We will use a simple example first with two-dimensional data\n",
"drawn from a multivariate normal distribution with the following mean and covariance matrix (we have fixed these quantities but will play around with them below):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mu = (-1,2) \\qquad \\Sigma = \\begin{bmatrix} 4 & 2 \\\\\n",
"2 & 2\n",
"\\end{bmatrix}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the mean refers to each column of data. \n",
"We will generate $n = 10000$ points $X = \\{ x_1, \\ldots, x_N \\}$ from\n",
"this distribution, and store them in the $1000 \\times 2$ matrix $\\boldsymbol{X}$. This is our design matrix where we have forced the covariance and mean values to take specific values.\n",
"\n",
"The following Python code aids in setting up the data and writing out the design matrix.\n",
"Note that the function **multivariate** returns also the covariance discussed above and that it is defined by dividing by $n-1$ instead of $n$."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from IPython.display import display\n",
"n = 10000\n",
"mean = (-1, 2)\n",
"cov = [[10, 0.01], [0.01, 2]]\n",
"X = np.random.multivariate_normal(mean, cov, n)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we are going to implement the PCA algorithm. We will break it down into various substeps.\n",
"\n",
"### Compute the sample mean and center the data\n",
"\n",
"The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mu_n = \\frac{1}{n} \\sum_{i=1}^n x_i\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and the mean-centered data $\\bar{X} = \\{ \\bar{x}_1, \\ldots, \\bar{x}_n \\}$ takes the form"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\bar{x}_i = x_i - \\mu_n.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When you are done with these steps, print out $\\mu_n$ to verify it is\n",
"close to $\\mu$ and plot your mean centered data to verify it is\n",
"centered at the origin! \n",
"The following code elements perform these operations using **pandas** or using our own functionality for doing so. The latter, using **numpy** is rather simple through the **mean()** function."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"df = pd.DataFrame(X)\n",
"# Pandas does the centering for us\n",
"df = df -df.mean()\n",
"# we center it ourselves\n",
"X_centered = X - X.mean(axis=0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Alternatively, we could use the functions we discussed\n",
"earlier for scaling the data set. That is, we could have used the\n",
"**StandardScaler** function in **Scikit-Learn**, a function which ensures\n",
"that for each feature/predictor we study the mean value is zero and\n",
"the variance is one (every column in the design/feature matrix). You\n",
"would then not get the same results, since we divide by the\n",
"variance. The diagonal covariance matrix elements will then be one,\n",
"while the non-diagonal ones need to be divided by $2\\sqrt{2}$ for our\n",
"specific case.\n",
"\n",
"### Compute the sample covariance\n",
"\n",
"Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Sigma_n = \\frac{1}{n-1} \\sum_{i=1}^n \\bar{x}_i^T \\bar{x}_i = \\frac{1}{n-1} \\sum_{i=1}^n (x_i - \\mu_n)^T (x_i - \\mu_n)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where the data points $x_i \\in \\mathbb{R}^p$ (here in this example $p = 2$) are column vectors and $x^T$ is the transpose of $x$.\n",
"We can write our own code or simply use either the functionaly of **numpy** or that of **pandas**, as follows"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 0 1\n",
"0 10.067769 0.008068\n",
"1 0.008068 2.024183\n",
"[[1.00677691e+01 8.06773313e-03]\n",
" [8.06773313e-03 2.02418284e+00]]\n"
]
}
],
"source": [
"print(df.cov())\n",
"print(np.cov(X_centered.T))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the way we define the covariance matrix here has a factor $n-1$ instead of $n$. This is included in the **cov()** function by **numpy** and **pandas**. \n",
"Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific $2\\times 2$ covariance matrix."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Centered covariance using own code\n",
"[[1.00677691e+01 8.06773313e-03]\n",
" [8.06773313e-03 2.02418284e+00]]\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAD4CAYAAADvsV2wA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nf2tX2A08BP8DYth8ATwCrL97oBp0Rcxx7yXyttVcpdRnwJ6VURcgrFkY4UW/wtdZL+vCx40CW7fkEwDswI7q49HT7lVK/BHYM8nAuNiPmOPYGrbU39P8zpdQ2jNDWSDf4dUqp8VrrWqXUeOCzoR7QUCAhnb7xCvAPSqk4pdQVwCRg/xCPacAJ/TBMVmAksUcSB4BJSqkrlFKxGIn4V4Z4TIOKUipRKZVkPga+yMg7rpF4Bbgn9PgeoLO79xFN1Hv4XaGUWgH8J5AO7FRKHdZa36S1LldK/Rb4EPADX9daB4ZyrIPE/1NKzcIIcxwDHhja4QwsWmu/UupBYBfgBJ7TWpcP8bAGmwxgm1IKjN//Fq31a0M7pIFFKfXfwCIgTSl1HPgu8EPgt0qp+4BPgduHboRDh0grCIIgRAkS0hEEQYgSxOALgiBECWLwBUEQogQx+IIgCFGCGHxBEIQoQQy+IAhClCAGXxAEIUr4XzA2mSFccU7tAAAAAElFTkSuQmCC\n",
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# extract the relevant columns from the centered design matrix of dim n x 2\n",
"x = X_centered[:,0]\n",
"y = X_centered[:,1]\n",
"Cov = np.zeros((2,2))\n",
"Cov[0,1] = np.sum(x.T@y)/(n-1.0)\n",
"Cov[0,0] = np.sum(x.T@x)/(n-1.0)\n",
"Cov[1,1] = np.sum(y.T@y)/(n-1.0)\n",
"Cov[1,0]= Cov[0,1]\n",
"print(\"Centered covariance using own code\")\n",
"print(Cov)\n",
"plt.plot(x, y, 'x')\n",
"plt.axis('equal')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Depending on the number of points $n$, we will get results that are close to the covariance values defined above.\n",
"The plot shows how the data are clustered around a line with slope close to one. Is this expected? Try to change the covariance and the mean values. For example, try to make the variance of the first element much larger than that of the second diagonal element. Try also to shrink the covariance (the non-diagonal elements) and see how the data points are distributed. \n",
"\n",
"### Diagonalize the sample covariance matrix to obtain the principal components\n",
"\n",
"Now we are ready to solve for the principal components! To do so we\n",
"diagonalize the sample covariance matrix $\\Sigma$. We can use the\n",
"function **np.linalg.eig** to do so. It will return the eigenvalues and\n",
"eigenvectors of $\\Sigma$. Once we have these we can perform the \n",
"following tasks:\n",
"\n",
"* We compute the percentage of the total variance captured by the first principal component\n",
"\n",
"* We plot the mean centered data and lines along the first and second principal components\n",
"\n",
"* Then we project the mean centered data onto the first and second principal components, and plot the projected data. \n",
"\n",
"* Finally, we approximate the data as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"x_i \\approx \\tilde{x}_i = \\mu_n + \\langle x_i, v_0 \\rangle v_0\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $v_0$ is the first principal component. \n",
"\n",
"Collecting all these steps we can write our own PCA function and\n",
"compare this with the functionality included in **Scikit-Learn**. \n",
"\n",
"The code here outlines some of the elements we could include in the\n",
"analysis. Feel free to extend upon this in order to address the above\n",
"questions."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Eigenvalues of Covariance matrix\n",
"10.06777716248222\n",
"2.024174751235422\n",
"First eigenvector\n",
"[0.9999995 0.001003 ]\n",
"Second eigenvector\n",
"[-0.001003 0.9999995]\n",
"Eigenvector of largest eigenvalue\n",
"[0.9999995 0.001003 ]\n"
]
}
],
"source": [
"# diagonalize and obtain eigenvalues, not necessarily sorted\n",
"EigValues, EigVectors = np.linalg.eig(Cov)\n",
"# sort eigenvectors and eigenvalues\n",
"#permute = EigValues.argsort()\n",
"#EigValues = EigValues[permute]\n",
"#EigVectors = EigVectors[:,permute]\n",
"print(\"Eigenvalues of Covariance matrix\")\n",
"for i in range(2):\n",
" print(EigValues[i])\n",
"FirstEigvector = EigVectors[:,0]\n",
"SecondEigvector = EigVectors[:,1]\n",
"print(\"First eigenvector\")\n",
"print(FirstEigvector)\n",
"print(\"Second eigenvector\")\n",
"print(SecondEigvector)\n",
"#thereafter we do a PCA with Scikit-learn\n",
"from sklearn.decomposition import PCA\n",
"pca = PCA(n_components = 2)\n",
"X2Dsl = pca.fit_transform(X)\n",
"print(\"Eigenvector of largest eigenvalue\")\n",
"print(pca.components_.T[:, 0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This code does not contain all the above elements, but it shows how we can use **Scikit-Learn** to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then? \n",
"\n",
"## Classical PCA Theorem\n",
"\n",
"We assume now that we have a design matrix $\\boldsymbol{X}$ which has been\n",
"centered as discussed above. For the sake of simplicity we skip the\n",
"overline symbol. The matrix is defined in terms of the various column\n",
"vectors $[\\boldsymbol{x}_0,\\boldsymbol{x}_1,\\dots, \\boldsymbol{x}_{p-1}]$ each with dimension\n",
"$\\boldsymbol{x}\\in {\\mathbb{R}}^{n}$.\n",
"\n",
"\n",
"\n",
"The PCA theorem states that minimizing the above reconstruction error\n",
"corresponds to setting $\\boldsymbol{W}=\\boldsymbol{S}$, the orthogonal matrix which\n",
"diagonalizes the empirical covariance(correlation) matrix. The optimal\n",
"low-dimensional encoding of the data is then given by a set of vectors\n",
"$\\boldsymbol{z}_i$ with at most $l$ vectors, with $l << p$, defined by the\n",
"orthogonal projection of the data onto the columns spanned by the\n",
"eigenvectors of the covariance(correlations matrix).\n",
"\n",
"\n",
"\n",
"## Proof of the PCA Theorem\n",
"\n",
"To show the PCA theorem let us start with the assumption that there is one vector $\\boldsymbol{s}_0$ which corresponds to a solution which minimized the reconstruction error $J$. This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of $\\boldsymbol{w}_0$ and $\\boldsymbol{z}_0$ as\n",
"\n",
"## PCA Proof continued\n",
"\n",
"\n",
"\n",
"We are almost there, we have obtained a relation between minimizing\n",
"the reconstruction error and the variance and the covariance\n",
"matrix. Minimizing the error is equivalent to maximizing the variance\n",
"of the projected data.\n",
"\n",
"## The final step\n",
"\n",
"We could trivially maximize the variance of the projection (and\n",
"thereby minimize the error in the reconstruction function) by letting\n",
"the norm-2 of $\\boldsymbol{w}_0$ go to infinity. However, this norm since we\n",
"want the matrix $\\boldsymbol{W}$ to be an orthogonal matrix, is constrained by\n",
"$\\vert\\vert \\boldsymbol{w}_0 \\vert\\vert_2^2=1$. Imposing this condition via a\n",
"Lagrange multiplier we can then in turn maximize"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"J(\\boldsymbol{w}_0)= \\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0+\\lambda_0(1-\\boldsymbol{w}_0^T\\boldsymbol{w}_0).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Taking the derivative with respect to $\\boldsymbol{w}_0$ we obtain"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial J(\\boldsymbol{w}_0)}{\\partial \\boldsymbol{w}_0}= 2\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0-2\\lambda_0\\boldsymbol{w}_0=0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"meaning that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0\\boldsymbol{w}_0.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix**! If we left multiply with $\\boldsymbol{w}_0^T$ we have the variance of the projected data is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we want to maximize the variance (minimize the construction error)\n",
"we simply pick the eigenvector of the covariance matrix with the\n",
"largest eigenvalue. This establishes the link between the minimization\n",
"of the reconstruction function $J$ in terms of an orthogonal matrix\n",
"and the maximization of the variance and thereby the covariance of our\n",
"observations encoded in the design/feature matrix $\\boldsymbol{X}$.\n",
"\n",
"The proof\n",
"for the other eigenvectors $\\boldsymbol{w}_1,\\boldsymbol{w}_2,\\dots$ can be\n",
"established by applying the above arguments and using the fact that\n",
"our basis of eigenvectors is orthogonal, see [Murphy chapter\n",
"12.2](https://mitpress.mit.edu/books/machine-learning-1). The\n",
"discussion in chapter 12.2 of Murphy's text has also a nice link with\n",
"the Singular Value Decomposition theorem. For categorical data, see\n",
"chapter 12.4 and discussion therein.\n",
"\n",
"For more details, see for example [Vidal, Ma and Sastry, chapter 2](https://www.springer.com/gp/book/9780387878102).\n",
"\n",
"## Geometric Interpretation and link with Singular Value Decomposition\n",
"\n",
"For a detailed demonstration of the geometric interpretation, see [Vidal, Ma and Sastry, section 2.1.2](https://www.springer.com/gp/book/9780387878102).\n",
"\n",
"\n",
"## Principal Component Analysis\n",
"\n",
"Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.\n",
"First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.\n",
"\n",
"The following Python code uses NumPys **svd()** function to obtain all the principal components of the\n",
"training set, then extracts the first two principal components. First we center the data using either **pandas** or our own code"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"from IPython.display import display\n",
"np.random.seed(100)\n",
"# setting up a 10 x 5 vanilla matrix \n",
"rows = 10\n",
"cols = 5\n",
"X = np.random.randn(rows,cols)\n",
"df = pd.DataFrame(X)\n",
"# Pandas does the centering for us\n",
"df = df -df.mean()\n",
"display(df)\n",
"\n",
"# we center it ourselves\n",
"X_centered = X - X.mean(axis=0)\n",
"# Then check the difference between pandas and our own set up\n",
"print(X_centered-df)\n",
"#Now we do an SVD\n",
"U, s, V = np.linalg.svd(X_centered)\n",
"c1 = V.T[:, 0]\n",
"c2 = V.T[:, 1]\n",
"W2 = V.T[:, :2]\n",
"X2D = X_centered.dot(W2)\n",
"print(X2D)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"PCA assumes that the dataset is centered around the origin. Scikit-Learns PCA classes take care of centering\n",
"the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, dont\n",
"forget to center the data first.\n",
"\n",
"Once you have identified all the principal components, you can reduce the dimensionality of the dataset\n",
"down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components.\n",
"Selecting this hyperplane ensures that the projection will preserve as much variance as possible."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"W2 = V.T[:, :2]\n",
"X2D = X_centered.dot(W2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- !split -->\n",
"## PCA and scikit-learn\n",
"\n",
"Scikit-Learns PCA class implements PCA using SVD decomposition just like we did before. The\n",
"following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note\n",
"that it automatically takes care of centering the data):"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"#thereafter we do a PCA with Scikit-learn\n",
"from sklearn.decomposition import PCA\n",
"pca = PCA(n_components = 2)\n",
"X2D = pca.fit_transform(X)\n",
"print(X2D)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"After fitting the PCA transformer to the dataset, you can access the principal components using the\n",
"components variable (note that it contains the PCs as horizontal vectors, so, for example, the first\n",
"principal component is equal to"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"pca.components_.T[:, 0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another very useful piece of information is the explained variance ratio of each principal component,\n",
"available via the $explained\\_variance\\_ratio$ variable. It indicates the proportion of the datasets\n",
"variance that lies along the axis of each principal component. \n",
"\n",
"## Back to the Cancer Data\n",
"We can now repeat the above but applied to real data, in this case our breast cancer data.\n",
"Here we compute performance scores on the training data using logistic regression."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split \n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.linear_model import LogisticRegression\n",
"cancer = load_breast_cancer()\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
"\n",
"logreg = LogisticRegression()\n",
"logreg.fit(X_train, y_train)\n",
"print(\"Train set accuracy from Logistic Regression: {:.2f}\".format(logreg.score(X_train,y_train)))\n",
"# We scale the data\n",
"from sklearn.preprocessing import StandardScaler\n",
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"# Then perform again a log reg fit\n",
"logreg.fit(X_train_scaled, y_train)\n",
"print(\"Train set accuracy scaled data: {:.2f}\".format(logreg.score(X_train_scaled,y_train)))\n",
"#thereafter we do a PCA with Scikit-learn\n",
"from sklearn.decomposition import PCA\n",
"pca = PCA(n_components = 2)\n",
"X2D_train = pca.fit_transform(X_train_scaled)\n",
"# and finally compute the log reg fit and the score on the training data\t\n",
"logreg.fit(X2D_train,y_train)\n",
"print(\"Train set accuracy scaled and PCA data: {:.2f}\".format(logreg.score(X2D_train,y_train)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. \n",
"\n",
"## More on the PCA\n",
"\n",
"Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to\n",
"choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).\n",
"Unless, of course, you are reducing dimensionality for data visualization — in that case you will\n",
"generally want to reduce the dimensionality down to 2 or 3.\n",
"The following code computes PCA without reducing dimensionality, then computes the minimum number\n",
"of dimensions required to preserve 95% of the training sets variance:"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"pca = PCA()\n",
"pca.fit(X)\n",
"cumsum = np.cumsum(pca.explained_variance_ratio_)\n",
"d = np.argmax(cumsum >= 0.95) + 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You could then set $n\\_components=d$ and run PCA again. However, there is a much better option: instead\n",
"of specifying the number of principal components you want to preserve, you can set $n\\_components$ to be\n",
"a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"pca = PCA(n_components=0.95)\n",
"X_reduced = pca.fit_transform(X)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Incremental PCA\n",
"\n",
"One problem with the preceding implementation of PCA is that it requires the whole training set to fit in\n",
"memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have\n",
"been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch\n",
"at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new\n",
"instances arrive).\n",
"\n",
"## Randomized PCA\n",
"\n",
"Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic\n",
"algorithm that quickly finds an approximation of the first d principal components. Its computational\n",
"complexity is $O(m \\times d^2)+O(d^3)$, instead of $O(m \\times n^2) + O(n^3)$, so it is dramatically faster than the\n",
"previous algorithms when $d$ is much smaller than $n$.\n",
"\n",
"\n",
"\n",
"\n",
"## Kernel PCA\n",
"\n",
"The kernel trick is a mathematical technique that implicitly maps instances into a\n",
"very high-dimensional space (called the feature space), enabling nonlinear classification and regression\n",
"with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature\n",
"space corresponds to a complex nonlinear decision boundary in the original space.\n",
"It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear\n",
"projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at\n",
"preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a\n",
"twisted manifold.\n",
"For example, the following code uses Scikit-Learns KernelPCA class to perform kPCA with an"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.decomposition import KernelPCA\n",
"rbf_pca = KernelPCA(n_components = 2, kernel=\"rbf\", gamma=0.04)\n",
"X_reduced = rbf_pca.fit_transform(X)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## LLE\n",
"\n",
"Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction\n",
"(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous\n",
"algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its\n",
"closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where\n",
"these local relationships are best preserved (more details shortly). \n",
"\n",
"\n",
"\n",
"## Other techniques\n",
"\n",
"\n",
"There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.\n",
"\n",
"Here are some of the most popular:\n",
"* **Multidimensional Scaling (MDS)** reduces dimensionality while trying to preserve the distances between the instances.\n",
"\n",
"* **Isomap** creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.\n",
"\n",
"* **t-Distributed Stochastic Neighbor Embedding** (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).\n",
"\n",
"* Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8"
}
},
"nbformat": 4,
"nbformat_minor": 4
}