diff --git a/doc/BookChapters/chapter11.ipynb b/doc/BookChapters/chapter11.ipynb deleted file mode 100644 index 00bf35796..000000000 --- a/doc/BookChapters/chapter11.ipynb +++ /dev/null @@ -1,3375 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "7660a7d5", - "metadata": { - "editable": true - }, - "source": [ - "" - ] - }, - { - "cell_type": "markdown", - "id": "7174820b", - "metadata": { - "editable": true - }, - "source": [ - "# Solving Differential Equations 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", - "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", - "id": "ac838a12", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "ccee4286", - "metadata": { - "editable": true - }, - "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", - "Let the trial solution $g_t(x)$ be" - ] - }, - { - "cell_type": "markdown", - "id": "39d7dabd", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "74f33170", - "metadata": { - "editable": true - }, - "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", - "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", - "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", - "id": "2565ab16", - "metadata": { - "editable": true - }, - "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", - "id": "83d4ee25", - "metadata": { - "editable": true - }, - "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", - "id": "a7a3a709", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "d3ca8026", - "metadata": { - "editable": true - }, - "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", - "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." - ] - }, - { - "cell_type": "markdown", - "id": "9bde4bd4", - "metadata": { - "editable": true - }, - "source": [ - "### Example: Exponential decay\n", - "\n", - "An exponential decay of a quantity $g(x)$ is described by the equation" - ] - }, - { - "cell_type": "markdown", - "id": "e74337c3", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{solve_expdec} \\tag{4}\n", - " g'(x) = -\\gamma g(x)\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "273549a4", - "metadata": { - "editable": true - }, - "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", - "id": "db3c6623", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "8547e3c8", - "metadata": { - "editable": true - }, - "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", - "The program will use a neural network to solve" - ] - }, - { - "cell_type": "markdown", - "id": "48341fc6", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{solveode} \\tag{6}\n", - "g'(x) = -\\gamma g(x)\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d25b1e02", - "metadata": { - "editable": true - }, - "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", - "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", - "id": "7c5dd91e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g_t(x, P) = h_1(x) + h_2(x, N(x, P))\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "24223062", - "metadata": { - "editable": true - }, - "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", - "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", - "id": "ebf04383", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "ea4a0013", - "metadata": { - "editable": true - }, - "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", - "id": "2351b84f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g_t(x, P) = g_0 + x \\cdot N(x, P)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f6cc00e4", - "metadata": { - "editable": true - }, - "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", - "id": "84e066a1", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "feff9ab3", - "metadata": { - "editable": true - }, - "source": [ - "is fulfilled as *best as possible*.\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", - "id": "0c6f0e79", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\min_{P}\\Big\\{ \\big(g_t'(x, P) - ( -\\gamma g_t(x, P) \\big)^2 \\Big\\}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9302a1dd", - "metadata": { - "editable": true - }, - "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", - "id": "f7f204bb", - "metadata": { - "editable": true - }, - "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", - "id": "8d61d75f", - "metadata": { - "editable": true - }, - "source": [ - "for an input value $x$.\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", - "id": "10d3aec9", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "5e296388", - "metadata": { - "editable": true - }, - "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", - "id": "fe010d79", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\min_{P} C(\\boldsymbol{x}, P)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "add715f9", - "metadata": { - "editable": true - }, - "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", - "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", - "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", - "id": "cb9b22eb", - "metadata": { - "editable": true - }, - "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", - "id": "49f3c493", - "metadata": { - "editable": true - }, - "source": [ - "The result after weighting the inputs at the $i$-th hidden neuron can be written as a vector:" - ] - }, - { - "cell_type": "markdown", - "id": "a352bd61", - "metadata": { - "editable": true - }, - "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", - "id": "e5636ad7", - "metadata": { - "editable": true - }, - "source": [ - "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", - "id": "68bb8b9c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(z) = \\frac{1}{1 + \\exp{(-z)}}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ff6e6536", - "metadata": { - "editable": true - }, - "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", - "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", - "id": "6fb4c55b", - "metadata": { - "editable": true - }, - "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", - "id": "09c31d8d", - "metadata": { - "editable": true - }, - "source": [ - "Expressing $z_{1,j}^{\\text{output}}$ as a vector gives the following way of weighting the inputs from the hidden layer:" - ] - }, - { - "cell_type": "markdown", - "id": "f81fe361", - "metadata": { - "editable": true - }, - "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", - "id": "c309a4ce", - "metadata": { - "editable": true - }, - "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", - "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", - "id": "ea47ae29", - "metadata": { - "editable": true - }, - "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", - "id": "9dd83767", - "metadata": { - "editable": true - }, - "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." - ] - }, - { - "cell_type": "markdown", - "id": "531a7b4f", - "metadata": { - "editable": true - }, - "source": [ - "### 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", - "id": "e10c204a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\omega}_{\\text{new} } = \\boldsymbol{\\omega} - \\lambda \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9f4fa48e", - "metadata": { - "editable": true - }, - "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", - "id": "4652fc79", - "metadata": { - "editable": true - }, - "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", - "id": "41ae0626", - "metadata": { - "editable": true - }, - "source": [ - "### The code for solving the ODE" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "af7c165f", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "875a0c0b", - "metadata": { - "editable": true - }, - "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, - "id": "00684827", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "5420c490", - "metadata": { - "editable": true - }, - "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", - "id": "1436ed3c", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "a590bdb6", - "metadata": { - "editable": true - }, - "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", - "Here, we will model a population $g(t)$ in an environment having carrying capacity $A$.\n", - "The population follows the model" - ] - }, - { - "cell_type": "markdown", - "id": "48d788d6", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "169c6c25", - "metadata": { - "editable": true - }, - "source": [ - "where $g(0) = g_0$.\n", - "\n", - "In this example, we let $\\alpha = 2$, $A = 1$, and $g_0 = 1.2$.\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 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, - "id": "6d2e33bf", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "e31ec549", - "metadata": { - "editable": true - }, - "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", - "id": "2e9ee105", - "metadata": { - "editable": true - }, - "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", - "id": "e876da16", - "metadata": { - "editable": true - }, - "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", - "id": "b79a3def", - "metadata": { - "editable": true - }, - "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", - "id": "9d99cb4e", - "metadata": { - "editable": true - }, - "source": [ - "Now, if $g_i = g(t_i)$ then" - ] - }, - { - "cell_type": "markdown", - "id": "3b9dcc24", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "65ce688e", - "metadata": { - "editable": true - }, - "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, - "id": "d5497948", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "fa8f0bb4", - "metadata": { - "editable": true - }, - "source": [ - "## Solving the one dimensional Poisson equation\n", - "\n", - "The Poisson equation for $g(x)$ in one dimension is" - ] - }, - { - "cell_type": "markdown", - "id": "f765b0ba", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{poisson} \\tag{13}\n", - " -g''(x) = f(x)\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bd63b92e", - "metadata": { - "editable": true - }, - "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", - "id": "c0a7face", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - " g(0) &= 0 \\\\\n", - " g(1) &= 0\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f71c3cb9", - "metadata": { - "editable": true - }, - "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", - "Here, the function $g(x)$ to solve for follows the equation" - ] - }, - { - "cell_type": "markdown", - "id": "35aa6a37", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "-g''(x) = f(x),\\qquad x \\in (0,1)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f8b35111", - "metadata": { - "editable": true - }, - "source": [ - "where $f(x)$ is a given function, along with the chosen conditions" - ] - }, - { - "cell_type": "markdown", - "id": "33813514", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{aligned}\n", - "g(0) = g(1) = 0\n", - "\\end{aligned}\\label{cond} \\tag{14}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c70aadd4", - "metadata": { - "editable": true - }, - "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", - "id": "d5719dee", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g_t(x) = x \\cdot (1-x) \\cdot N(P,x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a683041b", - "metadata": { - "editable": true - }, - "source": [ - "The analytical solution for this problem is" - ] - }, - { - "cell_type": "markdown", - "id": "672cdaff", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g(x) = x(1 - x)\\exp(x)\n", - "$$" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "66e6bebb", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "d425cba5", - "metadata": { - "editable": true - }, - "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", - "id": "a2efa110", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "5011ee25", - "metadata": { - "editable": true - }, - "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", - "id": "705ee300", - "metadata": { - "editable": true - }, - "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", - "id": "b390796d", - "metadata": { - "editable": true - }, - "source": [ - "Since we know from our problem that" - ] - }, - { - "cell_type": "markdown", - "id": "19c9ece4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - "-g''(x) &= f(x) \\\\\n", - "&= (3x + x^2)\\exp(x)\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6ade1a7a", - "metadata": { - "editable": true - }, - "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", - "id": "78b16d02", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "f2bfcca4", - "metadata": { - "editable": true - }, - "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", - "id": "a6191528", - "metadata": { - "editable": true - }, - "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", - "id": "aefef707", - "metadata": { - "editable": true - }, - "source": [ - "which makes it possible to solve for the vector $\\boldsymbol{g}$.\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, - "id": "471664cd", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "6f02e86d", - "metadata": { - "editable": true - }, - "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", - "id": "ad5c63e8", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "c7b98797", - "metadata": { - "editable": true - }, - "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." - ] - }, - { - "cell_type": "markdown", - "id": "52f9394e", - "metadata": { - "editable": true - }, - "source": [ - "### 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", - "id": "4d489854", - "metadata": { - "editable": true - }, - "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", - "id": "82311538", - "metadata": { - "editable": true - }, - "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." - ] - }, - { - "cell_type": "markdown", - "id": "9d134db4", - "metadata": { - "editable": true - }, - "source": [ - "### 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", - "id": "5a463498", - "metadata": { - "editable": true - }, - "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", - "id": "c40d8997", - "metadata": { - "editable": true - }, - "source": [ - "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", - "id": "cc033de6", - "metadata": { - "editable": true - }, - "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", - "id": "ae18b4f4", - "metadata": { - "editable": true - }, - "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", - "id": "44ca21bd", - "metadata": { - "editable": true - }, - "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", - "id": "fe94451e", - "metadata": { - "editable": true - }, - "source": [ - "## Example: The diffusion equation\n", - "\n", - "In one spatial dimension, the equation reads" - ] - }, - { - "cell_type": "markdown", - "id": "30a42273", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fd4077e7", - "metadata": { - "editable": true - }, - "source": [ - "where a possible choice of conditions are" - ] - }, - { - "cell_type": "markdown", - "id": "dbbf2e4b", - "metadata": { - "editable": true - }, - "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", - "id": "83653db9", - "metadata": { - "editable": true - }, - "source": [ - "with $u(x)$ being some given function.\n", - "\n", - "For this case, we want to find $g(x,t)$ such that" - ] - }, - { - "cell_type": "markdown", - "id": "d2c2ef4f", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "8fb27bdb", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "dc9297ab", - "metadata": { - "editable": true - }, - "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", - "id": "ab90784f", - "metadata": { - "editable": true - }, - "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", - "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, - "id": "b07e858c", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "9a167ec1", - "metadata": { - "editable": true - }, - "source": [ - "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", - "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, - "id": "921e5969", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "0bc00b69", - "metadata": { - "editable": true - }, - "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", - "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, - "id": "20734418", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "143f1c80", - "metadata": { - "editable": true - }, - "source": [ - "## Solving the wave equation with Neural Networks\n", - "\n", - "The wave equation is" - ] - }, - { - "cell_type": "markdown", - "id": "190bd4f2", - "metadata": { - "editable": true - }, - "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", - "id": "9719cfc5", - "metadata": { - "editable": true - }, - "source": [ - "with $c$ being the specified wave speed.\n", - "\n", - "Here, the chosen conditions are" - ] - }, - { - "cell_type": "markdown", - "id": "f69ec7fd", - "metadata": { - "editable": true - }, - "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", - "id": "6ce8c5a8", - "metadata": { - "editable": true - }, - "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 wave equation to solve for, is" - ] - }, - { - "cell_type": "markdown", - "id": "4be700d7", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "993f93ba", - "metadata": { - "editable": true - }, - "source": [ - "where $c$ is the given wave speed.\n", - "The chosen conditions for this equation are" - ] - }, - { - "cell_type": "markdown", - "id": "2cb2a80f", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\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", - "id": "3f1dcfd4", - "metadata": { - "editable": true - }, - "source": [ - "In this example, let $c = 1$ and $u(x) = \\sin(\\pi x)$ and $v(x) = -\\pi\\sin(\\pi x)$.\n", - "\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 for our specific problem, is\n", - "\n", - "$$\n", - "g(x,t) = \\sin(\\pi x)\\cos(\\pi t) - \\sin(\\pi x)\\sin(\\pi t)\n", - "$$" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "230a9aef", - "metadata": { - "collapsed": false, - "editable": true - }, - "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", - "id": "a23bd19a", - "metadata": { - "editable": true - }, - "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)" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/BookChapters/chapter12.do.txt b/doc/BookChapters/chapter12.do.txt index 6371c0102..851715e74 100644 --- a/doc/BookChapters/chapter12.do.txt +++ b/doc/BookChapters/chapter12.do.txt @@ -1,6 +1,7 @@ ======= Convolutional Neural Networks ======= + Convolutional neural networks (CNNs) were developed during the last decade of the previous century, with a focus on character recognition tasks. Nowadays, CNNs are a central element in the spectacular success @@ -18,12 +19,53 @@ loss function (for example Softmax) on the last (fully-connected) layer and all the tips/tricks we developed for learning regular Neural Networks still apply (back propagation, gradient descent etc etc). -What is the difference? _CNN architectures make the explicit assumption that + + +_CNN architectures make the explicit assumption that the inputs are images, which allows us to encode certain properties into the architecture. These then make the forward function more efficient to implement and vastly reduce the amount of parameters in the network._ +Here we provide only a superficial overview, for the more interested, we recommend highly the course +"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" +and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/". + +Another good read is the article here URL:"https://arxiv.org/pdf/1603.07285.pdf". + + + +===== Neural Networks vs CNNs ===== + +Neural networks are defined as _affine transformations_, that is +a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an +output (to which a bias vector is usually added before passing the result +through a nonlinear activation function). This is applicable to any type of input, be it an +image, a sound clip or an unordered collection of features: whatever their +dimensionality, their representation can always be flattened into a vector +before the transformation. + + + +However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic +structure. More formally, they share these important properties: +* They are stored as multi-dimensional arrays (think of the pixels of a figure) . +* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip). +* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track). + +These properties are not exploited when an affine transformation is applied; in +fact, all the axes are treated in the same way and the topological information +is not taken into account. Still, taking advantage of the implicit structure of +the data may prove very handy in solving some tasks, like computer vision and +speech recognition, and in these cases it would be best to preserve it. This is +where discrete convolutions come into play. + +A discrete convolution is a linear transformation that preserves this notion of +ordering. It is sparse (only a few input units contribute to a given output +unit) and reuses parameters (the same weights are applied to multiple locations +in the input). + + As an example, consider an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a @@ -42,7 +84,6 @@ would quickly lead to possible overfitting. FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network. - Convolutional Neural Networks take advantage of the fact that the input consists of images and they constrain the architecture in a more sensible way. @@ -67,11 +108,14 @@ end of the CNN architecture we will reduce the full image into a single vector of class scores, arranged along the depth dimension. -FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, heigh#t, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D out#put volume of neuron activations. In this example, the red input layer holds the image, so its width and heigh#t would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). +FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). +===== Layers used to build CNNs ===== + + A simple CNN is a sequence of layers, and every layer of a CNN transforms one volume of activations to another through a differentiable function. We use three main types of layers to build @@ -89,6 +133,7 @@ A simple CNN for image classification could have the architecture: + CNNs transform the original image layer by layer from the original pixel values to the final class scores. @@ -103,8 +148,6 @@ are consistent with the labels in the training set for each image. -=== CNNs in brief === - In summary: * A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores) @@ -114,6 +157,438 @@ In summary: * Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t) +A dense neural network is representd by an affine operation (like matrix-matrix multiplication) where all parameters are included. + +The key idea in CNNs for say imaging is that in images neighbor pixels tend to be related! So we connect +only neighboring neurons in the input instead of connecting all with the first hidden layer. + +We say we perform a filtering (convolution is the mathematical operation). + + + +===== Mathematics of CNNs ===== + +The mathematics of CNNs is based on the mathematical operation of +_convolution_. In mathematics (in particular in functional analysis), +convolution is represented by matheematical operation (integration, +summation etc) on two function in order to produce a third function +that expresses how the shape of one gets modified by the other. +Convolution has a plethora of applications in a variety of disciplines, spanning from statistics to signal processing, computer vision, solutions of differential equations,linear algebra, engineering, and yes, machine learning. + +Mathematically, convolution is defined as follows (one-dimensional example): +Let us define a continuous function $y(t)$ given by +!bt +\[ +y(t) = \int x(a) w(t-a) da, +\] +!et +where $x(a)$ represents a so-called input and $w(t-a)$ is normally called the weight function or kernel. + +The above integral is written in a more compact form as +!bt +\[ +y(t) = \left(x * w\right)(t). +\] +!et + +The discretized version reads +!bt +\[ +y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a). +\] +!et +Computing the inverse of the above convolution operations is known as deconvolution. + +How can we use this? And what does it mean? Let us study some familiar examples first. + + + +=== Convolution Examples: Polynomial multiplication === + +We have already met such an example in project 1 when we tried to set +up the design matrix for a two-dimensional function. This was an +example of polynomial multiplication. Let us recast such a problem in terms of the convolution operation. +Let us look a the following polynomials to second and third order, respectively: +!bt +\[ +p(t) = \alpha_0+\alpha_1 t+\alpha_2 t^2, +\] +!et +and +!bt +\[ +s(t) = \beta_0+\beta_1 t+\beta_2 t^2+\beta_3 t^3. +\] +!et + +The polynomial multiplication gives us a new polynomial of degree $5$ +!bt +\[ +z(t) = \delta_0+\delta_1 t+\delta_2 t^2+\delta_3 t^3+\delta_4 t^4+\delta_5 t^5. +\] +!et + + +Computing polynomial products can be implemented efficiently if we rewrite the more brute force multiplications using convolution. +We note first that the new coefficients are given as + +!bt +\begin{split} +\delta_0=&\alpha_0\beta_0\\ +\delta_1=&\alpha_1\beta_0+\alpha_1\beta_0\\ +\delta_2=&\alpha_0\beta_2+\alpha_1\beta_1+\alpha_2\beta_0\\ +\delta_3=&\alpha_1\beta_2+\alpha_2\beta_1+\alpha_0\beta_3\\ +\delta_4=&\alpha_2\beta_2+\alpha_1\beta_3\\ +\delta_5=&\alpha_2\beta_3.\\ +\end{split} +!et + + +We note that $\alpha_i=0$ except for $i\in \left\{0,1,2\right\}$ and $\beta_i=0$ except for $i\in\left\{0,1,2,3\right\}$. + +We can then rewrite the coefficients $\delta_j$ using a discrete convolution as +!bt +\[ +\delta_j = \sum_{i=-\infty}^{i=\infty}\alpha_i\beta_{j-i}=(\alpha * \beta)_j, +\] +!et +or as a double sum with restriction $l=i+j$ +!bt +\[ +\delta_l = \sum_{ij}\alpha_i\beta_{j}. +\] +!et + +Do you see a potential drawback with these equations? + + +Since we only have a finite number of $\alpha$ and $\beta$ values +which are non-zero, we can rewrite the above convolution expressions +as a matrix-vector multiplication + +!bt +\[ +\bm{\delta}=\begin{bmatrix}\alpha_0 & 0 & 0 & 0 \\ + \alpha_1 & \alpha_0 & 0 & 0 \\ + \alpha_2 & \alpha_1 & \alpha_0 & 0 \\ + 0 & \alpha_2 & \alpha_1 & \alpha_0 \\ + 0 & 0 & \alpha_2 & \alpha_1 \\ + 0 & 0 & 0 & \alpha_2 + \end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}. +\] +!et + +The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding $\beta$ and a vector holding $\alpha$. +In this case we have +!bt +\[ +\bm{\delta}=\begin{bmatrix}\beta_0 & 0 & 0 \\ + \beta_1 & \beta_0 & 0 \\ + \beta_2 & \beta_1 & \beta_0 \\ + \beta_3 & \beta_2 & \beta_1 \\ + 0 & \beta_3 & \beta_2 \\ + 0 & 0 & \beta_3 + \end{bmatrix}\begin{bmatrix} \alpha_0 \\ \alpha_1 \\ \alpha_2\end{bmatrix}. +\] +!et + +Note that the use of these matrices is for mathematical purposes only and not implementation purposes. +When implementing the above equation we do not encode (and allocate memory) the matrices explicitely. +We rather code the convolutions in the minimal memory footprint that they require. + +Does the number of floating point operations change here when we use the commutative property? + +=== Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms) === + +For problems with so-called harmonic oscillations, given by for example the following differential equation +!bt +\[ +m\frac{d^2x}{dt^2}+\eta\frac{dx}{dt}+x(t)=F(t), +\] +!et +where $F(t)$ is an applied external force acting on the system (often called a driving force), one can use the theory of Fourier transformations to find the solutions of this type of equations. + +If one has several driving forces, $F(t)=\sum_n F_n(t)$, one can find +the particular solution to each $F_n$, $x_{pn}(t)$, and the particular +solution for the entire driving force is then given by a series like + +!bt +\begin{equation} +x_p(t)=\sum_nx_{pn}(t). +\end{equation} +!et + + + +This is known as the principle of superposition. It only applies when +the homogenous equation is linear. If there were an anharmonic term +such as $x^3$ in the homogenous equation, then when one summed various +solutions, $x=(\sum_n x_n)^2$, one would get cross +terms. Superposition is especially useful when $F(t)$ can be written +as a sum of sinusoidal terms, because the solutions for each +sinusoidal (sine or cosine) term is analytic. + +Driving forces are often periodic, even when they are not +sinusoidal. Periodicity implies that for some time $\tau$ + +!bt +\begin{eqnarray} +F(t+\tau)=F(t). +\end{eqnarray} +!et + +One example of a non-sinusoidal periodic force is a square wave. Many +components in electric circuits are non-linear, e.g. diodes, which +makes many wave forms non-sinusoidal even when the circuits are being +driven by purely sinusoidal sources. + + +The code here shows a typical example of such a square wave generated using the functionality included in the _scipy_ Python package. We have used a period of $\tau=0.2$. + +!bc pycod +import numpy as np +import math +from scipy import signal +import matplotlib.pyplot as plt + +# number of points +n = 500 +# start and final times +t0 = 0.0 +tn = 1.0 +# Period +t = np.linspace(t0, tn, n, endpoint=False) +SqrSignal = np.zeros(n) +SqrSignal = 1.0+signal.square(2*np.pi*5*t) +plt.plot(t, SqrSignal) +plt.ylim(-0.5, 2.5) +plt.show() +!ec + + +For the sinusoidal example the +period is $\tau=2\pi/\omega$. However, higher harmonics can also +satisfy the periodicity requirement. In general, any force that +satisfies the periodicity requirement can be expressed as a sum over +harmonics, + +!bt +\begin{equation} +F(t)=\frac{f_0}{2}+\sum_{n>0} f_n\cos(2n\pi t/\tau)+g_n\sin(2n\pi t/\tau). +\end{equation} +!et + + +We can write down the answer for +$x_{pn}(t)$, by substituting $f_n/m$ or $g_n/m$ for $F_0/m$. By +writing each factor $2n\pi t/\tau$ as $n\omega t$, with $\omega\equiv +2\pi/\tau$, + +!bt +\begin{equation} +label{eq:fourierdef1} +F(t)=\frac{f_0}{2}+\sum_{n>0}f_n\cos(n\omega t)+g_n\sin(n\omega t). +\end{equation} +!et + +The solutions for $x(t)$ then come from replacing $\omega$ with +$n\omega$ for each term in the particular solution, + +!bt +\begin{eqnarray} +x_p(t)&=&\frac{f_0}{2k}+\sum_{n>0} \alpha_n\cos(n\omega t-\delta_n)+\beta_n\sin(n\omega t-\delta_n),\\ +\nonumber +\alpha_n&=&\frac{f_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\ +\nonumber +\beta_n&=&\frac{g_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\ +\nonumber +\delta_n&=&\tan^{-1}\left(\frac{2\beta n\omega}{\omega_0^2-n^2\omega^2}\right). +\end{eqnarray} +!et + + + +Because the forces have been applied for a long time, any non-zero +damping eliminates the homogenous parts of the solution, so one need +only consider the particular solution for each $n$. + +The problem is considered solved if one can find expressions for the +coefficients $f_n$ and $g_n$, even though the solutions are expressed +as an infinite sum. The coefficients can be extracted from the +function $F(t)$ by + +!bt +\begin{eqnarray} +label{eq:fourierdef2} +f_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\cos(2n\pi t/\tau),\\ +\nonumber +g_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\sin(2n\pi t/\tau). +\end{eqnarray} +!et + +To check the consistency of these expressions and to verify +Eq. (ref{eq:fourierdef2}), one can insert the expansion of $F(t)$ in +Eq. (ref{eq:fourierdef1}) into the expression for the coefficients in +Eq. (ref{eq:fourierdef2}) and see whether + +!bt +\begin{eqnarray} +f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~\left\{ +\frac{f_0}{2}+\sum_{m>0}f_m\cos(m\omega t)+g_m\sin(m\omega t) +\right\}\cos(n\omega t). +\end{eqnarray} +!et + +Immediately, one can throw away all the terms with $g_m$ because they +convolute an even and an odd function. The term with $f_0/2$ +disappears because $\cos(n\omega t)$ is equally positive and negative +over the interval and will integrate to zero. For all the terms +$f_m\cos(m\omega t)$ appearing in the sum, one can use angle addition +formulas to see that $\cos(m\omega t)\cos(n\omega +t)=(1/2)(\cos[(m+n)\omega t]+\cos[(m-n)\omega t]$. This will integrate +to zero unless $m=n$. In that case the $m=n$ term gives + +!bt +\begin{equation} +\int_{-\tau/2}^{\tau/2}dt~\cos^2(m\omega t)=\frac{\tau}{2}, +\end{equation} +!et + +and + +!bt +\begin{eqnarray} +f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~f_n/2\\ +\nonumber +&=&f_n~\checkmark. +\end{eqnarray} +!et + +The same method can be used to check for the consistency of $g_n$. + + + + +The code here uses the Fourier series applied to a +square wave signal. The code here +visualizes the various approximations given by Fourier series compared +with a square wave with period $T=0.2$ (dimensionless time), width $0.1$ and max value of the force $F=2$. We +see that when we increase the number of components in the Fourier +series, the Fourier series approximation gets closer and closer to the +square wave signal. + +!bc pycod +import numpy as np +import math +from scipy import signal +import matplotlib.pyplot as plt + +# number of points +n = 500 +# start and final times +t0 = 0.0 +tn = 1.0 +# Period +T =0.2 +# Max value of square signal +Fmax= 2.0 +# Width of signal +Width = 0.1 +t = np.linspace(t0, tn, n, endpoint=False) +SqrSignal = np.zeros(n) +FourierSeriesSignal = np.zeros(n) +SqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T) +a0 = Fmax*Width/T +FourierSeriesSignal = a0 +Factor = 2.0*Fmax/np.pi +for i in range(1,500): + FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T) +plt.plot(t, SqrSignal) +plt.plot(t, FourierSeriesSignal) +plt.ylim(-0.5, 2.5) +plt.show() +!ec + + + +===== Two-dimensional Objects ===== + +We often use convolutions over more than one dimension at a time. If +we have a two-dimensional image $I$ as input, we can have a _filter_ +defined by a two-dimensional _kernel_ $K$. This leads to an output $S$ + +!bt +\[ +S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(m,n)K(i-m,j-n). +\] +!et + +Convolution is a commutatitave process, which means we can rewrite this equation as +!bt +\[ +S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i-m,j-n)K(m,n). +\] +!et + +Normally the latter is more straightforward to implement in a machine elarning library since there is less variation in the range of values of $m$ and $n$. + + +Many deep learning libraries implement cross-correlation instead of convolution +!bt +\[ +S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i+m,j-+)K(m,n). +\] +!et + + +===== More on Dimensionalities ===== + +In fields like signal processing (and imaging as well), one designs +so-called filters. These filters are defined by the convolutions and +are often hand-crafted. One may specify filters for smoothing, edge +detection, frequency reshaping, and similar operations. However with +neural networks the idea is to automatically learn the filters and use +many of them in conjunction with non-linear operations (activation +functions). + +As an example consider a neural network operating on sound sequence +data. Assume that we an input vector $\bm{x}$ of length $d=10^6$. We +construct then a neural network with onle hidden layer only with +$10^4$ nodes. This means that we will have a weight matrix with +$10^4\times 10^6=10^{10}$ weights to be determined, together with $10^4$ biases. + +Assume furthermore that we have an output layer which is meant to train whether the sound sequence represents a human voice (true) or something else (false). +It means that we have only one output node. But since this output node connects to $10^4$ nodes in the hidden layer, there are in total $10^4$ weights to be determined for the output layer, plus one bias. In total we have + +!bt +\[ +\mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \approx 10^{10}, +\] +!et +that is ten billion parameters to determine. + + +===== Further Dimensionality Remarks ===== + +In today’s architecture one can train such neural networks, however +this is a huge number of parameters for the task at hand. In general, +it is a very wasteful and inefficient use of dense matrices as +parameters. Just as importantly, such trained network parameters are +very specific for the type of input data on which they were trained +and the network is not likely to generalize easily to variations in +the input. + + +The main principles that justify convolutions is locality of +information and repetion of patterns within the signal. Sound samples +of the input in adjacent spots are much more likely to affect each +other than those that are very far away. Similarly, sounds are +repeated in multiple times in the signal. While slightly simplistic, +reasoning about such a sound example demonstrates this. The same +principles then apply to images and other similar data. + + + ===== CNNs in more detail, building convolutional neural networks in Tensorflow and Keras ===== @@ -138,6 +613,7 @@ dataset of images, we require a 4D matrix or _tensor_. This tensor has the dimen !et +=== The MNIST dataset again === The MNIST dataset consists of grayscale images with a pixel size of $28\times 28$, meaning we require $28 \times 28 = 724$ weights to each @@ -183,6 +659,7 @@ small regions, and this serves as input to the next convolutional layer. +=== Systematic reduction === By systematically reducing the size of the input volume, through convolution and pooling, the network should create representations of @@ -194,7 +671,6 @@ then serves as input to the output layer, e.g. a softmax output for classification. - === Prerequisites: Collect and pre-process data === !bc pycod # import necessary packages @@ -240,7 +716,7 @@ plt.show() !ec -=== Importing Keras and Tensorflow === + !bc pycod from tensorflow.keras import datasets, layers, models from tensorflow.keras.layers import Input @@ -297,6 +773,7 @@ lmbd_vals = np.logspace(-5, 1, 7) !ec + !bc pycod CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) @@ -316,8 +793,8 @@ for i, eta in enumerate(eta_vals): print() !ec +!split -=== Final visualization === !bc pycod # visual representation of grid search @@ -378,7 +855,6 @@ train_images, test_images = train_images / 255.0, test_images / 255.0 - To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image. !bc pycod @@ -399,7 +875,7 @@ plt.show() !ec -The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers. +The six lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers. As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer. @@ -420,6 +896,8 @@ You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tenso + + To complete our model, you will feed the last output tensor from the convolutional base (of shape (4, 4, 64)) into one or more Dense layers to perform classification. Dense layers take vectors as input (which @@ -438,7 +916,6 @@ model.summary() !ec As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers. -Compile and train the model. !bc pycod model.compile(optimizer='adam', @@ -450,7 +927,7 @@ history = model.fit(train_images, train_labels, epochs=10, !ec -Finally, we evaluate the model. + !bc pycod plt.plot(history.history['accuracy'], label='accuracy') @@ -468,99 +945,7 @@ print(test_acc) -===== Recurrent neural networks: Overarching view ===== - -Till now our focus has been, including convolutional neural networks -as well, on feedforward neural networks. The output or the activations -flow only in one direction, from the input layer to the output layer. - -A recurrent neural network (RNN) looks very much like a feedforward -neural network, except that it also has connections pointing -backward. - -RNNs are used to analyze time series data such as stock prices, and -tell you when to buy or sell. In autonomous driving systems, they can -anticipate car trajectories and help avoid accidents. More generally, -they can work on sequences of arbitrary lengths, rather than on -fixed-sized inputs like all the nets we have discussed so far. For -example, they can take sentences, documents, or audio samples as -input, making them extremely useful for natural language processing -systems such as automatic translation and speech-to-text. -=== A simple example === - -!bc pycod -# Start importing packages -import pandas as pd -import numpy as np -import matplotlib.pyplot as plt -import tensorflow as tf -from tensorflow.keras import datasets, layers, models -from tensorflow.keras.layers import Input -from tensorflow.keras.models import Model, Sequential -from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU -from tensorflow.keras import optimizers -from tensorflow.keras import regularizers -from tensorflow.keras.utils import to_categorical - - - -# convert into dataset matrix -def convertToMatrix(data, step): - X, Y =[], [] - for i in range(len(data)-step): - d=i+step - X.append(data[i:d,]) - Y.append(data[d,]) - return np.array(X), np.array(Y) - -step = 4 -N = 1000 -Tp = 800 - -t=np.arange(0,N) -x=np.sin(0.02*t)+2*np.random.rand(N) -df = pd.DataFrame(x) -df.head() - -plt.plot(df) -plt.show() - -values=df.values -train,test = values[0:Tp,:], values[Tp:N,:] - -# add step elements into train and test -test = np.append(test,np.repeat(test[-1,],step)) -train = np.append(train,np.repeat(train[-1,],step)) - -trainX,trainY =convertToMatrix(train,step) -testX,testY =convertToMatrix(test,step) -trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1])) -testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1])) - -model = Sequential() -model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu")) -model.add(Dense(8, activation="relu")) -model.add(Dense(1)) -model.compile(loss='mean_squared_error', optimizer='rmsprop') -model.summary() - -model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2) -trainPredict = model.predict(trainX) -testPredict= model.predict(testX) -predicted=np.concatenate((trainPredict,testPredict),axis=0) - -trainScore = model.evaluate(trainX, trainY, verbose=0) -print(trainScore) - -index = df.index.values -plt.plot(index,df) -plt.plot(index,predicted) -plt.axvline(df.index[Tp], c="r") -plt.show() -!ec - - diff --git a/doc/BookChapters/chapter13.do.txt b/doc/BookChapters/chapter13.do.txt new file mode 100644 index 000000000..42755dbf7 --- /dev/null +++ b/doc/BookChapters/chapter13.do.txt @@ -0,0 +1,1246 @@ +======= Recurrent neural networks: Overarching view ======= + +Till now our focus has been, including convolutional neural networks +as well, on feedforward neural networks. The output or the activations +flow only in one direction, from the input layer to the output layer. + +A recurrent neural network (RNN) looks very much like a feedforward +neural network, except that it also has connections pointing +backward. + +RNNs are used to analyze time series data such as stock prices, and +tell you when to buy or sell. In autonomous driving systems, they can +anticipate car trajectories and help avoid accidents. More generally, +they can work on sequences of arbitrary lengths, rather than on +fixed-sized inputs like all the nets we have discussed so far. For +example, they can take sentences, documents, or audio samples as +input, making them extremely useful for natural language processing +systems such as automatic translation and speech-to-text. + + + + +More to text to be added + + +===== A simple example ===== + +!bc pycod +# Start importing packages +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +import tensorflow as tf +from tensorflow.keras import datasets, layers, models +from tensorflow.keras.layers import Input +from tensorflow.keras.models import Model, Sequential +from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU +from tensorflow.keras import optimizers +from tensorflow.keras import regularizers +from tensorflow.keras.utils import to_categorical + + + +# convert into dataset matrix +def convertToMatrix(data, step): + X, Y =[], [] + for i in range(len(data)-step): + d=i+step + X.append(data[i:d,]) + Y.append(data[d,]) + return np.array(X), np.array(Y) + +step = 4 +N = 1000 +Tp = 800 + +t=np.arange(0,N) +x=np.sin(0.02*t)+2*np.random.rand(N) +df = pd.DataFrame(x) +df.head() + +plt.plot(df) +plt.show() + +values=df.values +train,test = values[0:Tp,:], values[Tp:N,:] + +# add step elements into train and test +test = np.append(test,np.repeat(test[-1,],step)) +train = np.append(train,np.repeat(train[-1,],step)) + +trainX,trainY =convertToMatrix(train,step) +testX,testY =convertToMatrix(test,step) +trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1])) +testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1])) + +model = Sequential() +model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu")) +model.add(Dense(8, activation="relu")) +model.add(Dense(1)) +model.compile(loss='mean_squared_error', optimizer='rmsprop') +model.summary() + +model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2) +trainPredict = model.predict(trainX) +testPredict= model.predict(testX) +predicted=np.concatenate((trainPredict,testPredict),axis=0) + +trainScore = model.evaluate(trainX, trainY, verbose=0) +print(trainScore) + +index = df.index.values +plt.plot(index,df) +plt.plot(index,predicted) +plt.axvline(df.index[Tp], c="r") +plt.show() +!ec + + + +===== An extrapolation example ===== + +The following code provides an example of how recurrent neural +networks can be used to extrapolate to unknown values of physics data +sets. Specifically, the data sets used in this program come from +a quantum mechanical many-body calculation of energies as functions of the number of particles. + + +!bc pycod + +# For matrices and calculations +import numpy as np +# For machine learning (backend for keras) +import tensorflow as tf +# User-friendly machine learning library +# Front end for TensorFlow +import tensorflow.keras +# Different methods from Keras needed to create an RNN +# This is not necessary but it shortened function calls +# that need to be used in the code. +from tensorflow.keras import datasets, layers, models +from tensorflow.keras.layers import Input +from tensorflow.keras import regularizers +from tensorflow.keras.models import Model, Sequential +from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU +# For timing the code +from timeit import default_timer as timer +# For plotting +import matplotlib.pyplot as plt + + +# The data set +datatype='VaryDimension' +X_tot = np.arange(2, 42, 2) +y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846, + -0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, + -1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767]) + +!ec + + +The way the recurrent neural networks are trained in this program +differs from how machine learning algorithms are usually trained. +Typically a machine learning algorithm is trained by learning the +relationship between the x data and the y data. In this program, the +recurrent neural network will be trained to recognize the relationship +in a sequence of y values. This is type of data formatting is +typically used time series forcasting, but it can also be used in any +extrapolation (time series forecasting is just a specific type of +extrapolation along the time axis). This method of data formatting +does not use the x data and assumes that the y data are evenly spaced. + +For a standard machine learning algorithm, the training data has the +form of (x,y) so the machine learning algorithm learns to assiciate a +y value with a given x value. This is useful when the test data has x +values within the same range as the training data. However, for this +application, the x values of the test data are outside of the x values +of the training data and the traditional method of training a machine +learning algorithm does not work as well. For this reason, the +recurrent neural network is trained on sequences of y values of the +form ((y1, y2), y3), so that the network is concerned with learning +the pattern of the y data and not the relation between the x and y +data. As long as the pattern of y data outside of the training region +stays relatively stable compared to what was inside the training +region, this method of training can produce accurate extrapolations to +y values far removed from the training data set. + + + +!bc pycod +# FORMAT_DATA +def format_data(data, length_of_sequence = 2): + """ + Inputs: + data(a numpy array): the data that will be the inputs to the recurrent neural + network + length_of_sequence (an int): the number of elements in one iteration of the + sequence patter. For a function approximator use length_of_sequence = 2. + Returns: + rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its + dimensions are length of data - length of sequence, length of sequence, + dimnsion of data + rnn_output (a numpy array): the training data for the neural network + Formats data to be used in a recurrent neural network. + """ + + X, Y = [], [] + for i in range(len(data)-length_of_sequence): + # Get the next length_of_sequence elements + a = data[i:i+length_of_sequence] + # Get the element that immediately follows that + b = data[i+length_of_sequence] + # Reshape so that each data point is contained in its own array + a = np.reshape (a, (len(a), 1)) + X.append(a) + Y.append(b) + rnn_input = np.array(X) + rnn_output = np.array(Y) + + return rnn_input, rnn_output + + +# ## Defining the Recurrent Neural Network Using Keras +# +# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer. + +def rnn(length_of_sequences, batch_size = None, stateful = False): + """ + Inputs: + length_of_sequences (an int): the number of y values in "x data". This is determined + when the data is formatted + batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. + stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. + Returns: + model (a Keras model): The recurrent neural network that is built and compiled by this + method + Builds and compiles a recurrent neural network with one hidden layer and returns the model. + """ + # Number of neurons in the input and output layers + in_out_neurons = 1 + # Number of neurons in the hidden layer + hidden_neurons = 200 + # Define the input layer + inp = Input(batch_shape=(batch_size, + length_of_sequences, + in_out_neurons)) + # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to + # the network immediately after the input layer + rnn = SimpleRNN(hidden_neurons, + return_sequences=False, + stateful = stateful, + name="RNN")(inp) + # Define the output layer as a dense neural network layer (standard neural network layer) + #and add it to the network immediately after the hidden layer. + dens = Dense(in_out_neurons,name="dense")(rnn) + # Create the machine learning model starting with the input layer and ending with the + # output layer + model = Model(inputs=[inp],outputs=[dens]) + # Compile the machine learning model using the mean squared error function as the loss + # function and an Adams optimizer. + model.compile(loss="mean_squared_error", optimizer="adam") + return model + +!ec + +!split +===== Predicting New Points With A Trained Recurrent Neural Network ===== + +!bc pycod +def test_rnn (x1, y_test, plot_min, plot_max): + """ + Inputs: + x1 (a list or numpy array): The complete x component of the data set + y_test (a list or numpy array): The complete y component of the data set + plot_min (an int or float): the smallest x value used in the training data + plot_max (an int or float): the largest x valye used in the training data + Returns: + None. + Uses a trained recurrent neural network model to predict future points in the + series. Computes the MSE of the predicted data set from the true data set, saves + the predicted data set to a csv file, and plots the predicted and true data sets w + while also displaying the data range used for training. + """ + # Add the training data as the first dim points in the predicted data array as these + # are known values. + y_pred = y_test[:dim].tolist() + # Generate the first input to the trained recurrent neural network using the last two + # points of the training data. Based on how the network was trained this means that it + # will predict the first point in the data set after the training data. All of the + # brackets are necessary for Tensorflow. + next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]]) + # Save the very last point in the training data set. This will be used later. + last = [y_test[dim-1]] + + # Iterate until the complete data set is created. + for i in range (dim, len(y_test)): + # Predict the next point in the data set using the previous two points. + next = model.predict(next_input) + # Append just the number of the predicted data set + y_pred.append(next[0][0]) + # Create the input that will be used to predict the next data point in the data set. + next_input = np.array([[last, next[0]]], dtype=np.float64) + last = next + + # Print the mean squared error between the known data set and the predicted data set. + print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean()) + # Save the predicted data set as a csv file for later use + name = datatype + 'Predicted'+str(dim)+'.csv' + np.savetxt(name, y_pred, delimiter=',') + # Plot the known data set and the predicted data set. The red box represents the region that was used + # for the training data. + fig, ax = plt.subplots() + ax.plot(x1, y_test, label="true", linewidth=3) + ax.plot(x1, y_pred, 'g-.',label="predicted", linewidth=4) + ax.legend() + # Created a red region to represent the points used in the training data. + ax.axvspan(plot_min, plot_max, alpha=0.25, color='red') + plt.show() + +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) + +# This is the number of points that will be used in as the training data +dim=12 + +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] + + +# Generate the training data for the RNN, using a sequence of 2 +rnn_input, rnn_training = format_data(y_train, 2) + + +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +model = rnn(length_of_sequences = rnn_input.shape[1]) +model.summary() + +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) + +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) + +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() + +# Use the trained neural network to predict more points of the data set +test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) +!ec + + +Changing the size of the recurrent neural network and its parameters +can drastically change the results you get from the model. The below +code takes the simple recurrent neural network from above and adds a +second hidden layer, changes the number of neurons in the hidden +layer, and explicitly declares the activation function of the hidden +layers to be a sigmoid function. The loss function and optimizer can +also be changed but are kept the same as the above network. These +parameters can be tuned to provide the optimal result from the +network. For some ideas on how to improve the performance of a +"recurrent neural network":"https://danijar.com/tips-for-training-recurrent-neural-networks". + +!bc pycod +def rnn_2layers(length_of_sequences, batch_size = None, stateful = False): + """ + Inputs: + length_of_sequences (an int): the number of y values in "x data". This is determined + when the data is formatted + batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. + stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. + Returns: + model (a Keras model): The recurrent neural network that is built and compiled by this + method + Builds and compiles a recurrent neural network with two hidden layers and returns the model. + """ + # Number of neurons in the input and output layers + in_out_neurons = 1 + # Number of neurons in the hidden layer, increased from the first network + hidden_neurons = 500 + # Define the input layer + inp = Input(batch_shape=(batch_size, + length_of_sequences, + in_out_neurons)) + # Create two hidden layers instead of one hidden layer. Explicitly set the activation + # function to be the sigmoid function (the default value is hyperbolic tangent) + rnn1 = SimpleRNN(hidden_neurons, + return_sequences=True, # This needs to be True if another hidden layer is to follow + stateful = stateful, activation = 'sigmoid', + name="RNN1")(inp) + rnn2 = SimpleRNN(hidden_neurons, + return_sequences=False, activation = 'sigmoid', + stateful = stateful, + name="RNN2")(rnn1) + # Define the output layer as a dense neural network layer (standard neural network layer) + #and add it to the network immediately after the hidden layer. + dens = Dense(in_out_neurons,name="dense")(rnn2) + # Create the machine learning model starting with the input layer and ending with the + # output layer + model = Model(inputs=[inp],outputs=[dens]) + # Compile the machine learning model using the mean squared error function as the loss + # function and an Adams optimizer. + model.compile(loss="mean_squared_error", optimizer="adam") + return model + +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) + +# This is the number of points that will be used in as the training data +dim=12 + +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] + + +# Generate the training data for the RNN, using a sequence of 2 +rnn_input, rnn_training = format_data(y_train, 2) + + +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +model = rnn_2layers(length_of_sequences = 2) +model.summary() + +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) + + +# This section plots the training loss and the validation loss as a function of training iteration. +# This is not required for analyzing the couple cluster data but can help determine if the network is +# being overtrained. +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) + +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() + +# Use the trained neural network to predict more points of the data set +test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) +!ec + + +===== Other Types of Recurrent Neural Networks ===== + +Besides a simple recurrent neural network layer, there are two other +commonly used types of recurrent neural network layers: Long Short +Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short +introduction to these layers see URL:"https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b" +and URL:"https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b". + +The first network created below is similar to the previous network, +but it replaces the SimpleRNN layers with LSTM layers. The second +network below has two hidden layers made up of GRUs, which are +preceeded by two dense (feeddorward) neural network layers. These +dense layers "preprocess" the data before it reaches the recurrent +layers. This architecture has been shown to improve the performance +of recurrent neural networks (see the link above and also +URL:"https://arxiv.org/pdf/1807.02857.pdf". + +!bc pycod +def lstm_2layers(length_of_sequences, batch_size = None, stateful = False): + """ + Inputs: + length_of_sequences (an int): the number of y values in "x data". This is determined + when the data is formatted + batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. + stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. + Returns: + model (a Keras model): The recurrent neural network that is built and compiled by this + method + Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model. + """ + # Number of neurons on the input/output layer and the number of neurons in the hidden layer + in_out_neurons = 1 + hidden_neurons = 250 + # Input Layer + inp = Input(batch_shape=(batch_size, + length_of_sequences, + in_out_neurons)) + # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers) + rnn= LSTM(hidden_neurons, + return_sequences=True, + stateful = stateful, + name="RNN", use_bias=True, activation='tanh')(inp) + rnn1 = LSTM(hidden_neurons, + return_sequences=False, + stateful = stateful, + name="RNN1", use_bias=True, activation='tanh')(rnn) + # Output layer + dens = Dense(in_out_neurons,name="dense")(rnn1) + # Define the midel + model = Model(inputs=[inp],outputs=[dens]) + # Compile the model + model.compile(loss='mean_squared_error', optimizer='adam') + # Return the model + return model + +def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False): + """ + Inputs: + length_of_sequences (an int): the number of y values in "x data". This is determined + when the data is formatted + batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. + stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. + Returns: + model (a Keras model): The recurrent neural network that is built and compiled by this + method + Builds and compiles a recurrent neural network with four hidden layers (two dense followed by + two GRU layers) and returns the model. + """ + # Number of neurons on the input/output layers and hidden layers + in_out_neurons = 1 + hidden_neurons = 250 + # Input layer + inp = Input(batch_shape=(batch_size, + length_of_sequences, + in_out_neurons)) + # Hidden Dense (feedforward) layers + dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp) + dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn) + # Hidden GRU layers + rnn1 = GRU(hidden_neurons, + return_sequences=True, + stateful = stateful, + name="RNN1", use_bias=True)(dnn1) + rnn = GRU(hidden_neurons, + return_sequences=False, + stateful = stateful, + name="RNN", use_bias=True)(rnn1) + # Output layer + dens = Dense(in_out_neurons,name="dense")(rnn) + # Define the model + model = Model(inputs=[inp],outputs=[dens]) + # Compile the mdoel + model.compile(loss='mean_squared_error', optimizer='adam') + # Return the model + return model + +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) + +# This is the number of points that will be used in as the training data +dim=12 + +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] + + +# Generate the training data for the RNN, using a sequence of 2 +rnn_input, rnn_training = format_data(y_train, 2) + + +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +# Change the method name to reflect which network you want to use +model = dnn2_gru2(length_of_sequences = 2) +model.summary() + +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) + + +# This section plots the training loss and the validation loss as a function of training iteration. +# This is not required for analyzing the couple cluster data but can help determine if the network is +# being overtrained. +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) + +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() + +# Use the trained neural network to predict more points of the data set +test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) + + +# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data) +# +# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation. + +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) + +# This is the number of points that will be used in as the training data +dim=12 + +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] + +# Reshape the data for Keras specifications +X_train = X_train.reshape((dim, 1)) +y_train = y_train.reshape((dim, 1)) + + +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +# Set the sequence length to 1 for regular data formatting +model = rnn(length_of_sequences = 1) +model.summary() + +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(X_train, y_train, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) + + +# This section plots the training loss and the validation loss as a function of training iteration. +# This is not required for analyzing the couple cluster data but can help determine if the network is +# being overtrained. +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) + +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() + +# Use the trained neural network to predict the remaining data points +X_pred = X_tot[dim:] +X_pred = X_pred.reshape((len(X_pred), 1)) +y_model = model.predict(X_pred) +y_pred = np.concatenate((y_tot[:dim], y_model.flatten())) + +# Plot the known data set and the predicted data set. The red box represents the region that was used +# for the training data. +fig, ax = plt.subplots() +ax.plot(X_tot, y_tot, label="true", linewidth=3) +ax.plot(X_tot, y_pred, 'g-.',label="predicted", linewidth=4) +ax.legend() +# Created a red region to represent the points used in the training data. +ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red') +plt.show() + +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) + +!ec + + + + + + +======= Generative Models ======= + +_Generative models_ describe a class of statistical models that are a contrast +to _discriminative models_. Informally we say that generative models can +generate new data instances while discriminative models discriminate between +different kinds of data instances. A generative model could generate new photos +of animals that look like 'real' animals while a discriminative model could tell +a dog from a cat. More formally, given a data set $x$ and a set of labels / +targets $y$. Generative models capture the joint probability $p(x, y)$, or +just $p(x)$ if there are no labels, while discriminative models capture the +conditional probability $p(y | x)$. Discriminative models generally try to draw +boundaries in the data space (often high dimensional), while generative models +try to model how data is placed throughout the space. + +_Note_: this material is thanks to Linus Ekstrøm. + +===== Generative Adversarial Networks ===== + +_Generative Adversarial Networks_ are a type of unsupervised machine learning +algorithm proposed by "Goodfellow et. al": "https://arxiv.org/pdf/1406.2661.pdf" +in 2014 (short and good article). + +The simplest formulation of +the model is based on a game theoretic approach, *zero sum game*, where we pit +two neural networks against one another. We define two rival networks, one +generator $g$, and one discriminator $d$. The generator directly produces +samples +!bt +\begin{equation} + x = g(z; \theta^{(g)}) +\end{equation} +!et + + +The discriminator attempts to distinguish between samples drawn from the +training data and samples drawn from the generator. In other words, it tries to +tell the difference between the fake data produced by $g$ and the actual data +samples we want to do prediction on. The discriminator outputs a probability +value given by + +!bt +\begin{equation} + d(x; \theta^{(d)}) +\end{equation} +!et + +indicating the probability that $x$ is a real training example rather than a +fake sample the generator has generated. The simplest way to formulate the +learning process in a generative adversarial network is a zero-sum game, in +which a function + +!bt +\begin{equation} + v(\theta^{(g)}, \theta^{(d)}) +\end{equation} +!et + +determines the reward for the discriminator, while the generator gets the +conjugate reward + +!bt +\begin{equation} + -v(\theta^{(g)}, \theta^{(d)}) +\end{equation} +!et + + + +During learning both of the networks maximize their own reward function, so that +the generator gets better and better at tricking the discriminator, while the +discriminator gets better and better at telling the difference between the fake +and real data. The generator and discriminator alternate on which one trains at +one time (i.e. for one epoch). In other words, we keep the generator constant +and train the discriminator, then we keep the discriminator constant to train +the generator and repeat. It is this back and forth dynamic which lets GANs +tackle otherwise intractable generative problems. As the generator improves with + training, the discriminator's performance gets worse because it cannot easily + tell the difference between real and fake. If the generator ends up succeeding + perfectly, the the discriminator will do no better than random guessing i.e. + 50\%. This progression in the training poses a problem for the convergence + criteria for GANs. The discriminator feedback gets less meaningful over time, + if we continue training after this point then the generator is effectively + training on junk data which can undo the learning up to that point. Therefore, + we stop training when the discriminator starts outputting $1/2$ everywhere. + + + +At convergence we have + +!bt +\begin{equation} + g^* = \underset{g}{\mathrm{argmin}}\hspace{2pt} + \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) +\end{equation} +!et +The default choice for $v$ is +!bt +\begin{equation} + v(\theta^{(g)}, \theta^{(d)}) = \mathbb{E}_{x\sim p_\mathrm{data}}\log d(x) + + \mathbb{E}_{x\sim p_\mathrm{model}} + \log (1 - d(x)) +\end{equation} +!et +The main motivation for the design of GANs is that the learning process requires +neither approximate inference (variational autoencoders for example) nor +approximation of a partition function. In the case where +!bt +\begin{equation} + \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) +\end{equation} +!et +is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is +asymptotically consistent +( "Seth Lloyd on QuGANs": "https://arxiv.org/pdf/1804.09139.pdf" ). + + +This is in +general not the case and it is possible to get situations where the training +process never converges because the generator and discriminator chase one +another around in the parameter space indefinitely. A much deeper discussion on +the currently open research problem of GAN convergence is available +"here": "https://www.deeplearningbook.org/contents/generative_models.html". To +anyone interested in learning more about GANs it is a highly recommended read. +Direct quote: "In this best-performing formulation, the generator aims to +increase the log probability that the discriminator makes a mistake, rather than +aiming to decrease the log probability that the discriminator makes the correct +prediction." "Another interesting read": "https://arxiv.org/abs/1701.00160" + + + +===== Writing Our First Generative Adversarial Network ===== +Let us now move on to actually implementing a GAN in tensorflow. We will study +the performance of our GAN on the MNIST dataset. This code is based on and +adapted from the +"google tutorial": "https://www.tensorflow.org/tutorials/generative/dcgan" + +First we import our libraries + +!bc pycod +import os +import time +import numpy as np +import tensorflow as tf +import matplotlib.pyplot as plt +from tensorflow.keras import layers +from tensorflow.keras.utils import plot_model +!ec + +Next we define our hyperparameters and import our data the usual way + +!bc pycod +BUFFER_SIZE = 60000 +BATCH_SIZE = 256 +EPOCHS = 30 + +data = tf.keras.datasets.mnist.load_data() +(train_images, train_labels), (test_images, test_labels) = data +train_images = np.reshape(train_images, (train_images.shape[0], + 28, + 28, + 1)).astype('float32') + +# we normalize between -1 and 1 +train_images = (train_images - 127.5) / 127.5 +training_dataset = tf.data.Dataset.from_tensor_slices( + train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE) +!ec + + +=== MNIST and GANs === + +Let's have a quick look + +!bc pycod +plt.imshow(train_images[0], cmap='Greys') +plt.show() +!ec + +Now we define our two models. This is where the 'magic' happens. There are a +huge amount of possible formulations for both models. A lot of engineering and +trial and error can be done here to try to produce better performing models. For +more advanced GANs this is by far the step where you can 'make or break' a +model. + +We start with the generator. As stated in the introductory text the generator +$g$ upsamples from a random sample to the shape of what we want to predict. In +our case we are trying to predict MNIST images ($28\times 28$ pixels). + +!bc pycod +def generator_model(): + """ + The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to + produce an image from a random seed. We start with a Dense layer taking this + random sample as an input and subsequently upsample through multiple + convolutional layers. + """ + + # we define our model + model = tf.keras.Sequential() + + + # adding our input layer. Dense means that every neuron is connected and + # the input shape is the shape of our random noise. The units need to match + # in some sense the upsampling strides to reach our desired output shape. + # we are using 100 random numbers as our seed + model.add(layers.Dense(units=7*7*BATCH_SIZE, + use_bias=False, + input_shape=(100, ))) + # we normalize the output form the Dense layer + model.add(layers.BatchNormalization()) + # and add an activation function to our 'layer'. LeakyReLU avoids vanishing + # gradient problem + model.add(layers.LeakyReLU()) + model.add(layers.Reshape((7, 7, BATCH_SIZE))) + assert model.output_shape == (None, 7, 7, BATCH_SIZE) + # even though we just added four keras layers we think of everything above + # as 'one' layer + + # next we add our upscaling convolutional layers + model.add(layers.Conv2DTranspose(filters=128, + kernel_size=(5, 5), + strides=(1, 1), + padding='same', + use_bias=False)) + model.add(layers.BatchNormalization()) + model.add(layers.LeakyReLU()) + assert model.output_shape == (None, 7, 7, 128) + + model.add(layers.Conv2DTranspose(filters=64, + kernel_size=(5, 5), + strides=(2, 2), + padding='same', + use_bias=False)) + model.add(layers.BatchNormalization()) + model.add(layers.LeakyReLU()) + assert model.output_shape == (None, 14, 14, 64) + + model.add(layers.Conv2DTranspose(filters=1, + kernel_size=(5, 5), + strides=(2, 2), + padding='same', + use_bias=False, + activation='tanh')) + assert model.output_shape == (None, 28, 28, 1) + + return model + +!ec + +And there we have our 'simple' generator model. Now we move on to defining our +discriminator model $d$, which is a convolutional neural network based image +classifier. + +!bc pycod +def discriminator_model(): + """ + The discriminator is a convolutional neural network based image classifier + """ + + # we define our model + model = tf.keras.Sequential() + model.add(layers.Conv2D(filters=64, + kernel_size=(5, 5), + strides=(2, 2), + padding='same', + input_shape=[28, 28, 1])) + model.add(layers.LeakyReLU()) + # adding a dropout layer as you do in conv-nets + model.add(layers.Dropout(0.3)) + + + model.add(layers.Conv2D(filters=128, + kernel_size=(5, 5), + strides=(2, 2), + padding='same')) + model.add(layers.LeakyReLU()) + # adding a dropout layer as you do in conv-nets + model.add(layers.Dropout(0.3)) + + model.add(layers.Flatten()) + model.add(layers.Dense(1)) + + return model +!ec + + + +Let us take a look at our models. + +!bc pycod +generator = generator_model() +plot_model(generator, show_shapes=True, rankdir='LR') +!ec + +!bc pycod +discriminator = discriminator_model() +plot_model(discriminator, show_shapes=True, rankdir='LR') +!ec + +Next we need a few helper objects we will use in training + +!bc pycod +cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True) +generator_optimizer = tf.keras.optimizers.Adam(1e-4) +discriminator_optimizer = tf.keras.optimizers.Adam(1e-4) +!ec + +The first object, *cross_entropy* is our loss function and the two others are +our optimizers. Notice we use the same learning rate for both $g$ and $d$. This +is because they need to improve their accuracy at approximately equal speeds to +get convergence (not necessarily exactly equal). Now we define our loss +functions + +!bc pycod +def generator_loss(fake_output): + loss = cross_entropy(tf.ones_like(fake_output), fake_output) + + return loss +!ec + +!bc pycod +def discriminator_loss(real_output, fake_output): + real_loss = cross_entropy(tf.ones_like(real_output), real_output) + fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output) + total_loss = real_loss + fake_loss + + return total_loss +!ec + +Next we define a kind of seed to help us compare the learning process over +multiple training epochs. + +!bc pycod +noise_dimension = 100 +n_examples_to_generate = 16 +seed_images = tf.random.normal([n_examples_to_generate, noise_dimension]) +!ec + + +Now we have everything we need to define our training step, which we will apply +for every step in our training loop. Notice the @tf.function flag signifying +that the function is tensorflow 'compiled'. Removing this flag doubles the +computation time. + +!bc pycod +@tf.function +def train_step(images): + noise = tf.random.normal([BATCH_SIZE, noise_dimension]) + + with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: + generated_images = generator(noise, training=True) + + real_output = discriminator(images, training=True) + fake_output = discriminator(generated_images, training=True) + + gen_loss = generator_loss(fake_output) + disc_loss = discriminator_loss(real_output, fake_output) + + gradients_of_generator = gen_tape.gradient(gen_loss, + generator.trainable_variables) + gradients_of_discriminator = disc_tape.gradient(disc_loss, + discriminator.trainable_variables) + generator_optimizer.apply_gradients(zip(gradients_of_generator, + generator.trainable_variables)) + discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, + discriminator.trainable_variables)) + + return gen_loss, disc_loss +!ec + + +Next we define a helper function to produce an output over our training epochs +to see the predictive progression of our generator model. _Note_: I am including +this code here, but comment it out in the training loop. +!bc pycod +def generate_and_save_images(model, epoch, test_input): + # we're making inferences here + predictions = model(test_input, training=False) + + fig = plt.figure(figsize=(4, 4)) + + for i in range(predictions.shape[0]): + plt.subplot(4, 4, i+1) + plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray') + plt.axis('off') + + plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png') + plt.close() + #plt.show() +!ec + + + +Setting up checkpoints to periodically save our model during training so that +everything is not lost even if the program were to somehow terminate while +training. + +!bc pycod +# Setting up checkpoints to save model during training +checkpoint_dir = './training_checkpoints' +checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt') +checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer, + discriminator_optimizer=discriminator_optimizer, + generator=generator, + discriminator=discriminator) +!ec + +Now we define our training loop + +!bc pycod +def train(dataset, epochs): + generator_loss_list = [] + discriminator_loss_list = [] + + for epoch in range(epochs): + start = time.time() + + for image_batch in dataset: + gen_loss, disc_loss = train_step(image_batch) + generator_loss_list.append(gen_loss.numpy()) + discriminator_loss_list.append(disc_loss.numpy()) + + #generate_and_save_images(generator, epoch + 1, seed_images) + + if (epoch + 1) % 15 == 0: + checkpoint.save(file_prefix=checkpoint_prefix) + + print(f'Time for epoch {epoch} is {time.time() - start}') + + #generate_and_save_images(generator, epochs, seed_images) + + loss_file = './data/lossfile.txt' + with open(loss_file, 'w') as outfile: + outfile.write(str(generator_loss_list)) + outfile.write('\n') + outfile.write('\n') + outfile.write(str(discriminator_loss_list)) + outfile.write('\n') + outfile.write('\n') +!ec + + +To train simply call this function. _Warning_: this might take a long time so +there is a folder of a pretrained network already included in the repository. + +!bc pycod +train(train_dataset, EPOCHS) +!ec + + +Now to avoid having to train and everything, which will take a while depending +on your computer setup we now load in the model which produced the above gif. + +!bc pycod +checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir)) +restored_generator = checkpoint.generator +restored_discriminator = checkpoint.discriminator + +print(restored_generator) +print(restored_discriminator) +!ec + + + +We have successfully loaded in our latest model. Let us now play around a bit +and see what kind of things we can learn about this model. Our generator takes +an array of 100 numbers. One idea can be to try to systematically change our +input. Let us try and see what we get + +!bc pycod +def generate_latent_points(number=100, scale_means=1, scale_stds=1): + latent_dim = 100 + means = scale_means * tf.linspace(-1, 1, num=latent_dim) + stds = scale_stds * tf.linspace(-1, 1, num=latent_dim) + latent_space_value_range = tf.random.normal([number, latent_dim], + means, + stds, + dtype=tf.float64) + + return latent_space_value_range + +def generate_images(latent_points): + # notice we set training to false because we are making inferences + generated_images = restored_generator.predict(latent_points) + + return generated_images +!ec + +!bc pycod +def plot_result(generated_images, number=100): + # obviously this assumes sqrt number is an int + fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)), + figsize=(10, 10)) + + for i in range(int(np.sqrt(number))): + for j in range(int(np.sqrt(number))): + axs[i, j].imshow(generated_images[i*j], cmap='Greys') + axs[i, j].axis('off') + + plt.show() +!ec + +!bc pycod +generated_images = generate_images(generate_latent_points()) +plot_result(generated_images) +!ec + + +We see that the generator generates images that look like MNIST +numbers: $1, 4, 7, 9$. Let's try to tweak it a bit more to see if we are able +to generate a similar plot where we generate every MNIST number. Let us now try +to 'move' a bit around in the latent space. _Note_: decrease the plot number if +these following cells take too long to run on your computer. + +!bc pycod +plot_number = 225 + +generated_images = generate_images(generate_latent_points(number=plot_number, + scale_means=5, + scale_stds=1)) +plot_result(generated_images, number=plot_number) + +generated_images = generate_images(generate_latent_points(number=plot_number, + scale_means=-5, + scale_stds=1)) +plot_result(generated_images, number=plot_number) + +generated_images = generate_images(generate_latent_points(number=plot_number, + scale_means=1, + scale_stds=5)) +plot_result(generated_images, number=plot_number) +!ec + +Again, we have found something interesting. *Moving* around using our means +takes us from digit to digit, while *moving* around using our standard +deviations seem to increase the number of different digits! In the last image +above, we can barely make out every MNIST digit. Let us make on last plot using +this information by upping the standard deviation of our Gaussian noises. + +!bc pycod +plot_number = 400 +generated_images = generate_images(generate_latent_points(number=plot_number, + scale_means=1, + scale_stds=10)) +plot_result(generated_images, number=plot_number) +!ec +A pretty cool result! We see that our generator indeed has learned a +distribution which qualitatively looks a whole lot like the MNIST dataset. + + +Another interesting way to explore the latent space of our generator model is by +interpolating between the MNIST digits. This section is largely based on +"this excellent blogpost": "https://machinelearningmastery.com/how-to-interpolate-and-perform-vector-arithmetic-with-faces-using-a-generative-adversarial-network/" +by Jason Brownlee. + +So let us start by defining a function to interpolate between two points in the +latent space. + +!bc pycod +def interpolation(point_1, point_2, n_steps=10): + ratios = np.linspace(0, 1, num=n_steps) + vectors = [] + for i, ratio in enumerate(ratios): + vectors.append(((1.0 - ratio) * point_1 + ratio * point_2)) + + return tf.stack(vectors) +!ec + +Now we have all we need to do our interpolation analysis. + +!bc pycod +plot_number = 100 +latent_points = generate_latent_points(number=plot_number) +results = None +for i in range(0, 2*np.sqrt(plot_number), 2): + interpolated = interpolation(latent_points[i], latent_points[i+1]) + generated_images = generate_images(interpolated) + + if results is None: + results = generated_images + else: + results = tf.stack((results, generated_images)) + +plot_results(results, plot_number) +!ec + diff --git a/doc/BookChapters/chapteroptimization.do.txt b/doc/BookChapters/chapteroptimization.do.txt index 121e59113..d22d9ead4 100644 --- a/doc/BookChapters/chapteroptimization.do.txt +++ b/doc/BookChapters/chapteroptimization.do.txt @@ -922,7 +922,31 @@ plt.show() -===== Stochastic Gradient Descent ===== +===== Stochastic Gradient Descent (SGD) ===== + +In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set. + +This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. + +In our notes with SGD we mean stochastic gradient descent with mini-batches. + + Stochastic gradient descent (SGD) and variants thereof address some of the shortcomings of the Gradient descent method discussed above. @@ -954,7 +978,6 @@ minibatches. We denote these minibatches by $B_k$ where $k=1,\cdots,n/M$. - As an example, suppose we have $10$ data points $(\mathbf{x}_1,\cdots, \mathbf{x}_{10})$ and we choose to have $M=5$ minibathces, then each minibatch contains two data points. In particular we have @@ -991,11 +1014,12 @@ minibathces (n/M) is commonly referred to as an epoch. Thus it is typical to choose a number of epochs and for each epoch iterate over the number of minibatches, as exemplified in the code below. + !bc pycod import numpy as np n = 100 #100 datapoints -M = 5 #size of each minibatch +M = 5 #size of each mini-batche m = int(n/M) #number of minibatches n_epochs = 10 #number of epochs @@ -1017,7 +1041,6 @@ cheaper since we sum over the datapoints in the $k-th$ minibatch and not all $n$ datapoints. - A natural question is when do we stop the search for a new minimum? One possibility is to compute the full gradient after a given number of epochs and check if the norm of the gradient is smaller than some @@ -1030,7 +1053,6 @@ compare the values of the cost function and keep the $\beta$ that gave the lowest value. - Another approach is to let the step length $\gamma_j$ depend on the number of epochs in such a way that it becomes very small after a reasonable time such that we do not move at all. @@ -1071,37 +1093,41 @@ print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j)) !ec +We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters $t_0$ and $t_1$. + + + === Program for stochastic gradient === !bc pycod # Importing various packages +# Importing various packages from math import exp, sqrt from random import random, seed import numpy as np import matplotlib.pyplot as plt -from sklearn.linear_model import SGDRegressor -m = 100 -x = 2*np.random.rand(m,1) -y = 4+3*x+np.random.randn(m,1) +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) -X = np.c_[np.ones((m,1)), x] +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y) print("Own inversion") print(theta_linreg) -sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1) -sgdreg.fit(x,y.ravel()) -print("sgdreg from scikit") -print(sgdreg.intercept_, sgdreg.coef_) - +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") theta = np.random.randn(2,1) -eta = 0.1 +eta = 1.0/np.max(EigValues) Niterations = 1000 for iter in range(Niterations): - gradients = 2.0/m*X.T @ ((X @ theta)-y) + gradients = 2.0/n*X.T @ ((X @ theta)-y) theta -= eta*gradients print("theta from own gd") print(theta) @@ -1111,8 +1137,9 @@ Xnew = np.c_[np.ones((2,1)), xnew] ypredict = Xnew.dot(theta) ypredict2 = Xnew.dot(theta_linreg) - n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches t0, t1 = 5, 50 def learning_schedule(t): return t0/(t+t1) @@ -1120,16 +1147,20 @@ def learning_schedule(t): theta = np.random.randn(2,1) for epoch in range(n_epochs): +# Can you figure out a better way of setting up the contributions to each batch? for i in range(m): - random_index = np.random.randint(m) - xi = X[random_index:random_index+1] - yi = y[random_index:random_index+1] - gradients = 2 * xi.T @ ((xi @ theta)-yi) + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi) eta = learning_schedule(epoch*m+i) theta = theta - eta*gradients print("theta from own sdg") print(theta) + + + plt.plot(xnew, ypredict, "r-") plt.plot(xnew, ypredict2, "b-") plt.plot(x, y ,'ro') @@ -1142,6 +1173,13 @@ plt.show() !ec +In the above code, we have use replacement in setting up the +mini-batches. The discussion +"here":"https://sebastianraschka.com/faq/docs/sgd-methods.html" may be +useful. More material will be added later. + + + ===== Momentum based GD ===== The stochastic gradient descent (SGD) is almost always used with a @@ -1175,7 +1213,6 @@ earlier. An equivalent way of writing the updates is where we have defined $\Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1}$. - Let us try to get more intuition from these equations. It is helpful to consider a simple physical analogy with a particle of mass $m$ moving in a viscous medium with drag coefficient $\mu$ and potential @@ -1205,7 +1242,6 @@ Rearranging this equation, we can rewrite this as !et - Notice that this equation is identical to previous one if we identify the position of the particle, $\mathbf{w}$, with the parameters $\boldsymbol{\theta}$. This allows us to identify the momentum @@ -1254,6 +1290,7 @@ One of the major advantages of NAG is that it allows for the use of a larger lea + In stochastic gradient descent, with and without momentum, we still have to specify a schedule for tuning the learning rates $\eta_t$ as a function of time. As discussed in the context of Newton's @@ -1272,10 +1309,9 @@ Hessians. Recently, a number of methods have been introduced that accomplish this by tracking not only the gradient, but also the second moment of -the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and +the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and ADAM. - === RMS prop === In RMS prop, in addition to keeping a running average of the first @@ -1301,6 +1337,8 @@ directions where the norm of the gradient is consistently large. This greatly speeds up the convergence by allowing us to use a larger learning rate for flat directions. + + === ADAM optimizer === A related algorithm is the ADAM optimizer. In ADAM, we keep a running @@ -1359,6 +1397,7 @@ update rule for this parameter is given by * _Adaptive optimization methods don't always have good generalization._ Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications. + ===== Automatic differentiation ===== "Automatic differentiation (AD)":"https://en.wikipedia.org/wiki/Automatic_differentiation", @@ -1540,7 +1579,6 @@ might be easier to work with, as the output is closer to what one could expect form a gradient-evaluting function. - !bc pycod import autograd.numpy as np from autograd import grad @@ -1581,7 +1619,6 @@ print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x))) !ec - !bc pycod import autograd.numpy as np from autograd import grad @@ -1654,21 +1691,21 @@ print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical)) Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. -Autograd supports many features. However, there are some functions that are not supported (yet) by Autograd. +Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. -Assigning a value to the variable being differentiated with respect to is an example thereof. +Assigning a value to the variable being differentiated with respect to !bc pycod -#import autograd.numpy as np -#from autograd import grad -#def f8(x): # Assume x is an array -# x[2] = 3 -# return x*2 +import autograd.numpy as np +from autograd import grad +def f8(x): # Assume x is an array + x[2] = 3 + return x*2 -#f8_grad = grad(f8) +f8_grad = grad(f8) -#x = 8.4 +x = 8.4 -#print("The derivative of f8 is:",f8_grad(x)) +print("The derivative of f8 is:",f8_grad(x)) !ec Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. @@ -1718,10 +1755,186 @@ a /=b !ec -More examples will be added, in particular how to compare autograd with own codes for the gradients. + +===== Using Autograd with OLS ===== + +We conclude the part on optmization by showing how we can make codes +for linear regression and logistic regression using _autograd_. The +first example shows results with ordinary leats squares. + +!bc pycod +# Using Autograd to calculate gradients for OLS +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +def CostOLS(beta): + return (1.0/n)*np.sum((y-X @ beta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 +# define the gradient +training_gradient = grad(CostOLS) + +for iter in range(Niterations): + gradients = training_gradient(theta) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') +plt.show() + +!ec +=== Including Stochastic Gradient Descent with Autograd === +In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using _autograd_. + +!bc pycod +# Using Autograd to calculate gradients using SGD +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) + +for iter in range(Niterations): + gradients = (1.0/n)*training_gradient(y, X, theta) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') +plt.show() + +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +t0, t1 = 5, 50 +def learning_schedule(t): + return t0/(t+t1) + +theta = np.random.randn(2,1) + +for epoch in range(n_epochs): +# Can you figure out a better way of setting up the contributions to each batch? + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + eta = learning_schedule(epoch*m+i) + theta = theta - eta*gradients +print("theta from own sdg") +print(theta) +!ec + + +=== And Logistic Regression === + +!bc pycod +import autograd.numpy as np +from autograd import grad + +def sigmoid(x): + return 0.5 * (np.tanh(x / 2.) + 1) + +def logistic_predictions(weights, inputs): + # Outputs probability of a label being true according to logistic model. + return sigmoid(np.dot(inputs, weights)) + +def training_loss(weights): + # Training loss is the negative log-likelihood of the training labels. + preds = logistic_predictions(weights, inputs) + label_probabilities = preds * targets + (1 - preds) * (1 - targets) + return -np.sum(np.log(label_probabilities)) + +# Build a toy dataset. +inputs = np.array([[0.52, 1.12, 0.77], + [0.88, -1.08, 0.15], + [0.52, 0.06, -1.30], + [0.74, -2.49, 1.39]]) +targets = np.array([True, True, False, True]) + +# Define a function that returns gradients of training loss using Autograd. +training_gradient_fun = grad(training_loss) + +# Optimize weights using gradient descent. +weights = np.array([0.0, 0.0, 0.0]) +print("Initial loss:", training_loss(weights)) +for i in range(100): + weights -= training_gradient_fun(weights) * 0.01 + +print("Trained loss:", training_loss(weights)) +!ec + diff --git a/doc/BookChapters/ipynb-chapter12-src.tar.gz b/doc/BookChapters/ipynb-chapter12-src.tar.gz index 4e69853b7..f43147c7c 100644 Binary files a/doc/BookChapters/ipynb-chapter12-src.tar.gz and b/doc/BookChapters/ipynb-chapter12-src.tar.gz differ diff --git a/doc/LectureNotes/_toc.yml b/doc/LectureNotes/_toc.yml index ee8322237..7f154e6a0 100644 --- a/doc/LectureNotes/_toc.yml +++ b/doc/LectureNotes/_toc.yml @@ -29,9 +29,12 @@ parts: numbered: true chapters: - file: chapter8.ipynb + - file: clustering.ipynb - caption: Deep Learning Methods numbered: true chapters: - file: chapter9.ipynb - file: chapter10.ipynb - file: chapter11.ipynb + - file: chapter12.ipynb + - file: chapter13.ipynb diff --git a/doc/LectureNotes/chapter11.ipynb b/doc/LectureNotes/chapter11.ipynb index c03e4a368..00bf35796 100644 --- a/doc/LectureNotes/chapter11.ipynb +++ b/doc/LectureNotes/chapter11.ipynb @@ -2,7 +2,21 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "7660a7d5", + "metadata": { + "editable": true + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "7174820b", + "metadata": { + "editable": true + }, "source": [ "# Solving Differential Equations with Deep Learning\n", "\n", @@ -10,7 +24,6 @@ "approximate any function at a single hidden layer along with one input\n", "and output layer to any given precision. \n", "\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" @@ -18,7 +31,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ac838a12", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -32,7 +48,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ccee4286", + "metadata": { + "editable": true + }, "source": [ "where $g(x)$ is the function to find, and $g^{(n)}(x)$ is the $n$-th derivative of $g(x)$.\n", "\n", @@ -42,14 +61,15 @@ "Along with ([1](#ode)), some additional conditions of the function $g(x)$ are typically given\n", "for the solution to be unique.\n", "\n", - "\n", - "\n", "Let the trial solution $g_t(x)$ be" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "39d7dabd", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -64,7 +84,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "74f33170", + "metadata": { + "editable": true + }, "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", @@ -77,11 +100,8 @@ "\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", - "\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", @@ -92,7 +112,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2565ab16", + "metadata": { + "editable": true + }, "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", @@ -101,7 +124,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "83d4ee25", + "metadata": { + "editable": true + }, "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" @@ -109,7 +135,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a7a3a709", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -123,20 +152,28 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d3ca8026", + "metadata": { + "editable": true + }, "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", - "\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", + "Automatic differentiation is a method of finding the derivatives numerically with very high precision." + ] + }, + { + "cell_type": "markdown", + "id": "9bde4bd4", + "metadata": { + "editable": true + }, + "source": [ "### Example: Exponential decay\n", "\n", "An exponential decay of a quantity $g(x)$ is described by the equation" @@ -144,7 +181,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e74337c3", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -158,7 +198,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "273549a4", + "metadata": { + "editable": true + }, "source": [ "with $g(0) = g_0$ for some chosen initial value $g_0$.\n", "\n", @@ -167,7 +210,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "db3c6623", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -182,18 +228,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8547e3c8", + "metadata": { + "editable": true + }, "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", - "\n", "The program will use a neural network to solve" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "48341fc6", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -207,19 +257,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d25b1e02", + "metadata": { + "editable": true + }, "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", - "\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": {}, + "id": "7c5dd91e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g_t(x, P) = h_1(x) + h_2(x, N(x, P))\n", @@ -228,12 +283,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "24223062", + "metadata": { + "editable": true + }, "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", - "\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", @@ -247,7 +303,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ebf04383", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -261,7 +320,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ea4a0013", + "metadata": { + "editable": true + }, "source": [ "### Reformulating the problem\n", "\n", @@ -277,7 +339,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2351b84f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g_t(x, P) = g_0 + x \\cdot N(x, P)\n", @@ -286,14 +351,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f6cc00e4", + "metadata": { + "editable": true + }, "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": {}, + "id": "84e066a1", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -307,11 +378,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "feff9ab3", + "metadata": { + "editable": true + }, "source": [ "is fulfilled as *best as possible*.\n", "\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", @@ -321,7 +394,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0c6f0e79", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\min_{P}\\Big\\{ \\big(g_t'(x, P) - ( -\\gamma g_t(x, P) \\big)^2 \\Big\\}\n", @@ -330,7 +406,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9302a1dd", + "metadata": { + "editable": true + }, "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", @@ -339,7 +418,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f7f204bb", + "metadata": { + "editable": true + }, "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", @@ -348,18 +430,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8d61d75f", + "metadata": { + "editable": true + }, "source": [ "for an input value $x$.\n", "\n", - "\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": {}, + "id": "10d3aec9", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -373,14 +459,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5e296388", + "metadata": { + "editable": true + }, "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": {}, + "id": "fe010d79", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\min_{P} C(\\boldsymbol{x}, P)\n", @@ -389,7 +481,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "add715f9", + "metadata": { + "editable": true + }, "source": [ "In terms of $P_{\\text{hidden} }$ and $P_{\\text{output} }$, this could also be expressed as\n", "\n", @@ -397,20 +492,21 @@ "\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }} C(\\boldsymbol{x}, \\{P_{\\text{hidden} }, P_{\\text{output} }\\})\n", "$$\n", "\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", - "\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": {}, + "id": "cb9b22eb", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -429,14 +525,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "49f3c493", + "metadata": { + "editable": true + }, "source": [ "The result after weighting the inputs at the $i$-th hidden neuron can be written as a vector:" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "a352bd61", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -456,7 +558,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e5636ad7", + "metadata": { + "editable": true + }, "source": [ "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", @@ -467,7 +572,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "68bb8b9c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(z) = \\frac{1}{1 + \\exp{(-z)}}\n", @@ -476,7 +584,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ff6e6536", + "metadata": { + "editable": true + }, "source": [ "It is possible to use other activations functions for the hidden layer also.\n", "\n", @@ -494,14 +605,15 @@ "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", - "\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": {}, + "id": "6fb4c55b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -519,14 +631,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "09c31d8d", + "metadata": { + "editable": true + }, "source": [ "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": {}, + "id": "f81fe361", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{z}_{1}^{\\text{output}} =\n", @@ -542,11 +660,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c309a4ce", + "metadata": { + "editable": true + }, "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", - "\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" @@ -554,7 +674,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ea47ae29", + "metadata": { + "editable": true + }, "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", @@ -563,12 +686,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9dd83767", + "metadata": { + "editable": true + }, "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", + "Here, gradient descent with a constant step size has been chosen." + ] + }, + { + "cell_type": "markdown", + "id": "531a7b4f", + "metadata": { + "editable": true + }, + "source": [ "### Gradient descent\n", "\n", "The idea of the gradient descent algorithm is to update parameters in\n", @@ -581,7 +715,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e10c204a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\omega}_{\\text{new} } = \\boldsymbol{\\omega} - \\lambda \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})\n", @@ -590,7 +727,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9f4fa48e", + "metadata": { + "editable": true + }, "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", @@ -609,7 +749,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4652fc79", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -621,14 +764,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "41ae0626", + "metadata": { + "editable": true + }, "source": [ "### The code for solving the ODE" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, + "id": "af7c165f", "metadata": { "collapsed": false, "editable": true @@ -785,7 +932,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "875a0c0b", + "metadata": { + "editable": true + }, "source": [ "## The network with one input layer, specified number of hidden layers, and one output layer\n", "\n", @@ -796,7 +946,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, + "id": "00684827", "metadata": { "collapsed": false, "editable": true @@ -965,7 +1116,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5420c490", + "metadata": { + "editable": true + }, "source": [ "### Example: Population growth\n", "\n", @@ -975,7 +1129,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1436ed3c", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -989,7 +1146,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a590bdb6", + "metadata": { + "editable": true + }, "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", @@ -999,15 +1159,16 @@ "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", - "\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": {}, + "id": "48d788d6", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1021,13 +1182,15 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "169c6c25", + "metadata": { + "editable": true + }, "source": [ "where $g(0) = g_0$.\n", "\n", "In this example, we let $\\alpha = 2$, $A = 1$, and $g_0 = 1.2$.\n", "\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", @@ -1045,14 +1208,13 @@ "g(t) = \\frac{Ag_0}{g_0 + (A - g_0)\\exp(-\\alpha A t)}\n", "$$\n", "\n", - "\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": null, + "execution_count": 3, + "id": "6d2e33bf", "metadata": { "collapsed": false, "editable": true @@ -1226,7 +1388,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e31ec549", + "metadata": { + "editable": true + }, "source": [ "## Using forward Euler to solve the ODE\n", "\n", @@ -1243,7 +1408,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2e9ee105", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1255,7 +1423,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e876da16", + "metadata": { + "editable": true + }, "source": [ "along with the condition that $g(0) = g_0$.\n", "\n", @@ -1266,7 +1437,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b79a3def", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1279,14 +1453,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9d99cb4e", + "metadata": { + "editable": true + }, "source": [ "Now, if $g_i = g(t_i)$ then" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "3b9dcc24", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1305,7 +1485,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "65ce688e", + "metadata": { + "editable": true + }, "source": [ "for $i \\geq 1$ and $g_0 = g(t_0) = g(0) = g_0$.\n", "\n", @@ -1315,7 +1498,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, + "id": "d5497948", "metadata": { "collapsed": false, "editable": true @@ -1391,7 +1575,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fa8f0bb4", + "metadata": { + "editable": true + }, "source": [ "## Solving the one dimensional Poisson equation\n", "\n", @@ -1400,7 +1587,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f765b0ba", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1414,7 +1604,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bd63b92e", + "metadata": { + "editable": true + }, "source": [ "where $f(x)$ is a given function for $x \\in (0,1)$.\n", "\n", @@ -1423,7 +1616,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c0a7face", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -1435,19 +1631,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f71c3cb9", + "metadata": { + "editable": true + }, "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", - "\n", "Here, the function $g(x)$ to solve for follows the equation" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "35aa6a37", + "metadata": { + "editable": true + }, "source": [ "$$\n", "-g''(x) = f(x),\\qquad x \\in (0,1)\n", @@ -1456,14 +1657,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f8b35111", + "metadata": { + "editable": true + }, "source": [ "where $f(x)$ is a given function, along with the chosen conditions" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "33813514", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1477,7 +1684,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c70aadd4", + "metadata": { + "editable": true + }, "source": [ "In this example, we consider the case when $f(x) = (3x + x^2)\\exp(x)$.\n", "\n", @@ -1486,7 +1696,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d5719dee", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g_t(x) = x \\cdot (1-x) \\cdot N(P,x)\n", @@ -1495,14 +1708,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a683041b", + "metadata": { + "editable": true + }, "source": [ "The analytical solution for this problem is" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "672cdaff", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g(x) = x(1 - x)\\exp(x)\n", @@ -1511,7 +1730,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, + "id": "66e6bebb", "metadata": { "collapsed": false, "editable": true @@ -1672,7 +1892,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d425cba5", + "metadata": { + "editable": true + }, "source": [ "### Comparing with a numerical scheme\n", "\n", @@ -1691,7 +1914,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a2efa110", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1705,14 +1931,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5011ee25", + "metadata": { + "editable": true + }, "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": {}, + "id": "705ee300", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1724,14 +1956,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b390796d", + "metadata": { + "editable": true + }, "source": [ "Since we know from our problem that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "19c9ece4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1743,7 +1981,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6ade1a7a", + "metadata": { + "editable": true + }, "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:" @@ -1751,7 +1992,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "78b16d02", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1768,7 +2012,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f2bfcca4", + "metadata": { + "editable": true + }, "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", @@ -1777,7 +2024,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a6191528", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1811,17 +2061,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "aefef707", + "metadata": { + "editable": true + }, "source": [ "which makes it possible to solve for the vector $\\boldsymbol{g}$.\n", "\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": null, + "execution_count": 6, + "id": "471664cd", "metadata": { "collapsed": false, "editable": true @@ -2022,7 +2275,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6f02e86d", + "metadata": { + "editable": true + }, "source": [ "## Partial Differential Equations\n", "\n", @@ -2036,7 +2292,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ad5c63e8", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2050,10 +2309,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c7b98797", + "metadata": { + "editable": true + }, + "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." + ] + }, + { + "cell_type": "markdown", + "id": "52f9394e", + "metadata": { + "editable": true + }, "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", @@ -2064,7 +2334,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4d489854", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -2075,15 +2348,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "82311538", + "metadata": { + "editable": true + }, "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", - "\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." + ] + }, + { + "cell_type": "markdown", + "id": "9d134db4", + "metadata": { + "editable": true + }, + "source": [ "### Network requirements\n", "\n", "The network tries then the minimize the cost function following the\n", @@ -2099,7 +2381,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5a463498", + "metadata": { + "editable": true + }, "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", @@ -2108,14 +2393,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c40d8997", + "metadata": { + "editable": true + }, "source": [ "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": {}, + "id": "cc033de6", + "metadata": { + "editable": true + }, "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", @@ -2124,14 +2415,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ae18b4f4", + "metadata": { + "editable": true + }, "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": {}, + "id": "44ca21bd", + "metadata": { + "editable": true + }, "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", @@ -2140,7 +2437,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fe94451e", + "metadata": { + "editable": true + }, "source": [ "## Example: The diffusion equation\n", "\n", @@ -2149,7 +2449,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "30a42273", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", @@ -2158,14 +2461,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fd4077e7", + "metadata": { + "editable": true + }, "source": [ "where a possible choice of conditions are" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "dbbf2e4b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -2178,18 +2487,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "83653db9", + "metadata": { + "editable": true + }, "source": [ "with $u(x)$ being some given function.\n", "\n", - "\n", - "\n", "For this case, we want to find $g(x,t)$ such that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d2c2ef4f", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2203,14 +2516,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8fb27bdb", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "dc9297ab", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -2223,7 +2542,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ab90784f", + "metadata": { + "editable": true + }, "source": [ "with $u(x) = \\sin(\\pi x)$.\n", "\n", @@ -2231,9 +2553,6 @@ "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", - "\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", @@ -2245,7 +2564,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, + "id": "b07e858c", "metadata": { "collapsed": false, "editable": true @@ -2300,7 +2620,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9a167ec1", + "metadata": { + "editable": true + }, "source": [ "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", @@ -2322,8 +2645,6 @@ "$$\n", "since $(0) = u(1) = 0$ and $u(x) = \\sin(\\pi x)$.\n", "\n", - "\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", @@ -2345,7 +2666,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, + "id": "921e5969", "metadata": { "collapsed": false, "editable": true @@ -2392,7 +2714,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0bc00b69", + "metadata": { + "editable": true + }, "source": [ "### Setting up the network using Autograd; The full program\n", "\n", @@ -2408,14 +2733,14 @@ "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": null, + "execution_count": 9, + "id": "20734418", "metadata": { "collapsed": false, "editable": true @@ -2649,7 +2974,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "143f1c80", + "metadata": { + "editable": true + }, "source": [ "## Solving the wave equation with Neural Networks\n", "\n", @@ -2658,7 +2986,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "190bd4f2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2\\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", @@ -2667,7 +2998,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9719cfc5", + "metadata": { + "editable": true + }, "source": [ "with $c$ being the specified wave speed.\n", "\n", @@ -2676,7 +3010,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f69ec7fd", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -2690,17 +3027,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6ce8c5a8", + "metadata": { + "editable": true + }, "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", - "\n", "The wave equation to solve for, is" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4be700d7", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2714,7 +3056,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "993f93ba", + "metadata": { + "editable": true + }, "source": [ "where $c$ is the given wave speed.\n", "The chosen conditions for this equation are" @@ -2722,7 +3067,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2cb2a80f", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2739,12 +3087,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3f1dcfd4", + "metadata": { + "editable": true + }, "source": [ "In this example, let $c = 1$ and $u(x) = \\sin(\\pi x)$ and $v(x) = -\\pi\\sin(\\pi x)$.\n", "\n", - "\n", - "\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", @@ -2762,7 +3111,6 @@ "\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", - "\n", "The analytical solution for our specific problem, is\n", "\n", "$$\n", @@ -2772,7 +3120,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, + "id": "230a9aef", "metadata": { "collapsed": false, "editable": true @@ -3003,7 +3352,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a23bd19a", + "metadata": { + "editable": true + }, "source": [ "## Resources on differential equations and deep learning\n", "\n", @@ -3019,5 +3371,5 @@ ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 } diff --git a/doc/LectureNotes/chapter12.ipynb b/doc/LectureNotes/chapter12.ipynb new file mode 100644 index 000000000..c0569826b --- /dev/null +++ b/doc/LectureNotes/chapter12.ipynb @@ -0,0 +1,1577 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "b1ad0b52", + "metadata": { + "editable": true + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "9548423d", + "metadata": { + "editable": true + }, + "source": [ + "# Convolutional Neural Networks\n", + "\n", + "Convolutional neural networks (CNNs) were developed during the last\n", + "decade of the previous century, with a focus on character recognition\n", + "tasks. Nowadays, CNNs are a central element in the spectacular success\n", + "of deep learning methods. The success in for example image\n", + "classifications have made them a central tool for most machine\n", + "learning practitioners.\n", + "\n", + "CNNs are very similar to ordinary Neural Networks.\n", + "They are made up of neurons that have learnable weights and\n", + "biases. Each neuron receives some inputs, performs a dot product and\n", + "optionally follows it with a non-linearity. The whole network still\n", + "expresses a single differentiable score function: from the raw image\n", + "pixels on one end to class scores at the other. And they still have a\n", + "loss function (for example Softmax) on the last (fully-connected) layer\n", + "and all the tips/tricks we developed for learning regular Neural\n", + "Networks still apply (back propagation, gradient descent etc etc).\n", + "\n", + "**CNN architectures make the explicit assumption that\n", + "the inputs are images, which allows us to encode certain properties\n", + "into the architecture. These then make the forward function more\n", + "efficient to implement and vastly reduce the amount of parameters in\n", + "the network.**\n", + "\n", + "Here we provide only a superficial overview, for the more interested, we recommend highly the course\n", + "[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n", + "and the slides of [CS231](http://cs231n.github.io/convolutional-networks/).\n", + "\n", + "Another good read is the article here ." + ] + }, + { + "cell_type": "markdown", + "id": "315b8308", + "metadata": { + "editable": true + }, + "source": [ + "## Neural Networks vs CNNs\n", + "\n", + "Neural networks are defined as **affine transformations**, that is \n", + "a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an\n", + "output (to which a bias vector is usually added before passing the result\n", + "through a nonlinear activation function). This is applicable to any type of input, be it an\n", + "image, a sound clip or an unordered collection of features: whatever their\n", + "dimensionality, their representation can always be flattened into a vector\n", + "before the transformation.\n", + "\n", + "However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic\n", + "structure. More formally, they share these important properties:\n", + "* They are stored as multi-dimensional arrays (think of the pixels of a figure) .\n", + "\n", + "* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).\n", + "\n", + "* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).\n", + "\n", + "These properties are not exploited when an affine transformation is applied; in\n", + "fact, all the axes are treated in the same way and the topological information\n", + "is not taken into account. Still, taking advantage of the implicit structure of\n", + "the data may prove very handy in solving some tasks, like computer vision and\n", + "speech recognition, and in these cases it would be best to preserve it. This is\n", + "where discrete convolutions come into play.\n", + "\n", + "A discrete convolution is a linear transformation that preserves this notion of\n", + "ordering. It is sparse (only a few input units contribute to a given output\n", + "unit) and reuses parameters (the same weights are applied to multiple locations\n", + "in the input).\n", + "\n", + "As an example, consider\n", + "an image of size $32\\times 32\\times 3$ (32 wide, 32 high, 3 color channels), so a\n", + "single fully-connected neuron in a first hidden layer of a regular\n", + "Neural Network would have $32\\times 32\\times 3 = 3072$ weights. This amount still\n", + "seems manageable, but clearly this fully-connected structure does not\n", + "scale to larger images. For example, an image of more respectable\n", + "size, say $200\\times 200\\times 3$, would lead to neurons that have \n", + "$200\\times 200\\times 3 = 120,000$ weights. \n", + "\n", + "We could have\n", + "several such neurons, and the parameters would add up quickly! Clearly,\n", + "this full connectivity is wasteful and the huge number of parameters\n", + "would quickly lead to possible overfitting.\n", + "\n", + "\n", + "\n", + "\n", + "

Figure 1: A regular 3-layer Neural Network.

\n", + "\n", + "\n", + "Convolutional Neural Networks take advantage of the fact that the\n", + "input consists of images and they constrain the architecture in a more\n", + "sensible way. \n", + "\n", + "In particular, unlike a regular Neural Network, the\n", + "layers of a CNN have neurons arranged in 3 dimensions: width,\n", + "height, depth. (Note that the word depth here refers to the third\n", + "dimension of an activation volume, not to the depth of a full Neural\n", + "Network, which can refer to the total number of layers in a network.)\n", + "\n", + "To understand it better, the above example of an image \n", + "with an input volume of\n", + "activations has dimensions $32\\times 32\\times 3$ (width, height,\n", + "depth respectively). \n", + "\n", + "The neurons in a layer will\n", + "only be connected to a small region of the layer before it, instead of\n", + "all of the neurons in a fully-connected manner. Moreover, the final\n", + "output layer could for this specific image have dimensions $1\\times 1 \\times 10$, \n", + "because by the\n", + "end of the CNN architecture we will reduce the full image into a\n", + "single vector of class scores, arranged along the depth\n", + "dimension. \n", + "\n", + "\n", + "\n", + "\n", + "

Figure 1: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).

\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "a142cd5d", + "metadata": { + "editable": true + }, + "source": [ + "## Layers used to build CNNs\n", + "\n", + "A simple CNN is a sequence of layers, and every layer of a CNN\n", + "transforms one volume of activations to another through a\n", + "differentiable function. We use three main types of layers to build\n", + "CNN architectures: Convolutional Layer, Pooling Layer, and\n", + "Fully-Connected Layer (exactly as seen in regular Neural Networks). We\n", + "will stack these layers to form a full CNN architecture.\n", + "\n", + "A simple CNN for image classification could have the architecture:\n", + "\n", + "* **INPUT** ($32\\times 32 \\times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.\n", + "\n", + "* **CONV** (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\\times 32\\times 12]$ if we decided to use 12 filters.\n", + "\n", + "* **RELU** layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\\times 32\\times 12]$).\n", + "\n", + "* **POOL** (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\\times 16\\times 12]$.\n", + "\n", + "* **FC** (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\\times 1\\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.\n", + "\n", + "CNNs transform the original image layer by layer from the original\n", + "pixel values to the final class scores. \n", + "\n", + "Observe that some layers contain\n", + "parameters and other don’t. In particular, the CNN layers perform\n", + "transformations that are a function of not only the activations in the\n", + "input volume, but also of the parameters (the weights and biases of\n", + "the neurons). On the other hand, the RELU/POOL layers will implement a\n", + "fixed function. The parameters in the CONV/FC layers will be trained\n", + "with gradient descent so that the class scores that the CNN computes\n", + "are consistent with the labels in the training set for each image.\n", + "\n", + "In summary:\n", + "\n", + "* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)\n", + "\n", + "* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n", + "\n", + "* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n", + "\n", + "* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)\n", + "\n", + "* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)\n", + "\n", + "A dense neural network is representd by an affine operation (like matrix-matrix multiplication) where all parameters are included.\n", + "\n", + "The key idea in CNNs for say imaging is that in images neighbor pixels tend to be related! So we connect\n", + "only neighboring neurons in the input instead of connecting all with the first hidden layer.\n", + "\n", + "We say we perform a filtering (convolution is the mathematical operation)." + ] + }, + { + "cell_type": "markdown", + "id": "bb1e3617", + "metadata": { + "editable": true + }, + "source": [ + "## Mathematics of CNNs\n", + "\n", + "The mathematics of CNNs is based on the mathematical operation of\n", + "**convolution**. In mathematics (in particular in functional analysis),\n", + "convolution is represented by matheematical operation (integration,\n", + "summation etc) on two function in order to produce a third function\n", + "that expresses how the shape of one gets modified by the other.\n", + "Convolution has a plethora of applications in a variety of disciplines, spanning from statistics to signal processing, computer vision, solutions of differential equations,linear algebra, engineering, and yes, machine learning.\n", + "\n", + "Mathematically, convolution is defined as follows (one-dimensional example):\n", + "Let us define a continuous function $y(t)$ given by" + ] + }, + { + "cell_type": "markdown", + "id": "051485e5", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(t) = \\int x(a) w(t-a) da,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "799b8e5f", + "metadata": { + "editable": true + }, + "source": [ + "where $x(a)$ represents a so-called input and $w(t-a)$ is normally called the weight function or kernel.\n", + "\n", + "The above integral is written in a more compact form as" + ] + }, + { + "cell_type": "markdown", + "id": "3353345f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(t) = \\left(x * w\\right)(t).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ef341ee6", + "metadata": { + "editable": true + }, + "source": [ + "The discretized version reads" + ] + }, + { + "cell_type": "markdown", + "id": "ca8f7582", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(t) = \\sum_{a=-\\infty}^{a=\\infty}x(a)w(t-a).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "216e011f", + "metadata": { + "editable": true + }, + "source": [ + "Computing the inverse of the above convolution operations is known as deconvolution.\n", + "\n", + "How can we use this? And what does it mean? Let us study some familiar examples first." + ] + }, + { + "cell_type": "markdown", + "id": "5545738c", + "metadata": { + "editable": true + }, + "source": [ + "### Convolution Examples: Polynomial multiplication\n", + "\n", + "We have already met such an example in project 1 when we tried to set\n", + "up the design matrix for a two-dimensional function. This was an\n", + "example of polynomial multiplication. Let us recast such a problem in terms of the convolution operation.\n", + "Let us look a the following polynomials to second and third order, respectively:" + ] + }, + { + "cell_type": "markdown", + "id": "9f317908", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "p(t) = \\alpha_0+\\alpha_1 t+\\alpha_2 t^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "eb6f1070", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "9fe61b3c", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "s(t) = \\beta_0+\\beta_1 t+\\beta_2 t^2+\\beta_3 t^3.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "38c68ea7", + "metadata": { + "editable": true + }, + "source": [ + "The polynomial multiplication gives us a new polynomial of degree $5$" + ] + }, + { + "cell_type": "markdown", + "id": "3e91a9f1", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "z(t) = \\delta_0+\\delta_1 t+\\delta_2 t^2+\\delta_3 t^3+\\delta_4 t^4+\\delta_5 t^5.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5e24ac44", + "metadata": { + "editable": true + }, + "source": [ + "Computing polynomial products can be implemented efficiently if we rewrite the more brute force multiplications using convolution.\n", + "We note first that the new coefficients are given as" + ] + }, + { + "cell_type": "markdown", + "id": "ac215eb9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{split}\n", + "\\delta_0=&\\alpha_0\\beta_0\\\\\n", + "\\delta_1=&\\alpha_1\\beta_0+\\alpha_1\\beta_0\\\\\n", + "\\delta_2=&\\alpha_0\\beta_2+\\alpha_1\\beta_1+\\alpha_2\\beta_0\\\\\n", + "\\delta_3=&\\alpha_1\\beta_2+\\alpha_2\\beta_1+\\alpha_0\\beta_3\\\\\n", + "\\delta_4=&\\alpha_2\\beta_2+\\alpha_1\\beta_3\\\\\n", + "\\delta_5=&\\alpha_2\\beta_3.\\\\\n", + "\\end{split}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "eca51025", + "metadata": { + "editable": true + }, + "source": [ + "We note that $\\alpha_i=0$ except for $i\\in \\left\\{0,1,2\\right\\}$ and $\\beta_i=0$ except for $i\\in\\left\\{0,1,2,3\\right\\}$.\n", + "\n", + "We can then rewrite the coefficients $\\delta_j$ using a discrete convolution as" + ] + }, + { + "cell_type": "markdown", + "id": "0d517816", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\delta_j = \\sum_{i=-\\infty}^{i=\\infty}\\alpha_i\\beta_{j-i}=(\\alpha * \\beta)_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "8cf1037e", + "metadata": { + "editable": true + }, + "source": [ + "or as a double sum with restriction $l=i+j$" + ] + }, + { + "cell_type": "markdown", + "id": "efe18d99", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\delta_l = \\sum_{ij}\\alpha_i\\beta_{j}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "14ae41db", + "metadata": { + "editable": true + }, + "source": [ + "Do you see a potential drawback with these equations?\n", + "\n", + "Since we only have a finite number of $\\alpha$ and $\\beta$ values\n", + "which are non-zero, we can rewrite the above convolution expressions\n", + "as a matrix-vector multiplication" + ] + }, + { + "cell_type": "markdown", + "id": "046e108b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\delta}=\\begin{bmatrix}\\alpha_0 & 0 & 0 & 0 \\\\\n", + " \\alpha_1 & \\alpha_0 & 0 & 0 \\\\\n", + "\t\t\t \\alpha_2 & \\alpha_1 & \\alpha_0 & 0 \\\\\n", + "\t\t\t 0 & \\alpha_2 & \\alpha_1 & \\alpha_0 \\\\\n", + "\t\t\t 0 & 0 & \\alpha_2 & \\alpha_1 \\\\\n", + "\t\t\t 0 & 0 & 0 & \\alpha_2\n", + "\t\t\t \\end{bmatrix}\\begin{bmatrix} \\beta_0 \\\\ \\beta_1 \\\\ \\beta_2 \\\\ \\beta_3\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0c73a726", + "metadata": { + "editable": true + }, + "source": [ + "The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding $\\beta$ and a vector holding $\\alpha$.\n", + "In this case we have" + ] + }, + { + "cell_type": "markdown", + "id": "81bc84d0", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\delta}=\\begin{bmatrix}\\beta_0 & 0 & 0 \\\\\n", + " \\beta_1 & \\beta_0 & 0 \\\\\n", + "\t\t\t \\beta_2 & \\beta_1 & \\beta_0 \\\\\n", + "\t\t\t \\beta_3 & \\beta_2 & \\beta_1 \\\\\n", + "\t\t\t 0 & \\beta_3 & \\beta_2 \\\\\n", + "\t\t\t 0 & 0 & \\beta_3\n", + "\t\t\t \\end{bmatrix}\\begin{bmatrix} \\alpha_0 \\\\ \\alpha_1 \\\\ \\alpha_2\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6f314582", + "metadata": { + "editable": true + }, + "source": [ + "Note that the use of these matrices is for mathematical purposes only and not implementation purposes.\n", + "When implementing the above equation we do not encode (and allocate memory) the matrices explicitely.\n", + "We rather code the convolutions in the minimal memory footprint that they require.\n", + "\n", + "Does the number of floating point operations change here when we use the commutative property?" + ] + }, + { + "cell_type": "markdown", + "id": "e01eb276", + "metadata": { + "editable": true + }, + "source": [ + "### Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms)\n", + "\n", + "For problems with so-called harmonic oscillations, given by for example the following differential equation" + ] + }, + { + "cell_type": "markdown", + "id": "1016b422", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "m\\frac{d^2x}{dt^2}+\\eta\\frac{dx}{dt}+x(t)=F(t),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c237cb74", + "metadata": { + "editable": true + }, + "source": [ + "where $F(t)$ is an applied external force acting on the system (often called a driving force), one can use the theory of Fourier transformations to find the solutions of this type of equations.\n", + "\n", + "If one has several driving forces, $F(t)=\\sum_n F_n(t)$, one can find\n", + "the particular solution to each $F_n$, $x_{pn}(t)$, and the particular\n", + "solution for the entire driving force is then given by a series like" + ] + }, + { + "cell_type": "markdown", + "id": "4f2f2089", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "x_p(t)=\\sum_nx_{pn}(t).\n", + "\\label{_auto1} \\tag{1}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a32fa928", + "metadata": { + "editable": true + }, + "source": [ + "This is known as the principle of superposition. It only applies when\n", + "the homogenous equation is linear. If there were an anharmonic term\n", + "such as $x^3$ in the homogenous equation, then when one summed various\n", + "solutions, $x=(\\sum_n x_n)^2$, one would get cross\n", + "terms. Superposition is especially useful when $F(t)$ can be written\n", + "as a sum of sinusoidal terms, because the solutions for each\n", + "sinusoidal (sine or cosine) term is analytic. \n", + "\n", + "Driving forces are often periodic, even when they are not\n", + "sinusoidal. Periodicity implies that for some time $\\tau$" + ] + }, + { + "cell_type": "markdown", + "id": "0b6ca2c5", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{eqnarray}\n", + "F(t+\\tau)=F(t). \n", + "\\end{eqnarray}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "789cd636", + "metadata": { + "editable": true + }, + "source": [ + "One example of a non-sinusoidal periodic force is a square wave. Many\n", + "components in electric circuits are non-linear, e.g. diodes, which\n", + "makes many wave forms non-sinusoidal even when the circuits are being\n", + "driven by purely sinusoidal sources.\n", + "\n", + "The code here shows a typical example of such a square wave generated using the functionality included in the **scipy** Python package. We have used a period of $\\tau=0.2$." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "2c90eb89", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "import numpy as np\n", + "import math\n", + "from scipy import signal\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# number of points \n", + "n = 500\n", + "# start and final times \n", + "t0 = 0.0\n", + "tn = 1.0\n", + "# Period \n", + "t = np.linspace(t0, tn, n, endpoint=False)\n", + "SqrSignal = np.zeros(n)\n", + "SqrSignal = 1.0+signal.square(2*np.pi*5*t)\n", + "plt.plot(t, SqrSignal)\n", + "plt.ylim(-0.5, 2.5)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "8e7b8f5c", + "metadata": { + "editable": true + }, + "source": [ + "For the sinusoidal example the\n", + "period is $\\tau=2\\pi/\\omega$. However, higher harmonics can also\n", + "satisfy the periodicity requirement. In general, any force that\n", + "satisfies the periodicity requirement can be expressed as a sum over\n", + "harmonics," + ] + }, + { + "cell_type": "markdown", + "id": "4453c025", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "F(t)=\\frac{f_0}{2}+\\sum_{n>0} f_n\\cos(2n\\pi t/\\tau)+g_n\\sin(2n\\pi t/\\tau).\n", + "\\label{_auto2} \\tag{2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "32d5f410", + "metadata": { + "editable": true + }, + "source": [ + "We can write down the answer for\n", + "$x_{pn}(t)$, by substituting $f_n/m$ or $g_n/m$ for $F_0/m$. By\n", + "writing each factor $2n\\pi t/\\tau$ as $n\\omega t$, with $\\omega\\equiv\n", + "2\\pi/\\tau$," + ] + }, + { + "cell_type": "markdown", + "id": "4a58698d", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\label{eq:fourierdef1} \\tag{3}\n", + "F(t)=\\frac{f_0}{2}+\\sum_{n>0}f_n\\cos(n\\omega t)+g_n\\sin(n\\omega t).\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5664f63d", + "metadata": { + "editable": true + }, + "source": [ + "The solutions for $x(t)$ then come from replacing $\\omega$ with\n", + "$n\\omega$ for each term in the particular solution," + ] + }, + { + "cell_type": "markdown", + "id": "0d9a2811", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{eqnarray}\n", + "x_p(t)&=&\\frac{f_0}{2k}+\\sum_{n>0} \\alpha_n\\cos(n\\omega t-\\delta_n)+\\beta_n\\sin(n\\omega t-\\delta_n),\\\\\n", + "\\nonumber\n", + "\\alpha_n&=&\\frac{f_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n", + "\\nonumber\n", + "\\beta_n&=&\\frac{g_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n", + "\\nonumber\n", + "\\delta_n&=&\\tan^{-1}\\left(\\frac{2\\beta n\\omega}{\\omega_0^2-n^2\\omega^2}\\right).\n", + "\\end{eqnarray}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ac8b5fff", + "metadata": { + "editable": true + }, + "source": [ + "Because the forces have been applied for a long time, any non-zero\n", + "damping eliminates the homogenous parts of the solution, so one need\n", + "only consider the particular solution for each $n$.\n", + "\n", + "The problem is considered solved if one can find expressions for the\n", + "coefficients $f_n$ and $g_n$, even though the solutions are expressed\n", + "as an infinite sum. The coefficients can be extracted from the\n", + "function $F(t)$ by" + ] + }, + { + "cell_type": "markdown", + "id": "5bb70ae9", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{eqnarray}\n", + "\\label{eq:fourierdef2} \\tag{4}\n", + "f_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\cos(2n\\pi t/\\tau),\\\\\n", + "\\nonumber\n", + "g_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\sin(2n\\pi t/\\tau).\n", + "\\end{eqnarray}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4f64082e", + "metadata": { + "editable": true + }, + "source": [ + "To check the consistency of these expressions and to verify\n", + "Eq. ([4](#eq:fourierdef2)), one can insert the expansion of $F(t)$ in\n", + "Eq. ([3](#eq:fourierdef1)) into the expression for the coefficients in\n", + "Eq. ([4](#eq:fourierdef2)) and see whether" + ] + }, + { + "cell_type": "markdown", + "id": "bdd9e4e8", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{eqnarray}\n", + "f_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~\\left\\{\n", + "\\frac{f_0}{2}+\\sum_{m>0}f_m\\cos(m\\omega t)+g_m\\sin(m\\omega t)\n", + "\\right\\}\\cos(n\\omega t).\n", + "\\end{eqnarray}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e64a4a4c", + "metadata": { + "editable": true + }, + "source": [ + "Immediately, one can throw away all the terms with $g_m$ because they\n", + "convolute an even and an odd function. The term with $f_0/2$\n", + "disappears because $\\cos(n\\omega t)$ is equally positive and negative\n", + "over the interval and will integrate to zero. For all the terms\n", + "$f_m\\cos(m\\omega t)$ appearing in the sum, one can use angle addition\n", + "formulas to see that $\\cos(m\\omega t)\\cos(n\\omega\n", + "t)=(1/2)(\\cos[(m+n)\\omega t]+\\cos[(m-n)\\omega t]$. This will integrate\n", + "to zero unless $m=n$. In that case the $m=n$ term gives" + ] + }, + { + "cell_type": "markdown", + "id": "d51a4f59", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\int_{-\\tau/2}^{\\tau/2}dt~\\cos^2(m\\omega t)=\\frac{\\tau}{2},\n", + "\\label{_auto3} \\tag{5}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "44804e35", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "7de0dbe5", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{eqnarray}\n", + "f_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~f_n/2\\\\\n", + "\\nonumber\n", + "&=&f_n~\\checkmark.\n", + "\\end{eqnarray}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4d1a02e0", + "metadata": { + "editable": true + }, + "source": [ + "The same method can be used to check for the consistency of $g_n$.\n", + "\n", + "The code here uses the Fourier series applied to a \n", + "square wave signal. The code here\n", + "visualizes the various approximations given by Fourier series compared\n", + "with a square wave with period $T=0.2$ (dimensionless time), width $0.1$ and max value of the force $F=2$. We\n", + "see that when we increase the number of components in the Fourier\n", + "series, the Fourier series approximation gets closer and closer to the\n", + "square wave signal." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "4ae0ec42", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import math\n", + "from scipy import signal\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# number of points \n", + "n = 500\n", + "# start and final times \n", + "t0 = 0.0\n", + "tn = 1.0\n", + "# Period \n", + "T =0.2\n", + "# Max value of square signal \n", + "Fmax= 2.0\n", + "# Width of signal \n", + "Width = 0.1\n", + "t = np.linspace(t0, tn, n, endpoint=False)\n", + "SqrSignal = np.zeros(n)\n", + "FourierSeriesSignal = np.zeros(n)\n", + "SqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T)\n", + "a0 = Fmax*Width/T\n", + "FourierSeriesSignal = a0\n", + "Factor = 2.0*Fmax/np.pi\n", + "for i in range(1,500):\n", + " FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T)\n", + "plt.plot(t, SqrSignal)\n", + "plt.plot(t, FourierSeriesSignal)\n", + "plt.ylim(-0.5, 2.5)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "acd75ab0", + "metadata": { + "editable": true + }, + "source": [ + "## Two-dimensional Objects\n", + "\n", + "We often use convolutions over more than one dimension at a time. If\n", + "we have a two-dimensional image $I$ as input, we can have a **filter**\n", + "defined by a two-dimensional **kernel** $K$. This leads to an output $S$" + ] + }, + { + "cell_type": "markdown", + "id": "0cdf3af8", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "S_(i,j)=(I * K)(i,j) = \\sum_m\\sum_n I(m,n)K(i-m,j-n).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1640aae2", + "metadata": { + "editable": true + }, + "source": [ + "Convolution is a commutatitave process, which means we can rewrite this equation as" + ] + }, + { + "cell_type": "markdown", + "id": "11491f4c", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "S_(i,j)=(I * K)(i,j) = \\sum_m\\sum_n I(i-m,j-n)K(m,n).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a1e3ef9d", + "metadata": { + "editable": true + }, + "source": [ + "Normally the latter is more straightforward to implement in a machine elarning library since there is less variation in the range of values of $m$ and $n$.\n", + "\n", + "Many deep learning libraries implement cross-correlation instead of convolution" + ] + }, + { + "cell_type": "markdown", + "id": "919fb5e9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "S_(i,j)=(I * K)(i,j) = \\sum_m\\sum_n I(i+m,j-+)K(m,n).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c42d55ac", + "metadata": { + "editable": true + }, + "source": [ + "## More on Dimensionalities\n", + "\n", + "In fields like signal processing (and imaging as well), one designs\n", + "so-called filters. These filters are defined by the convolutions and\n", + "are often hand-crafted. One may specify filters for smoothing, edge\n", + "detection, frequency reshaping, and similar operations. However with\n", + "neural networks the idea is to automatically learn the filters and use\n", + "many of them in conjunction with non-linear operations (activation\n", + "functions).\n", + "\n", + "As an example consider a neural network operating on sound sequence\n", + "data. Assume that we an input vector $\\boldsymbol{x}$ of length $d=10^6$. We\n", + "construct then a neural network with onle hidden layer only with\n", + "$10^4$ nodes. This means that we will have a weight matrix with\n", + "$10^4\\times 10^6=10^{10}$ weights to be determined, together with $10^4$ biases.\n", + "\n", + "Assume furthermore that we have an output layer which is meant to train whether the sound sequence represents a human voice (true) or something else (false).\n", + "It means that we have only one output node. But since this output node connects to $10^4$ nodes in the hidden layer, there are in total $10^4$ weights to be determined for the output layer, plus one bias. In total we have" + ] + }, + { + "cell_type": "markdown", + "id": "4ebd8c85", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \\approx 10^{10},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6d886fa7", + "metadata": { + "editable": true + }, + "source": [ + "that is ten billion parameters to determine." + ] + }, + { + "cell_type": "markdown", + "id": "cd3b731e", + "metadata": { + "editable": true + }, + "source": [ + "## Further Dimensionality Remarks\n", + "\n", + "In today’s architecture one can train such neural networks, however\n", + "this is a huge number of parameters for the task at hand. In general,\n", + "it is a very wasteful and inefficient use of dense matrices as\n", + "parameters. Just as importantly, such trained network parameters are\n", + "very specific for the type of input data on which they were trained\n", + "and the network is not likely to generalize easily to variations in\n", + "the input.\n", + "\n", + "The main principles that justify convolutions is locality of\n", + "information and repetion of patterns within the signal. Sound samples\n", + "of the input in adjacent spots are much more likely to affect each\n", + "other than those that are very far away. Similarly, sounds are\n", + "repeated in multiple times in the signal. While slightly simplistic,\n", + "reasoning about such a sound example demonstrates this. The same\n", + "principles then apply to images and other similar data." + ] + }, + { + "cell_type": "markdown", + "id": "fc38055c", + "metadata": { + "editable": true + }, + "source": [ + "## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n", + "\n", + "As discussed above, CNNs are neural networks built from the assumption that the inputs\n", + "to the network are 2D images. This is important because the number of features or pixels in images\n", + "grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n", + "\n", + "As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n", + "are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n", + "In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n", + "matrices, typically 1 for each color dimension (Red, Green, Blue). \n", + "\n", + "It means that to represent the entire\n", + "dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:" + ] + }, + { + "cell_type": "markdown", + "id": "c153f6eb", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f45ab21d", + "metadata": { + "editable": true + }, + "source": [ + "### The MNIST dataset again\n", + "\n", + "The MNIST dataset consists of grayscale images with a pixel size of\n", + "$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n", + "neuron in the first hidden layer.\n", + "\n", + "If we were to analyze images of size $128\\times 128$ we would require\n", + "$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n", + "dealing with color images, as most images are, we have an image matrix\n", + "of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n", + "meaning 3 times the number of weights $= 49152$ are required for every\n", + "single neuron in the first hidden layer.\n", + "\n", + "Images typically have strong local correlations, meaning that a small\n", + "part of the image varies little from its neighboring regions. If for\n", + "example we have an image of a blue car, we can roughly assume that a\n", + "small blue part of the image is surrounded by other blue regions.\n", + "\n", + "Therefore, instead of connecting every single pixel to a neuron in the\n", + "first hidden layer, as we have previously done with deep neural\n", + "networks, we can instead connect each neuron to a small part of the\n", + "image (in all 3 RGB depth dimensions). The size of each small area is\n", + "fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).\n", + "\n", + "The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n", + "The input image is typically a square matrix of depth 3. \n", + "\n", + "A **convolution** is performed on the image which outputs\n", + "a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n", + "\n", + "Each filter slides along the input image, taking the dot product\n", + "between each small part of the image and the filter, in all depth\n", + "dimensions. This is then passed through a non-linear function,\n", + "typically the **Rectified Linear (ReLu)** function, which serves as the\n", + "activation of the neurons in the first convolutional layer. This is\n", + "further passed through a **pooling layer**, which reduces the size of the\n", + "convolutional layer, e.g. by taking the maximum or average across some\n", + "small regions, and this serves as input to the next convolutional\n", + "layer." + ] + }, + { + "cell_type": "markdown", + "id": "4af74ca7", + "metadata": { + "editable": true + }, + "source": [ + "### Systematic reduction\n", + "\n", + "By systematically reducing the size of the input volume, through\n", + "convolution and pooling, the network should create representations of\n", + "small parts of the input, and then from them assemble representations\n", + "of larger areas. The final pooling layer is flattened to serve as\n", + "input to a hidden layer, such that each neuron in the final pooling\n", + "layer is connected to every single neuron in the hidden layer. This\n", + "then serves as input to the output layer, e.g. a softmax output for\n", + "classification." + ] + }, + { + "cell_type": "markdown", + "id": "2b435dc0", + "metadata": { + "editable": true + }, + "source": [ + "### Prerequisites: Collect and pre-process data" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "ffb4904f", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn import datasets\n", + "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "# RGB images have a depth of 3\n", + "# our images are grayscale so they should have a depth of 1\n", + "inputs = inputs[:,:,:,np.newaxis]\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "n_inputs = len(inputs)\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "bb2db46c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from tensorflow.keras import datasets, layers, models\n", + "from tensorflow.keras.layers import Input\n", + "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", + "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", + "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", + "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", + "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", + "#from tensorflow.keras import Conv2D\n", + "#from tensorflow.keras import MaxPooling2D\n", + "#from tensorflow.keras import Flatten\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# representation of labels\n", + "labels = to_categorical(labels)\n", + "\n", + "# split into train and test data\n", + "# one-liner from scikit-learn library\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "100a8d6d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def create_convolutional_neural_network_keras(input_shape, receptive_field,\n", + " n_filters, n_neurons_connected, n_categories,\n", + " eta, lmbd):\n", + " model = Sequential()\n", + " model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n", + " activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n", + " model.add(layers.Flatten())\n", + " model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))\n", + " \n", + " sgd = optimizers.SGD(lr=eta)\n", + " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", + " \n", + " return model\n", + "\n", + "epochs = 100\n", + "batch_size = 100\n", + "input_shape = X_train.shape[1:4]\n", + "receptive_field = 3\n", + "n_filters = 10\n", + "n_neurons_connected = 50\n", + "n_categories = 10\n", + "\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "635da5a7", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n", + " n_filters, n_neurons_connected, n_categories,\n", + " eta, lmbd)\n", + " CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", + " scores = CNN.evaluate(X_test, Y_test)\n", + " \n", + " CNN_keras[i][j] = CNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % scores[1])\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "df145244", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " CNN = CNN_keras[i][j]\n", + "\n", + " train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n", + " test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a6724f1c", + "metadata": { + "editable": true + }, + "source": [ + "## The CIFAR01 data set\n", + "\n", + "The CIFAR10 dataset contains 60,000 color images in 10 classes, with\n", + "6,000 images in each class. The dataset is divided into 50,000\n", + "training images and 10,000 testing images. The classes are mutually\n", + "exclusive and there is no overlap between them." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "90c28005", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import tensorflow as tf\n", + "\n", + "from tensorflow.keras import datasets, layers, models\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# We import the data set\n", + "(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()\n", + "\n", + "# Normalize pixel values to be between 0 and 1 by dividing by 255. \n", + "train_images, test_images = train_images / 255.0, test_images / 255.0" + ] + }, + { + "cell_type": "markdown", + "id": "759ea77a", + "metadata": { + "editable": true + }, + "source": [ + "To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "494edadd", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n", + " 'dog', 'frog', 'horse', 'ship', 'truck']\n", + "​\n", + "plt.figure(figsize=(10,10))\n", + "for i in range(25):\n", + " plt.subplot(5,5,i+1)\n", + " plt.xticks([])\n", + " plt.yticks([])\n", + " plt.grid(False)\n", + " plt.imshow(train_images[i], cmap=plt.cm.binary)\n", + " # The CIFAR labels happen to be arrays, \n", + " # which is why you need the extra index\n", + " plt.xlabel(class_names[train_labels[i][0]])\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "46d2ea5d", + "metadata": { + "editable": true + }, + "source": [ + "The six lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.\n", + "\n", + "As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "044310ec", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "model = models.Sequential()\n", + "model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\n", + "model.add(layers.MaxPooling2D((2, 2)))\n", + "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n", + "model.add(layers.MaxPooling2D((2, 2)))\n", + "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n", + "\n", + "# Let's display the architecture of our model so far.\n", + "\n", + "model.summary()" + ] + }, + { + "cell_type": "markdown", + "id": "738f34a7", + "metadata": { + "editable": true + }, + "source": [ + "You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.\n", + "\n", + "To complete our model, you will feed the last output tensor from the\n", + "convolutional base (of shape (4, 4, 64)) into one or more Dense layers\n", + "to perform classification. Dense layers take vectors as input (which\n", + "are 1D), while the current output is a 3D tensor. First, you will\n", + "flatten (or unroll) the 3D output to 1D, then add one or more Dense\n", + "layers on top. CIFAR has 10 output classes, so you use a final Dense\n", + "layer with 10 outputs and a softmax activation." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "e0fea435", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "model.add(layers.Flatten())\n", + "model.add(layers.Dense(64, activation='relu'))\n", + "model.add(layers.Dense(10))\n", + "Here's the complete architecture of our model.\n", + "\n", + "model.summary()" + ] + }, + { + "cell_type": "markdown", + "id": "62f1e50d", + "metadata": { + "editable": true + }, + "source": [ + "As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "e2d8f4f2", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "model.compile(optimizer='adam',\n", + " loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", + " metrics=['accuracy'])\n", + "​\n", + "history = model.fit(train_images, train_labels, epochs=10, \n", + " validation_data=(test_images, test_labels))" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "d2965f40", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "plt.plot(history.history['accuracy'], label='accuracy')\n", + "plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Accuracy')\n", + "plt.ylim([0.5, 1])\n", + "plt.legend(loc='lower right')\n", + "\n", + "test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n", + "\n", + "print(test_acc)" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/LectureNotes/chapter13.ipynb b/doc/LectureNotes/chapter13.ipynb new file mode 100644 index 000000000..7d78135c1 --- /dev/null +++ b/doc/LectureNotes/chapter13.ipynb @@ -0,0 +1,1873 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "6d2db899", + "metadata": { + "editable": true + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "f4908a97", + "metadata": { + "editable": true + }, + "source": [ + "# Recurrent neural networks: Overarching view\n", + "\n", + "Till now our focus has been, including convolutional neural networks\n", + "as well, on feedforward neural networks. The output or the activations\n", + "flow only in one direction, from the input layer to the output layer.\n", + "\n", + "A recurrent neural network (RNN) looks very much like a feedforward\n", + "neural network, except that it also has connections pointing\n", + "backward. \n", + "\n", + "RNNs are used to analyze time series data such as stock prices, and\n", + "tell you when to buy or sell. In autonomous driving systems, they can\n", + "anticipate car trajectories and help avoid accidents. More generally,\n", + "they can work on sequences of arbitrary lengths, rather than on\n", + "fixed-sized inputs like all the nets we have discussed so far. For\n", + "example, they can take sentences, documents, or audio samples as\n", + "input, making them extremely useful for natural language processing\n", + "systems such as automatic translation and speech-to-text.\n", + "\n", + "More to text to be added" + ] + }, + { + "cell_type": "markdown", + "id": "43cb4913", + "metadata": { + "editable": true + }, + "source": [ + "## A simple example" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "cf6b9dab", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "# Start importing packages\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import tensorflow as tf\n", + "from tensorflow.keras import datasets, layers, models\n", + "from tensorflow.keras.layers import Input\n", + "from tensorflow.keras.models import Model, Sequential \n", + "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n", + "from tensorflow.keras import optimizers \n", + "from tensorflow.keras import regularizers \n", + "from tensorflow.keras.utils import to_categorical \n", + "\n", + "\n", + "\n", + "# convert into dataset matrix\n", + "def convertToMatrix(data, step):\n", + " X, Y =[], []\n", + " for i in range(len(data)-step):\n", + " d=i+step \n", + " X.append(data[i:d,])\n", + " Y.append(data[d,])\n", + " return np.array(X), np.array(Y)\n", + "\n", + "step = 4\n", + "N = 1000 \n", + "Tp = 800 \n", + "\n", + "t=np.arange(0,N)\n", + "x=np.sin(0.02*t)+2*np.random.rand(N)\n", + "df = pd.DataFrame(x)\n", + "df.head()\n", + "\n", + "plt.plot(df)\n", + "plt.show()\n", + "\n", + "values=df.values\n", + "train,test = values[0:Tp,:], values[Tp:N,:]\n", + "\n", + "# add step elements into train and test\n", + "test = np.append(test,np.repeat(test[-1,],step))\n", + "train = np.append(train,np.repeat(train[-1,],step))\n", + " \n", + "trainX,trainY =convertToMatrix(train,step)\n", + "testX,testY =convertToMatrix(test,step)\n", + "trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\n", + "testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n", + "\n", + "model = Sequential()\n", + "model.add(SimpleRNN(units=32, input_shape=(1,step), activation=\"relu\"))\n", + "model.add(Dense(8, activation=\"relu\")) \n", + "model.add(Dense(1))\n", + "model.compile(loss='mean_squared_error', optimizer='rmsprop')\n", + "model.summary()\n", + "\n", + "model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)\n", + "trainPredict = model.predict(trainX)\n", + "testPredict= model.predict(testX)\n", + "predicted=np.concatenate((trainPredict,testPredict),axis=0)\n", + "\n", + "trainScore = model.evaluate(trainX, trainY, verbose=0)\n", + "print(trainScore)\n", + "\n", + "index = df.index.values\n", + "plt.plot(index,df)\n", + "plt.plot(index,predicted)\n", + "plt.axvline(df.index[Tp], c=\"r\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "897a47c7", + "metadata": { + "editable": true + }, + "source": [ + "## An extrapolation example\n", + "\n", + "The following code provides an example of how recurrent neural\n", + "networks can be used to extrapolate to unknown values of physics data\n", + "sets. Specifically, the data sets used in this program come from\n", + "a quantum mechanical many-body calculation of energies as functions of the number of particles." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "6776ae2a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "\n", + "# For matrices and calculations\n", + "import numpy as np\n", + "# For machine learning (backend for keras)\n", + "import tensorflow as tf\n", + "# User-friendly machine learning library\n", + "# Front end for TensorFlow\n", + "import tensorflow.keras\n", + "# Different methods from Keras needed to create an RNN\n", + "# This is not necessary but it shortened function calls \n", + "# that need to be used in the code.\n", + "from tensorflow.keras import datasets, layers, models\n", + "from tensorflow.keras.layers import Input\n", + "from tensorflow.keras import regularizers\n", + "from tensorflow.keras.models import Model, Sequential\n", + "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n", + "# For timing the code\n", + "from timeit import default_timer as timer\n", + "# For plotting\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "# The data set\n", + "datatype='VaryDimension'\n", + "X_tot = np.arange(2, 42, 2)\n", + "y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,\n", + "\t-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, \n", + "\t-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])" + ] + }, + { + "cell_type": "markdown", + "id": "35227d36", + "metadata": { + "editable": true + }, + "source": [ + "The way the recurrent neural networks are trained in this program\n", + "differs from how machine learning algorithms are usually trained.\n", + "Typically a machine learning algorithm is trained by learning the\n", + "relationship between the x data and the y data. In this program, the\n", + "recurrent neural network will be trained to recognize the relationship\n", + "in a sequence of y values. This is type of data formatting is\n", + "typically used time series forcasting, but it can also be used in any\n", + "extrapolation (time series forecasting is just a specific type of\n", + "extrapolation along the time axis). This method of data formatting\n", + "does not use the x data and assumes that the y data are evenly spaced.\n", + "\n", + "For a standard machine learning algorithm, the training data has the\n", + "form of (x,y) so the machine learning algorithm learns to assiciate a\n", + "y value with a given x value. This is useful when the test data has x\n", + "values within the same range as the training data. However, for this\n", + "application, the x values of the test data are outside of the x values\n", + "of the training data and the traditional method of training a machine\n", + "learning algorithm does not work as well. For this reason, the\n", + "recurrent neural network is trained on sequences of y values of the\n", + "form ((y1, y2), y3), so that the network is concerned with learning\n", + "the pattern of the y data and not the relation between the x and y\n", + "data. As long as the pattern of y data outside of the training region\n", + "stays relatively stable compared to what was inside the training\n", + "region, this method of training can produce accurate extrapolations to\n", + "y values far removed from the training data set." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "7dc577d1", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# FORMAT_DATA\n", + "def format_data(data, length_of_sequence = 2): \n", + " \"\"\"\n", + " Inputs:\n", + " data(a numpy array): the data that will be the inputs to the recurrent neural\n", + " network\n", + " length_of_sequence (an int): the number of elements in one iteration of the\n", + " sequence patter. For a function approximator use length_of_sequence = 2.\n", + " Returns:\n", + " rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its\n", + " dimensions are length of data - length of sequence, length of sequence, \n", + " dimnsion of data\n", + " rnn_output (a numpy array): the training data for the neural network\n", + " Formats data to be used in a recurrent neural network.\n", + " \"\"\"\n", + "\n", + " X, Y = [], []\n", + " for i in range(len(data)-length_of_sequence):\n", + " # Get the next length_of_sequence elements\n", + " a = data[i:i+length_of_sequence]\n", + " # Get the element that immediately follows that\n", + " b = data[i+length_of_sequence]\n", + " # Reshape so that each data point is contained in its own array\n", + " a = np.reshape (a, (len(a), 1))\n", + " X.append(a)\n", + " Y.append(b)\n", + " rnn_input = np.array(X)\n", + " rnn_output = np.array(Y)\n", + "\n", + " return rnn_input, rnn_output\n", + "\n", + "\n", + "# ## Defining the Recurrent Neural Network Using Keras\n", + "# \n", + "# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.\n", + "\n", + "def rnn(length_of_sequences, batch_size = None, stateful = False):\n", + " \"\"\"\n", + " Inputs:\n", + " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n", + " when the data is formatted\n", + " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n", + " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n", + " Returns:\n", + " model (a Keras model): The recurrent neural network that is built and compiled by this\n", + " method\n", + " Builds and compiles a recurrent neural network with one hidden layer and returns the model.\n", + " \"\"\"\n", + " # Number of neurons in the input and output layers\n", + " in_out_neurons = 1\n", + " # Number of neurons in the hidden layer\n", + " hidden_neurons = 200\n", + " # Define the input layer\n", + " inp = Input(batch_shape=(batch_size, \n", + " length_of_sequences, \n", + " in_out_neurons)) \n", + " # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to \n", + " # the network immediately after the input layer\n", + " rnn = SimpleRNN(hidden_neurons, \n", + " return_sequences=False,\n", + " stateful = stateful,\n", + " name=\"RNN\")(inp)\n", + " # Define the output layer as a dense neural network layer (standard neural network layer)\n", + " #and add it to the network immediately after the hidden layer.\n", + " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n", + " # Create the machine learning model starting with the input layer and ending with the \n", + " # output layer\n", + " model = Model(inputs=[inp],outputs=[dens])\n", + " # Compile the machine learning model using the mean squared error function as the loss \n", + " # function and an Adams optimizer.\n", + " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n", + " return model" + ] + }, + { + "cell_type": "markdown", + "id": "1978b6a1", + "metadata": { + "editable": true + }, + "source": [ + "## Predicting New Points With A Trained Recurrent Neural Network" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "d4ad417a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def test_rnn (x1, y_test, plot_min, plot_max):\n", + " \"\"\"\n", + " Inputs:\n", + " x1 (a list or numpy array): The complete x component of the data set\n", + " y_test (a list or numpy array): The complete y component of the data set\n", + " plot_min (an int or float): the smallest x value used in the training data\n", + " plot_max (an int or float): the largest x valye used in the training data\n", + " Returns:\n", + " None.\n", + " Uses a trained recurrent neural network model to predict future points in the \n", + " series. Computes the MSE of the predicted data set from the true data set, saves\n", + " the predicted data set to a csv file, and plots the predicted and true data sets w\n", + " while also displaying the data range used for training.\n", + " \"\"\"\n", + " # Add the training data as the first dim points in the predicted data array as these\n", + " # are known values.\n", + " y_pred = y_test[:dim].tolist()\n", + " # Generate the first input to the trained recurrent neural network using the last two \n", + " # points of the training data. Based on how the network was trained this means that it\n", + " # will predict the first point in the data set after the training data. All of the \n", + " # brackets are necessary for Tensorflow.\n", + " next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])\n", + " # Save the very last point in the training data set. This will be used later.\n", + " last = [y_test[dim-1]]\n", + "\n", + " # Iterate until the complete data set is created.\n", + " for i in range (dim, len(y_test)):\n", + " # Predict the next point in the data set using the previous two points.\n", + " next = model.predict(next_input)\n", + " # Append just the number of the predicted data set\n", + " y_pred.append(next[0][0])\n", + " # Create the input that will be used to predict the next data point in the data set.\n", + " next_input = np.array([[last, next[0]]], dtype=np.float64)\n", + " last = next\n", + "\n", + " # Print the mean squared error between the known data set and the predicted data set.\n", + " print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())\n", + " # Save the predicted data set as a csv file for later use\n", + " name = datatype + 'Predicted'+str(dim)+'.csv'\n", + " np.savetxt(name, y_pred, delimiter=',')\n", + " # Plot the known data set and the predicted data set. The red box represents the region that was used\n", + " # for the training data.\n", + " fig, ax = plt.subplots()\n", + " ax.plot(x1, y_test, label=\"true\", linewidth=3)\n", + " ax.plot(x1, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n", + " ax.legend()\n", + " # Created a red region to represent the points used in the training data.\n", + " ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')\n", + " plt.show()\n", + "\n", + "# Check to make sure the data set is complete\n", + "assert len(X_tot) == len(y_tot)\n", + "\n", + "# This is the number of points that will be used in as the training data\n", + "dim=12\n", + "\n", + "# Separate the training data from the whole data set\n", + "X_train = X_tot[:dim]\n", + "y_train = y_tot[:dim]\n", + "\n", + "\n", + "# Generate the training data for the RNN, using a sequence of 2\n", + "rnn_input, rnn_training = format_data(y_train, 2)\n", + "\n", + "\n", + "# Create a recurrent neural network in Keras and produce a summary of the \n", + "# machine learning model\n", + "model = rnn(length_of_sequences = rnn_input.shape[1])\n", + "model.summary()\n", + "\n", + "# Start the timer. Want to time training+testing\n", + "start = timer()\n", + "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n", + "# validation split. Setting verbose to True prints information about each training iteration.\n", + "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n", + " verbose=True,validation_split=0.05)\n", + "\n", + "for label in [\"loss\",\"val_loss\"]:\n", + " plt.plot(hist.history[label],label=label)\n", + "\n", + "plt.ylabel(\"loss\")\n", + "plt.xlabel(\"epoch\")\n", + "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n", + "plt.legend()\n", + "plt.show()\n", + "\n", + "# Use the trained neural network to predict more points of the data set\n", + "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n", + "# Stop the timer and calculate the total time needed.\n", + "end = timer()\n", + "print('Time: ', end-start)" + ] + }, + { + "cell_type": "markdown", + "id": "e2cad4fc", + "metadata": { + "editable": true + }, + "source": [ + "Changing the size of the recurrent neural network and its parameters\n", + "can drastically change the results you get from the model. The below\n", + "code takes the simple recurrent neural network from above and adds a\n", + "second hidden layer, changes the number of neurons in the hidden\n", + "layer, and explicitly declares the activation function of the hidden\n", + "layers to be a sigmoid function. The loss function and optimizer can\n", + "also be changed but are kept the same as the above network. These\n", + "parameters can be tuned to provide the optimal result from the\n", + "network. For some ideas on how to improve the performance of a\n", + "[recurrent neural network](https://danijar.com/tips-for-training-recurrent-neural-networks)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "c39f1516", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):\n", + " \"\"\"\n", + " Inputs:\n", + " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n", + " when the data is formatted\n", + " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n", + " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n", + " Returns:\n", + " model (a Keras model): The recurrent neural network that is built and compiled by this\n", + " method\n", + " Builds and compiles a recurrent neural network with two hidden layers and returns the model.\n", + " \"\"\"\n", + " # Number of neurons in the input and output layers\n", + " in_out_neurons = 1\n", + " # Number of neurons in the hidden layer, increased from the first network\n", + " hidden_neurons = 500\n", + " # Define the input layer\n", + " inp = Input(batch_shape=(batch_size, \n", + " length_of_sequences, \n", + " in_out_neurons)) \n", + " # Create two hidden layers instead of one hidden layer. Explicitly set the activation\n", + " # function to be the sigmoid function (the default value is hyperbolic tangent)\n", + " rnn1 = SimpleRNN(hidden_neurons, \n", + " return_sequences=True, # This needs to be True if another hidden layer is to follow\n", + " stateful = stateful, activation = 'sigmoid',\n", + " name=\"RNN1\")(inp)\n", + " rnn2 = SimpleRNN(hidden_neurons, \n", + " return_sequences=False, activation = 'sigmoid',\n", + " stateful = stateful,\n", + " name=\"RNN2\")(rnn1)\n", + " # Define the output layer as a dense neural network layer (standard neural network layer)\n", + " #and add it to the network immediately after the hidden layer.\n", + " dens = Dense(in_out_neurons,name=\"dense\")(rnn2)\n", + " # Create the machine learning model starting with the input layer and ending with the \n", + " # output layer\n", + " model = Model(inputs=[inp],outputs=[dens])\n", + " # Compile the machine learning model using the mean squared error function as the loss \n", + " # function and an Adams optimizer.\n", + " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n", + " return model\n", + "\n", + "# Check to make sure the data set is complete\n", + "assert len(X_tot) == len(y_tot)\n", + "\n", + "# This is the number of points that will be used in as the training data\n", + "dim=12\n", + "\n", + "# Separate the training data from the whole data set\n", + "X_train = X_tot[:dim]\n", + "y_train = y_tot[:dim]\n", + "\n", + "\n", + "# Generate the training data for the RNN, using a sequence of 2\n", + "rnn_input, rnn_training = format_data(y_train, 2)\n", + "\n", + "\n", + "# Create a recurrent neural network in Keras and produce a summary of the \n", + "# machine learning model\n", + "model = rnn_2layers(length_of_sequences = 2)\n", + "model.summary()\n", + "\n", + "# Start the timer. Want to time training+testing\n", + "start = timer()\n", + "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n", + "# validation split. Setting verbose to True prints information about each training iteration.\n", + "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n", + " verbose=True,validation_split=0.05)\n", + "\n", + "\n", + "# This section plots the training loss and the validation loss as a function of training iteration.\n", + "# This is not required for analyzing the couple cluster data but can help determine if the network is\n", + "# being overtrained.\n", + "for label in [\"loss\",\"val_loss\"]:\n", + " plt.plot(hist.history[label],label=label)\n", + "\n", + "plt.ylabel(\"loss\")\n", + "plt.xlabel(\"epoch\")\n", + "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n", + "plt.legend()\n", + "plt.show()\n", + "\n", + "# Use the trained neural network to predict more points of the data set\n", + "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n", + "# Stop the timer and calculate the total time needed.\n", + "end = timer()\n", + "print('Time: ', end-start)" + ] + }, + { + "cell_type": "markdown", + "id": "842c7602", + "metadata": { + "editable": true + }, + "source": [ + "## Other Types of Recurrent Neural Networks\n", + "\n", + "Besides a simple recurrent neural network layer, there are two other\n", + "commonly used types of recurrent neural network layers: Long Short\n", + "Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short\n", + "introduction to these layers see \n", + "and .\n", + "\n", + "The first network created below is similar to the previous network,\n", + "but it replaces the SimpleRNN layers with LSTM layers. The second\n", + "network below has two hidden layers made up of GRUs, which are\n", + "preceeded by two dense (feeddorward) neural network layers. These\n", + "dense layers \"preprocess\" the data before it reaches the recurrent\n", + "layers. This architecture has been shown to improve the performance\n", + "of recurrent neural networks (see the link above and also\n", + "." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "6f0e9b62", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):\n", + " \"\"\"\n", + " Inputs:\n", + " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n", + " when the data is formatted\n", + " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n", + " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n", + " Returns:\n", + " model (a Keras model): The recurrent neural network that is built and compiled by this\n", + " method\n", + " Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.\n", + " \"\"\"\n", + " # Number of neurons on the input/output layer and the number of neurons in the hidden layer\n", + " in_out_neurons = 1\n", + " hidden_neurons = 250\n", + " # Input Layer\n", + " inp = Input(batch_shape=(batch_size, \n", + " length_of_sequences, \n", + " in_out_neurons)) \n", + " # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)\n", + " rnn= LSTM(hidden_neurons, \n", + " return_sequences=True,\n", + " stateful = stateful,\n", + " name=\"RNN\", use_bias=True, activation='tanh')(inp)\n", + " rnn1 = LSTM(hidden_neurons, \n", + " return_sequences=False,\n", + " stateful = stateful,\n", + " name=\"RNN1\", use_bias=True, activation='tanh')(rnn)\n", + " # Output layer\n", + " dens = Dense(in_out_neurons,name=\"dense\")(rnn1)\n", + " # Define the midel\n", + " model = Model(inputs=[inp],outputs=[dens])\n", + " # Compile the model\n", + " model.compile(loss='mean_squared_error', optimizer='adam') \n", + " # Return the model\n", + " return model\n", + "\n", + "def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):\n", + " \"\"\"\n", + " Inputs:\n", + " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n", + " when the data is formatted\n", + " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n", + " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n", + " Returns:\n", + " model (a Keras model): The recurrent neural network that is built and compiled by this\n", + " method\n", + " Builds and compiles a recurrent neural network with four hidden layers (two dense followed by\n", + " two GRU layers) and returns the model.\n", + " \"\"\" \n", + " # Number of neurons on the input/output layers and hidden layers\n", + " in_out_neurons = 1\n", + " hidden_neurons = 250\n", + " # Input layer\n", + " inp = Input(batch_shape=(batch_size, \n", + " length_of_sequences, \n", + " in_out_neurons)) \n", + " # Hidden Dense (feedforward) layers\n", + " dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)\n", + " dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)\n", + " # Hidden GRU layers\n", + " rnn1 = GRU(hidden_neurons, \n", + " return_sequences=True,\n", + " stateful = stateful,\n", + " name=\"RNN1\", use_bias=True)(dnn1)\n", + " rnn = GRU(hidden_neurons, \n", + " return_sequences=False,\n", + " stateful = stateful,\n", + " name=\"RNN\", use_bias=True)(rnn1)\n", + " # Output layer\n", + " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n", + " # Define the model\n", + " model = Model(inputs=[inp],outputs=[dens])\n", + " # Compile the mdoel\n", + " model.compile(loss='mean_squared_error', optimizer='adam') \n", + " # Return the model\n", + " return model\n", + "\n", + "# Check to make sure the data set is complete\n", + "assert len(X_tot) == len(y_tot)\n", + "\n", + "# This is the number of points that will be used in as the training data\n", + "dim=12\n", + "\n", + "# Separate the training data from the whole data set\n", + "X_train = X_tot[:dim]\n", + "y_train = y_tot[:dim]\n", + "\n", + "\n", + "# Generate the training data for the RNN, using a sequence of 2\n", + "rnn_input, rnn_training = format_data(y_train, 2)\n", + "\n", + "\n", + "# Create a recurrent neural network in Keras and produce a summary of the \n", + "# machine learning model\n", + "# Change the method name to reflect which network you want to use\n", + "model = dnn2_gru2(length_of_sequences = 2)\n", + "model.summary()\n", + "\n", + "# Start the timer. Want to time training+testing\n", + "start = timer()\n", + "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n", + "# validation split. Setting verbose to True prints information about each training iteration.\n", + "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n", + " verbose=True,validation_split=0.05)\n", + "\n", + "\n", + "# This section plots the training loss and the validation loss as a function of training iteration.\n", + "# This is not required for analyzing the couple cluster data but can help determine if the network is\n", + "# being overtrained.\n", + "for label in [\"loss\",\"val_loss\"]:\n", + " plt.plot(hist.history[label],label=label)\n", + "\n", + "plt.ylabel(\"loss\")\n", + "plt.xlabel(\"epoch\")\n", + "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n", + "plt.legend()\n", + "plt.show()\n", + "\n", + "# Use the trained neural network to predict more points of the data set\n", + "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n", + "# Stop the timer and calculate the total time needed.\n", + "end = timer()\n", + "print('Time: ', end-start)\n", + "\n", + "\n", + "# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)\n", + "# \n", + "# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.\n", + "\n", + "# Check to make sure the data set is complete\n", + "assert len(X_tot) == len(y_tot)\n", + "\n", + "# This is the number of points that will be used in as the training data\n", + "dim=12\n", + "\n", + "# Separate the training data from the whole data set\n", + "X_train = X_tot[:dim]\n", + "y_train = y_tot[:dim]\n", + "\n", + "# Reshape the data for Keras specifications\n", + "X_train = X_train.reshape((dim, 1))\n", + "y_train = y_train.reshape((dim, 1))\n", + "\n", + "\n", + "# Create a recurrent neural network in Keras and produce a summary of the \n", + "# machine learning model\n", + "# Set the sequence length to 1 for regular data formatting \n", + "model = rnn(length_of_sequences = 1)\n", + "model.summary()\n", + "\n", + "# Start the timer. Want to time training+testing\n", + "start = timer()\n", + "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n", + "# validation split. Setting verbose to True prints information about each training iteration.\n", + "hist = model.fit(X_train, y_train, batch_size=None, epochs=150, \n", + " verbose=True,validation_split=0.05)\n", + "\n", + "\n", + "# This section plots the training loss and the validation loss as a function of training iteration.\n", + "# This is not required for analyzing the couple cluster data but can help determine if the network is\n", + "# being overtrained.\n", + "for label in [\"loss\",\"val_loss\"]:\n", + " plt.plot(hist.history[label],label=label)\n", + "\n", + "plt.ylabel(\"loss\")\n", + "plt.xlabel(\"epoch\")\n", + "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n", + "plt.legend()\n", + "plt.show()\n", + "\n", + "# Use the trained neural network to predict the remaining data points\n", + "X_pred = X_tot[dim:]\n", + "X_pred = X_pred.reshape((len(X_pred), 1))\n", + "y_model = model.predict(X_pred)\n", + "y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))\n", + "\n", + "# Plot the known data set and the predicted data set. The red box represents the region that was used\n", + "# for the training data.\n", + "fig, ax = plt.subplots()\n", + "ax.plot(X_tot, y_tot, label=\"true\", linewidth=3)\n", + "ax.plot(X_tot, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n", + "ax.legend()\n", + "# Created a red region to represent the points used in the training data.\n", + "ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')\n", + "plt.show()\n", + "\n", + "# Stop the timer and calculate the total time needed.\n", + "end = timer()\n", + "print('Time: ', end-start)" + ] + }, + { + "cell_type": "markdown", + "id": "0752ba7f", + "metadata": { + "editable": true + }, + "source": [ + "# Generative Models\n", + "\n", + "**Generative models** describe a class of statistical models that are a contrast\n", + "to **discriminative models**. Informally we say that generative models can\n", + "generate new data instances while discriminative models discriminate between\n", + "different kinds of data instances. A generative model could generate new photos\n", + "of animals that look like 'real' animals while a discriminative model could tell\n", + "a dog from a cat. More formally, given a data set $x$ and a set of labels /\n", + "targets $y$. Generative models capture the joint probability $p(x, y)$, or\n", + "just $p(x)$ if there are no labels, while discriminative models capture the\n", + "conditional probability $p(y | x)$. Discriminative models generally try to draw\n", + "boundaries in the data space (often high dimensional), while generative models\n", + "try to model how data is placed throughout the space.\n", + "\n", + "**Note**: this material is thanks to Linus Ekstrøm." + ] + }, + { + "cell_type": "markdown", + "id": "784138f8", + "metadata": { + "editable": true + }, + "source": [ + "## Generative Adversarial Networks\n", + "\n", + "**Generative Adversarial Networks** are a type of unsupervised machine learning\n", + "algorithm proposed by [Goodfellow et. al](https://arxiv.org/pdf/1406.2661.pdf)\n", + "in 2014 (short and good article).\n", + "\n", + "The simplest formulation of\n", + "the model is based on a game theoretic approach, *zero sum game*, where we pit\n", + "two neural networks against one another. We define two rival networks, one\n", + "generator $g$, and one discriminator $d$. The generator directly produces\n", + "samples" + ] + }, + { + "cell_type": "markdown", + "id": "a42f89ee", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " x = g(z; \\theta^{(g)})\n", + "\\label{_auto1} \\tag{1}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "abe7212f", + "metadata": { + "editable": true + }, + "source": [ + "The discriminator attempts to distinguish between samples drawn from the\n", + "training data and samples drawn from the generator. In other words, it tries to\n", + "tell the difference between the fake data produced by $g$ and the actual data\n", + "samples we want to do prediction on. The discriminator outputs a probability\n", + "value given by" + ] + }, + { + "cell_type": "markdown", + "id": "0821eaee", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " d(x; \\theta^{(d)})\n", + "\\label{_auto2} \\tag{2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "55e0ccf6", + "metadata": { + "editable": true + }, + "source": [ + "indicating the probability that $x$ is a real training example rather than a\n", + "fake sample the generator has generated. The simplest way to formulate the\n", + "learning process in a generative adversarial network is a zero-sum game, in\n", + "which a function" + ] + }, + { + "cell_type": "markdown", + "id": "f37ece14", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " v(\\theta^{(g)}, \\theta^{(d)})\n", + "\\label{_auto3} \\tag{3}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d6d6d5fa", + "metadata": { + "editable": true + }, + "source": [ + "determines the reward for the discriminator, while the generator gets the\n", + "conjugate reward" + ] + }, + { + "cell_type": "markdown", + "id": "3c74b45c", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " -v(\\theta^{(g)}, \\theta^{(d)})\n", + "\\label{_auto4} \\tag{4}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "605ac8c9", + "metadata": { + "editable": true + }, + "source": [ + "During learning both of the networks maximize their own reward function, so that\n", + "the generator gets better and better at tricking the discriminator, while the\n", + "discriminator gets better and better at telling the difference between the fake\n", + "and real data. The generator and discriminator alternate on which one trains at\n", + "one time (i.e. for one epoch). In other words, we keep the generator constant\n", + "and train the discriminator, then we keep the discriminator constant to train\n", + "the generator and repeat. It is this back and forth dynamic which lets GANs\n", + "tackle otherwise intractable generative problems. As the generator improves with\n", + " training, the discriminator's performance gets worse because it cannot easily\n", + " tell the difference between real and fake. If the generator ends up succeeding\n", + " perfectly, the the discriminator will do no better than random guessing i.e.\n", + " 50\\%. This progression in the training poses a problem for the convergence\n", + " criteria for GANs. The discriminator feedback gets less meaningful over time,\n", + " if we continue training after this point then the generator is effectively\n", + " training on junk data which can undo the learning up to that point. Therefore,\n", + " we stop training when the discriminator starts outputting $1/2$ everywhere.\n", + "\n", + "At convergence we have" + ] + }, + { + "cell_type": "markdown", + "id": "cfec7462", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " g^* = \\underset{g}{\\mathrm{argmin}}\\hspace{2pt}\n", + " \\underset{d}{\\mathrm{max}}v(\\theta^{(g)}, \\theta^{(d)})\n", + "\\label{_auto5} \\tag{5}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "37c65d4c", + "metadata": { + "editable": true + }, + "source": [ + "The default choice for $v$ is" + ] + }, + { + "cell_type": "markdown", + "id": "c868a092", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " v(\\theta^{(g)}, \\theta^{(d)}) = \\mathbb{E}_{x\\sim p_\\mathrm{data}}\\log d(x)\n", + " + \\mathbb{E}_{x\\sim p_\\mathrm{model}}\n", + " \\log (1 - d(x))\n", + "\\label{_auto6} \\tag{6}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ad465af3", + "metadata": { + "editable": true + }, + "source": [ + "The main motivation for the design of GANs is that the learning process requires\n", + "neither approximate inference (variational autoencoders for example) nor\n", + "approximation of a partition function. In the case where" + ] + }, + { + "cell_type": "markdown", + "id": "27858a4e", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\underset{d}{\\mathrm{max}}v(\\theta^{(g)}, \\theta^{(d)})\n", + "\\label{_auto7} \\tag{7}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "86006023", + "metadata": { + "editable": true + }, + "source": [ + "is convex in $\\theta^{(g)} then the procedure is guaranteed to converge and is\n", + "asymptotically consistent\n", + "( [Seth Lloyd on QuGANs](https://arxiv.org/pdf/1804.09139.pdf) ).\n", + "\n", + "This is in\n", + "general not the case and it is possible to get situations where the training\n", + "process never converges because the generator and discriminator chase one\n", + "another around in the parameter space indefinitely. A much deeper discussion on\n", + "the currently open research problem of GAN convergence is available\n", + "[here](https://www.deeplearningbook.org/contents/generative_models.html). To\n", + "anyone interested in learning more about GANs it is a highly recommended read.\n", + "Direct quote: \"In this best-performing formulation, the generator aims to\n", + "increase the log probability that the discriminator makes a mistake, rather than\n", + "aiming to decrease the log probability that the discriminator makes the correct\n", + "prediction.\" [Another interesting read](https://arxiv.org/abs/1701.00160)" + ] + }, + { + "cell_type": "markdown", + "id": "2fee38bd", + "metadata": { + "editable": true + }, + "source": [ + "## Writing Our First Generative Adversarial Network\n", + "Let us now move on to actually implementing a GAN in tensorflow. We will study\n", + "the performance of our GAN on the MNIST dataset. This code is based on and\n", + "adapted from the\n", + "[google tutorial](https://www.tensorflow.org/tutorials/generative/dcgan)\n", + "\n", + "First we import our libraries" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "004a0b53", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import os\n", + "import time\n", + "import numpy as np\n", + "import tensorflow as tf\n", + "import matplotlib.pyplot as plt\n", + "from tensorflow.keras import layers\n", + "from tensorflow.keras.utils import plot_model" + ] + }, + { + "cell_type": "markdown", + "id": "353af161", + "metadata": { + "editable": true + }, + "source": [ + "Next we define our hyperparameters and import our data the usual way" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "8cbaf16a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "BUFFER_SIZE = 60000\n", + "BATCH_SIZE = 256\n", + "EPOCHS = 30\n", + "\n", + "data = tf.keras.datasets.mnist.load_data()\n", + "(train_images, train_labels), (test_images, test_labels) = data\n", + "train_images = np.reshape(train_images, (train_images.shape[0],\n", + " 28,\n", + " 28,\n", + " 1)).astype('float32')\n", + "\n", + "# we normalize between -1 and 1\n", + "train_images = (train_images - 127.5) / 127.5\n", + "training_dataset = tf.data.Dataset.from_tensor_slices(\n", + " train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)" + ] + }, + { + "cell_type": "markdown", + "id": "822b8cc7", + "metadata": { + "editable": true + }, + "source": [ + "### MNIST and GANs\n", + "\n", + "Let's have a quick look" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "52b5965c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "plt.imshow(train_images[0], cmap='Greys')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "21c5199c", + "metadata": { + "editable": true + }, + "source": [ + "Now we define our two models. This is where the 'magic' happens. There are a\n", + "huge amount of possible formulations for both models. A lot of engineering and\n", + "trial and error can be done here to try to produce better performing models. For\n", + "more advanced GANs this is by far the step where you can 'make or break' a\n", + "model.\n", + "\n", + "We start with the generator. As stated in the introductory text the generator\n", + "$g$ upsamples from a random sample to the shape of what we want to predict. In\n", + "our case we are trying to predict MNIST images ($28\\times 28$ pixels)." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "356759c7", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def generator_model():\n", + " \"\"\"\n", + " The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to\n", + " produce an image from a random seed. We start with a Dense layer taking this\n", + " random sample as an input and subsequently upsample through multiple\n", + " convolutional layers.\n", + " \"\"\"\n", + "\n", + " # we define our model\n", + " model = tf.keras.Sequential()\n", + "\n", + "\n", + " # adding our input layer. Dense means that every neuron is connected and\n", + " # the input shape is the shape of our random noise. The units need to match\n", + " # in some sense the upsampling strides to reach our desired output shape.\n", + " # we are using 100 random numbers as our seed\n", + " model.add(layers.Dense(units=7*7*BATCH_SIZE,\n", + " use_bias=False,\n", + " input_shape=(100, )))\n", + " # we normalize the output form the Dense layer\n", + " model.add(layers.BatchNormalization())\n", + " # and add an activation function to our 'layer'. LeakyReLU avoids vanishing\n", + " # gradient problem\n", + " model.add(layers.LeakyReLU())\n", + " model.add(layers.Reshape((7, 7, BATCH_SIZE)))\n", + " assert model.output_shape == (None, 7, 7, BATCH_SIZE)\n", + " # even though we just added four keras layers we think of everything above\n", + " # as 'one' layer\n", + "\n", + " # next we add our upscaling convolutional layers\n", + " model.add(layers.Conv2DTranspose(filters=128,\n", + " kernel_size=(5, 5),\n", + " strides=(1, 1),\n", + " padding='same',\n", + " use_bias=False))\n", + " model.add(layers.BatchNormalization())\n", + " model.add(layers.LeakyReLU())\n", + " assert model.output_shape == (None, 7, 7, 128)\n", + "\n", + " model.add(layers.Conv2DTranspose(filters=64,\n", + " kernel_size=(5, 5),\n", + " strides=(2, 2),\n", + " padding='same',\n", + " use_bias=False))\n", + " model.add(layers.BatchNormalization())\n", + " model.add(layers.LeakyReLU())\n", + " assert model.output_shape == (None, 14, 14, 64)\n", + "\n", + " model.add(layers.Conv2DTranspose(filters=1,\n", + " kernel_size=(5, 5),\n", + " strides=(2, 2),\n", + " padding='same',\n", + " use_bias=False,\n", + " activation='tanh'))\n", + " assert model.output_shape == (None, 28, 28, 1)\n", + "\n", + " return model" + ] + }, + { + "cell_type": "markdown", + "id": "854bcd6b", + "metadata": { + "editable": true + }, + "source": [ + "And there we have our 'simple' generator model. Now we move on to defining our\n", + "discriminator model $d$, which is a convolutional neural network based image\n", + "classifier." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "41473304", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def discriminator_model():\n", + " \"\"\"\n", + " The discriminator is a convolutional neural network based image classifier\n", + " \"\"\"\n", + "\n", + " # we define our model\n", + " model = tf.keras.Sequential()\n", + " model.add(layers.Conv2D(filters=64,\n", + " kernel_size=(5, 5),\n", + " strides=(2, 2),\n", + " padding='same',\n", + " input_shape=[28, 28, 1]))\n", + " model.add(layers.LeakyReLU())\n", + " # adding a dropout layer as you do in conv-nets\n", + " model.add(layers.Dropout(0.3))\n", + "\n", + "\n", + " model.add(layers.Conv2D(filters=128,\n", + " kernel_size=(5, 5),\n", + " strides=(2, 2),\n", + " padding='same'))\n", + " model.add(layers.LeakyReLU())\n", + " # adding a dropout layer as you do in conv-nets\n", + " model.add(layers.Dropout(0.3))\n", + "\n", + " model.add(layers.Flatten())\n", + " model.add(layers.Dense(1))\n", + "\n", + " return model" + ] + }, + { + "cell_type": "markdown", + "id": "353af567", + "metadata": { + "editable": true + }, + "source": [ + "Let us take a look at our models." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "f899d4e3", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "generator = generator_model()\n", + "plot_model(generator, show_shapes=True, rankdir='LR')" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "87ef384b", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "discriminator = discriminator_model()\n", + "plot_model(discriminator, show_shapes=True, rankdir='LR')" + ] + }, + { + "cell_type": "markdown", + "id": "b2bef82d", + "metadata": { + "editable": true + }, + "source": [ + "Next we need a few helper objects we will use in training" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "e397847a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n", + "generator_optimizer = tf.keras.optimizers.Adam(1e-4)\n", + "discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)" + ] + }, + { + "cell_type": "markdown", + "id": "db3396cc", + "metadata": { + "editable": true + }, + "source": [ + "The first object, *cross_entropy* is our loss function and the two others are\n", + "our optimizers. Notice we use the same learning rate for both $g$ and $d$. This\n", + "is because they need to improve their accuracy at approximately equal speeds to\n", + "get convergence (not necessarily exactly equal). Now we define our loss\n", + "functions" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "931eaced", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def generator_loss(fake_output):\n", + " loss = cross_entropy(tf.ones_like(fake_output), fake_output)\n", + "\n", + " return loss" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "0c4a44bb", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def discriminator_loss(real_output, fake_output):\n", + " real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n", + " fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output)\n", + " total_loss = real_loss + fake_loss\n", + "\n", + " return total_loss" + ] + }, + { + "cell_type": "markdown", + "id": "fcf8f066", + "metadata": { + "editable": true + }, + "source": [ + "Next we define a kind of seed to help us compare the learning process over\n", + "multiple training epochs." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "eea2bbee", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "noise_dimension = 100\n", + "n_examples_to_generate = 16\n", + "seed_images = tf.random.normal([n_examples_to_generate, noise_dimension])" + ] + }, + { + "cell_type": "markdown", + "id": "94a6e341", + "metadata": { + "editable": true + }, + "source": [ + "Now we have everything we need to define our training step, which we will apply\n", + "for every step in our training loop. Notice the @tf.function flag signifying\n", + "that the function is tensorflow 'compiled'. Removing this flag doubles the\n", + "computation time." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "8d48470b", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "@tf.function\n", + "def train_step(images):\n", + " noise = tf.random.normal([BATCH_SIZE, noise_dimension])\n", + "\n", + " with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n", + " generated_images = generator(noise, training=True)\n", + "\n", + " real_output = discriminator(images, training=True)\n", + " fake_output = discriminator(generated_images, training=True)\n", + "\n", + " gen_loss = generator_loss(fake_output)\n", + " disc_loss = discriminator_loss(real_output, fake_output)\n", + "\n", + " gradients_of_generator = gen_tape.gradient(gen_loss,\n", + " generator.trainable_variables)\n", + " gradients_of_discriminator = disc_tape.gradient(disc_loss,\n", + " discriminator.trainable_variables)\n", + " generator_optimizer.apply_gradients(zip(gradients_of_generator,\n", + " generator.trainable_variables))\n", + " discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator,\n", + " discriminator.trainable_variables))\n", + "\n", + " return gen_loss, disc_loss" + ] + }, + { + "cell_type": "markdown", + "id": "62015b88", + "metadata": { + "editable": true + }, + "source": [ + "Next we define a helper function to produce an output over our training epochs\n", + "to see the predictive progression of our generator model. **Note**: I am including\n", + "this code here, but comment it out in the training loop." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "b189ed96", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def generate_and_save_images(model, epoch, test_input):\n", + " # we're making inferences here\n", + " predictions = model(test_input, training=False)\n", + "\n", + " fig = plt.figure(figsize=(4, 4))\n", + "\n", + " for i in range(predictions.shape[0]):\n", + " plt.subplot(4, 4, i+1)\n", + " plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')\n", + " plt.axis('off')\n", + "\n", + " plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png')\n", + " plt.close()\n", + " #plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "ba2c82d5", + "metadata": { + "editable": true + }, + "source": [ + "Setting up checkpoints to periodically save our model during training so that\n", + "everything is not lost even if the program were to somehow terminate while\n", + "training." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "a0e2fc8a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Setting up checkpoints to save model during training\n", + "checkpoint_dir = './training_checkpoints'\n", + "checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')\n", + "checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n", + " discriminator_optimizer=discriminator_optimizer,\n", + " generator=generator,\n", + " discriminator=discriminator)" + ] + }, + { + "cell_type": "markdown", + "id": "4d93a0f7", + "metadata": { + "editable": true + }, + "source": [ + "Now we define our training loop" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "a1275556", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def train(dataset, epochs):\n", + " generator_loss_list = []\n", + " discriminator_loss_list = []\n", + "\n", + " for epoch in range(epochs):\n", + " start = time.time()\n", + "\n", + " for image_batch in dataset:\n", + " gen_loss, disc_loss = train_step(image_batch)\n", + " generator_loss_list.append(gen_loss.numpy())\n", + " discriminator_loss_list.append(disc_loss.numpy())\n", + "\n", + " #generate_and_save_images(generator, epoch + 1, seed_images)\n", + "\n", + " if (epoch + 1) % 15 == 0:\n", + " checkpoint.save(file_prefix=checkpoint_prefix)\n", + "\n", + " print(f'Time for epoch {epoch} is {time.time() - start}')\n", + "\n", + " #generate_and_save_images(generator, epochs, seed_images)\n", + "\n", + " loss_file = './data/lossfile.txt'\n", + " with open(loss_file, 'w') as outfile:\n", + " outfile.write(str(generator_loss_list))\n", + " outfile.write('\\n')\n", + " outfile.write('\\n')\n", + " outfile.write(str(discriminator_loss_list))\n", + " outfile.write('\\n')\n", + " outfile.write('\\n')" + ] + }, + { + "cell_type": "markdown", + "id": "6ff3a75a", + "metadata": { + "editable": true + }, + "source": [ + "To train simply call this function. **Warning**: this might take a long time so\n", + "there is a folder of a pretrained network already included in the repository." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "371ed41a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "train(train_dataset, EPOCHS)" + ] + }, + { + "cell_type": "markdown", + "id": "654399f1", + "metadata": { + "editable": true + }, + "source": [ + "Now to avoid having to train and everything, which will take a while depending\n", + "on your computer setup we now load in the model which produced the above gif." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "dec4b560", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))\n", + "restored_generator = checkpoint.generator\n", + "restored_discriminator = checkpoint.discriminator\n", + "\n", + "print(restored_generator)\n", + "print(restored_discriminator)" + ] + }, + { + "cell_type": "markdown", + "id": "296bfa5c", + "metadata": { + "editable": true + }, + "source": [ + "We have successfully loaded in our latest model. Let us now play around a bit\n", + "and see what kind of things we can learn about this model. Our generator takes\n", + "an array of 100 numbers. One idea can be to try to systematically change our\n", + "input. Let us try and see what we get" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "eecfbb1f", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def generate_latent_points(number=100, scale_means=1, scale_stds=1):\n", + " latent_dim = 100\n", + " means = scale_means * tf.linspace(-1, 1, num=latent_dim)\n", + " stds = scale_stds * tf.linspace(-1, 1, num=latent_dim)\n", + " latent_space_value_range = tf.random.normal([number, latent_dim],\n", + " means,\n", + " stds,\n", + " dtype=tf.float64)\n", + "\n", + " return latent_space_value_range\n", + "\n", + "def generate_images(latent_points):\n", + " # notice we set training to false because we are making inferences\n", + " generated_images = restored_generator.predict(latent_points)\n", + "\n", + " return generated_images" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "333a593d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def plot_result(generated_images, number=100):\n", + " # obviously this assumes sqrt number is an int\n", + " fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)),\n", + " figsize=(10, 10))\n", + "\n", + " for i in range(int(np.sqrt(number))):\n", + " for j in range(int(np.sqrt(number))):\n", + " axs[i, j].imshow(generated_images[i*j], cmap='Greys')\n", + " axs[i, j].axis('off')\n", + "\n", + " plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "2f5f0154", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "generated_images = generate_images(generate_latent_points())\n", + "plot_result(generated_images)" + ] + }, + { + "cell_type": "markdown", + "id": "ff581bf2", + "metadata": { + "editable": true + }, + "source": [ + "We see that the generator generates images that look like MNIST\n", + "numbers: $1, 4, 7, 9$. Let's try to tweak it a bit more to see if we are able\n", + "to generate a similar plot where we generate every MNIST number. Let us now try\n", + "to 'move' a bit around in the latent space. **Note**: decrease the plot number if\n", + "these following cells take too long to run on your computer." + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "d3617ad8", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "plot_number = 225\n", + "\n", + "generated_images = generate_images(generate_latent_points(number=plot_number,\n", + " scale_means=5,\n", + " scale_stds=1))\n", + "plot_result(generated_images, number=plot_number)\n", + "\n", + "generated_images = generate_images(generate_latent_points(number=plot_number,\n", + " scale_means=-5,\n", + " scale_stds=1))\n", + "plot_result(generated_images, number=plot_number)\n", + "\n", + "generated_images = generate_images(generate_latent_points(number=plot_number,\n", + " scale_means=1,\n", + " scale_stds=5))\n", + "plot_result(generated_images, number=plot_number)" + ] + }, + { + "cell_type": "markdown", + "id": "1a074f93", + "metadata": { + "editable": true + }, + "source": [ + "Again, we have found something interesting. *Moving* around using our means\n", + "takes us from digit to digit, while *moving* around using our standard\n", + "deviations seem to increase the number of different digits! In the last image\n", + "above, we can barely make out every MNIST digit. Let us make on last plot using\n", + "this information by upping the standard deviation of our Gaussian noises." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "4ef8937d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "plot_number = 400\n", + "generated_images = generate_images(generate_latent_points(number=plot_number,\n", + " scale_means=1,\n", + " scale_stds=10))\n", + "plot_result(generated_images, number=plot_number)" + ] + }, + { + "cell_type": "markdown", + "id": "385a2d0a", + "metadata": { + "editable": true + }, + "source": [ + "A pretty cool result! We see that our generator indeed has learned a\n", + "distribution which qualitatively looks a whole lot like the MNIST dataset.\n", + "\n", + "Another interesting way to explore the latent space of our generator model is by\n", + "interpolating between the MNIST digits. This section is largely based on\n", + "[this excellent blogpost](https://machinelearningmastery.com/how-to-interpolate-and-perform-vector-arithmetic-with-faces-using-a-generative-adversarial-network/)\n", + "by Jason Brownlee.\n", + "\n", + "So let us start by defining a function to interpolate between two points in the\n", + "latent space." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "57de87b8", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def interpolation(point_1, point_2, n_steps=10):\n", + " ratios = np.linspace(0, 1, num=n_steps)\n", + " vectors = []\n", + " for i, ratio in enumerate(ratios):\n", + " vectors.append(((1.0 - ratio) * point_1 + ratio * point_2))\n", + "\n", + " return tf.stack(vectors)" + ] + }, + { + "cell_type": "markdown", + "id": "cfb76bb6", + "metadata": { + "editable": true + }, + "source": [ + "Now we have all we need to do our interpolation analysis." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "e25decef", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "plot_number = 100\n", + "latent_points = generate_latent_points(number=plot_number)\n", + "results = None\n", + "for i in range(0, 2*np.sqrt(plot_number), 2):\n", + " interpolated = interpolation(latent_points[i], latent_points[i+1])\n", + " generated_images = generate_images(interpolated)\n", + "\n", + " if results is None:\n", + " results = generated_images\n", + " else:\n", + " results = tf.stack((results, generated_images))\n", + "\n", + "plot_results(results, plot_number)" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/LectureNotes/chapteroptimization.ipynb b/doc/LectureNotes/chapteroptimization.ipynb index e8dc9fc17..5d83c5b50 100644 --- a/doc/LectureNotes/chapteroptimization.ipynb +++ b/doc/LectureNotes/chapteroptimization.ipynb @@ -2,7 +2,21 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "4d72e1df", + "metadata": { + "editable": true + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "fb6e8fcd", + "metadata": { + "editable": true + }, "source": [ "# Optimization, the central part of any Machine Learning algortithm\n", "\n", @@ -15,9 +29,6 @@ "analytically, however this is not possible in general and we must use\n", "some approximative/numerical method to compute the minimum.\n", "\n", - "\n", - "\n", - "\n", "In our discussion on Logistic Regression we studied the \n", "case of\n", "two classes, with $y_i$ either\n", @@ -28,7 +39,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a507b82a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -40,12 +54,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4071429e", + "metadata": { + "editable": true + }, "source": [ "where $\\boldsymbol{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n", "\n", - "\n", - "\n", "Our compact equations used a definition of a vector $\\boldsymbol{y}$ with $n$\n", "elements $y_i$, an $n\\times p$ matrix $\\boldsymbol{X}$ which contains the\n", "$x_i$ values and a vector $\\boldsymbol{p}$ of fitted probabilities\n", @@ -55,7 +70,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a3cca0b2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = -\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{p}\\right).\n", @@ -64,7 +82,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "12a4ad28", + "metadata": { + "editable": true + }, "source": [ "If we in addition define a diagonal matrix $\\boldsymbol{W}$ with elements \n", "$p(y_i\\vert x_i,\\boldsymbol{\\beta})(1-p(y_i\\vert x_i,\\boldsymbol{\\beta})$, we can obtain a compact expression of the second derivative as" @@ -72,7 +93,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5d6e7796", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T} = \\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X}.\n", @@ -81,12 +105,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b324ae78", + "metadata": { + "editable": true + }, "source": [ "This defines what is called the Hessian matrix.\n", "\n", - "\n", - "\n", "If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives. \n", "\n", "Our iterative scheme is then given by" @@ -94,7 +119,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7c39cc3f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\beta}^{\\mathrm{new}} = \\boldsymbol{\\beta}^{\\mathrm{old}}-\\left(\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\right)^{-1}_{\\boldsymbol{\\beta}^{\\mathrm{old}}}\\times \\left(\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}\\right)_{\\boldsymbol{\\beta}^{\\mathrm{old}}},\n", @@ -103,14 +131,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "10749f5d", + "metadata": { + "editable": true + }, "source": [ "or in matrix form as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "3ec50136", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\beta}^{\\mathrm{new}} = \\boldsymbol{\\beta}^{\\mathrm{old}}-\\left(\\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X} \\right)^{-1}\\times \\left(-\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{p}) \\right)_{\\boldsymbol{\\beta}^{\\mathrm{old}}}.\n", @@ -119,13 +153,15 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0145d9eb", + "metadata": { + "editable": true + }, "source": [ "The right-hand side is computed with the old values of $\\beta$. \n", "\n", "If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement. \n", "\n", - "\n", "Let us quickly remind ourselves how we derive the above method.\n", "\n", "Perhaps the most celebrated of all one-dimensional root-finding\n", @@ -136,8 +172,6 @@ "numerically and/or your function is not of the smooth type, we\n", "normally discourage the use of this method.\n", "\n", - "\n", - "\n", "The Newton-Raphson formula consists geometrically of extending the\n", "tangent line at a current point until it crosses zero, then setting\n", "the next guess to the abscissa of that zero-crossing. The mathematics\n", @@ -147,7 +181,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "43c17534", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -160,7 +197,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "32ef04f0", + "metadata": { + "editable": true + }, "source": [ "For small enough values of the function and for well-behaved\n", "functions, the terms beyond linear are unimportant, hence we obtain" @@ -168,7 +208,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6700017c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(x)+(s-x)f'(x)\\approx 0,\n", @@ -177,14 +220,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8791dec4", + "metadata": { + "editable": true + }, "source": [ "yielding" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "69008872", + "metadata": { + "editable": true + }, "source": [ "$$\n", "s\\approx x-\\frac{f(x)}{f'(x)}.\n", @@ -193,14 +242,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fce4ef1f", + "metadata": { + "editable": true + }, "source": [ "Having in mind an iterative procedure, it is natural to start iterating with" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e64aef7e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "x_{n+1}=x_n-\\frac{f(x_n)}{f'(x_n)}.\n", @@ -209,7 +264,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9acecc44", + "metadata": { + "editable": true + }, "source": [ "The above is Newton-Raphson's method. It has a simple geometric\n", "interpretation, namely $x_{n+1}$ is the point where the tangent from\n", @@ -223,16 +281,16 @@ "guess near such a local extremum, so that the first derivative nearly\n", "vanishes, then Newton-Raphson may fail totally\n", "\n", - "\n", - "\n", - "\n", "Newton's method can be generalized to systems of several non-linear equations\n", "and variables. Consider the case with two equations" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "18bc9fd6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{array}{cc} f_1(x_1,x_2) &=0\\\\\n", @@ -242,14 +300,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7dcad370", + "metadata": { + "editable": true + }, "source": [ "which we Taylor expand to obtain" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f1724121", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1\n", @@ -264,14 +328,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d04bfa9f", + "metadata": { + "editable": true + }, "source": [ "Defining the Jacobian matrix $\\boldsymbol{J}$ we have" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "a4d3a9e3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{J}=\\left( \\begin{array}{cc}\n", @@ -283,14 +353,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d9d6ff69", + "metadata": { + "editable": true + }, "source": [ "we can rephrase Newton's method as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "362a86a3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\left(\\begin{array}{c} x_1^{n+1} \\\\ x_2^{n+1} \\end{array} \\right)=\n", @@ -301,14 +377,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4b8c2937", + "metadata": { + "editable": true + }, "source": [ "where we have defined" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "7580aa9a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right)=\n", @@ -319,18 +401,26 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a2e3adc3", + "metadata": { + "editable": true + }, "source": [ "We need thus to compute the inverse of the Jacobian matrix and it\n", "is to understand that difficulties may\n", "arise in case $\\boldsymbol{J}$ is nearly singular.\n", "\n", "It is rather straightforward to extend the above scheme to systems of\n", - "more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. \n", - "\n", - "\n", - "\n", - "\n", + "more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function." + ] + }, + { + "cell_type": "markdown", + "id": "83a585c9", + "metadata": { + "editable": true + }, + "source": [ "## Steepest descent\n", "\n", "The basic idea of gradient descent is\n", @@ -343,7 +433,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e127ea11", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k),\n", @@ -352,7 +445,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bce435bc", + "metadata": { + "editable": true + }, "source": [ "with $\\gamma_k > 0$.\n", "\n", @@ -360,7 +456,6 @@ "F(\\mathbf{x}_k)$. This means that for a sufficiently small $\\gamma_k$\n", "we are always moving towards smaller function values, i.e a minimum.\n", "\n", - "\n", "The previous observation is the basis of the method of steepest\n", "descent, which is also referred to as just gradient descent (GD). One\n", "starts with an initial guess $\\mathbf{x}_0$ for a minimum of $F$ and\n", @@ -369,7 +464,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2691da5f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k), \\ \\ k \\geq 0.\n", @@ -378,12 +476,14 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e7ae7322", + "metadata": { + "editable": true + }, "source": [ "The parameter $\\gamma_k$ is often referred to as the step length or\n", "the learning rate within the context of Machine Learning.\n", "\n", - "\n", "Ideally the sequence $\\{\\mathbf{x}_k \\}_{k=0}$ converges to a global\n", "minimum of the function $F$. In general we do not know if we are in a\n", "global or local minimum. In the special case when $F$ is a convex\n", @@ -402,9 +502,6 @@ "Note that the gradient is a function of $\\mathbf{x} =\n", "(x_1,\\cdots,x_n)$ which makes it expensive to compute numerically.\n", "\n", - "\n", - "\n", - "\n", "The gradient descent method \n", "is sensitive to the choice of learning rate $\\gamma_k$. This is due\n", "to the fact that we are only guaranteed that $F(\\mathbf{x}_{k+1}) \\leq\n", @@ -415,10 +512,16 @@ "\n", "Many of these shortcomings can be alleviated by introducing\n", "randomness. One such method is that of Stochastic Gradient Descent\n", - "(SGD), see below.\n", - "\n", - "\n", - "\n", + "(SGD), see below." + ] + }, + { + "cell_type": "markdown", + "id": "a6a44ea7", + "metadata": { + "editable": true + }, + "source": [ "## Convex functions\n", "\n", "Ideally we want our cost/loss function to be convex(concave).\n", @@ -433,11 +536,8 @@ "$\\mathbb{R}$. Examples of convex sets of $\\mathbb{R}^2$ are the\n", "regular polygons (triangles, rectangles, pentagons, etc...).\n", "\n", - "\n", - "\n", "**Convex function**: Let $X \\subset \\mathbb{R}^n$ be a convex set. Assume that the function $f: X \\rightarrow \\mathbb{R}$ is continuous, then $f$ is said to be convex if $$f(tx_1 + (1-t)x_2) \\leq tf(x_1) + (1-t)f(x_2) $$ for all $x_1, x_2 \\in X$ and for all $t \\in [0,1]$. If $\\leq$ is replaced with a strict inequaltiy in the definition, we demand $x_1 \\neq x_2$ and $t\\in(0,1)$ then $f$ is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the value of the function on the interval $[x_1,x_2]$ is always below the line as illustrated below.\n", "\n", - "\n", "In the following we state first and second-order conditions which\n", "ensures convexity of a function $f$. We write $D_f$ to denote the\n", "domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more\n", @@ -454,8 +554,6 @@ "make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and\n", "note that it is always below the graph.\n", "\n", - "\n", - "\n", "**Second order condition.**\n", "\n", "Assume that $f$ is twice\n", @@ -465,12 +563,8 @@ "single-variable function this reduces to $f''(x) \\geq 0$. Geometrically this means that $f$ has nonnegative curvature\n", "everywhere.\n", "\n", - "\n", - "\n", "This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition.\n", "\n", - "\n", - "\n", "The next result is of great importance to us and the reason why we are\n", "going on about convex functions. In machine learning we frequently\n", "have to minimize a loss/cost function in order to find the best\n", @@ -487,11 +581,16 @@ "is minimal, where $f$ is convex and differentiable. Then, any point\n", "$x^*$ that satisfies $\\nabla f(x^*) = 0$ is a global minimum.\n", "\n", - "\n", - "\n", - "This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum.\n", - "\n", - "\n", + "This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum." + ] + }, + { + "cell_type": "markdown", + "id": "809f8f01", + "metadata": { + "editable": true + }, + "source": [ "### Some simple problems\n", "\n", "1. Show that $f(x)=x^2$ is convex for $x \\in \\mathbb{R}$ using the definition of convexity. Hint: If you re-write the definition, $f$ is convex if the following holds for all $x,y \\in D_f$ and any $\\lambda \\in [0,1]$ $\\lambda f(x)+(1-\\lambda)f(y)-f(\\lambda x + (1-\\lambda) y ) \\geq 0$.\n", @@ -502,7 +601,6 @@ "\n", " * $g(x) = -\\ln(x)$ is convex for $x \\in (0,\\infty)$.\n", "\n", - "\n", "3. Let $f(x) = x^2$ and $g(x) = e^x$. Show that $f(g(x))$ and $g(f(x))$ is convex for $x \\in \\mathbb{R}$. Also show that if $f(x)$ is any convex function than $h(x) = e^{f(x)}$ is convex.\n", "\n", "4. A norm is any function that satisfy the following properties\n", @@ -513,13 +611,18 @@ "\n", " * $f(x) \\leq 0$ for all $x \\in \\mathbb{R}^n$ with equality if and only if $x = 0$\n", "\n", - "\n", - "Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this).\n", - "\n", - "\n", + "Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this)." + ] + }, + { + "cell_type": "markdown", + "id": "f3b91277", + "metadata": { + "editable": true + }, + "source": [ "## Standard steepest descent\n", "\n", - "\n", "Before we proceed, we would like to discuss the approach called the\n", "**standard Steepest descent** (different from the above steepest descent discussion), which again leads to us having to be able\n", "to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG).\n", @@ -533,7 +636,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ec752109", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{A}\\boldsymbol{x} = \\boldsymbol{b}.\n", @@ -542,14 +648,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "eb64c8e7", + "metadata": { + "editable": true + }, "source": [ "In the iterative process we end up with a problem like" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "7e99eb7f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{r}= \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x},\n", @@ -558,20 +670,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3a3f6414", + "metadata": { + "editable": true + }, "source": [ "where $\\boldsymbol{r}$ is the so-called residual or error in the iterative process.\n", "\n", "When we have found the exact solution, $\\boldsymbol{r}=0$.\n", "\n", - "\n", - "\n", "The residual is zero when we reach the minimum of the quadratic equation" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "a88175a4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "P(\\boldsymbol{x})=\\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x} - \\boldsymbol{x}^T\\boldsymbol{b},\n", @@ -580,19 +696,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6992cc4f", + "metadata": { + "editable": true + }, "source": [ "with the constraint that the matrix $\\boldsymbol{A}$ is positive definite and\n", "symmetric. This defines also the Hessian and we want it to be positive definite. \n", "\n", - "\n", "We denote the initial guess for $\\boldsymbol{x}$ as $\\boldsymbol{x}_0$. \n", "We can assume without loss of generality that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "00e22e2b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{x}_0=0,\n", @@ -601,14 +722,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "faab896d", + "metadata": { + "editable": true + }, "source": [ "or consider the system" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "02cb8061", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{A}\\boldsymbol{z} = \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_0,\n", @@ -617,17 +744,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fe52c448", + "metadata": { + "editable": true + }, "source": [ "instead.\n", "\n", - "\n", "One can show that the solution $\\boldsymbol{x}$ is also the unique minimizer of the quadratic form" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f698b7fe", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(\\boldsymbol{x}) = \\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x} - \\boldsymbol{x}^T \\boldsymbol{x} , \\quad \\boldsymbol{x}\\in\\mathbf{R}^n.\n", @@ -636,7 +768,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "022bda7f", + "metadata": { + "editable": true + }, "source": [ "This suggests taking the first basis vector $\\boldsymbol{r}_1$ (see below for definition) \n", "to be the gradient of $f$ at $\\boldsymbol{x}=\\boldsymbol{x}_0$, \n", @@ -645,7 +780,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b64077bc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{A}\\boldsymbol{x}_0-\\boldsymbol{b},\n", @@ -654,18 +792,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dec06904", + "metadata": { + "editable": true + }, "source": [ "and \n", "$\\boldsymbol{x}_0=0$ it is equal $-\\boldsymbol{b}$.\n", "\n", - "\n", "We can compute the residual iteratively as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b566de75", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{r}_{k+1}=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_{k+1},\n", @@ -674,14 +817,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2c2d16e7", + "metadata": { + "editable": true + }, "source": [ "which equals" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6c97f03d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{b}-\\boldsymbol{A}(\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{r}_k),\n", @@ -690,14 +839,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2b40818b", + "metadata": { + "editable": true + }, "source": [ "or" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6619d064", + "metadata": { + "editable": true + }, "source": [ "$$\n", "(\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k)-\\alpha_k\\boldsymbol{A}\\boldsymbol{r}_k,\n", @@ -706,14 +861,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "467c71be", + "metadata": { + "editable": true + }, "source": [ "which gives" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d58fd1af", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\alpha_k = \\frac{\\boldsymbol{r}_k^T\\boldsymbol{r}_k}{\\boldsymbol{r}_k^T\\boldsymbol{A}\\boldsymbol{r}_k}\n", @@ -722,14 +883,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "38e32957", + "metadata": { + "editable": true + }, "source": [ "leading to the iterative scheme" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "98043fd6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{x}_{k+1}=\\boldsymbol{x}_k-\\alpha_k\\boldsymbol{r}_{k},\n", @@ -738,7 +905,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, + "id": "8c7efe84", "metadata": { "collapsed": false, "editable": true @@ -771,14 +939,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3bdeb3c1", + "metadata": { + "editable": true + }, "source": [ "And then as countor plot" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, + "id": "e6e460db", "metadata": { "collapsed": false, "editable": true @@ -792,14 +964,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d165add7", + "metadata": { + "editable": true + }, "source": [ "Find guesses" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, + "id": "236615ae", "metadata": { "collapsed": false, "editable": true @@ -812,14 +988,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4b90442c", + "metadata": { + "editable": true + }, "source": [ "Run it!" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, + "id": "0346fd1d", "metadata": { "collapsed": false, "editable": true @@ -837,14 +1017,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ecff8b5b", + "metadata": { + "editable": true + }, "source": [ "What happened?" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, + "id": "0d9b7732", "metadata": { "collapsed": false, "editable": true @@ -859,7 +1043,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b0f8920b", + "metadata": { + "editable": true + }, "source": [ "## Conjugate gradient method\n", "In the CG method we define so-called conjugate directions and two vectors \n", @@ -870,7 +1057,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "67b215c6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{s}^T\\boldsymbol{A}\\boldsymbol{t}= 0.\n", @@ -879,7 +1069,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "efc1c192", + "metadata": { + "editable": true + }, "source": [ "The philosophy of the CG method is to perform searches in various conjugate directions\n", "of our vectors $\\boldsymbol{x}_i$ obeying the above criterion, namely" @@ -887,7 +1080,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "eb4e1832", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{x}_i^T\\boldsymbol{A}\\boldsymbol{x}_j= 0.\n", @@ -896,7 +1092,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "775cf999", + "metadata": { + "editable": true + }, "source": [ "Two vectors are conjugate if they are orthogonal with respect to \n", "this inner product. Being conjugate is a symmetric relation: if $\\boldsymbol{s}$ is conjugate to $\\boldsymbol{t}$, then $\\boldsymbol{t}$ is conjugate to $\\boldsymbol{s}$.\n", @@ -906,7 +1105,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "95893950", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{v}_i^T\\boldsymbol{A}\\boldsymbol{v}_j= \\lambda\\boldsymbol{v}_i^T\\boldsymbol{v}_j,\n", @@ -915,7 +1117,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "16bfad5c", + "metadata": { + "editable": true + }, "source": [ "which is zero unless $i=j$. \n", "\n", @@ -925,7 +1130,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e2577f1c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{x}_{i+1}=\\boldsymbol{x}_{i}+\\alpha_i\\boldsymbol{p}_{i}.\n", @@ -934,7 +1142,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e4defaaf", + "metadata": { + "editable": true + }, "source": [ "We assume that $\\boldsymbol{p}_{i}$ is a sequence of $n$ mutually conjugate directions. \n", "Then the $\\boldsymbol{p}_{i}$ form a basis of $R^n$ and we can expand the solution \n", @@ -943,7 +1154,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b4632612", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{x} = \\sum^{n}_{i=1} \\alpha_i \\boldsymbol{p}_i.\n", @@ -952,14 +1166,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a0a06bf2", + "metadata": { + "editable": true + }, "source": [ "The coefficients are given by" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "1db7cc6a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{A}\\mathbf{x} = \\sum^{n}_{i=1} \\alpha_i \\mathbf{A} \\mathbf{p}_i = \\mathbf{b}.\n", @@ -968,14 +1188,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e7aa5384", + "metadata": { + "editable": true + }, "source": [ "Multiplying with $\\boldsymbol{p}_k^T$ from the left gives" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "884580b0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{p}_k^T \\boldsymbol{A}\\boldsymbol{x} = \\sum^{n}_{i=1} \\alpha_i\\boldsymbol{p}_k^T \\boldsymbol{A}\\boldsymbol{p}_i= \\boldsymbol{p}_k^T \\boldsymbol{b},\n", @@ -984,14 +1210,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "934990e4", + "metadata": { + "editable": true + }, "source": [ "and we can define the coefficients $\\alpha_k$ as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8be96384", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\alpha_k = \\frac{\\boldsymbol{p}_k^T \\boldsymbol{b}}{\\boldsymbol{p}_k^T \\boldsymbol{A} \\boldsymbol{p}_k}\n", @@ -1000,7 +1232,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "44f4d8d5", + "metadata": { + "editable": true + }, "source": [ "If we choose the conjugate vectors $\\boldsymbol{p}_k$ carefully, \n", "then we may not need all of them to obtain a good approximation to the solution \n", @@ -1015,7 +1250,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a8739d7d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{x}_0=0,\n", @@ -1024,14 +1262,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d871e171", + "metadata": { + "editable": true + }, "source": [ "or consider the system" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "7ed84e84", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{A}\\boldsymbol{z} = \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_0,\n", @@ -1040,7 +1284,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b690f75b", + "metadata": { + "editable": true + }, "source": [ "instead.\n", "\n", @@ -1049,7 +1296,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "86ce9e8a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(\\boldsymbol{x}) = \\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x} - \\boldsymbol{x}^T \\boldsymbol{x} , \\quad \\boldsymbol{x}\\in\\mathbf{R}^n.\n", @@ -1058,7 +1308,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7968787f", + "metadata": { + "editable": true + }, "source": [ "This suggests taking the first basis vector $\\boldsymbol{p}_1$ \n", "to be the gradient of $f$ at $\\boldsymbol{x}=\\boldsymbol{x}_0$, \n", @@ -1067,7 +1320,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0d510b11", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{A}\\boldsymbol{x}_0-\\boldsymbol{b},\n", @@ -1076,7 +1332,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c7c47a8e", + "metadata": { + "editable": true + }, "source": [ "and \n", "$\\boldsymbol{x}_0=0$ it is equal $-\\boldsymbol{b}$.\n", @@ -1088,7 +1347,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5dc0e4ac", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{r}_k=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k.\n", @@ -1097,7 +1359,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0aecb4b3", + "metadata": { + "editable": true + }, "source": [ "Note that $\\boldsymbol{r}_k$ is the negative gradient of $f$ at \n", "$\\boldsymbol{x}=\\boldsymbol{x}_k$, \n", @@ -1110,7 +1375,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f3dfc701", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{p}_{k+1}=\\boldsymbol{r}_k-\\frac{\\boldsymbol{p}_k^T \\boldsymbol{A}\\boldsymbol{r}_k}{\\boldsymbol{p}_k^T\\boldsymbol{A}\\boldsymbol{p}_k} \\boldsymbol{p}_k.\n", @@ -1119,14 +1387,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "12e92892", + "metadata": { + "editable": true + }, "source": [ "We can also compute the residual iteratively as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "1514b03f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{r}_{k+1}=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_{k+1},\n", @@ -1135,14 +1409,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7b09db3d", + "metadata": { + "editable": true + }, "source": [ "which equals" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4a0638f8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{b}-\\boldsymbol{A}(\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{p}_k),\n", @@ -1151,14 +1431,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "298f5e46", + "metadata": { + "editable": true + }, "source": [ "or" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "acd35abb", + "metadata": { + "editable": true + }, "source": [ "$$\n", "(\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k)-\\alpha_k\\boldsymbol{A}\\boldsymbol{p}_k,\n", @@ -1167,14 +1453,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "79625f01", + "metadata": { + "editable": true + }, "source": [ "which gives" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "dc5888e2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{r}_{k+1}=\\boldsymbol{r}_k-\\boldsymbol{A}\\boldsymbol{p}_{k},\n", @@ -1183,7 +1475,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d11b96a9", + "metadata": { + "editable": true + }, "source": [ "## Revisiting our Linear Regression Solvers\n", "\n", @@ -1203,7 +1498,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, + "id": "cf7c349e", "metadata": { "collapsed": false, "editable": true @@ -1217,7 +1513,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "adf34219", + "metadata": { + "editable": true + }, "source": [ "with $x_i \\in [0,1] $ is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution $\\cal {N}(0,1)$. \n", "The linear regression model is given by" @@ -1225,7 +1524,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d28eb4e0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "h_\\beta(x) = \\boldsymbol{y} = \\beta_0 + \\beta_1 x,\n", @@ -1234,14 +1536,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "60060fcb", + "metadata": { + "editable": true + }, "source": [ "such that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "82983f16", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{y}_i = \\beta_0 + \\beta_1 x_i.\n", @@ -1250,7 +1558,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "60fc4bc0", + "metadata": { + "editable": true + }, "source": [ "Let $\\mathbf{y} = (y_1,\\cdots,y_n)^T$, $\\mathbf{\\boldsymbol{y}} = (\\boldsymbol{y}_1,\\cdots,\\boldsymbol{y}_n)^T$ and $\\beta = (\\beta_0, \\beta_1)^T$\n", "\n", @@ -1259,7 +1570,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0c5dac72", + "metadata": { + "editable": true + }, "source": [ "$$\n", "X \\equiv \\begin{bmatrix}\n", @@ -1272,14 +1586,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "002d8c9b", + "metadata": { + "editable": true + }, "source": [ "The cost/loss/risk function is given by (" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b91d8b5a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\beta) = \\frac{1}{n}||X\\beta-\\mathbf{y}||_{2}^{2} = \\frac{1}{n}\\sum_{i=1}^{100}\\left[ (\\beta_0 + \\beta_1 x_i)^2 - 2 y_i (\\beta_0 + \\beta_1 x_i) + y_i^2\\right]\n", @@ -1288,17 +1608,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d0fc6c20", + "metadata": { + "editable": true + }, "source": [ "and we want to find $\\beta$ such that $C(\\beta)$ is minimized.\n", "\n", - "\n", "Computing $\\partial C(\\beta) / \\partial \\beta_0$ and $\\partial C(\\beta) / \\partial \\beta_1$ we can show that the gradient can be written as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "3f99dab5", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\nabla_{\\beta} C(\\beta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n", @@ -1309,17 +1634,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e1305a22", + "metadata": { + "editable": true + }, "source": [ "where $X$ is the design matrix defined above.\n", "\n", - "\n", "The Hessian matrix of $C(\\beta)$ is given by" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "ef62073f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n", @@ -1331,18 +1661,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dfb78235", + "metadata": { + "editable": true + }, "source": [ "This result implies that $C(\\beta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite.\n", "\n", - "\n", - "\n", "We can now write a program that minimizes $C(\\beta)$ using the gradient descent method with a constant learning rate $\\gamma$ according to" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "56cee86c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\beta_{k+1} = \\beta_k - \\gamma \\nabla_\\beta C(\\beta_k), \\ k=0,1,\\cdots\n", @@ -1351,7 +1685,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6cc71454", + "metadata": { + "editable": true + }, "source": [ "We can use the expression we computed for the gradient and let use a\n", "$\\beta_0$ be chosen randomly and let $\\gamma = 0.001$. Stop iterating\n", @@ -1360,14 +1697,13 @@ "And finally we can compare our solution for $\\beta$ with the analytic result given by \n", "$\\beta= (X^TX)^{-1} X^T \\mathbf{y}$.\n", "\n", - "\n", - "\n", "Here is our simple example" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, + "id": "90fab6b7", "metadata": { "collapsed": false, "editable": true @@ -1424,14 +1760,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "48ba87fe", + "metadata": { + "editable": true + }, "source": [ "Alternatively, we can use **Scikit-Learn** as done here" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, + "id": "7522775d", "metadata": { "collapsed": false, "editable": true @@ -1458,14 +1798,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "90552e2f", + "metadata": { + "editable": true + }, "source": [ "We have also discussed Ridge regression where the loss function contains a regularized term given by the $L_2$ norm of $\\beta$," ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "5d7c032c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C_{\\text{ridge}}(\\beta) = \\frac{1}{n}||X\\beta -\\mathbf{y}||^2 + \\lambda ||\\beta||^2, \\ \\lambda \\geq 0.\n", @@ -1474,14 +1820,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ed86f1ba", + "metadata": { + "editable": true + }, "source": [ "In order to minimize $C_{\\text{ridge}}(\\beta)$ using GD we only have adjust the gradient as follows" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "0386e23c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\nabla_\\beta C_{\\text{ridge}}(\\beta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n", @@ -1492,14 +1844,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b65523fc", + "metadata": { + "editable": true + }, "source": [ "We can easily extend our program to minimize $C_{\\text{ridge}}(\\beta)$ using gradient descent and compare with the analytical solution given by" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c62584ee", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\beta_{\\text{ridge}} = \\left(X^T X + \\lambda I_{2 \\times 2} \\right)^{-1} X^T \\mathbf{y}.\n", @@ -1508,7 +1866,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 9, + "id": "e8d43667", "metadata": { "collapsed": false, "editable": true @@ -1562,7 +1921,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1ca83847", + "metadata": { + "editable": true + }, "source": [ "## Using gradient descent methods, limitations\n", "\n", @@ -1576,9 +1938,39 @@ "\n", "* **GD treats all directions in parameter space uniformly.** Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive. \n", "\n", - "* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.\n", + "* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points." + ] + }, + { + "cell_type": "markdown", + "id": "dcf3e808", + "metadata": { + "editable": true + }, + "source": [ + "## Stochastic Gradient Descent (SGD)\n", "\n", - "## Stochastic Gradient Descent\n", + "In stochastic gradient descent, the extreme case is the case where we\n", + "have only one batch, that is we include the whole data set.\n", + "\n", + "This process is called Stochastic Gradient\n", + "Descent (SGD) (or also sometimes on-line gradient descent). This is\n", + "relatively less common to see because in practice due to vectorized\n", + "code optimizations it can be computationally much more efficient to\n", + "evaluate the gradient for 100 examples, than the gradient for one\n", + "example 100 times. Even though SGD technically refers to using a\n", + "single example at a time to evaluate the gradient, you will hear\n", + "people use the term SGD even when referring to mini-batch gradient\n", + "descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD\n", + "for “Batch gradient descent” are rare to see), where it is usually\n", + "assumed that mini-batches are used. The size of the mini-batch is a\n", + "hyperparameter but it is not very common to cross-validate or bootstrap it. It is\n", + "usually based on memory constraints (if any), or set to some value,\n", + "e.g. 32, 64 or 128. We use powers of 2 in practice because many\n", + "vectorized operation implementations work faster when their inputs are\n", + "sized in powers of 2.\n", + "\n", + "In our notes with SGD we mean stochastic gradient descent with mini-batches.\n", "\n", "Stochastic gradient descent (SGD) and variants thereof address some of\n", "the shortcomings of the Gradient descent method discussed above.\n", @@ -1590,7 +1982,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "473b1af6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n", @@ -1600,7 +1995,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3353fe2a", + "metadata": { + "editable": true + }, "source": [ "This in turn means that the gradient can be\n", "computed as a sum over $i$-gradients" @@ -1608,7 +2006,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6e8e47c3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", @@ -1618,7 +2019,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a2eeb6ad", + "metadata": { + "editable": true + }, "source": [ "Stochasticity/randomness is introduced by only taking the\n", "gradient on a subset of the data called minibatches. If there are $n$\n", @@ -1626,8 +2030,6 @@ "minibatches. We denote these minibatches by $B_k$ where\n", "$k=1,\\cdots,n/M$.\n", "\n", - "\n", - "\n", "As an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \n", "and we choose to have $M=5$ minibathces,\n", "then each minibatch contains two data points. In particular we have\n", @@ -1644,7 +2046,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5a7a0f8b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\nabla_{\\beta}\n", @@ -1656,14 +2061,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b7b5884f", + "metadata": { + "editable": true + }, "source": [ "Thus a gradient descent step now looks like" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6492d660", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\beta_{j+1} = \\beta_j - \\gamma_j \\sum_{i \\in B_k}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", @@ -1673,7 +2084,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "584164f4", + "metadata": { + "editable": true + }, "source": [ "where $k$ is picked at random with equal\n", "probability from $[1,n/M]$. An iteration over the number of\n", @@ -1684,7 +2098,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, + "id": "42d97cf8", "metadata": { "collapsed": false, "editable": true @@ -1694,7 +2109,7 @@ "import numpy as np \n", "\n", "n = 100 #100 datapoints \n", - "M = 5 #size of each minibatch\n", + "M = 5 #size of each mini-batche\n", "m = int(n/M) #number of minibatches\n", "n_epochs = 10 #number of epochs\n", "\n", @@ -1709,7 +2124,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ca9c6c58", + "metadata": { + "editable": true + }, "source": [ "Taking the gradient only on a subset of the data has two important\n", "benefits. First, it introduces randomness which decreases the chance\n", @@ -1719,8 +2137,6 @@ "cheaper since we sum over the datapoints in the $k-th$ minibatch and not\n", "all $n$ datapoints.\n", "\n", - "\n", - "\n", "A natural question is when do we stop the search for a new minimum?\n", "One possibility is to compute the full gradient after a given number\n", "of epochs and check if the norm of the gradient is smaller than some\n", @@ -1732,8 +2148,6 @@ "compare the values of the cost function and keep the $\\beta$ that\n", "gave the lowest value.\n", "\n", - "\n", - "\n", "Another approach is to let the step length $\\gamma_j$ depend on the\n", "number of epochs in such a way that it becomes very small after a\n", "reasonable time such that we do not move at all.\n", @@ -1749,7 +2163,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, + "id": "d2921658", "metadata": { "collapsed": false, "editable": true @@ -1784,48 +2199,62 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "84469eb8", + "metadata": { + "editable": true + }, + "source": [ + "We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters $t_0$ and $t_1$." + ] + }, + { + "cell_type": "markdown", + "id": "b4b94e7a", + "metadata": { + "editable": true + }, "source": [ "### Program for stochastic gradient" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 12, + "id": "71dcdb35", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ + "# Importing various packages\n", "# Importing various packages\n", "from math import exp, sqrt\n", "from random import random, seed\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import SGDRegressor\n", "\n", - "m = 100\n", - "x = 2*np.random.rand(m,1)\n", - "y = 4+3*x+np.random.randn(m,1)\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", "\n", - "X = np.c_[np.ones((m,1)), x]\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", "theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", "print(\"Own inversion\")\n", "print(theta_linreg)\n", - "sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)\n", - "sgdreg.fit(x,y.ravel())\n", - "print(\"sgdreg from scikit\")\n", - "print(sgdreg.intercept_, sgdreg.coef_)\n", - "\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", "\n", "theta = np.random.randn(2,1)\n", - "eta = 0.1\n", + "eta = 1.0/np.max(EigValues)\n", "Niterations = 1000\n", "\n", "\n", "for iter in range(Niterations):\n", - " gradients = 2.0/m*X.T @ ((X @ theta)-y)\n", + " gradients = 2.0/n*X.T @ ((X @ theta)-y)\n", " theta -= eta*gradients\n", "print(\"theta from own gd\")\n", "print(theta)\n", @@ -1835,8 +2264,9 @@ "ypredict = Xnew.dot(theta)\n", "ypredict2 = Xnew.dot(theta_linreg)\n", "\n", - "\n", "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", "t0, t1 = 5, 50\n", "def learning_schedule(t):\n", " return t0/(t+t1)\n", @@ -1844,16 +2274,20 @@ "theta = np.random.randn(2,1)\n", "\n", "for epoch in range(n_epochs):\n", + "# Can you figure out a better way of setting up the contributions to each batch?\n", " for i in range(m):\n", - " random_index = np.random.randint(m)\n", - " xi = X[random_index:random_index+1]\n", - " yi = y[random_index:random_index+1]\n", - " gradients = 2 * xi.T @ ((xi @ theta)-yi)\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)\n", " eta = learning_schedule(epoch*m+i)\n", " theta = theta - eta*gradients\n", "print(\"theta from own sdg\")\n", "print(theta)\n", "\n", + "\n", + "\n", + "\n", "plt.plot(xnew, ypredict, \"r-\")\n", "plt.plot(xnew, ypredict2, \"b-\")\n", "plt.plot(x, y ,'ro')\n", @@ -1866,7 +2300,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6231b86f", + "metadata": { + "editable": true + }, + "source": [ + "In the above code, we have use replacement in setting up the\n", + "mini-batches. The discussion\n", + "[here](https://sebastianraschka.com/faq/docs/sgd-methods.html) may be\n", + "useful. More material will be added later." + ] + }, + { + "cell_type": "markdown", + "id": "8d50214c", + "metadata": { + "editable": true + }, "source": [ "## Momentum based GD\n", "\n", @@ -1878,7 +2328,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "45d43ca3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", @@ -1887,7 +2340,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dcdd91bf", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1902,7 +2358,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c7519d1e", + "metadata": { + "editable": true + }, "source": [ "where we have introduced a momentum parameter $\\gamma$, with\n", "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", @@ -1918,7 +2377,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f4d4340d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", @@ -1927,12 +2389,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "41ad532a", + "metadata": { + "editable": true + }, "source": [ "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$.\n", "\n", - "\n", - "\n", "Let us try to get more intuition from these equations. It is helpful\n", "to consider a simple physical analogy with a particle of mass $m$\n", "moving in a viscous medium with drag coefficient $\\mu$ and potential\n", @@ -1942,7 +2405,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "eef8ae92", + "metadata": { + "editable": true + }, "source": [ "$$\n", "m {d^2 \\mathbf{w} \\over dt^2} + \\mu {d \\mathbf{w} \\over dt }= -\\nabla_w E(\\mathbf{w}).\n", @@ -1951,14 +2417,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "80481a6d", + "metadata": { + "editable": true + }, "source": [ "We can discretize this equation in the usual way to get" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6aab8db7", + "metadata": { + "editable": true + }, "source": [ "$$\n", "m { \\mathbf{w}_{t+\\Delta t}-2 \\mathbf{w}_{t} +\\mathbf{w}_{t-\\Delta t} \\over (\\Delta t)^2}+\\mu {\\mathbf{w}_{t+\\Delta t}- \\mathbf{w}_{t} \\over \\Delta t} = -\\nabla_w E(\\mathbf{w}).\n", @@ -1967,14 +2439,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dd6414d2", + "metadata": { + "editable": true + }, "source": [ "Rearranging this equation, we can rewrite this as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b76a8372", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\Delta \\mathbf{w}_{t +\\Delta t}= - { (\\Delta t)^2 \\over m +\\mu \\Delta t} \\nabla_w E(\\mathbf{w})+ {m \\over m +\\mu \\Delta t} \\Delta \\mathbf{w}_t.\n", @@ -1983,7 +2461,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "07bbe6db", + "metadata": { + "editable": true + }, "source": [ "Notice that this equation is identical to previous one if we identify\n", "the position of the particle, $\\mathbf{w}$, with the parameters\n", @@ -1994,7 +2475,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7a9a2ecf", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n", @@ -2003,7 +2487,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fe5a2bbc", + "metadata": { + "editable": true + }, "source": [ "Thus, as the name suggests, the momentum parameter is proportional to\n", "the mass of the particle and effectively provides inertia.\n", @@ -2033,7 +2520,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "04540023", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1}) \\nonumber\n", @@ -2042,7 +2532,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dfbf53a5", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2057,12 +2550,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "32ac3869", + "metadata": { + "editable": true + }, "source": [ "One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\\gamma$.\n", "\n", - "\n", - "\n", "In stochastic gradient descent, with and without momentum, we still\n", "have to specify a schedule for tuning the learning rates $\\eta_t$\n", "as a function of time. As discussed in the context of Newton's\n", @@ -2081,10 +2575,17 @@ "\n", "Recently, a number of methods have been introduced that accomplish\n", "this by tracking not only the gradient, but also the second moment of\n", - "the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and\n", - "ADAM.\n", - "\n", - "\n", + "the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and\n", + "ADAM." + ] + }, + { + "cell_type": "markdown", + "id": "6f575b16", + "metadata": { + "editable": true + }, + "source": [ "### RMS prop\n", "\n", "In RMS prop, in addition to keeping a running average of the first\n", @@ -2095,7 +2596,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "274604c4", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2110,7 +2614,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cd679323", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n", @@ -2119,7 +2626,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0a7f8e9d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\mathbf{g}_t \\over \\sqrt{\\mathbf{s}_t +\\epsilon}}, \\nonumber\n", @@ -2128,7 +2638,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "48ba8fff", + "metadata": { + "editable": true + }, "source": [ "where $\\beta$ controls the averaging time of the second moment and is\n", "typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate\n", @@ -2138,8 +2651,16 @@ "is clear from this formula that the learning rate is reduced in\n", "directions where the norm of the gradient is consistently large. This\n", "greatly speeds up the convergence by allowing us to use a larger\n", - "learning rate for flat directions.\n", - "\n", + "learning rate for flat directions." + ] + }, + { + "cell_type": "markdown", + "id": "83140ab2", + "metadata": { + "editable": true + }, + "source": [ "### ADAM optimizer\n", "\n", "A related algorithm is the ADAM optimizer. In ADAM, we keep a running\n", @@ -2158,7 +2679,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "61874dc3", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2173,7 +2697,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "24e19d86", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n", @@ -2182,7 +2709,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "506f78ea", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n", @@ -2191,7 +2721,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cb4b8585", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", @@ -2200,7 +2733,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9b5b11b1", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", @@ -2209,7 +2745,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "92292a73", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\boldsymbol{\\mathbf{m}}_t \\over \\sqrt{\\boldsymbol{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n", @@ -2218,7 +2757,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1a264832", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2232,7 +2774,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6a307202", + "metadata": { + "editable": true + }, "source": [ "where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and\n", "second moment and are typically taken to be $0.9$ and $0.99$\n", @@ -2248,7 +2793,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3285f010", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\Delta \\theta_{t+1}= -\\eta_t { \\boldsymbol{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n", @@ -2257,7 +2805,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "657349da", + "metadata": { + "editable": true + }, "source": [ "## Practical tips\n", "\n", @@ -2267,8 +2818,16 @@ "\n", "* **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.\n", "\n", - "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.\n", - "\n", + "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications." + ] + }, + { + "cell_type": "markdown", + "id": "65044ac7", + "metadata": { + "editable": true + }, + "source": [ "## Automatic differentiation\n", "\n", "[Automatic differentiation (AD)](https://en.wikipedia.org/wiki/Automatic_differentiation), \n", @@ -2296,15 +2855,16 @@ "while numerical differentiation can introduce round-off errors in the\n", "discretization process and cancellation\n", "\n", - "\n", - "\n", "Python has tools for so-called **automatic differentiation**.\n", "Consider the following example" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "dacf05cf", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n", @@ -2313,14 +2873,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "da4ad36e", + "metadata": { + "editable": true + }, "source": [ "which has the following derivative" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f4c3e6c4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f'(x) = \\cos\\left(2\\pi x + x^2\\right)\\left(2\\pi + 2x\\right)\n", @@ -2329,14 +2895,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1c8bfd4a", + "metadata": { + "editable": true + }, "source": [ "Using **autograd** we have" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 13, + "id": "e1d91b8b", "metadata": { "collapsed": false, "editable": true @@ -2381,7 +2951,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cd1158a5", + "metadata": { + "editable": true + }, "source": [ "Here we\n", "experiment with what kind of functions Autograd is capable\n", @@ -2392,7 +2965,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, + "id": "e2e9faff", "metadata": { "collapsed": false, "editable": true @@ -2420,7 +2994,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e4a83059", + "metadata": { + "editable": true + }, "source": [ "To differentiate with respect to two (or more) arguments of a Python\n", "function, Autograd need to know at which variable the function if\n", @@ -2429,7 +3006,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, + "id": "f65983d8", "metadata": { "collapsed": false, "editable": true @@ -2473,14 +3051,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1d369f97", + "metadata": { + "editable": true + }, "source": [ "Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, + "id": "46ea0652", "metadata": { "collapsed": false, "editable": true @@ -2508,7 +3090,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9cc6674a", + "metadata": { + "editable": true + }, "source": [ "Note that in this case, when sending an array as input argument, the\n", "output from Autograd is another array. This is the true gradient of\n", @@ -2520,7 +3105,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 17, + "id": "17813055", "metadata": { "collapsed": false, "editable": true @@ -2548,7 +3134,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 18, + "id": "6da49540", "metadata": { "collapsed": false, "editable": true @@ -2572,39 +3159,45 @@ ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": 19, + "id": "a8ff2c17", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ - "1\n", - "8\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "C\n", - "O\n", - "D\n", - "E\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K\n", - " \n", - " \n", - "p\n", - "y\n", - "c\n", - "o\n", - "d" + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f6_for(x):\n", + " val = 0\n", + " for i in range(10):\n", + " val = val + x**i\n", + " return val\n", + "\n", + "def f6_while(x):\n", + " val = 0\n", + " i = 0\n", + " while i < 10:\n", + " val = val + x**i\n", + " i = i + 1\n", + " return val\n", + "\n", + "f6_for_grad = grad(f6_for)\n", + "f6_while_grad = grad(f6_while)\n", + "\n", + "x = 0.5\n", + "\n", + "# Print the computed derivaties of f6_for and f6_while\n", + "print(\"The computed derivative of f6_for at x = %g is: %g\"%(x,f6_for_grad(x)))\n", + "print(\"The computed derivative of f6_while at x = %g is: %g\"%(x,f6_while_grad(x)))" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 20, + "id": "ec67d4a3", "metadata": { "collapsed": false, "editable": true @@ -2624,7 +3217,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 21, + "id": "742a2d68", "metadata": { "collapsed": false, "editable": true @@ -2662,48 +3256,55 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e7be6348", + "metadata": { + "editable": true + }, "source": [ "Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.\n", "\n", + "Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.\n", "\n", - "Autograd supports many features. However, there are some functions that are not supported (yet) by Autograd.\n", - "\n", - "Assigning a value to the variable being differentiated with respect to is an example thereof." + "Assigning a value to the variable being differentiated with respect to" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 22, + "id": "c551058c", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ - "#import autograd.numpy as np\n", - "#from autograd import grad\n", - "#def f8(x): # Assume x is an array\n", - "# x[2] = 3\n", - "# return x*2\n", + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f8(x): # Assume x is an array\n", + " x[2] = 3\n", + " return x*2\n", "\n", - "#f8_grad = grad(f8)\n", + "f8_grad = grad(f8)\n", "\n", - "#x = 8.4\n", + "x = 8.4\n", "\n", - "#print(\"The derivative of f8 is:\",f8_grad(x))" + "print(\"The derivative of f8 is:\",f8_grad(x))" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "7a13b21d", + "metadata": { + "editable": true + }, "source": [ "Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 23, + "id": "19c7502b", "metadata": { "collapsed": false, "editable": true @@ -2725,7 +3326,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4450885d", + "metadata": { + "editable": true + }, "source": [ "Here we are told that the 'dot' function does not belong to Autograd's\n", "version of a Numpy array. To overcome this, an alternative syntax\n", @@ -2734,7 +3338,8 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 24, + "id": "013fc7f8", "metadata": { "collapsed": false, "editable": true @@ -2759,14 +3364,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8d360f7d", + "metadata": { + "editable": true + }, "source": [ "The documentation recommends to avoid inplace operations such as" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 25, + "id": "e29a24eb", "metadata": { "collapsed": false, "editable": true @@ -2781,13 +3390,233 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ad8fbbb7", + "metadata": { + "editable": true + }, "source": [ - "More examples will be added, in particular how to compare autograd with own codes for the gradients." + "## Using Autograd with OLS\n", + "\n", + "We conclude the part on optmization by showing how we can make codes\n", + "for linear regression and logistic regression using **autograd**. The\n", + "first example shows results with ordinary leats squares." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "904f65dc", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients for OLS\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "ce338980", + "metadata": { + "editable": true + }, + "source": [ + "### Including Stochastic Gradient Descent with Autograd\n", + "\n", + "In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using **autograd**." + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "de261f10", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using SGD\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = (1.0/n)*training_gradient(y, X, theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "for epoch in range(n_epochs):\n", + "# Can you figure out a better way of setting up the contributions to each batch?\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "ccd8829e", + "metadata": { + "editable": true + }, + "source": [ + "### And Logistic Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "cc5811d1", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "\n", + "def sigmoid(x):\n", + " return 0.5 * (np.tanh(x / 2.) + 1)\n", + "\n", + "def logistic_predictions(weights, inputs):\n", + " # Outputs probability of a label being true according to logistic model.\n", + " return sigmoid(np.dot(inputs, weights))\n", + "\n", + "def training_loss(weights):\n", + " # Training loss is the negative log-likelihood of the training labels.\n", + " preds = logistic_predictions(weights, inputs)\n", + " label_probabilities = preds * targets + (1 - preds) * (1 - targets)\n", + " return -np.sum(np.log(label_probabilities))\n", + "\n", + "# Build a toy dataset.\n", + "inputs = np.array([[0.52, 1.12, 0.77],\n", + " [0.88, -1.08, 0.15],\n", + " [0.52, 0.06, -1.30],\n", + " [0.74, -2.49, 1.39]])\n", + "targets = np.array([True, True, False, True])\n", + "\n", + "# Define a function that returns gradients of training loss using Autograd.\n", + "training_gradient_fun = grad(training_loss)\n", + "\n", + "# Optimize weights using gradient descent.\n", + "weights = np.array([0.0, 0.0, 0.0])\n", + "print(\"Initial loss:\", training_loss(weights))\n", + "for i in range(100):\n", + " weights -= training_gradient_fun(weights) * 0.01\n", + "\n", + "print(\"Trained loss:\", training_loss(weights))" ] } ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 }