diff --git a/doc/HandWrittenNotes/2023/Exercisesweek44.pdf b/doc/HandWrittenNotes/2023/Exercisesweek44.pdf new file mode 100644 index 000000000..c000607fb Binary files /dev/null and b/doc/HandWrittenNotes/2023/Exercisesweek44.pdf differ diff --git a/doc/LectureNotes/.ipynb_checkpoints/week41-checkpoint.ipynb b/doc/LectureNotes/.ipynb_checkpoints/week41-checkpoint.ipynb new file mode 100644 index 000000000..7c1e7c629 --- /dev/null +++ b/doc/LectureNotes/.ipynb_checkpoints/week41-checkpoint.ipynb @@ -0,0 +1,3537 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "9a4eccc2", + "metadata": {}, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "243c5d47", + "metadata": {}, + "source": [ + "# Week 41 Neural networks and constructing a neural network code\n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", + "\n", + "Date: **Week 41**" + ] + }, + { + "cell_type": "markdown", + "id": "0cae636e", + "metadata": {}, + "source": [ + "## Plan for week 41\n", + "\n", + "**Material for the active learning sessions on Tuesday and Wednesday.**\n", + "\n", + " * Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation\n", + "\n", + " * One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code\n", + "\n", + " * Discussion of project 2\n", + "\n", + " * Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent\n", + "\n", + " \n", + "\n", + "**Material for the lecture on Thursday October 12, 2023.**\n", + "\n", + " * Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.\n", + "\n", + " * Building our own Feed-forward Neural Network\n", + "\n", + " * [Video of lecture notes](https://youtu.be/5-RRTO9uDvI)\n", + "\n", + " * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesOct12.pdf)\n", + "\n", + " * Readings and Videos:\n", + "\n", + " * These lecture notes\n", + "\n", + " * For neural networks we recommend Goodfellow et al chapter 6.\n", + "\n", + " * [Neural Networks demystified](https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs)\n", + "\n", + " * [Building Neural Networks from scratch](https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex)\n", + "\n", + " * [Video on Neural Networks](https://www.youtube.com/watch?v=CqOfi41LfDw)\n", + "\n", + " * [Video on the back propagation algorithm](https://www.youtube.com/watch?v=Ilg3gGewQ5U)\n", + "\n", + "I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at ." + ] + }, + { + "cell_type": "markdown", + "id": "51ff64f7", + "metadata": {}, + "source": [ + "## Lecture Thursday October 12" + ] + }, + { + "cell_type": "markdown", + "id": "07ff4601", + "metadata": {}, + "source": [ + "## Introduction to Neural networks\n", + "\n", + "Artificial neural networks are computational systems that can learn to\n", + "perform tasks by considering examples, generally without being\n", + "programmed with any task-specific rules. It is supposed to mimic a\n", + "biological system, wherein neurons interact by sending signals in the\n", + "form of mathematical functions between layers. All layers can contain\n", + "an arbitrary number of neurons, and each connection is represented by\n", + "a weight variable." + ] + }, + { + "cell_type": "markdown", + "id": "4806cddf", + "metadata": {}, + "source": [ + "## Artificial neurons\n", + "\n", + "The field of artificial neural networks has a long history of\n", + "development, and is closely connected with the advancement of computer\n", + "science and computers in general. A model of artificial neurons was\n", + "first developed by McCulloch and Pitts in 1943 to study signal\n", + "processing in the brain and has later been refined by others. The\n", + "general idea is to mimic neural networks in the human brain, which is\n", + "composed of billions of neurons that communicate with each other by\n", + "sending electrical signals. Each neuron accumulates its incoming\n", + "signals, which must exceed an activation threshold to yield an\n", + "output. If the threshold is not overcome, the neuron remains inactive,\n", + "i.e. has zero output.\n", + "\n", + "This behaviour has inspired a simple mathematical model for an artificial neuron." + ] + }, + { + "cell_type": "markdown", + "id": "ccfdcf2b", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y = f\\left(\\sum_{i=1}^n w_ix_i\\right) = f(u)\n", + "\\label{artificialNeuron} \\tag{1}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "900fd38b", + "metadata": {}, + "source": [ + "Here, the output $y$ of the neuron is the value of its activation function, which have as input\n", + "a weighted sum of signals $x_i, \\dots ,x_n$ received by $n$ other neurons.\n", + "\n", + "Conceptually, it is helpful to divide neural networks into four\n", + "categories:\n", + "1. general purpose neural networks for supervised learning,\n", + "\n", + "2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),\n", + "\n", + "3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and\n", + "\n", + "4. neural networks for unsupervised learning such as Deep Boltzmann Machines.\n", + "\n", + "In natural science, DNNs and CNNs have already found numerous\n", + "applications. In statistical physics, they have been applied to detect\n", + "phase transitions in 2D Ising and Potts models, lattice gauge\n", + "theories, and different phases of polymers, or solving the\n", + "Navier-Stokes equation in weather forecasting. Deep learning has also\n", + "found interesting applications in quantum physics. Various quantum\n", + "phase transitions can be detected and studied using DNNs and CNNs,\n", + "topological phases, and even non-equilibrium many-body\n", + "localization. Representing quantum states as DNNs quantum state\n", + "tomography are among some of the impressive achievements to reveal the\n", + "potential of DNNs to facilitate the study of quantum systems.\n", + "\n", + "In quantum information theory, it has been shown that one can perform\n", + "gate decompositions with the help of neural. \n", + "\n", + "The applications are not limited to the natural sciences. There is a\n", + "plethora of applications in essentially all disciplines, from the\n", + "humanities to life science and medicine." + ] + }, + { + "cell_type": "markdown", + "id": "15e0098f", + "metadata": {}, + "source": [ + "## Neural network types\n", + "\n", + "An artificial neural network (ANN), is a computational model that\n", + "consists of layers of connected neurons, or nodes or units. We will\n", + "refer to these interchangeably as units or nodes, and sometimes as\n", + "neurons.\n", + "\n", + "It is supposed to mimic a biological nervous system by letting each\n", + "neuron interact with other neurons by sending signals in the form of\n", + "mathematical functions between layers. A wide variety of different\n", + "ANNs have been developed, but most of them consist of an input layer,\n", + "an output layer and eventual layers in-between, called *hidden\n", + "layers*. All layers can contain an arbitrary number of nodes, and each\n", + "connection between two nodes is associated with a weight variable.\n", + "\n", + "Neural networks (also called neural nets) are neural-inspired\n", + "nonlinear models for supervised learning. As we will see, neural nets\n", + "can be viewed as natural, more powerful extensions of supervised\n", + "learning methods such as linear and logistic regression and soft-max\n", + "methods we discussed earlier." + ] + }, + { + "cell_type": "markdown", + "id": "70d3fe5d", + "metadata": {}, + "source": [ + "## Feed-forward neural networks\n", + "\n", + "The feed-forward neural network (FFNN) was the first and simplest type\n", + "of ANNs that were devised. In this network, the information moves in\n", + "only one direction: forward through the layers.\n", + "\n", + "Nodes are represented by circles, while the arrows display the\n", + "connections between the nodes, including the direction of information\n", + "flow. Additionally, each arrow corresponds to a weight variable\n", + "(figure to come). We observe that each node in a layer is connected\n", + "to *all* nodes in the subsequent layer, making this a so-called\n", + "*fully-connected* FFNN." + ] + }, + { + "cell_type": "markdown", + "id": "838210ba", + "metadata": {}, + "source": [ + "## Convolutional Neural Network\n", + "\n", + "A different variant of FFNNs are *convolutional neural networks*\n", + "(CNNs), which have a connectivity pattern inspired by the animal\n", + "visual cortex. Individual neurons in the visual cortex only respond to\n", + "stimuli from small sub-regions of the visual field, called a receptive\n", + "field. This makes the neurons well-suited to exploit the strong\n", + "spatially local correlation present in natural images. The response of\n", + "each neuron can be approximated mathematically as a convolution\n", + "operation. (figure to come)\n", + "\n", + "Convolutional neural networks emulate the behaviour of neurons in the\n", + "visual cortex by enforcing a *local* connectivity pattern between\n", + "nodes of adjacent layers: Each node in a convolutional layer is\n", + "connected only to a subset of the nodes in the previous layer, in\n", + "contrast to the fully-connected FFNN. Often, CNNs consist of several\n", + "convolutional layers that learn local features of the input, with a\n", + "fully-connected layer at the end, which gathers all the local data and\n", + "produces the outputs. They have wide applications in image and video\n", + "recognition." + ] + }, + { + "cell_type": "markdown", + "id": "8a78d22d", + "metadata": {}, + "source": [ + "## Recurrent neural networks\n", + "\n", + "So far we have only mentioned ANNs where information flows in one\n", + "direction: forward. *Recurrent neural networks* on the other hand,\n", + "have connections between nodes that form directed *cycles*. This\n", + "creates a form of internal memory which are able to capture\n", + "information on what has been calculated before; the output is\n", + "dependent on the previous computations. Recurrent NNs make use of\n", + "sequential information by performing the same task for every element\n", + "in a sequence, where each element depends on previous elements. An\n", + "example of such information is sentences, making recurrent NNs\n", + "especially well-suited for handwriting and speech recognition." + ] + }, + { + "cell_type": "markdown", + "id": "4ca0b479", + "metadata": {}, + "source": [ + "## Other types of networks\n", + "\n", + "There are many other kinds of ANNs that have been developed. One type\n", + "that is specifically designed for interpolation in multidimensional\n", + "space is the radial basis function (RBF) network. RBFs are typically\n", + "made up of three layers: an input layer, a hidden layer with\n", + "non-linear radial symmetric activation functions and a linear output\n", + "layer (''linear'' here means that each node in the output layer has a\n", + "linear activation function). The layers are normally fully-connected\n", + "and there are no cycles, thus RBFs can be viewed as a type of\n", + "fully-connected FFNN. They are however usually treated as a separate\n", + "type of NN due the unusual activation functions." + ] + }, + { + "cell_type": "markdown", + "id": "b80ebf1a", + "metadata": {}, + "source": [ + "## Multilayer perceptrons\n", + "\n", + "One uses often so-called fully-connected feed-forward neural networks\n", + "with three or more layers (an input layer, one or more hidden layers\n", + "and an output layer) consisting of neurons that have non-linear\n", + "activation functions.\n", + "\n", + "Such networks are often called *multilayer perceptrons* (MLPs)." + ] + }, + { + "cell_type": "markdown", + "id": "749545b4", + "metadata": {}, + "source": [ + "## Why multilayer perceptrons?\n", + "\n", + "According to the *Universal approximation theorem*, a feed-forward\n", + "neural network with just a single hidden layer containing a finite\n", + "number of neurons can approximate a continuous multidimensional\n", + "function to arbitrary accuracy, assuming the activation function for\n", + "the hidden layer is a **non-constant, bounded and\n", + "monotonically-increasing continuous function**.\n", + "\n", + "Note that the requirements on the activation function only applies to\n", + "the hidden layer, the output nodes are always assumed to be linear, so\n", + "as to not restrict the range of output values." + ] + }, + { + "cell_type": "markdown", + "id": "f524768e", + "metadata": {}, + "source": [ + "## Illustration of a single perceptron model and a multi-perceptron model\n", + "\n", + "\n", + "\n", + "\n", + "

Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "6c2f8b44", + "metadata": {}, + "source": [ + "## Examples of XOR, OR and AND gates\n", + "\n", + "Let us first try to fit various gates using standard linear\n", + "regression. The gates we are thinking of are the classical XOR, OR and\n", + "AND gates, well-known elements in computer science. The tables here\n", + "show how we can set up the inputs $x_1$ and $x_2$ in order to yield a\n", + "specific target $y_i$." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "8dfb9c06", + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"\n", + "Simple code that tests XOR, OR and AND gates with linear regression\n", + "\"\"\"\n", + "\n", + "import numpy as np\n", + "# Design matrix\n", + "X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)\n", + "print(f\"The X.TX matrix:{X.T @ X}\")\n", + "Xinv = np.linalg.pinv(X.T @ X)\n", + "print(f\"The invers of X.TX matrix:{Xinv}\")\n", + "\n", + "# The XOR gate \n", + "yXOR = np.array( [ 0, 1 ,1, 0])\n", + "ThetaXOR = Xinv @ X.T @ yXOR\n", + "print(f\"The values of theta for the XOR gate:{ThetaXOR}\")\n", + "print(f\"The linear regression prediction for the XOR gate:{X @ ThetaXOR}\")\n", + "\n", + "\n", + "# The OR gate \n", + "yOR = np.array( [ 0, 1 ,1, 1])\n", + "ThetaOR = Xinv @ X.T @ yOR\n", + "print(f\"The values of theta for the OR gate:{ThetaOR}\")\n", + "print(f\"The linear regression prediction for the OR gate:{X @ ThetaOR}\")\n", + "\n", + "\n", + "# The OR gate \n", + "yAND = np.array( [ 0, 0 ,0, 1])\n", + "ThetaAND = Xinv @ X.T @ yAND\n", + "print(f\"The values of theta for the AND gate:{ThetaAND}\")\n", + "print(f\"The linear regression prediction for the AND gate:{X @ ThetaAND}\")" + ] + }, + { + "cell_type": "markdown", + "id": "b0033599", + "metadata": {}, + "source": [ + "What is happening here?" + ] + }, + { + "cell_type": "markdown", + "id": "4663d22e", + "metadata": {}, + "source": [ + "## Does Logistic Regression do a better Job?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "846ae942", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "\"\"\"\n", + "Simple code that tests XOR and OR gates with linear regression\n", + "and logistic regression\n", + "\"\"\"\n", + "\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LogisticRegression\n", + "import numpy as np\n", + "\n", + "# Design matrix\n", + "X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)\n", + "print(f\"The X.TX matrix:{X.T @ X}\")\n", + "Xinv = np.linalg.pinv(X.T @ X)\n", + "print(f\"The invers of X.TX matrix:{Xinv}\")\n", + "\n", + "# The XOR gate \n", + "yXOR = np.array( [ 0, 1 ,1, 0])\n", + "ThetaXOR = Xinv @ X.T @ yXOR\n", + "print(f\"The values of theta for the XOR gate:{ThetaXOR}\")\n", + "print(f\"The linear regression prediction for the XOR gate:{X @ ThetaXOR}\")\n", + "\n", + "\n", + "# The OR gate \n", + "yOR = np.array( [ 0, 1 ,1, 1])\n", + "ThetaOR = Xinv @ X.T @ yOR\n", + "print(f\"The values of theta for the OR gate:{ThetaOR}\")\n", + "print(f\"The linear regression prediction for the OR gate:{X @ ThetaOR}\")\n", + "\n", + "\n", + "# The OR gate \n", + "yAND = np.array( [ 0, 0 ,0, 1])\n", + "ThetaAND = Xinv @ X.T @ yAND\n", + "print(f\"The values of theta for the AND gate:{ThetaAND}\")\n", + "print(f\"The linear regression prediction for the AND gate:{X @ ThetaAND}\")\n", + "\n", + "# Now we change to logistic regression\n", + "\n", + "\n", + "# Logistic Regression\n", + "logreg = LogisticRegression()\n", + "logreg.fit(X, yOR)\n", + "print(\"Test set accuracy with Logistic Regression for OR gate: {:.2f}\".format(logreg.score(X,yOR)))\n", + "\n", + "logreg.fit(X, yXOR)\n", + "print(\"Test set accuracy with Logistic Regression for XOR gate: {:.2f}\".format(logreg.score(X,yXOR)))\n", + "\n", + "\n", + "logreg.fit(X, yAND)\n", + "print(\"Test set accuracy with Logistic Regression for AND gate: {:.2f}\".format(logreg.score(X,yAND)))" + ] + }, + { + "cell_type": "markdown", + "id": "22786e56", + "metadata": {}, + "source": [ + "Not exactly impressive, but somewhat better." + ] + }, + { + "cell_type": "markdown", + "id": "b6bdebe1", + "metadata": {}, + "source": [ + "## Adding Neural Networks" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "fdfb8244", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "# and now neural networks with Scikit-Learn and the XOR\n", + "\n", + "from sklearn.neural_network import MLPClassifier\n", + "from sklearn.datasets import make_classification\n", + "X, yXOR = make_classification(n_samples=100, random_state=1)\n", + "FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)\n", + "FFNN.predict_proba(X)\n", + "print(f\"Test set accuracy with Feed Forward Neural Network for XOR gate:{FFNN.score(X, yXOR)}\")" + ] + }, + { + "cell_type": "markdown", + "id": "13c5155d", + "metadata": {}, + "source": [ + "## Mathematical model\n", + "\n", + "The output $y$ is produced via the activation function $f$" + ] + }, + { + "cell_type": "markdown", + "id": "47b4c719", + "metadata": {}, + "source": [ + "$$\n", + "y = f\\left(\\sum_{i=1}^n w_ix_i + b_i\\right) = f(z),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d65d78c7", + "metadata": {}, + "source": [ + "This function receives $x_i$ as inputs.\n", + "Here the activation $z=(\\sum_{i=1}^n w_ix_i+b_i)$. \n", + "In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of\n", + "the neurons in the preceding layer. Furthermore, an MLP is\n", + "fully-connected, which means that each neuron receives a weighted sum\n", + "of the outputs of *all* neurons in the previous layer." + ] + }, + { + "cell_type": "markdown", + "id": "b8605d0d", + "metadata": {}, + "source": [ + "## Mathematical model\n", + "\n", + "First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$," + ] + }, + { + "cell_type": "markdown", + "id": "be0a2d56", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} z_i^1 = \\sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1\n", + "\\label{_auto1} \\tag{2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "8a8ec932", + "metadata": {}, + "source": [ + "Here $b_i$ is the so-called bias which is normally needed in\n", + "case of zero activation weights or inputs. How to fix the biases and\n", + "the weights will be discussed below. The value of $z_i^1$ is the\n", + "argument to the activation function $f_i$ of each node $i$, The\n", + "variable $M$ stands for all possible inputs to a given node $i$ in the\n", + "first layer. We define the output $y_i^1$ of all neurons in layer 1 as" + ] + }, + { + "cell_type": "markdown", + "id": "30b5df75", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y_i^1 = f(z_i^1) = f\\left(\\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\\right)\n", + "\\label{outputLayer1} \\tag{3}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9906f339", + "metadata": {}, + "source": [ + "where we assume that all nodes in the same layer have identical\n", + "activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.\n", + "In this case we would identify these functions with a superscript $l$ for the $l$-th layer," + ] + }, + { + "cell_type": "markdown", + "id": "705c18d2", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y_i^l = f^l(u_i^l) = f^l\\left(\\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\\right)\n", + "\\label{generalLayer} \\tag{4}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c0779fc6", + "metadata": {}, + "source": [ + "where $N_l$ is the number of nodes in layer $l$. When the output of\n", + "all the nodes in the first hidden layer are computed, the values of\n", + "the subsequent layer can be calculated and so forth until the output\n", + "is obtained." + ] + }, + { + "cell_type": "markdown", + "id": "128a41e3", + "metadata": {}, + "source": [ + "## Mathematical model\n", + "\n", + "The output of neuron $i$ in layer 2 is thus," + ] + }, + { + "cell_type": "markdown", + "id": "e8efb8a6", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y_i^2 = f^2\\left(\\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\\right) \n", + "\\label{_auto2} \\tag{5}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f975dcc6", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + " = f^2\\left[\\sum_{j=1}^N w_{ij}^2f^1\\left(\\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\\right) + b_i^2\\right]\n", + "\\label{outputLayer2} \\tag{6}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7c3843f7", + "metadata": {}, + "source": [ + "where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads" + ] + }, + { + "cell_type": "markdown", + "id": "0008d41a", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y_i^3 = f^3\\left(\\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\\right) \n", + "\\label{_auto3} \\tag{7}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e8dc6d51", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + " = f_3\\left[\\sum_{j} w_{ij}^3 f^2\\left(\\sum_{k} w_{jk}^2 f^1\\left(\\sum_{m} w_{km}^1 x_m + b_k^1\\right) + b_j^2\\right)\n", + " + b_1^3\\right]\n", + "\\label{_auto4} \\tag{8}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1455a093", + "metadata": {}, + "source": [ + "## Mathematical model\n", + "\n", + "We can generalize this expression to an MLP with $l$ hidden\n", + "layers. The complete functional form is," + ] + }, + { + "cell_type": "markdown", + "id": "c2affab6", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "y^{l+1}_i = f^{l+1}\\left[\\!\\sum_{j=1}^{N_l} w_{ij}^3 f^l\\left(\\sum_{k=1}^{N_{l-1}}w_{jk}^{l-1}\\left(\\dots f^1\\left(\\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\\right)\\dots\\right)+b_k^2\\right)+b_1^3\\right] \n", + "\\label{completeNN} \\tag{9}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c7910d23", + "metadata": {}, + "source": [ + "which illustrates a basic property of MLPs: The only independent\n", + "variables are the input values $x_n$." + ] + }, + { + "cell_type": "markdown", + "id": "ec9e660d", + "metadata": {}, + "source": [ + "## Mathematical model\n", + "\n", + "This confirms that an MLP, despite its quite convoluted mathematical\n", + "form, is nothing more than an analytic function, specifically a\n", + "mapping of real-valued vectors $\\hat{x} \\in \\mathbb{R}^n \\rightarrow\n", + "\\hat{y} \\in \\mathbb{R}^m$.\n", + "\n", + "Furthermore, the flexibility and universality of an MLP can be\n", + "illustrated by realizing that the expression is essentially a nested\n", + "sum of scaled activation functions of the form" + ] + }, + { + "cell_type": "markdown", + "id": "29c77377", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " f(x) = c_1 f(c_2 x + c_3) + c_4\n", + "\\label{_auto5} \\tag{10}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f52146ef", + "metadata": {}, + "source": [ + "where the parameters $c_i$ are weights and biases. By adjusting these\n", + "parameters, the activation functions can be shifted up and down or\n", + "left and right, change slope or be rescaled which is the key to the\n", + "flexibility of a neural network." + ] + }, + { + "cell_type": "markdown", + "id": "7f9f65ce", + "metadata": {}, + "source": [ + "### Matrix-vector notation\n", + "\n", + "We can introduce a more convenient notation for the activations in an A NN. \n", + "\n", + "Additionally, we can represent the biases and activations\n", + "as layer-wise column vectors $\\hat{b}_l$ and $\\hat{y}_l$, so that the $i$-th element of each vector \n", + "is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. \n", + "\n", + "We have that $\\mathrm{W}_l$ is an $N_{l-1} \\times N_l$ matrix, while $\\hat{b}_l$ and $\\hat{y}_l$ are $N_l \\times 1$ column vectors. \n", + "With this notation, the sum becomes a matrix-vector multiplication, and we can write\n", + "the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as" + ] + }, + { + "cell_type": "markdown", + "id": "7aec05b7", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\hat{y}_2 = f_2(\\mathrm{W}_2 \\hat{y}_{1} + \\hat{b}_{2}) = \n", + " f_2\\left(\\left[\\begin{array}{ccc}\n", + " w^2_{11} &w^2_{12} &w^2_{13} \\\\\n", + " w^2_{21} &w^2_{22} &w^2_{23} \\\\\n", + " w^2_{31} &w^2_{32} &w^2_{33} \\\\\n", + " \\end{array} \\right] \\cdot\n", + " \\left[\\begin{array}{c}\n", + " y^1_1 \\\\\n", + " y^1_2 \\\\\n", + " y^1_3 \\\\\n", + " \\end{array}\\right] + \n", + " \\left[\\begin{array}{c}\n", + " b^2_1 \\\\\n", + " b^2_2 \\\\\n", + " b^2_3 \\\\\n", + " \\end{array}\\right]\\right).\n", + "\\label{_auto6} \\tag{11}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "524f3145", + "metadata": {}, + "source": [ + "### Matrix-vector notation and activation\n", + "\n", + "The activation of node $i$ in layer 2 is" + ] + }, + { + "cell_type": "markdown", + "id": "67ea322c", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y^2_i = f_2\\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\\Bigr) = \n", + " f_2\\left(\\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\\right).\n", + "\\label{_auto7} \\tag{12}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "fb2a1836", + "metadata": {}, + "source": [ + "This is not just a convenient and compact notation, but also a useful\n", + "and intuitive way to think about MLPs: The output is calculated by a\n", + "series of matrix-vector multiplications and vector additions that are\n", + "used as input to the activation functions. For each operation\n", + "$\\mathrm{W}_l \\hat{y}_{l-1}$ we move forward one layer." + ] + }, + { + "cell_type": "markdown", + "id": "c6e37074", + "metadata": {}, + "source": [ + "### Activation functions\n", + "\n", + "A property that characterizes a neural network, other than its\n", + "connectivity, is the choice of activation function(s). As described\n", + "in, the following restrictions are imposed on an activation function\n", + "for a FFNN to fulfill the universal approximation theorem\n", + "\n", + " * Non-constant\n", + "\n", + " * Bounded\n", + "\n", + " * Monotonically-increasing\n", + "\n", + " * Continuous" + ] + }, + { + "cell_type": "markdown", + "id": "516427eb", + "metadata": {}, + "source": [ + "### Activation functions, Logistic and Hyperbolic ones\n", + "\n", + "The second requirement excludes all linear functions. Furthermore, in\n", + "a MLP with only linear activation functions, each layer simply\n", + "performs a linear transformation of its inputs.\n", + "\n", + "Regardless of the number of layers, the output of the NN will be\n", + "nothing but a linear function of the inputs. Thus we need to introduce\n", + "some kind of non-linearity to the NN to be able to fit non-linear\n", + "functions Typical examples are the logistic *Sigmoid*" + ] + }, + { + "cell_type": "markdown", + "id": "607e0e1f", + "metadata": {}, + "source": [ + "$$\n", + "f(x) = \\frac{1}{1 + e^{-x}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4147fa7c", + "metadata": {}, + "source": [ + "and the *hyperbolic tangent* function" + ] + }, + { + "cell_type": "markdown", + "id": "4c880e2a", + "metadata": {}, + "source": [ + "$$\n", + "f(x) = \\tanh(x)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "56c9cd1b", + "metadata": {}, + "source": [ + "### Relevance\n", + "\n", + "The *sigmoid* function are more biologically plausible because the\n", + "output of inactive neurons are zero. Such activation function are\n", + "called *one-sided*. However, it has been shown that the hyperbolic\n", + "tangent performs better than the sigmoid for training MLPs. has\n", + "become the most popular for *deep neural networks*" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "187aa1c5", + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"The sigmoid function (or the logistic curve) is a \n", + "function that takes any real number, z, and outputs a number (0,1).\n", + "It is useful in neural networks for assigning weights on a relative scale.\n", + "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n", + "\n", + "import numpy\n", + "import matplotlib.pyplot as plt\n", + "import math as mt\n", + "\n", + "z = numpy.arange(-5, 5, .1)\n", + "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n", + "sigma = sigma_fn(z)\n", + "\n", + "fig = plt.figure()\n", + "ax = fig.add_subplot(111)\n", + "ax.plot(z, sigma)\n", + "ax.set_ylim([-0.1, 1.1])\n", + "ax.set_xlim([-5,5])\n", + "ax.grid(True)\n", + "ax.set_xlabel('z')\n", + "ax.set_title('sigmoid function')\n", + "\n", + "plt.show()\n", + "\n", + "\"\"\"Step Function\"\"\"\n", + "z = numpy.arange(-5, 5, .02)\n", + "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n", + "step = step_fn(z)\n", + "\n", + "fig = plt.figure()\n", + "ax = fig.add_subplot(111)\n", + "ax.plot(z, step)\n", + "ax.set_ylim([-0.5, 1.5])\n", + "ax.set_xlim([-5,5])\n", + "ax.grid(True)\n", + "ax.set_xlabel('z')\n", + "ax.set_title('step function')\n", + "\n", + "plt.show()\n", + "\n", + "\"\"\"Sine Function\"\"\"\n", + "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n", + "t = numpy.sin(z)\n", + "\n", + "fig = plt.figure()\n", + "ax = fig.add_subplot(111)\n", + "ax.plot(z, t)\n", + "ax.set_ylim([-1.0, 1.0])\n", + "ax.set_xlim([-2*mt.pi,2*mt.pi])\n", + "ax.grid(True)\n", + "ax.set_xlabel('z')\n", + "ax.set_title('sine function')\n", + "\n", + "plt.show()\n", + "\n", + "\"\"\"Plots a graph of the squashing function used by a rectified linear\n", + "unit\"\"\"\n", + "z = numpy.arange(-2, 2, .1)\n", + "zero = numpy.zeros(len(z))\n", + "y = numpy.max([zero, z], axis=0)\n", + "\n", + "fig = plt.figure()\n", + "ax = fig.add_subplot(111)\n", + "ax.plot(z, y)\n", + "ax.set_ylim([-2.0, 2.0])\n", + "ax.set_xlim([-2.0, 2.0])\n", + "ax.grid(True)\n", + "ax.set_xlabel('z')\n", + "ax.set_title('Rectified linear unit')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "e3195fd0", + "metadata": {}, + "source": [ + "## The multilayer perceptron (MLP)\n", + "\n", + "The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of\n", + "1. A neural network with one or more layers of nodes between the input and the output nodes.\n", + "\n", + "2. The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.\n", + "\n", + "3. The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.\n", + "\n", + "As a convention it is normal to call a network with one layer of input units, one layer of hidden\n", + "units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc.\n", + "\n", + "For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units.\n", + "Hereafter we will call the various entities of a layer for nodes.\n", + "There are also no connections within a single layer.\n", + "\n", + "The number of input nodes does not need to equal the number of output\n", + "nodes. This applies also to the hidden layers. Each layer may have its\n", + "own number of nodes and activation functions.\n", + "\n", + "The hidden layers have their name from the fact that they are not\n", + "linked to observables and as we will see below when we define the\n", + "so-called activation $\\hat{z}$, we can think of this as a basis\n", + "expansion of the original inputs $\\hat{x}$. The difference however\n", + "between neural networks and say linear regression is that now these\n", + "basis functions (which will correspond to the weights in the network)\n", + "are learned from data. This results in an important difference between\n", + "neural networks and deep learning approaches on one side and methods\n", + "like logistic regression or linear regression and their modifications on the other side." + ] + }, + { + "cell_type": "markdown", + "id": "f15de9c4", + "metadata": {}, + "source": [ + "## From one to many layers, the universal approximation theorem\n", + "\n", + "A neural network with only one layer, what we called the simple\n", + "perceptron, is best suited if we have a standard binary model with\n", + "clear (linear) boundaries between the outcomes. As such it could\n", + "equally well be replaced by standard linear regression or logistic\n", + "regression. Networks with one or more hidden layers approximate\n", + "systems with more complex boundaries.\n", + "\n", + "As stated earlier, \n", + "an important theorem in studies of neural networks, restated without\n", + "proof here, is the [universal approximation\n", + "theorem](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf).\n", + "\n", + "It states that a feed-forward network with a single hidden layer\n", + "containing a finite number of neurons can approximate continuous\n", + "functions on compact subsets of real functions. The theorem thus\n", + "states that simple neural networks can represent a wide variety of\n", + "interesting functions when given appropriate parameters. It is the\n", + "multilayer feedforward architecture itself which gives neural networks\n", + "the potential of being universal approximators." + ] + }, + { + "cell_type": "markdown", + "id": "9d79d680", + "metadata": {}, + "source": [ + "## Deriving the back propagation code for a multilayer perceptron model\n", + "\n", + "As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications.\n", + "The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible.\n", + "This leads us to the famous [back propagation algorithm](https://www.nature.com/articles/323533a0).\n", + "\n", + "The questions we want to ask are how do changes in the biases and the\n", + "weights in our network change the cost function and how can we use the\n", + "final output to modify the weights?\n", + "\n", + "To derive these equations let us start with a plain regression problem\n", + "and define our cost function as" + ] + }, + { + "cell_type": "markdown", + "id": "31e1a9b1", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal C}(\\hat{W}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "890921b9", + "metadata": {}, + "source": [ + "where the $t_i$s are our $n$ targets (the values we want to\n", + "reproduce), while the outputs of the network after having propagated\n", + "all inputs $\\hat{x}$ are given by $y_i$. Below we will demonstrate\n", + "how the basic equations arising from the back propagation algorithm\n", + "can be modified in order to study classification problems with $K$\n", + "classes." + ] + }, + { + "cell_type": "markdown", + "id": "fe55dffb", + "metadata": {}, + "source": [ + "## Definitions\n", + "\n", + "With our definition of the targets $\\hat{t}$, the outputs of the\n", + "network $\\hat{y}$ and the inputs $\\hat{x}$ we\n", + "define now the activation $z_j^l$ of node/neuron/unit $j$ of the\n", + "$l$-th layer as a function of the bias, the weights which add up from\n", + "the previous layer $l-1$ and the forward passes/outputs\n", + "$\\hat{a}^{l-1}$ from the previous layer as" + ] + }, + { + "cell_type": "markdown", + "id": "61548fd5", + "metadata": {}, + "source": [ + "$$\n", + "z_j^l = \\sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7b437827", + "metadata": {}, + "source": [ + "where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$\n", + "represents the total number of nodes/neurons/units of layer $l-1$. The\n", + "figure here illustrates this equation. We can rewrite this in a more\n", + "compact form as the matrix-vector products we discussed earlier," + ] + }, + { + "cell_type": "markdown", + "id": "88aeaf0f", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{z}^l = \\left(\\hat{W}^l\\right)^T\\hat{a}^{l-1}+\\hat{b}^l.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d81878b1", + "metadata": {}, + "source": [ + "With the activation values $\\hat{z}^l$ we can in turn define the\n", + "output of layer $l$ as $\\hat{a}^l = f(\\hat{z}^l)$ where $f$ is our\n", + "activation function. In the examples here we will use the sigmoid\n", + "function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers\n", + "and their nodes. It means we have" + ] + }, + { + "cell_type": "markdown", + "id": "aa3e6b55", + "metadata": {}, + "source": [ + "$$\n", + "a_j^l = f(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "282fc0f1", + "metadata": {}, + "source": [ + "## Derivatives and the chain rule\n", + "\n", + "From the definition of the activation $z_j^l$ we have" + ] + }, + { + "cell_type": "markdown", + "id": "5007c640", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ed8b0010", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "3174619f", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "448a714d", + "metadata": {}, + "source": [ + "With our definition of the activation function we have that (note that this function depends only on $z_j^l$)" + ] + }, + { + "cell_type": "markdown", + "id": "862da704", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial a_j^l}{\\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9958b437", + "metadata": {}, + "source": [ + "## Derivative of the cost function\n", + "\n", + "With these definitions we can now compute the derivative of the cost function in terms of the weights.\n", + "\n", + "Let us specialize to the output layer $l=L$. Our cost function is" + ] + }, + { + "cell_type": "markdown", + "id": "be3a329b", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal C}(\\hat{W^L}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2=\\frac{1}{2}\\sum_{i=1}^n\\left(a_i^L - t_i\\right)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2237bf2b", + "metadata": {}, + "source": [ + "The derivative of this function with respect to the weights is" + ] + }, + { + "cell_type": "markdown", + "id": "74e6185e", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "462a7694", + "metadata": {}, + "source": [ + "The last partial derivative can easily be computed and reads (by applying the chain rule)" + ] + }, + { + "cell_type": "markdown", + "id": "cde99728", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}} = \\frac{\\partial a_j^L}{\\partial z_{j}^{L}}\\frac{\\partial z_j^L}{\\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "11c5d932", + "metadata": {}, + "source": [ + "## Bringing it together, first back propagation equation\n", + "\n", + "We have thus" + ] + }, + { + "cell_type": "markdown", + "id": "d46a1cc5", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)a_j^L(1-a_j^L)a_k^{L-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7f634831", + "metadata": {}, + "source": [ + "Defining" + ] + }, + { + "cell_type": "markdown", + "id": "c2245dab", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L = a_j^L(1-a_j^L)\\left(a_j^L - t_j\\right) = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "fbda1939", + "metadata": {}, + "source": [ + "and using the Hadamard product of two vectors we can write this as" + ] + }, + { + "cell_type": "markdown", + "id": "54e8fb49", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\delta}^L = f'(\\hat{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\hat{a}^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0fa8b43d", + "metadata": {}, + "source": [ + "This is an important expression. The second term on the right handside\n", + "measures how fast the cost function is changing as a function of the $j$th\n", + "output activation. If, for example, the cost function doesn't depend\n", + "much on a particular output node $j$, then $\\delta_j^L$ will be small,\n", + "which is what we would expect. The first term on the right, measures\n", + "how fast the activation function $f$ is changing at a given activation\n", + "value $z_j^L$.\n", + "\n", + "Notice that everything in the above equations is easily computed. In\n", + "particular, we compute $z_j^L$ while computing the behaviour of the\n", + "network, and it is only a small additional overhead to compute\n", + "$f'(z^L_j)$. The exact form of the derivative with respect to the\n", + "output depends on the form of the cost function.\n", + "However, provided the cost function is known there should be little\n", + "trouble in calculating" + ] + }, + { + "cell_type": "markdown", + "id": "00455d1e", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "8a503b44", + "metadata": {}, + "source": [ + "With the definition of $\\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely" + ] + }, + { + "cell_type": "markdown", + "id": "28aaa847", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ca7f309e", + "metadata": {}, + "source": [ + "## Derivatives in terms of $z_j^L$\n", + "\n", + "It is also easy to see that our previous equation can be written as" + ] + }, + { + "cell_type": "markdown", + "id": "79b5d957", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L =\\frac{\\partial {\\cal C}}{\\partial z_j^L}= \\frac{\\partial {\\cal C}}{\\partial a_j^L}\\frac{\\partial a_j^L}{\\partial z_j^L},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ba24b0ba", + "metadata": {}, + "source": [ + "which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely" + ] + }, + { + "cell_type": "markdown", + "id": "2f98d5ae", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L}\\frac{\\partial b_j^L}{\\partial z_j^L}=\\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "596bd7eb", + "metadata": {}, + "source": [ + "That is, the error $\\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias." + ] + }, + { + "cell_type": "markdown", + "id": "9144dcb7", + "metadata": {}, + "source": [ + "## Bringing it together\n", + "\n", + "We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are\n", + "\n", + "**The starting equations.**" + ] + }, + { + "cell_type": "markdown", + "id": "4f2e52cb", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1},\n", + "\\label{_auto8} \\tag{13}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3b94d154", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "18f353fd", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", + "\\label{_auto9} \\tag{14}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "631f4feb", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "1793bcd7", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", + "\\label{_auto10} \\tag{15}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0cc3885e", + "metadata": {}, + "source": [ + "An interesting consequence of the above equations is that when the\n", + "activation $a_k^{L-1}$ is small, the gradient term, that is the\n", + "derivative of the cost function with respect to the weights, will also\n", + "tend to be small. We say then that the weight learns slowly, meaning\n", + "that it changes slowly when we minimize the weights via say gradient\n", + "descent. In this case we say the system learns slowly.\n", + "\n", + "Another interesting feature is that is when the activation function,\n", + "represented by the sigmoid function here, is rather flat when we move towards\n", + "its end values $0$ and $1$ (see the above Python codes). In these\n", + "cases, the derivatives of the activation function will also be close\n", + "to zero, meaning again that the gradients will be small and the\n", + "network learns slowly again.\n", + "\n", + "We need a fourth equation and we are set. We are going to propagate\n", + "backwards in order to the determine the weights and biases. In order\n", + "to do so we need to represent the error in the layer before the final\n", + "one $L-1$ in terms of the errors in the final output layer." + ] + }, + { + "cell_type": "markdown", + "id": "7f697fec", + "metadata": {}, + "source": [ + "## Final back propagating equation\n", + "\n", + "We have that (replacing $L$ with a general layer $l$)" + ] + }, + { + "cell_type": "markdown", + "id": "42a9acc8", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ac01943b", + "metadata": {}, + "source": [ + "We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have" + ] + }, + { + "cell_type": "markdown", + "id": "a6ec5df0", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l =\\sum_k \\frac{\\partial {\\cal C}}{\\partial z_k^{l+1}}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}}=\\sum_k \\delta_k^{l+1}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "8b0f324a", + "metadata": {}, + "source": [ + "and recalling that" + ] + }, + { + "cell_type": "markdown", + "id": "4ae4c890", + "metadata": {}, + "source": [ + "$$\n", + "z_j^{l+1} = \\sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b8af6a3b", + "metadata": {}, + "source": [ + "with $M_l$ being the number of nodes in layer $l$, we obtain" + ] + }, + { + "cell_type": "markdown", + "id": "c5a36652", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l =\\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "eb9f0a42", + "metadata": {}, + "source": [ + "This is our final equation.\n", + "\n", + "We are now ready to set up the algorithm for back propagation and learning the weights and biases." + ] + }, + { + "cell_type": "markdown", + "id": "cd78653c", + "metadata": {}, + "source": [ + "## Setting up the Back propagation algorithm\n", + "\n", + "The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", + "\n", + "First, we set up the input data $\\hat{x}$ and the activations\n", + "$\\hat{z}_1$ of the input layer and compute the activation function and\n", + "the pertinent outputs $\\hat{a}^1$.\n", + "\n", + "Secondly, we perform then the feed forward till we reach the output\n", + "layer and compute all $\\hat{z}_l$ of the input layer and compute the\n", + "activation function and the pertinent outputs $\\hat{a}^l$ for\n", + "$l=2,3,\\dots,L$.\n", + "\n", + "Thereafter we compute the ouput error $\\hat{\\delta}^L$ by computing all" + ] + }, + { + "cell_type": "markdown", + "id": "adab4f13", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9091074a", + "metadata": {}, + "source": [ + "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" + ] + }, + { + "cell_type": "markdown", + "id": "da04b8a8", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d707b6e0", + "metadata": {}, + "source": [ + "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" + ] + }, + { + "cell_type": "markdown", + "id": "f26ac396", + "metadata": {}, + "source": [ + "$$\n", + "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1d5d1ed0", + "metadata": {}, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d686cbb0", + "metadata": {}, + "source": [ + "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", + "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." + ] + }, + { + "cell_type": "markdown", + "id": "31554688", + "metadata": {}, + "source": [ + "## Setting up the Back propagation algorithm\n", + "\n", + "The four equations above provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", + "\n", + "First, we set up the input data $\\boldsymbol{x}$ and the activations\n", + "$\\boldsymbol{z}_1$ of the input layer and compute the activation function and\n", + "the pertinent outputs $\\boldsymbol{a}^1$.\n", + "\n", + "Secondly, we perform then the feed forward till we reach the output\n", + "layer and compute all $\\boldsymbol{z}_l$ of the input layer and compute the\n", + "activation function and the pertinent outputs $\\boldsymbol{a}^l$ for\n", + "$l=2,3,\\dots,L$.\n", + "\n", + "Thereafter we compute the ouput error $\\boldsymbol{\\delta}^L$ by computing all" + ] + }, + { + "cell_type": "markdown", + "id": "a34466dc", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "742b0899", + "metadata": {}, + "source": [ + "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" + ] + }, + { + "cell_type": "markdown", + "id": "813c7f07", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "88fccb02", + "metadata": {}, + "source": [ + "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" + ] + }, + { + "cell_type": "markdown", + "id": "a5d5593c", + "metadata": {}, + "source": [ + "$$\n", + "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1b5aeaa8", + "metadata": {}, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "29156297", + "metadata": {}, + "source": [ + "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", + "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." + ] + }, + { + "cell_type": "markdown", + "id": "752b2b7a", + "metadata": {}, + "source": [ + "## Setting up the Back propagation algorithm\n", + "\n", + "The four equations derived discussed above provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", + "\n", + "First, we set up the input data $\\boldsymbol{x}$ and the activations\n", + "$\\boldsymbol{z}_1$ of the input layer and compute the activation function and\n", + "the pertinent outputs $\\boldsymbol{a}^1$.\n", + "\n", + "Secondly, we perform then the feed forward till we reach the output\n", + "layer and compute all $\\boldsymbol{z}_l$ of the input layer and compute the\n", + "activation function and the pertinent outputs $\\boldsymbol{a}^l$ for\n", + "$l=2,3,\\dots,L$.\n", + "\n", + "Thereafter we compute the ouput error $\\boldsymbol{\\delta}^L$ by computing all" + ] + }, + { + "cell_type": "markdown", + "id": "29bb348b", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2cbb4812", + "metadata": {}, + "source": [ + "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" + ] + }, + { + "cell_type": "markdown", + "id": "73fa8d95", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d815b24a", + "metadata": {}, + "source": [ + "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" + ] + }, + { + "cell_type": "markdown", + "id": "43d2f617", + "metadata": {}, + "source": [ + "$$\n", + "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "bf7af7f5", + "metadata": {}, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9a5e5eaf", + "metadata": {}, + "source": [ + "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", + "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." + ] + }, + { + "cell_type": "markdown", + "id": "e62f23f4", + "metadata": {}, + "source": [ + "## Setting up a Multi-layer perceptron model for classification\n", + "\n", + "We are now gong to develop an example based on the MNIST data\n", + "base. This is a classification problem and we need to use our\n", + "cross-entropy function we discussed in connection with logistic\n", + "regression. The cross-entropy defines our cost function for the\n", + "classificaton problems with neural networks.\n", + "\n", + "In binary classification with two classes $(0, 1)$ we define the\n", + "logistic/sigmoid function as the probability that a particular input\n", + "is in class $0$ or $1$. This is possible because the logistic\n", + "function takes any input from the real numbers and inputs a number\n", + "between 0 and 1, and can therefore be interpreted as a probability. It\n", + "also has other nice properties, such as a derivative that is simple to\n", + "calculate.\n", + "\n", + "For an input $\\boldsymbol{a}$ from the hidden layer, the probability that the input $\\boldsymbol{x}$\n", + "is in class 0 or 1 is just. We let $\\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$\n", + "represents our activation values $z$. We have" + ] + }, + { + "cell_type": "markdown", + "id": "42d7a94e", + "metadata": {}, + "source": [ + "$$\n", + "P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = \\frac{1}{1 + \\exp{(- \\boldsymbol{x}})} ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5bfea505", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "9f6b8143", + "metadata": {}, + "source": [ + "$$\n", + "P(y = 1 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = 1 - P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "194f2cbe", + "metadata": {}, + "source": [ + "where $y \\in \\{0, 1\\}$ and $\\boldsymbol{\\theta}$ represents the weights and biases\n", + "of our network." + ] + }, + { + "cell_type": "markdown", + "id": "20cd18e6", + "metadata": {}, + "source": [ + "## Defining the cost function\n", + "\n", + "Our cost function is given as (see the Logistic regression lectures)" + ] + }, + { + "cell_type": "markdown", + "id": "b3e52796", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = - \\sum_{i=1}^n\n", + "y_i \\ln[P(y_i = 0)] + (1 - y_i) \\ln [1 - P(y_i = 0)] = \\sum_{i=1}^n \\mathcal{L}_i(\\boldsymbol{\\theta}) .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7cb68d89", + "metadata": {}, + "source": [ + "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", + "for each point in the dataset $\\mathcal{L}_i(\\boldsymbol{\\theta})$. \n", + "The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather\n", + "than maximizing a negative number. \n", + "\n", + "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", + "\n", + "$y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and\n", + "\n", + "$y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ \n", + "\n", + "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. \n", + "\n", + "If $\\boldsymbol{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th\n", + "output vector $\\boldsymbol{y}_i$. \n", + "The probability of $\\boldsymbol{x}_i$ being in class $c$ will be given by the softmax function:" + ] + }, + { + "cell_type": "markdown", + "id": "0a98f80a", + "metadata": {}, + "source": [ + "$$\n", + "P(y_{ic} = 1 \\mid \\boldsymbol{x}_i, \\boldsymbol{\\theta}) = \\frac{\\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_c)}}\n", + "{\\sum_{c'=0}^{C-1} \\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_{c'})}} ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b86447a6", + "metadata": {}, + "source": [ + "which reduces to the logistic function in the binary case. \n", + "The likelihood of this $C$-class classifier\n", + "is now given as:" + ] + }, + { + "cell_type": "markdown", + "id": "942e0060", + "metadata": {}, + "source": [ + "$$\n", + "P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "99eae6f4", + "metadata": {}, + "source": [ + "Again we take the negative log-likelihood to define our cost function:" + ] + }, + { + "cell_type": "markdown", + "id": "872017e1", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\boldsymbol{\\theta})}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f55259c0", + "metadata": {}, + "source": [ + "See the logistic regression lectures for a full definition of the cost function.\n", + "\n", + "The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!" + ] + }, + { + "cell_type": "markdown", + "id": "db983bc4", + "metadata": {}, + "source": [ + "## Example: binary classification problem\n", + "\n", + "As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\\beta$ as" + ] + }, + { + "cell_type": "markdown", + "id": "165881cf", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\boldsymbol{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\boldsymbol{\\beta})}+(1-y_i)\\log{1-p(y_i \\vert x_i,\\boldsymbol{\\beta})}\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "50ecaa83", + "metadata": {}, + "source": [ + "where we had defined the logistic (sigmoid) function" + ] + }, + { + "cell_type": "markdown", + "id": "b16d30f7", + "metadata": {}, + "source": [ + "$$\n", + "p(y_i =1\\vert x_i,\\boldsymbol{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2d4c1829", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "4d7a8c79", + "metadata": {}, + "source": [ + "$$\n", + "p(y_i =0\\vert x_i,\\boldsymbol{\\beta})=1-p(y_i =1\\vert x_i,\\boldsymbol{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7c4a0d89", + "metadata": {}, + "source": [ + "The parameters $\\boldsymbol{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", + "\n", + "Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. \n", + "We have then" + ] + }, + { + "cell_type": "markdown", + "id": "96bccb9e", + "metadata": {}, + "source": [ + "$$\n", + "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "01f9ae68", + "metadata": {}, + "source": [ + "with" + ] + }, + { + "cell_type": "markdown", + "id": "590fc8bd", + "metadata": {}, + "source": [ + "$$\n", + "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f3dc3a43", + "metadata": {}, + "source": [ + "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", + "Our cost function at the final layer $l=L$ is now" + ] + }, + { + "cell_type": "markdown", + "id": "7dd1bbaa", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\boldsymbol{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(1-t_i)\\log{(1-a_i^L)}\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "dc472c94", + "metadata": {}, + "source": [ + "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" + ] + }, + { + "cell_type": "markdown", + "id": "372c5019", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial \\mathcal{C}(\\boldsymbol{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "783cc2c1", + "metadata": {}, + "source": [ + "In case we use another activation function than the logistic one, we need to evaluate other derivatives." + ] + }, + { + "cell_type": "markdown", + "id": "d37a48b8", + "metadata": {}, + "source": [ + "## The Softmax function\n", + "In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need" + ] + }, + { + "cell_type": "markdown", + "id": "e6790133", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", + "\\frac{\\partial f(z_i^l)}{\\partial z_j^l} \\frac{\\partial z_j^l}{\\partial w_{jk}^l}= \\frac{\\partial f(z_i^l)}{\\partial z_j^l}a_k^{l-1}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "97578009", + "metadata": {}, + "source": [ + "For the Softmax function we have" + ] + }, + { + "cell_type": "markdown", + "id": "13822f62", + "metadata": {}, + "source": [ + "$$\n", + "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "10bf9fb7", + "metadata": {}, + "source": [ + "Its derivative with respect to $z_j^l$ gives" + ] + }, + { + "cell_type": "markdown", + "id": "cf59a594", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "80a4d3d7", + "metadata": {}, + "source": [ + "which in case of the simply binary model reduces to having $i=j$." + ] + }, + { + "cell_type": "markdown", + "id": "91baac68", + "metadata": {}, + "source": [ + "## Developing a code for doing neural networks with back propagation\n", + "\n", + "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", + "\n", + "1. Collect and pre-process data \n", + "\n", + "2. Define model and architecture \n", + "\n", + "3. Choose cost function and optimizer \n", + "\n", + "4. Train the model \n", + "\n", + "5. Evaluate model performance on test data \n", + "\n", + "6. Adjust hyperparameters (if necessary, network architecture)" + ] + }, + { + "cell_type": "markdown", + "id": "b4d8a71e", + "metadata": {}, + "source": [ + "## Collect and pre-process data\n", + "\n", + "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", + "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", + "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", + "of handwritten digits that is commonly used for training various image processing systems. \n", + "The MNIST dataset consists of 70 000 images of size $28\\times 28$ pixels, each labeled from 0 to 9. \n", + "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", + "\n", + "To feed data into a feed-forward neural network we need to represent\n", + "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n", + "row represents an *input*, in this case a handwritten digit, and\n", + "each column represents a *feature*, in this case a pixel. The\n", + "correct answers, also known as *labels* or *targets* are\n", + "represented as a 1D array of integers \n", + "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", + "\n", + "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", + "measurements of height (in m) \n", + "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n", + "\n", + "$$ X = \\begin{bmatrix}\n", + "1.85 & 81\\\\\n", + "1.71 & 65\\\\\n", + "1.95 & 103\\\\\n", + "1.55 & 42\\\\\n", + "1.63 & 56\n", + "\\end{bmatrix} ,$$ \n", + "\n", + "and the targets would be: \n", + "\n", + "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", + "\n", + "Since each input image is a 2D matrix, we need to flatten the image\n", + "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", + "design/feature matrix. This means we lose all spatial information in the\n", + "image, such as locality and translational invariance. More complicated\n", + "architectures such as Convolutional Neural Networks can take advantage\n", + "of such information, and are most commonly applied when analyzing\n", + "images." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "ad941e6f", + "metadata": {}, + "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", + "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# flatten the image\n", + "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", + "n_inputs = len(inputs)\n", + "inputs = inputs.reshape(n_inputs, -1)\n", + "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", + "\n", + "\n", + "# choose some random images to display\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": "markdown", + "id": "c2f821dc", + "metadata": {}, + "source": [ + "## Train and test datasets\n", + "\n", + "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", + "\n", + "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", + "\n", + "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", + "no bias in the sampling. \n", + "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", + "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", + "collected from 12.00 to 24.00." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "d368bcd4", + "metadata": {}, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\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)\n", + "\n", + "# equivalently in numpy\n", + "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", + " n_inputs = len(inputs)\n", + " inputs_shuffled = inputs.copy()\n", + " labels_shuffled = labels.copy()\n", + " \n", + " np.random.shuffle(inputs_shuffled)\n", + " np.random.shuffle(labels_shuffled)\n", + " \n", + " train_end = int(n_inputs*train_size)\n", + " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", + " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", + " \n", + " return X_train, X_test, Y_train, Y_test\n", + "\n", + "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", + "\n", + "print(\"Number of training images: \" + str(len(X_train)))\n", + "print(\"Number of test images: \" + str(len(X_test)))" + ] + }, + { + "cell_type": "markdown", + "id": "c0e21c2d", + "metadata": {}, + "source": [ + "## Define model and architecture\n", + "\n", + "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", + "\n", + "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", + "\n", + "$$ y = f(z) ,$$\n", + "\n", + "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", + "and $w_i$ is the weight to input $i$. \n", + "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", + "\n", + "The simplest activation function for a neuron is the *Heaviside* function:\n", + "\n", + "$$ f(z) = \n", + "\\begin{cases}\n", + "1, & z > 0\\\\\n", + "0, & \\text{otherwise}\n", + "\\end{cases}\n", + "$$\n", + "\n", + "A feed-forward neural network with this activation is known as a *perceptron*. \n", + "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", + "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", + "and we call these architectures *multiclass perceptrons*. \n", + "\n", + "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", + "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", + "\n", + "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", + "We will be using the sigmoid function $\\sigma(x)$: \n", + "\n", + "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", + "\n", + "which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions." + ] + }, + { + "cell_type": "markdown", + "id": "ba8404a4", + "metadata": {}, + "source": [ + "## Layers\n", + "\n", + "* Input \n", + "\n", + "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", + "\n", + "* Hidden layer\n", + "\n", + "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", + "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", + "\n", + "* Output\n", + "\n", + "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", + "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", + "\n", + "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", + "\n", + "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", + "\n", + "$$ P(\\text{class $j$} \\mid \\text{input $\\boldsymbol{a}$}) = \\frac{\\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_j)}}\n", + "{\\sum_{c=0}^{9} \\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_c)}} ,$$ \n", + "\n", + "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\boldsymbol{a}$, with $\\boldsymbol{w}_j$ the weights of neuron $j$ to the inputs. \n", + "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", + "The exponent is just the weighted sum of inputs as before: \n", + "\n", + "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", + "\n", + "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", + "weights to the output layer." + ] + }, + { + "cell_type": "markdown", + "id": "5ea9e948", + "metadata": {}, + "source": [ + "## Weights and biases\n", + "\n", + "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", + "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", + "\n", + "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", + "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", + "\n", + "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", + "\n", + "The bias weights $\\boldsymbol{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "890bc8b7", + "metadata": {}, + "outputs": [], + "source": [ + "# building our neural network\n", + "\n", + "n_inputs, n_features = X_train.shape\n", + "n_hidden_neurons = 50\n", + "n_categories = 10\n", + "\n", + "# we make the weights normally distributed using numpy.random.randn\n", + "\n", + "# weights and bias in the hidden layer\n", + "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", + "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", + "\n", + "# weights and bias in the output layer\n", + "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", + "output_bias = np.zeros(n_categories) + 0.01" + ] + }, + { + "cell_type": "markdown", + "id": "1acc9cfe", + "metadata": {}, + "source": [ + "## Feed-forward pass\n", + "\n", + "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", + "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", + "\n", + "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", + "\n", + "this is then passed through our activation function \n", + "\n", + "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", + "\n", + "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", + "\n", + "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", + "\n", + "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", + "\n", + "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", + "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$" + ] + }, + { + "cell_type": "markdown", + "id": "e13f966a", + "metadata": {}, + "source": [ + "## Matrix multiplications\n", + "\n", + "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", + "layer have the dimensions \n", + "$W_{hidden} = (n_{features}, n_{hidden})$,\n", + "we can easily feed the network all our training data in one go by taking the matrix product \n", + "\n", + "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", + "\n", + "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", + "for each input image and each hidden neuron. \n", + "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", + "\n", + "$$ \\boldsymbol{z}^{l} = \\boldsymbol{X} \\boldsymbol{W}^{l} + \\boldsymbol{b}^{l} ,$$\n", + "\n", + "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", + "This is then passed through the activation: \n", + "\n", + "$$ \\boldsymbol{a}^{l} = f(\\boldsymbol{z}^l) .$$ \n", + "\n", + "This is fed to the output layer: \n", + "\n", + "$$ \\boldsymbol{z}^{L} = \\boldsymbol{a}^{L} \\boldsymbol{W}^{L} + \\boldsymbol{b}^{L} .$$\n", + "\n", + "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", + "\n", + "$$ output = softmax (\\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "8df5db3a", + "metadata": {}, + "outputs": [], + "source": [ + "# setup the feed-forward pass, subscript h = hidden layer\n", + "\n", + "def sigmoid(x):\n", + " return 1/(1 + np.exp(-x))\n", + "\n", + "def feed_forward(X):\n", + " # weighted sum of inputs to the hidden layer\n", + " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", + " # activation in the hidden layer\n", + " a_h = sigmoid(z_h)\n", + " \n", + " # weighted sum of inputs to the output layer\n", + " z_o = np.matmul(a_h, output_weights) + output_bias\n", + " # softmax output\n", + " # axis 0 holds each input and axis 1 the probabilities of each category\n", + " exp_term = np.exp(z_o)\n", + " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + " \n", + " return probabilities\n", + "\n", + "probabilities = feed_forward(X_train)\n", + "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", + "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", + "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", + "print()\n", + "\n", + "# we obtain a prediction by taking the class with the highest likelihood\n", + "def predict(X):\n", + " probabilities = feed_forward(X)\n", + " return np.argmax(probabilities, axis=1)\n", + "\n", + "predictions = predict(X_train)\n", + "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", + "print(\"prediction for image 0: \" + str(predictions[0]))\n", + "print(\"correct label for image 0: \" + str(Y_train[0]))" + ] + }, + { + "cell_type": "markdown", + "id": "aa73fc1e", + "metadata": {}, + "source": [ + "## Choose cost function and optimizer\n", + "\n", + "To measure how well our neural network is doing we need to introduce a cost function. \n", + "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", + "that gives the total error of our network across all samples the *cost* function.\n", + "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", + "\n", + "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", + "\n", + "$$ y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", + "\n", + "$$ y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", + "\n", + "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", + "\n", + "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", + "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\boldsymbol{x}_i$ in the dataset.\n", + "\n", + "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", + "probability of the correct category $c'$ \n", + "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", + "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\boldsymbol{\\theta}$ represents the parameters of our network, i.e. all the weights and biases." + ] + }, + { + "cell_type": "markdown", + "id": "74081e44", + "metadata": {}, + "source": [ + "## Optimizing the cost function\n", + "\n", + "The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent\n", + "is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. \n", + "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", + "\n", + "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", + "\n", + "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", + "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", + "\n", + "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", + "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", + "on a subset of the data called a *minibatch*. \n", + "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", + "is $N/M$. \n", + "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", + "\n", + "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", + "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", + "\n", + "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", + "\n", + "This has two important benefits: \n", + "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", + "\n", + "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", + "\n", + "The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html)." + ] + }, + { + "cell_type": "markdown", + "id": "1e1c4fe3", + "metadata": {}, + "source": [ + "## Regularization\n", + "\n", + "It is common to add an extra term to the cost function, proportional\n", + "to the size of the weights. This is equivalent to constraining the\n", + "size of the weights, so that they do not grow out of control.\n", + "Constraining the size of the weights means that the weights cannot\n", + "grow arbitrarily large to fit the training data, and in this way\n", + "reduces *overfitting*.\n", + "\n", + "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", + "\n", + "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", + "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\boldsymbol{w} \\rvert \\rvert_2^2 \n", + "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", + "\n", + "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", + "\n", + "In order to train the model, we need to calculate the derivative of\n", + "the cost function with respect to every bias and weight in the\n", + "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", + "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", + "layer ($+1$ for the bias), and the gradient must be calculated for\n", + "every parameter. We use the *backpropagation* algorithm discussed\n", + "above. This is a clever use of the chain rule that allows us to\n", + "calculate the gradient efficently." + ] + }, + { + "cell_type": "markdown", + "id": "6f66a9ad", + "metadata": {}, + "source": [ + "## Matrix multiplication\n", + "\n", + "To more efficently train our network these equations are implemented using matrix operations. \n", + "The error in the output layer is calculated simply as, with $\\boldsymbol{t}$ being our targets, \n", + "\n", + "$$ \\delta_L = \\boldsymbol{t} - \\boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ \n", + "\n", + "The gradient for the output weights is calculated as \n", + "\n", + "$$ \\nabla W_{L} = \\boldsymbol{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", + "\n", + "where $\\boldsymbol{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", + "Since we are going backwards we have to transpose the activation matrix. \n", + "\n", + "The gradient with respect to the output bias is then \n", + "\n", + "$$ \\nabla \\boldsymbol{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", + "\n", + "The error in the hidden layer is \n", + "\n", + "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", + "\n", + "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", + "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", + "the *Hadamard product*, meaning element-wise multiplication. \n", + "\n", + "This again gives us the gradients in the hidden layer: \n", + "\n", + "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", + "\n", + "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "b4ba72fe", + "metadata": {}, + "outputs": [], + "source": [ + "# to categorical turns our integer vector into a onehot representation\n", + "from sklearn.metrics import accuracy_score\n", + "\n", + "# one-hot in numpy\n", + "def to_categorical_numpy(integer_vector):\n", + " n_inputs = len(integer_vector)\n", + " n_categories = np.max(integer_vector) + 1\n", + " onehot_vector = np.zeros((n_inputs, n_categories))\n", + " onehot_vector[range(n_inputs), integer_vector] = 1\n", + " \n", + " return onehot_vector\n", + "\n", + "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", + "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", + "\n", + "def feed_forward_train(X):\n", + " # weighted sum of inputs to the hidden layer\n", + " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", + " # activation in the hidden layer\n", + " a_h = sigmoid(z_h)\n", + " \n", + " # weighted sum of inputs to the output layer\n", + " z_o = np.matmul(a_h, output_weights) + output_bias\n", + " # softmax output\n", + " # axis 0 holds each input and axis 1 the probabilities of each category\n", + " exp_term = np.exp(z_o)\n", + " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + " \n", + " # for backpropagation need activations in hidden and output layers\n", + " return a_h, probabilities\n", + "\n", + "def backpropagation(X, Y):\n", + " a_h, probabilities = feed_forward_train(X)\n", + " \n", + " # error in the output layer\n", + " error_output = probabilities - Y\n", + " # error in the hidden layer\n", + " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", + " \n", + " # gradients for the output layer\n", + " output_weights_gradient = np.matmul(a_h.T, error_output)\n", + " output_bias_gradient = np.sum(error_output, axis=0)\n", + " \n", + " # gradient for the hidden layer\n", + " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", + " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", + "\n", + " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", + "\n", + "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", + "\n", + "eta = 0.01\n", + "lmbd = 0.01\n", + "for i in range(1000):\n", + " # calculate gradients\n", + " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", + " \n", + " # regularization term gradients\n", + " dWo += lmbd * output_weights\n", + " dWh += lmbd * hidden_weights\n", + " \n", + " # update weights and biases\n", + " output_weights -= eta * dWo\n", + " output_bias -= eta * dBo\n", + " hidden_weights -= eta * dWh\n", + " hidden_bias -= eta * dBh\n", + "\n", + "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" + ] + }, + { + "cell_type": "markdown", + "id": "1bf824b2", + "metadata": {}, + "source": [ + "## Improving performance\n", + "\n", + "As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. \n", + "In order to obtain a network that does something useful, we will have to do a bit more work. \n", + "\n", + "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", + "\n", + "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", + "going through the entire dataset ($n/M$ batches) an *epoch*.\n", + "\n", + "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", + "Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/)." + ] + }, + { + "cell_type": "markdown", + "id": "c98cec8d", + "metadata": {}, + "source": [ + "## Full object-oriented implementation\n", + "\n", + "It is very natural to think of the network as an object, with specific instances of the network\n", + "being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "26d4691e", + "metadata": {}, + "outputs": [], + "source": [ + "class NeuralNetwork:\n", + " def __init__(\n", + " self,\n", + " X_data,\n", + " Y_data,\n", + " n_hidden_neurons=50,\n", + " n_categories=10,\n", + " epochs=10,\n", + " batch_size=100,\n", + " eta=0.1,\n", + " lmbd=0.0):\n", + "\n", + " self.X_data_full = X_data\n", + " self.Y_data_full = Y_data\n", + "\n", + " self.n_inputs = X_data.shape[0]\n", + " self.n_features = X_data.shape[1]\n", + " self.n_hidden_neurons = n_hidden_neurons\n", + " self.n_categories = n_categories\n", + "\n", + " self.epochs = epochs\n", + " self.batch_size = batch_size\n", + " self.iterations = self.n_inputs // self.batch_size\n", + " self.eta = eta\n", + " self.lmbd = lmbd\n", + "\n", + " self.create_biases_and_weights()\n", + "\n", + " def create_biases_and_weights(self):\n", + " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", + " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", + "\n", + " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", + " self.output_bias = np.zeros(self.n_categories) + 0.01\n", + "\n", + " def feed_forward(self):\n", + " # feed-forward for training\n", + " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", + " self.a_h = sigmoid(self.z_h)\n", + "\n", + " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", + "\n", + " exp_term = np.exp(self.z_o)\n", + " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + "\n", + " def feed_forward_out(self, X):\n", + " # feed-forward for output\n", + " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", + " a_h = sigmoid(z_h)\n", + "\n", + " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", + " \n", + " exp_term = np.exp(z_o)\n", + " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + " return probabilities\n", + "\n", + " def backpropagation(self):\n", + " error_output = self.probabilities - self.Y_data\n", + " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", + "\n", + " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", + " self.output_bias_gradient = np.sum(error_output, axis=0)\n", + "\n", + " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", + " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", + "\n", + " if self.lmbd > 0.0:\n", + " self.output_weights_gradient += self.lmbd * self.output_weights\n", + " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", + "\n", + " self.output_weights -= self.eta * self.output_weights_gradient\n", + " self.output_bias -= self.eta * self.output_bias_gradient\n", + " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", + " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", + "\n", + " def predict(self, X):\n", + " probabilities = self.feed_forward_out(X)\n", + " return np.argmax(probabilities, axis=1)\n", + "\n", + " def predict_probabilities(self, X):\n", + " probabilities = self.feed_forward_out(X)\n", + " return probabilities\n", + "\n", + " def train(self):\n", + " data_indices = np.arange(self.n_inputs)\n", + "\n", + " for i in range(self.epochs):\n", + " for j in range(self.iterations):\n", + " # pick datapoints with replacement\n", + " chosen_datapoints = np.random.choice(\n", + " data_indices, size=self.batch_size, replace=False\n", + " )\n", + "\n", + " # minibatch training data\n", + " self.X_data = self.X_data_full[chosen_datapoints]\n", + " self.Y_data = self.Y_data_full[chosen_datapoints]\n", + "\n", + " self.feed_forward()\n", + " self.backpropagation()" + ] + }, + { + "cell_type": "markdown", + "id": "24f75613", + "metadata": {}, + "source": [ + "## Evaluate model performance on test data\n", + "\n", + "To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. \n", + "We measure the performance of the network using the *accuracy* score. \n", + "The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. \n", + "\n", + "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\tilde{y}_i = y_i)}{n} ,$$ \n", + "\n", + "where $I$ is the indicator function, $1$ if $\\tilde{y}_i = y_i$ and $0$ otherwise." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "52a987ae", + "metadata": {}, + "outputs": [], + "source": [ + "epochs = 100\n", + "batch_size = 100\n", + "\n", + "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", + " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", + "dnn.train()\n", + "test_predict = dnn.predict(X_test)\n", + "\n", + "# accuracy score from scikit library\n", + "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", + "\n", + "# equivalent in numpy\n", + "def accuracy_score_numpy(Y_test, Y_pred):\n", + " return np.sum(Y_test == Y_pred) / len(Y_test)\n", + "\n", + "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" + ] + }, + { + "cell_type": "markdown", + "id": "1605eb14", + "metadata": {}, + "source": [ + "## Adjust hyperparameters\n", + "\n", + "We now perform a grid search to find the optimal hyperparameters for the network. \n", + "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "952131d2", + "metadata": {}, + "outputs": [], + "source": [ + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)\n", + "# store the models for later use\n", + "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + "\n", + "# grid search\n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", + " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", + " dnn.train()\n", + " \n", + " DNN_numpy[i][j] = dnn\n", + " \n", + " test_predict = dnn.predict(X_test)\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "id": "182a8a49", + "metadata": {}, + "source": [ + "## Visualization" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "d3d1b7d5", + "metadata": {}, + "outputs": [], + "source": [ + "# visual representation of grid search\n", + "# uses seaborn heatmap, you can also do this with matplotlib imshow\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", + " dnn = DNN_numpy[i][j]\n", + " \n", + " train_pred = dnn.predict(X_train) \n", + " test_pred = dnn.predict(X_test)\n", + "\n", + " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", + " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\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": "aa705900", + "metadata": {}, + "source": [ + "## scikit-learn implementation\n", + "\n", + "**scikit-learn** focuses more\n", + "on traditional machine learning methods, such as regression,\n", + "clustering, decision trees, etc. As such, it has only two types of\n", + "neural networks: Multi Layer Perceptron outputting continuous values,\n", + "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", + "*MLPClassifier*. We will see how simple it is to use these classes.\n", + "\n", + "**scikit-learn** implements a few improvements from our neural network,\n", + "such as early stopping, a varying learning rate, different\n", + "optimization methods, etc. We would therefore expect a better\n", + "performance overall." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "09c32314", + "metadata": {}, + "outputs": [], + "source": [ + "from sklearn.neural_network import MLPClassifier\n", + "# store models for later use\n", + "DNN_scikit = 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", + " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", + " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", + " dnn.fit(X_train, Y_train)\n", + " \n", + " DNN_scikit[i][j] = dnn\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "id": "fde4721e", + "metadata": {}, + "source": [ + "## Visualization" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "e855729e", + "metadata": {}, + "outputs": [], + "source": [ + "# optional\n", + "# 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", + " dnn = DNN_scikit[i][j]\n", + " \n", + " train_pred = dnn.predict(X_train) \n", + " test_pred = dnn.predict(X_test)\n", + "\n", + " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", + " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\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": "765ac227", + "metadata": {}, + "source": [ + "## Testing our code for the XOR, OR and AND gates\n", + "\n", + "Last week we discussed three different types of gates, the so-called\n", + "XOR, the OR and the AND gates. Their inputs and outputs can be\n", + "summarized using the following tables, first for the OR gate with\n", + "inputs $x_1$ and $x_2$ and outputs $y$:\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 1
" + ] + }, + { + "cell_type": "markdown", + "id": "02d395cd", + "metadata": {}, + "source": [ + "## The AND and XOR Gates\n", + "\n", + "The AND gate is defined as\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
$x_1$ $x_2$ $y$
0 0 0
0 1 0
1 0 0
1 1 1
\n", + "\n", + "And finally we have the XOR gate\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 0
" + ] + }, + { + "cell_type": "markdown", + "id": "0fba1e7d", + "metadata": {}, + "source": [ + "## Representing the Data Sets\n", + "\n", + "Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads" + ] + }, + { + "cell_type": "markdown", + "id": "9a3c4e68", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", + " 0 & 1 \\\\\n", + "\t\t 1 & 0 \\\\\n", + "\t\t 1 & 1 \\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "545fccde", + "metadata": {}, + "source": [ + "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate." + ] + }, + { + "cell_type": "markdown", + "id": "678395d0", + "metadata": {}, + "source": [ + "## Setting up the Neural Network\n", + "\n", + "We define first our design matrix and the various output vectors for the different gates." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "7c64daef", + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"\n", + "Simple code that tests XOR, OR and AND gates with linear regression\n", + "\"\"\"\n", + "\n", + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn import datasets\n", + "\n", + "def sigmoid(x):\n", + " return 1/(1 + np.exp(-x))\n", + "\n", + "def feed_forward(X):\n", + " # weighted sum of inputs to the hidden layer\n", + " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", + " # activation in the hidden layer\n", + " a_h = sigmoid(z_h)\n", + " \n", + " # weighted sum of inputs to the output layer\n", + " z_o = np.matmul(a_h, output_weights) + output_bias\n", + " # softmax output\n", + " # axis 0 holds each input and axis 1 the probabilities of each category\n", + " probabilities = sigmoid(z_o)\n", + " return probabilities\n", + "\n", + "# we obtain a prediction by taking the class with the highest likelihood\n", + "def predict(X):\n", + " probabilities = feed_forward(X)\n", + " return np.argmax(probabilities, axis=1)\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# Design matrix\n", + "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", + "\n", + "# The XOR gate\n", + "yXOR = np.array( [ 0, 1 ,1, 0])\n", + "# The OR gate\n", + "yOR = np.array( [ 0, 1 ,1, 1])\n", + "# The AND gate\n", + "yAND = np.array( [ 0, 0 ,0, 1])\n", + "\n", + "# Defining the neural network\n", + "n_inputs, n_features = X.shape\n", + "n_hidden_neurons = 2\n", + "n_categories = 2\n", + "n_features = 2\n", + "\n", + "# we make the weights normally distributed using numpy.random.randn\n", + "\n", + "# weights and bias in the hidden layer\n", + "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", + "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", + "\n", + "# weights and bias in the output layer\n", + "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", + "output_bias = np.zeros(n_categories) + 0.01\n", + "\n", + "probabilities = feed_forward(X)\n", + "print(probabilities)\n", + "\n", + "\n", + "predictions = predict(X)\n", + "print(predictions)" + ] + }, + { + "cell_type": "markdown", + "id": "c35ff8f2", + "metadata": {}, + "source": [ + "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." + ] + }, + { + "cell_type": "markdown", + "id": "3b5396c0", + "metadata": {}, + "source": [ + "## The Code using Scikit-Learn" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "3d4e508b", + "metadata": {}, + "outputs": [], + "source": [ + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.neural_network import MLPClassifier\n", + "from sklearn.metrics import accuracy_score\n", + "import seaborn as sns\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# Design matrix\n", + "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", + "\n", + "# The XOR gate\n", + "yXOR = np.array( [ 0, 1 ,1, 0])\n", + "# The OR gate\n", + "yOR = np.array( [ 0, 1 ,1, 1])\n", + "# The AND gate\n", + "yAND = np.array( [ 0, 0 ,0, 1])\n", + "\n", + "# Defining the neural network\n", + "n_inputs, n_features = X.shape\n", + "n_hidden_neurons = 2\n", + "n_categories = 2\n", + "n_features = 2\n", + "\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)\n", + "# store models for later use\n", + "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + "epochs = 100\n", + "\n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", + " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", + " dnn.fit(X, yXOR)\n", + " DNN_scikit[i][j] = dnn\n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Accuracy score on data set: \", dnn.score(X, yXOR))\n", + " print()\n", + "\n", + "sns.set()\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " dnn = DNN_scikit[i][j]\n", + " test_pred = dnn.predict(X)\n", + " test_accuracy[i][j] = accuracy_score(yXOR, test_pred)\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()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.10" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/LectureNotes/.ipynb_checkpoints/week44-checkpoint.ipynb b/doc/LectureNotes/.ipynb_checkpoints/week44-checkpoint.ipynb new file mode 100644 index 000000000..b188679e4 --- /dev/null +++ b/doc/LectureNotes/.ipynb_checkpoints/week44-checkpoint.ipynb @@ -0,0 +1,5410 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "ba617ce1", + "metadata": {}, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "0aef8b39", + "metadata": {}, + "source": [ + "# Week 44, Convolutional Neural Networks (CNN)\n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **October 30-November 3**" + ] + }, + { + "cell_type": "markdown", + "id": "963a2f0d", + "metadata": {}, + "source": [ + "## Plan for week 44\n", + "\n", + "**Material for the active learning sessions on Tuesday and Wednesday.**\n", + "\n", + " * Exercise on writing your own neural network code, application to the OR and XOR gates, see notes from last week\n", + "\n", + " * The exercise this week is a continuation from last week\n", + "\n", + " * Discussion of project 2\n", + "\n", + " * [Video of lab session from last week](https://youtu.be/Ia6wwDLxqtM)\n", + "\n", + " \n", + "\n", + "**Material for the lecture on Thursday November 2, 2023.**\n", + "\n", + " * Convolutional Neural Networks\n", + "\n", + " * Readings and Videos:\n", + "\n", + " * These lecture notes\n", + "\n", + " * For a more in depth discussion on neural networks we recommend Goodfellow et al chapter 9. See also chapter 11 and 12 on practicalities and applications \n", + "\n", + " * Reading suggestions for implementation of CNNs: [Aurelien Geron's chapter 13](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf). \n", + "\n", + " * [Video on Deep Learning](https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi)\n", + "\n", + " * [Video on Convolutional Neural Networks from MIT](https://www.youtube.com/watch?v=iaSUYvmCekI&ab_channel=AlexanderAmini)\n", + "\n", + " * [Video on CNNs from Stanford](https://www.youtube.com/watch?v=bNb2fEVKeEo&list=PLC1qU-LWwrF64f4QKQT-Vg5Wr4qEE1Zxk&index=6&ab_channel=StanfordUniversitySchoolofEngineering)\n", + "\n", + "**And Lecture material on CNNs.**\n", + "\n", + "* [See Michael Nielsen's Lectures](http://neuralnetworksanddeeplearning.com/chap6.html)" + ] + }, + { + "cell_type": "markdown", + "id": "55d065ae", + "metadata": {}, + "source": [ + "## Material for Lecture Thursday November 2" + ] + }, + { + "cell_type": "markdown", + "id": "59207a59", + "metadata": {}, + "source": [ + "## Convolutional Neural Networks (recognizing images)\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)." + ] + }, + { + "cell_type": "markdown", + "id": "5dbf2651", + "metadata": {}, + "source": [ + "## What is the Difference\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.**" + ] + }, + { + "cell_type": "markdown", + "id": "805d6ec9", + "metadata": {}, + "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." + ] + }, + { + "cell_type": "markdown", + "id": "040f7963", + "metadata": {}, + "source": [ + "## Why CNNS for images, sound files, medical images from CT scans etc?\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)." + ] + }, + { + "cell_type": "markdown", + "id": "0b2761a4", + "metadata": {}, + "source": [ + "## Regular NNs don’t scale well to full images\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", + "" + ] + }, + { + "cell_type": "markdown", + "id": "148c281c", + "metadata": {}, + "source": [ + "## 3D volumes of neurons\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": "a8cd3791", + "metadata": {}, + "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." + ] + }, + { + "cell_type": "markdown", + "id": "dbfdb1bb", + "metadata": {}, + "source": [ + "## Transforming images\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." + ] + }, + { + "cell_type": "markdown", + "id": "ef624344", + "metadata": {}, + "source": [ + "## CNNs in brief\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", + "For more material on convolutional networks, we strongly recommend\n", + "the course\n", + "[CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n", + "\n", + "The textbook by Goodfellow et al, see chapter 9 contains an in depth discussion as well." + ] + }, + { + "cell_type": "markdown", + "id": "222c06f9", + "metadata": {}, + "source": [ + "## Key Idea\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": "a16255ff", + "metadata": {}, + "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 mathematical 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": "8e7516b9", + "metadata": {}, + "source": [ + "$$\n", + "y(t) = \\int x(a) w(t-a) da,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9e141e69", + "metadata": {}, + "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": "3b5e0f3e", + "metadata": {}, + "source": [ + "$$\n", + "y(t) = \\left(x * w\\right)(t).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "94239c1e", + "metadata": {}, + "source": [ + "The discretized version reads" + ] + }, + { + "cell_type": "markdown", + "id": "4c025970", + "metadata": {}, + "source": [ + "$$\n", + "y(t) = \\sum_{a=-\\infty}^{a=\\infty}x(a)w(t-a).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f957e92b", + "metadata": {}, + "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": "c1c2091a", + "metadata": {}, + "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": "4d4c8d1a", + "metadata": {}, + "source": [ + "$$\n", + "p(t) = \\alpha_0+\\alpha_1 t+\\alpha_2 t^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "05c9d6b9", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "97f48245", + "metadata": {}, + "source": [ + "$$\n", + "s(t) = \\beta_0+\\beta_1 t+\\beta_2 t^2+\\beta_3 t^3.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5166255e", + "metadata": {}, + "source": [ + "The polynomial multiplication gives us a new polynomial of degree $5$" + ] + }, + { + "cell_type": "markdown", + "id": "295382a6", + "metadata": {}, + "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": "5eaf190d", + "metadata": {}, + "source": [ + "## Efficient Polynomial Multiplication\n", + "\n", + "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": "0f92301f", + "metadata": {}, + "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": "0199fc42", + "metadata": {}, + "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": "3b34d0b1", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j = \\sum_{i=-\\infty}^{i=\\infty}\\alpha_i\\beta_{j-i}=(\\alpha * \\beta)_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4796ab01", + "metadata": {}, + "source": [ + "or as a double sum with restriction $l=i+j$" + ] + }, + { + "cell_type": "markdown", + "id": "b2d1bf1d", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_l = \\sum_{ij}\\alpha_i\\beta_{j}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0aa6a56e", + "metadata": {}, + "source": [ + "Do you see a potential drawback with these equations?" + ] + }, + { + "cell_type": "markdown", + "id": "b1063211", + "metadata": {}, + "source": [ + "## A more efficient way of coding the above Convolution\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": "65bff227", + "metadata": {}, + "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": "19c391a4", + "metadata": {}, + "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": "35aa0736", + "metadata": {}, + "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": "f30929d8", + "metadata": {}, + "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?\n", + "\n", + "The above matrices are examples of so-called [Toeplitz\n", + "matrices](https://link.springer.com/book/10.1007/978-93-86279-04-0). A\n", + "Toeplitz matrix is a matrix in which each descending diagonal from\n", + "left to right is constant. For instance the last matrix, which we\n", + "rewrite as" + ] + }, + { + "cell_type": "markdown", + "id": "b92c89bf", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{A}=\\begin{bmatrix}a_0 & 0 & 0 \\\\\n", + " a_1 & a_0 & 0 \\\\\n", + "\t\t\t a_2 & a_1 & a_0 \\\\\n", + "\t\t\t a_3 & a_2 & a_1 \\\\\n", + "\t\t\t 0 & a_3 & a_2 \\\\\n", + "\t\t\t 0 & 0 & a_3\n", + "\t\t\t \\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "58677db5", + "metadata": {}, + "source": [ + "with elements $a_{ii}=a_{i+1,j+1}=a_{i-j}$ is an example of a Toeplitz\n", + "matrix. Such a matrix does not need to be a square matrix. Toeplitz\n", + "matrices are also closely connected with Fourier series discussed\n", + "below, because the multiplication operator by a trigonometric\n", + "polynomial, compressed to a finite-dimensional space, can be\n", + "represented by such a matrix. The example above shows that we can\n", + "represent linear convolution as multiplication of a Toeplitz matrix by\n", + "a vector." + ] + }, + { + "cell_type": "markdown", + "id": "51de5ea3", + "metadata": {}, + "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": "8fa65373", + "metadata": {}, + "source": [ + "$$\n", + "m\\frac{d^2x}{dt^2}+\\eta\\frac{dx}{dt}+x(t)=F(t),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ca8f7fbb", + "metadata": {}, + "source": [ + "where $F(t)$ is an applied external force acting on the system (often\n", + "called a driving force), one can use the theory of Fourier\n", + "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 $x_{pn}(t)$ to the above differential equation for each $F_n$. The particular\n", + "solution for the entire driving force is then given by a series like" + ] + }, + { + "cell_type": "markdown", + "id": "d8afff8f", + "metadata": {}, + "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": "cfe7c6cb", + "metadata": {}, + "source": [ + "This is known as the principle of superposition. It only applies when\n", + "the homogenous equation is linear. \n", + "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 $t$ our function repeats itself periodically after a period $\\tau$, that is" + ] + }, + { + "cell_type": "markdown", + "id": "e4cb68fd", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{eqnarray}\n", + "F(t+\\tau)=F(t). \n", + "\\end{eqnarray}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9668712e", + "metadata": {}, + "source": [ + "One example of a non-sinusoidal periodic force is a square wave. Many\n", + "components in electric circuits are non-linear, for example diodes. This \n", + "makes many wave forms non-sinusoidal even when the circuits are being\n", + "driven by purely sinusoidal sources." + ] + }, + { + "cell_type": "markdown", + "id": "a47455dc", + "metadata": {}, + "source": [ + "## Simple Code Example\n", + "\n", + "The code here shows a typical example of such a square wave generated\n", + "using the functionality included in the **scipy** Python package. We\n", + "have used a period of $\\tau=0.2$." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "ea14d21d", + "metadata": {}, + "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": "d12e3c32", + "metadata": {}, + "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": "c4304af6", + "metadata": {}, + "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": "626f9f6d", + "metadata": {}, + "source": [ + "## Wrapping up Fourier transforms\n", + "\n", + "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": "2f563405", + "metadata": {}, + "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": "f99c330a", + "metadata": {}, + "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": "b240e4ec", + "metadata": {}, + "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": "905cc057", + "metadata": {}, + "source": [ + "## Finding the Coefficients\n", + "\n", + "Because the forces have been applied for a long time, any non-zero\n", + "damping eliminates the homogenous parts of the solution. We need then \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": "5841f5ce", + "metadata": {}, + "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": "03e7ed50", + "metadata": {}, + "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": "0397e306", + "metadata": {}, + "source": [ + "$$\n", + "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).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "fed2b29e", + "metadata": {}, + "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": "4db87a94", + "metadata": {}, + "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": "c34b0353", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "3cb68d87", + "metadata": {}, + "source": [ + "$$\n", + "f_n=\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~f_n/2=f_n.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "09cc733e", + "metadata": {}, + "source": [ + "The same method can be used to check for the consistency of $g_n$." + ] + }, + { + "cell_type": "markdown", + "id": "14d8af81", + "metadata": {}, + "source": [ + "## Final words on Fourier Transforms\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": "99fc76a1", + "metadata": {}, + "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": "1340474e", + "metadata": {}, + "source": [ + "### Fourier transforms and convolution\n", + "\n", + "We can use Fourier transforms in our studies of convolution as well. To see this, assume we have two functions $f$ and $g$ and their corresponding Fourier transforms $\\hat{f}$ and $\\hat{g}$. We remind the reader that the Fourier transform reads (say for the function $f$)" + ] + }, + { + "cell_type": "markdown", + "id": "5b1c005a", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{f}(y)=\\boldsymbol{F}[f(y)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{-i\\omega y} f(\\omega),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0ca09d82", + "metadata": {}, + "source": [ + "and similarly we have" + ] + }, + { + "cell_type": "markdown", + "id": "d49b6997", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{g}(y)=\\boldsymbol{F}[g(y)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{-i\\omega y} g(\\omega).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "75795dd4", + "metadata": {}, + "source": [ + "The inverse Fourier transform is given by" + ] + }, + { + "cell_type": "markdown", + "id": "bc49fd47", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{F}^{-1}[g(y)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{i\\omega y} g(\\omega).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ff256a0d", + "metadata": {}, + "source": [ + "The inverse Fourier transform of the product of the two functions $\\hat{f}\\hat{g}$ can be written as" + ] + }, + { + "cell_type": "markdown", + "id": "a334082e", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{F}^{-1}[(\\hat{f}\\hat{g})(x)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{i\\omega x} \\hat{f}(\\omega)\\hat{g}(\\omega).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "35b63bfc", + "metadata": {}, + "source": [ + "We can rewrite the latter as" + ] + }, + { + "cell_type": "markdown", + "id": "ea83e607", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{F}^{-1}[(\\hat{f}\\hat{g})(x)]=\\int_{-\\infty}^{\\infty} d\\omega \\exp{i\\omega x} \\hat{f}(\\omega)\\left[\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}g(y)dy \\exp{-i\\omega y}\\right]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}dy g(y)\\int_{-\\infty}^{\\infty} d\\omega \\hat{f}(\\omega) \\exp{i\\omega(x- y)},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "835bdbbd", + "metadata": {}, + "source": [ + "which is simply" + ] + }, + { + "cell_type": "markdown", + "id": "79d2b70c", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{F}^{-1}[(\\hat{f}\\hat{g})(x)]=\\int_{-\\infty}^{\\infty}dy g(y)f(x-y)=(f*g)(x),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "25fc980c", + "metadata": {}, + "source": [ + "the convolution of the functions $f$ and $g$." + ] + }, + { + "cell_type": "markdown", + "id": "9d47efce", + "metadata": {}, + "source": [ + "## Two-dimensional Objects\n", + "\n", + "We are now ready to start studying the discrete convolutions relevant for convolutional neural networks.\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": "b96e8fa0", + "metadata": {}, + "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": "90817709", + "metadata": {}, + "source": [ + "Convolution is a commutatitave process, which means we can rewrite this equation as" + ] + }, + { + "cell_type": "markdown", + "id": "ef889e3f", + "metadata": {}, + "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": "ad86a022", + "metadata": {}, + "source": [ + "Normally the latter is more straightforward to implement in a machine larning 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 (although it is referred to s convolution)" + ] + }, + { + "cell_type": "markdown", + "id": "379561b4", + "metadata": {}, + "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": "0c7b6540", + "metadata": {}, + "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": "47d923f0", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \\approx 10^{10},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f51762c0", + "metadata": {}, + "source": [ + "that is ten billion parameters to determine." + ] + }, + { + "cell_type": "markdown", + "id": "e9f8618d", + "metadata": {}, + "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": "14066a55", + "metadata": {}, + "source": [ + "## CNNs in more detail\n", + "\n", + "Let assume we have an input matrix $I$ of dimensionality $3\\times 3$\n", + "and a $2\\times 2$ filter $W$ given by the following matrices" + ] + }, + { + "cell_type": "markdown", + "id": "9cc57063", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{I}=\\begin{bmatrix}i_{00} & i_{01} & i_{02} \\\\\n", + " i_{10} & i_{11} & i_{12} \\\\\n", + "\t i_{20} & i_{21} & i_{22} \\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "40d9c084", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "814a3e68", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{W}=\\begin{bmatrix}w_{00} & w_{01} \\\\\n", + "\t w_{10} & w_{11}\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3014dcb3", + "metadata": {}, + "source": [ + "We introduce now the hyperparameter $S$ **stride**. Stride represents how the filter $W$ moves the convolution process on the matrix $I$.\n", + "We strongly recommend the repository on [Arithmetic of deep learning by Dumoulin and Visin](https://github.com/vdumoulin/conv_arithmetic) \n", + "\n", + "Here we set the stride equal to $S=1$, which means that, starting with the element $i_{00}$, the filter will act on $2\\times 2$ submatrices each time, starting with the upper corner and moving according to the stride value column by column. \n", + "\n", + "Here we perform the operation" + ] + }, + { + "cell_type": "markdown", + "id": "47a57310", + "metadata": {}, + "source": [ + "$$\n", + "S_(i,j)=(I * W)(i,j) = \\sum_m\\sum_n I(i-m,j-n)W(m,n),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "780c3b94", + "metadata": {}, + "source": [ + "and obtain" + ] + }, + { + "cell_type": "markdown", + "id": "6ad3ca13", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{S}=\\begin{bmatrix}i_{00}w_{00}+i_{01}w_{01}+i_{10}w_{10}+i_{11}w_{11} & i_{01}w_{00}+i_{02}w_{01}+i_{11}w_{10}+i_{12}w_{11} \\\\\n", + "\t i_{10}w_{00}+i_{11}w_{01}+i_{20}w_{10}+i_{21}w_{11} & i_{11}w_{00}+i_{12}w_{01}+i_{21}w_{10}+i_{22}w_{11}\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "cf2dec6f", + "metadata": {}, + "source": [ + "We can rewrite this operation in terms of a matrix-vector multiplication by defining a new vector where we flatten out the inputs as a vector $\\boldsymbol{I}'$ of length $9$ and\n", + "a matrix $\\boldsymbol{W}'$ with dimension $4\\times 9$ as" + ] + }, + { + "cell_type": "markdown", + "id": "f6b654b4", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{I}'=\\begin{bmatrix}i_{00} \\\\ i_{01} \\\\ i_{02} \\\\ i_{10} \\\\ i_{11} \\\\ i_{12} \\\\ i_{20} \\\\ i_{21} \\\\ i_{22} \\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "54b5f04e", + "metadata": {}, + "source": [ + "and the new matrix" + ] + }, + { + "cell_type": "markdown", + "id": "053dd929", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{W}'=\\begin{bmatrix} w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 & 0 & 0 & 0 \\\\\n", + " 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 & 0 & 0 \\\\\n", + "\t\t\t0 & 0 & 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 \\\\\n", + " 0 & 0 & 0 & 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11}\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "8afc19f4", + "metadata": {}, + "source": [ + "We see easily that performing the matrix-vector multiplication $\\boldsymbol{W}'\\boldsymbol{I}'$ is the same as the above convolution with stride $S=1$, that is" + ] + }, + { + "cell_type": "markdown", + "id": "e8f84c8a", + "metadata": {}, + "source": [ + "$$\n", + "S=(\\boldsymbol{W}*\\boldsymbol{I}),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1c04d062", + "metadata": {}, + "source": [ + "is now given by $\\boldsymbol{W}'\\boldsymbol{I}'$ which is a vector of length $4$ instead of the originally resulting $2\\times 2$ output matrix.\n", + "\n", + "The collection of kernels/filters $W$ defining a discrete convolution has a shape\n", + "corresponding to some permutation of $(n, m, k_1, \\ldots, k_N)$, where" + ] + }, + { + "cell_type": "markdown", + "id": "2c10c4d1", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{split}\n", + " n &\\equiv \\text{number of output feature maps},\\\\\n", + " m &\\equiv \\text{number of input feature maps},\\\\\n", + " k_j &\\equiv \\text{kernel size along axis $j$}.\n", + "\\end{split}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "edf2c021", + "metadata": {}, + "source": [ + "The following properties affect the output size $o_j$ of a convolutional layer\n", + "along axis $j$:\n", + "\n", + "1. $i_j$: input size along axis $j$,\n", + "\n", + "2. $k_j$: kernel/filter size along axis $j$,\n", + "\n", + "3. stride (distance between two consecutive positions of the kernel/filter) along axis $j$,\n", + "\n", + "4. zero padding (number of zeros concatenated at the beginning and at the end of an axis) along axis $j$.\n", + "\n", + "For instance, the above examples shows a $2\\times 2$ kernel/filter $\\boldsymbol{W}$ applied to a $3 \\times 3$ input padded with a $0 \\times 0$\n", + "border of zeros using $1 \\times 1$ strides.\n", + "\n", + "Note that strides constitute a form of **subsampling**. As an alternative to\n", + "being interpreted as a measure of how much the kernel/filter is translated, strides\n", + "can also be viewed as how much of the output is retained. For instance, moving\n", + "the kernel by hops of two is equivalent to moving the kernel by hops of one but\n", + "retaining only odd output elements." + ] + }, + { + "cell_type": "markdown", + "id": "5956ab9e", + "metadata": {}, + "source": [ + "## Pooling\n", + "\n", + "In addition to discrete convolutions themselves, {\\em pooling\\/} operations\n", + "make up another important building block in CNNs. Pooling operations reduce\n", + "the size of feature maps by using some function to summarize subregions, such\n", + "as taking the average or the maximum value.\n", + "\n", + "Pooling works by sliding a window across the input and feeding the content of\n", + "the window to a {\\em pooling function}. In some sense, pooling works very much\n", + "like a discrete convolution, but replaces the linear combination described by\n", + "the kernel with some other function. Poolin\n", + "provides an example for average pooling, and \n", + "does the same for max pooling.\n", + "\n", + "The following properties affect the output size $o_j$ of a pooling layer\n", + "along axis $j$:\n", + "\n", + "1. $i_j$: input size along axis $j$,\n", + "\n", + "2. $k_j$: pooling window size along axis $j$,\n", + "\n", + "3. $s_j$: stride (distance between two consecutive positions of the pooling window) along axis $j$.\n", + "\n", + "The analysis of the relationship between convolutional layer properties is eased\n", + "by the fact that they don't interact across axes, i.e., the choice of kernel\n", + "size, stride and zero padding along axis $j$ only affects the output size of\n", + "axis $j$. Because of that, we will focus on the following simplified\n", + "setting:\n", + "\n", + "1. 2-D discrete convolutions ($N = 2$),\n", + "\n", + "2. square inputs ($i_1 = i_2 = i$),\n", + "\n", + "3. square kernel size ($k_1 = k_2 = k$),\n", + "\n", + "4. same strides along both axes ($s_1 = s_2 = s$),\n", + "\n", + "5. same zero padding along both axes ($p_1 = p_2 = p$).\n", + "\n", + "This facilitates the analysis and the visualization, but keep in mind that the\n", + "results outlined here also generalize to the N-D and non-square cases." + ] + }, + { + "cell_type": "markdown", + "id": "1291dcfc", + "metadata": {}, + "source": [ + "## No zero padding, unit strides\n", + "\n", + "The simplest case to analyze is when the kernel just slides across every\n", + "position of the input (i.e., $s = 1$ and $p = 0$).\n", + "\n", + "For any $i$ and $k$, and for $s = 1$ and $p = 0$," + ] + }, + { + "cell_type": "markdown", + "id": "36403adf", + "metadata": {}, + "source": [ + "$$\n", + "o = (i - k) + 1.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5baecc1a", + "metadata": {}, + "source": [ + "## Zero padding, unit strides\n", + "\n", + "To factor in zero padding (i.e., only restricting to $s = 1$), let's consider\n", + "its effect on the effective input size: padding with $p$ zeros changes the\n", + "effective input size from $i$ to $i + 2p$. In the general case, we can infer the following\n", + "relationship\n", + "\n", + "For any $i$, $k$ and $p$, and for $s = 1$," + ] + }, + { + "cell_type": "markdown", + "id": "5f87df6c", + "metadata": {}, + "source": [ + "$$\n", + "o = (i - k) + 2p + 1.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "cdaece55", + "metadata": {}, + "source": [ + "## Half (same) padding\n", + "\n", + "Having the output size be the same as the input size (i.e., $o = i$) can be a\n", + "desirable property:\n", + "\n", + "For any $i$ and for $k$ odd ($k = 2n + 1, \\quad n \\in \\mathbb{N}$), $s = 1$ and\n", + "$p = \\lfloor k / 2 \\rfloor = n$," + ] + }, + { + "cell_type": "markdown", + "id": "a126c99f", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{split}\n", + " o &= i + 2 \\lfloor k / 2 \\rfloor - (k - 1) \\\\\n", + " &= i + 2n - 2n \\\\\n", + " &= i.\n", + "\\end{split}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f0882225", + "metadata": {}, + "source": [ + "## Full padding\n", + "\n", + "While convolving a kernel generally decreases the output size with\n", + "respect to the input size, sometimes the opposite is required. This can be\n", + "achieved with proper zero padding:\n", + "\n", + "For any $i$ and $k$, and for $p = k - 1$ and $s = 1$," + ] + }, + { + "cell_type": "markdown", + "id": "ec5ea353", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{split}\n", + " o &= i + 2(k - 1) - (k - 1) \\\\\n", + " &= i + (k - 1).\n", + "\\end{split}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ff523888", + "metadata": {}, + "source": [ + "This is sometimes referred to as full padding, because in this\n", + "setting every possible partial or complete superimposition of the kernel on the\n", + "input feature map is taken into account." + ] + }, + { + "cell_type": "markdown", + "id": "7fc1dd60", + "metadata": {}, + "source": [ + "## Pooling arithmetic\n", + "\n", + "In a neural network, pooling layers provide invariance to small translations of\n", + "the input. The most common kind of pooling is **max pooling**, which\n", + "consists in splitting the input in (usually non-overlapping) patches and\n", + "outputting the maximum value of each patch. Other kinds of pooling exist, e.g.,\n", + "mean or average pooling, which all share the same idea of aggregating the input\n", + "locally by applying a non-linearity to the content of some patches.\n", + "\n", + "Since pooling does not involve\n", + "zero padding, the relationship describing the general case is as follows:\n", + "\n", + "For any $i$, $k$ and $s$," + ] + }, + { + "cell_type": "markdown", + "id": "3ef94f77", + "metadata": {}, + "source": [ + "$$\n", + "o = \\left\\lfloor \\frac{i - k}{s} \\right\\rfloor + 1.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "551b830f", + "metadata": {}, + "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)." + ] + }, + { + "cell_type": "markdown", + "id": "c9f41dea", + "metadata": {}, + "source": [ + "## Setting it up\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": "3d199bb5", + "metadata": {}, + "source": [ + "$$\n", + "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "92ec055c", + "metadata": {}, + "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." + ] + }, + { + "cell_type": "markdown", + "id": "eb0031a2", + "metadata": {}, + "source": [ + "## Strong correlations\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)." + ] + }, + { + "cell_type": "markdown", + "id": "c7ce376c", + "metadata": {}, + "source": [ + "## Layers of a CNN\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": "92c06244", + "metadata": {}, + "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": "48038c16", + "metadata": {}, + "source": [ + "## Prerequisites: Collect and pre-process data" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "69c8a363", + "metadata": {}, + "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": "markdown", + "id": "d2f311c1", + "metadata": {}, + "source": [ + "## Importing Keras and Tensorflow" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "42abafc8", + "metadata": {}, + "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": "markdown", + "id": "fbf5e9da", + "metadata": {}, + "source": [ + "## Running with Keras" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "40605ae2", + "metadata": {}, + "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": "markdown", + "id": "60a23dcf", + "metadata": {}, + "source": [ + "## Final part" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "032146fe", + "metadata": {}, + "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": "markdown", + "id": "51a2dbec", + "metadata": {}, + "source": [ + "## Final visualization" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "f5b791f0", + "metadata": {}, + "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": "7f997c83", + "metadata": {}, + "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": "0a1859fe", + "metadata": {}, + "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": "d21fdb8b", + "metadata": {}, + "source": [ + "## Verifying the data set\n", + "\n", + "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": "d873925c", + "metadata": {}, + "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": "4c1d4824", + "metadata": {}, + "source": [ + "## Set up the model\n", + "\n", + "The 6 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": "cf685009", + "metadata": {}, + "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": "8a6c0580", + "metadata": {}, + "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." + ] + }, + { + "cell_type": "markdown", + "id": "b2e5625a", + "metadata": {}, + "source": [ + "## Add Dense layers on top\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": "32424489", + "metadata": {}, + "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": "832d8c60", + "metadata": {}, + "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": "markdown", + "id": "b72ea4e9", + "metadata": {}, + "source": [ + "## Compile and train the model" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "ef7e9721", + "metadata": {}, + "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": "markdown", + "id": "2d93dc5e", + "metadata": {}, + "source": [ + "## Finally, evaluate the model" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "286d29cd", + "metadata": {}, + "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)" + ] + }, + { + "cell_type": "markdown", + "id": "8eaa01af", + "metadata": {}, + "source": [ + "## Building our own CNN code\n", + "\n", + "Here we present a flexible and readable python code for a CNN\n", + "implemented with NumPy. We will present the code, showcase how to use\n", + "the codebase and fit a CNN that yields a 99% accuracy on the 28x28\n", + "MNIST dataset within reasonable time.\n", + "\n", + "The CNN is compatible with all schedulers, cost functions and\n", + "activation functions discussed in constructing our neural network\n", + "codes.\n", + "\n", + " The CNN code consists of different types of Layer classes, including\n", + "Convolution2DLayer, Pooling2DLayer, FlattenLayer, FullyConnectedLayer\n", + "and OutputLayer, which can be added to the CNN object using the\n", + "interface of the CNN class. This allows you to easily construct your\n", + "own CNN, as well as allowing you to get used to an interface similar\n", + "to that of TensorFlow which is used for real world applications. \n", + "\n", + "Another important feature of this code is that it throws errors if\n", + "unreasonable decisions are made (for example using a kernel that is\n", + "larger than the image, not using a FlattenLayer, etc), and provides\n", + "the user with an informative error message." + ] + }, + { + "cell_type": "markdown", + "id": "b13efbbf", + "metadata": {}, + "source": [ + "### List of contents:\n", + "\n", + "1. Schedulers\n", + "\n", + "2. Activation Functions\n", + "\n", + "3. Cost Functions \n", + "\n", + "4. Convolution\n", + "\n", + "5. Layers\n", + "\n", + "6. CNN \n", + "\n", + "7. Some final remarks" + ] + }, + { + "cell_type": "markdown", + "id": "d4bf9acd", + "metadata": {}, + "source": [ + "### Schedulers\n", + "\n", + "The code below shows object oriented implementations of the Constant,\n", + "Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All\n", + "of the classes belong to the shared abstract Scheduler class, and\n", + "share the update_change() and reset() methods allowing for any of the\n", + "schedulers to be seamlessly used during the training stage, as will\n", + "later be shown in the fit() method of the neural\n", + "network. Update_change() only has one parameter, the gradient\n", + "($\\delta^{l}_{j}a^{l-1}_k$), and returns the change which will be\n", + "subtracted from the weights. The reset() function takes no parameters,\n", + "and resets the desired variables. For Constant and Momentum, reset\n", + "does nothing." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "731fe634", + "metadata": {}, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "\n", + "class Scheduler:\n", + " \"\"\"\n", + " Abstract class for Schedulers\n", + " \"\"\"\n", + "\n", + " def __init__(self, eta):\n", + " self.eta = eta\n", + "\n", + " # should be overwritten\n", + " def update_change(self, gradient):\n", + " raise NotImplementedError\n", + "\n", + " # overwritten if needed\n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Constant(Scheduler):\n", + " def __init__(self, eta):\n", + " super().__init__(eta)\n", + "\n", + " def update_change(self, gradient):\n", + " return self.eta * gradient\n", + " \n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Momentum(Scheduler):\n", + " def __init__(self, eta: float, momentum: float):\n", + " super().__init__(eta)\n", + " self.momentum = momentum\n", + " self.change = 0\n", + "\n", + " def update_change(self, gradient):\n", + " self.change = self.momentum * self.change + self.eta * gradient\n", + " return self.change\n", + "\n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Adagrad(Scheduler):\n", + " def __init__(self, eta):\n", + " super().__init__(eta)\n", + " self.G_t = None\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " if self.G_t is None:\n", + " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", + "\n", + " self.G_t += gradient @ gradient.T\n", + "\n", + " G_t_inverse = 1 / (\n", + " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", + " )\n", + " return self.eta * gradient * G_t_inverse\n", + "\n", + " def reset(self):\n", + " self.G_t = None\n", + "\n", + "\n", + "class AdagradMomentum(Scheduler):\n", + " def __init__(self, eta, momentum):\n", + " super().__init__(eta)\n", + " self.G_t = None\n", + " self.momentum = momentum\n", + " self.change = 0\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " if self.G_t is None:\n", + " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", + "\n", + " self.G_t += gradient @ gradient.T\n", + "\n", + " G_t_inverse = 1 / (\n", + " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", + " )\n", + " self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse\n", + " return self.change\n", + "\n", + " def reset(self):\n", + " self.G_t = None\n", + "\n", + "\n", + "class RMS_prop(Scheduler):\n", + " def __init__(self, eta, rho):\n", + " super().__init__(eta)\n", + " self.rho = rho\n", + " self.second = 0.0\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + " self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient\n", + " return self.eta * gradient / (np.sqrt(self.second + delta))\n", + "\n", + " def reset(self):\n", + " self.second = 0.0\n", + "\n", + "\n", + "class Adam(Scheduler):\n", + " def __init__(self, eta, rho, rho2):\n", + " super().__init__(eta)\n", + " self.rho = rho\n", + " self.rho2 = rho2\n", + " self.moment = 0\n", + " self.second = 0\n", + " self.n_epochs = 1\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " self.moment = self.rho * self.moment + (1 - self.rho) * gradient\n", + " self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient\n", + "\n", + " moment_corrected = self.moment / (1 - self.rho**self.n_epochs)\n", + " second_corrected = self.second / (1 - self.rho2**self.n_epochs)\n", + "\n", + " return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))\n", + "\n", + " def reset(self):\n", + " self.n_epochs += 1\n", + " self.moment = 0\n", + " self.second = 0" + ] + }, + { + "cell_type": "markdown", + "id": "51a4758d", + "metadata": {}, + "source": [ + "### Usage of schedulers\n", + "\n", + "To initalize a scheduler, simply create the object and pass in the necessary parameters such as the learning rate and the momentum as shown below. As the Scheduler class is an abstract class it should not called directly, and will raise an error upon usage." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "cbe83098", + "metadata": {}, + "outputs": [], + "source": [ + "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", + "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)" + ] + }, + { + "cell_type": "markdown", + "id": "c180fcec", + "metadata": {}, + "source": [ + "Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "5469f02b", + "metadata": {}, + "outputs": [], + "source": [ + "weights = np.ones((3,3))\n", + "print(f\"Before scheduler:\\n{weights=}\")\n", + "\n", + "epochs = 10\n", + "for e in range(epochs):\n", + " gradient = np.random.rand(3, 3)\n", + " change = adam_scheduler.update_change(gradient)\n", + " weights = weights - change\n", + " adam_scheduler.reset()\n", + "\n", + "print(f\"\\nAfter scheduler:\\n{weights=}\")" + ] + }, + { + "cell_type": "markdown", + "id": "87d59625", + "metadata": {}, + "source": [ + "### Cost functions\n", + "\n", + "In this section we will quickly look at cost functions that can be\n", + "used when creating the neural network. Every cost function takes the\n", + "target vector as its parameter, and returns a function valued only at\n", + "X such that it may easily be differentiated." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "dd9d99c0", + "metadata": {}, + "outputs": [], + "source": [ + "def CostOLS(target):\n", + " \"\"\"\n", + " Return OLS function valued only at X, so\n", + " that it may be easily differentiated\n", + " \"\"\"\n", + "\n", + " def func(X):\n", + " return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)\n", + "\n", + " return func\n", + "\n", + "\n", + "def CostLogReg(target):\n", + " \"\"\"\n", + " Return Logistic Regression cost function\n", + " valued only at X, so that it may be easily differentiated\n", + " \"\"\"\n", + "\n", + " def func(X):\n", + " return -(1.0 / target.shape[0]) * np.sum(\n", + " (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))\n", + " )\n", + "\n", + " return func\n", + "\n", + "\n", + "def CostCrossEntropy(target):\n", + " \"\"\"\n", + " Return cross entropy cost function valued only at X, so\n", + " that it may be easily differentiated\n", + " \"\"\"\n", + " \n", + " def func(X):\n", + " return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))\n", + "\n", + " return func" + ] + }, + { + "cell_type": "markdown", + "id": "ea50c429", + "metadata": {}, + "source": [ + "### Usage of cost functions\n", + "\n", + "Below we will provide a short example of how these cost function may\n", + "be used to obtain results if you wish to test them out on your own\n", + "using AutoGrad's automatic differentiation." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "438d0249", + "metadata": {}, + "outputs": [], + "source": [ + "from autograd import grad\n", + "\n", + "target = np.array([[1, 2, 3]]).T\n", + "a = np.array([[4, 5, 6]]).T\n", + "\n", + "cost_func = CostCrossEntropy\n", + "cost_func_derivative = grad(cost_func(target))\n", + "\n", + "valued_at_a = cost_func_derivative(a)\n", + "print(f\"Derivative of cost function {cost_func.__name__} valued at a:\\n{valued_at_a}\")" + ] + }, + { + "cell_type": "markdown", + "id": "6060ed74", + "metadata": {}, + "source": [ + "### Activation functions\n", + "\n", + "Finally, before we look at the layers that make up the neural network,\n", + "we will look at the activation functions which can be specified\n", + "between the hidden layers and as the output function. Each function\n", + "can be valued for any given vector or matrix X, and can be\n", + "differentiated via derivate()." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "962289b4", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "import autograd.numpy as np\n", + "from autograd import elementwise_grad\n", + "\n", + "def identity(X):\n", + " return X\n", + "\n", + "\n", + "def sigmoid(X):\n", + " try:\n", + " return 1.0 / (1 + np.exp(-X))\n", + " except FloatingPointError:\n", + " return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))\n", + "\n", + "\n", + "def softmax(X):\n", + " X = X - np.max(X, axis=-1, keepdims=True)\n", + " delta = 10e-10\n", + " return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)\n", + "\n", + "\n", + "def RELU(X):\n", + " return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))\n", + "\n", + "\n", + "def LRELU(X):\n", + " delta = 10e-4\n", + " return np.where(X > np.zeros(X.shape), X, delta * X)\n", + "\n", + "\n", + "def derivate(func):\n", + " if func.__name__ == \"RELU\":\n", + "\n", + " def func(X):\n", + " return np.where(X > 0, 1, 0)\n", + "\n", + " return func\n", + "\n", + " elif func.__name__ == \"LRELU\":\n", + "\n", + " def func(X):\n", + " delta = 10e-4\n", + " return np.where(X > 0, 1, delta)\n", + "\n", + " return func\n", + "\n", + " else:\n", + " return elementwise_grad(func)" + ] + }, + { + "cell_type": "markdown", + "id": "e10ea31a", + "metadata": {}, + "source": [ + "### Usage of activation functions\n", + "\n", + "Below we present a short demonstration of how to use an activation\n", + "function. The derivative of the activation function will be important\n", + "when calculating the output delta term during backpropagation. Note\n", + "that derivate() can also be used for cost functions for a more\n", + "generalized approach." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "b374bde5", + "metadata": {}, + "outputs": [], + "source": [ + "z = np.array([[4, 5, 6]]).T\n", + "print(f\"Input to activation function:\\n{z}\")\n", + "\n", + "act_func = sigmoid\n", + "a = act_func(z)\n", + "print(f\"\\nOutput from {act_func.__name__} activation function:\\n{a}\")\n", + "\n", + "act_func_derivative = derivate(act_func)\n", + "valued_at_z = act_func_derivative(a)\n", + "print(f\"\\nDerivative of {act_func.__name__} activation function valued at z:\\n{valued_at_z}\")" + ] + }, + { + "cell_type": "markdown", + "id": "a67f2032", + "metadata": {}, + "source": [ + "### Convolution\n", + "\n", + "In order to construct a convolutional neural network (CNN), it is\n", + "crucial to comprehend the fundamental principles of convolution and\n", + "how it aids in extracting information from images. Convolution, at its\n", + "core, is merely a mathematical operation between two functions that\n", + "yields another function. It is represented by an integral between two\n", + "functions, which is typically expressed as:" + ] + }, + { + "cell_type": "markdown", + "id": "70c5cf9f", + "metadata": {}, + "source": [ + "$$\n", + "(f \\ast g)(t):=\\int_{-\\infty}^{\\infty} f(\\tau) g(t-\\tau) d \\tau.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a0738da9", + "metadata": {}, + "source": [ + "Here, f and g are the two functions on which we want to perform an\n", + "operation. The outcome of the convolution operation is represented by\n", + "$(f \\ast g)$, and it is derived by sliding the function g over f and\n", + "computing the integral of their product at each position. If both\n", + "functions are continuous, convolution takes the form shown\n", + "above. However, if we discretize both f and g, the convolution\n", + "operation will take the form of a sum between the elements of f and g:" + ] + }, + { + "cell_type": "markdown", + "id": "fa290f29", + "metadata": {}, + "source": [ + "$$\n", + "(f \\ast g)[n]=\\sum_{m=0}^{n-1} f[m] g[n-m].\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "78ece2fc", + "metadata": {}, + "source": [ + "The key idea we utilize to extract the information contained in an\n", + "image is to slide an $m \\times n$ matrix *g* over an $m \\times n$\n", + "matrix *f*. In our case, *f* represents the image, while *g*\n", + "represents the kernel, oftentimes called a filter. However, since our\n", + "convolution will be a two-dimensional variant, we need to extend our\n", + "mathematical formula with an additional summation:" + ] + }, + { + "cell_type": "markdown", + "id": "b19ddb5e", + "metadata": {}, + "source": [ + "$$\n", + "(f \\ast g)[i, j]\\sum_{m=0}^{M-1}\\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n].\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3a97d8af", + "metadata": {}, + "source": [ + "It is imperative to note that the size of the kernel g is\n", + "significantly smaller than the size of the input image f, thereby\n", + "reducing the amount of computation necessary for feature\n", + "extraction. Furthermore, the kernel is usually a trainable parameter\n", + "in a convolutional neural network, allowing the network to learn\n", + "appropriate kernels for specific tasks.\n", + "\n", + "To give you an example of how 2D convolution works in practice,\n", + "suppose we have an image *f* of dimension $6 \\times 6$" + ] + }, + { + "cell_type": "markdown", + "id": "1a5462e2", + "metadata": {}, + "source": [ + "$$\n", + "f = \\begin{bmatrix}\n", + "4 & 1 & 2 & 9 & 8 & 6 \\\\\n", + "9 & 5 & 9 & 5 & 8 & 5 \\\\\n", + "1 & 5 & 9 & 7 & 6 & 4 \\\\\n", + "2 & 9 & 8 & 3 & 7 & 1 \\\\\n", + "8 & 1 & 6 & 4 & 2 & 2 \\\\\n", + "1 & 0 & 5 & 7 & 8 & 2 \\\\\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2e904e3d", + "metadata": {}, + "source": [ + "and a $3 \\times 3$ kernel *g* called a low-pass filter. Note that the\n", + "kernel is usually rotated by 180 degrees during convolution, however\n", + "this has no effect on this kernel." + ] + }, + { + "cell_type": "markdown", + "id": "65c5e545", + "metadata": {}, + "source": [ + "$$\n", + "g = \\frac{1}{9}\n", + "\\begin{bmatrix}\n", + "1 & 1 & 1 \\\\\n", + "1 & 1 & 1 \\\\\n", + "1 & 1 & 1 \\\\\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6fedef15", + "metadata": {}, + "source": [ + "In order to filter the image, we have to extract a $3 \\times 3$\n", + "element from the upper left corner of *f*, and perform element-wise\n", + "multiplication of the extracted image pixels with the elements of the\n", + "kernel *g*:" + ] + }, + { + "cell_type": "markdown", + "id": "e0abec0e", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{bmatrix}\n", + "4 & 1 & 2 \\\\\n", + "9 & 5 & 9 \\\\\n", + "1 & 5 & 9 \\\\\n", + "\\end{bmatrix}\n", + "\\cdot\n", + "\\begin{bmatrix}\n", + "\\frac{1}{9} & \\frac{1}{9} & \\frac{1}{9} \\\\\n", + "\\frac{1}{9} & \\frac{1}{9} & \\frac{1}{9} \\\\\n", + "\\frac{1}{9} & \\frac{1}{9} & \\frac{1}{9} \\\\\n", + "\\end{bmatrix}\n", + "=\n", + "\\begin{bmatrix}\n", + "\\frac{4}{9} & \\frac{1}{9} & \\frac{2}{9} \\\\\n", + "\\frac{9}{9} & \\frac{5}{9} & \\frac{9}{9} \\\\\n", + "\\frac{1}{9} & \\frac{5}{9} & \\frac{9}{9} \\\\\n", + "\\end {bmatrix}\n", + "= \\textbf{A}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "aef3b0ae", + "metadata": {}, + "source": [ + "Then, following the multiplication, we summarize all the elements of the resulting matrix A:" + ] + }, + { + "cell_type": "markdown", + "id": "b9ce4351", + "metadata": {}, + "source": [ + "$$\n", + "(f \\ast g)[0, 0]= \\sum_{i=0}^{2} \\sum_{j=0}^{2} a_{i,j} = 5\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e58be5c7", + "metadata": {}, + "source": [ + "Which corresponds to the first element of the filtered image $(f \\ast g)$.\n", + "\n", + "Here we use a stride of 1, a parameter denoted *s* which describes how\n", + "many indexes we move the kernel *g* to the right before repeating the\n", + "calculations above for the next $3 \\times 3$ element of the image\n", + "*f*. It is usually presumed that *s*=1, however, larger values for *s*\n", + "can be used to reduce the dimentionality of the filtered image such\n", + "that the convolution operation is more computationally efficient. In\n", + "the context of a convolutional neural network, this will become very\n", + "useful.\n", + "\n", + "The full result of the convolution is:" + ] + }, + { + "cell_type": "markdown", + "id": "68d7caf4", + "metadata": {}, + "source": [ + "$$\n", + "(f \\ast g) =\n", + "\\begin{bmatrix}\n", + "5 & 5.78 & 7 & 6.44 \\\\\n", + "6.33 & 6.67 & 6.89 & 5.11 \\\\\n", + "5.44 & 5.78 & 5.78 & 4 \\\\\n", + "4.44 & 4.78 & 5.56 & 4 \\\\\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "67df8548", + "metadata": {}, + "source": [ + "The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image.\n", + "How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with *r* additional rows and *c* additional columns." + ] + }, + { + "cell_type": "markdown", + "id": "ca837258", + "metadata": {}, + "source": [ + "$$\n", + "r =\\lfloor \\frac{kernel\\ height}{2} \\rfloor \\cdot 2 \\\\\n", + "c =\\lfloor \\frac{kernel\\ width}{2} \\rfloor \\cdot 2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9013a50e", + "metadata": {}, + "source": [ + "Note the notation $\\lfloor \\frac{kernel width}{2} \\rfloor$ means that\n", + "we floor the result of the division, meaning we round down to a whole\n", + "number in case $\\frac{kernel width}{2}$ results in a floating point\n", + "number.\n", + "\n", + "Using those simple equations, we find out by how much we have to\n", + "extend the dimensions of the original image. Before proceeding,\n", + "however, we might ask what we shall fill the additional rows and\n", + "columns with? One of the most common approaches to padding is\n", + "zero-padding, which as the name suggest, involves filling the rows and\n", + "columns with zeros. This is the approach that we will be using for\n", + "this demonstration. If we apply this padding to out original $6 \\times 6$\n", + "image, the result will be an $8 \\times 8$ image as the kernel has a width and\n", + "height of 3. Note that the original image is encapsuled by the\n", + "zero-padded rows and columns:" + ] + }, + { + "cell_type": "markdown", + "id": "27ab00a4", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{bmatrix}\n", + "0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n", + "0 & 4 & 1 & 2 & 9 & 8 & 6 & 0 \\\\\n", + "0 & 9 & 5 & 9 & 5 & 8 & 5 & 0 \\\\\n", + "0 & 1 & 5 & 9 & 7 & 6 & 4 & 0 \\\\\n", + "0 & 2 & 9 & 8 & 3 & 7 & 1 & 0 \\\\\n", + "0 & 8 & 1 & 6 & 4 & 2 & 2 & 0 \\\\\n", + "0 & 1 & 0 & 5 & 7 & 8 & 2 & 0 \\\\\n", + "0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n", + "\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "dedb1313", + "metadata": {}, + "source": [ + "Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding.~" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "76641906", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "def padding(image, kernel):\n", + " # calculate r and c\n", + " r = (kernel.shape[0] // 2) * 2\n", + " c = (kernel.shape[1] // 2) * 2\n", + " \n", + " # padded image dimensions\n", + " padded_height = image.shape[0] + r\n", + " padded_width = image.shape[1] + c\n", + " \n", + " # for more readable code\n", + " k_half_height = kernel.shape[0] // 2\n", + " k_half_width = kernel.shape[1] // 2\n", + "\n", + " # zero matrix with padded dimensions\n", + " padded_img = np.zeros((padded_height, padded_width))\n", + "\n", + " # place image into zero matrix\n", + " padded_img[k_half_height : padded_height - k_half_height,\n", + " k_half_width : padded_width - k_half_width] = image[:, :]\n", + "\n", + " return padded_img\n", + "\n", + "def convolve(original_image, padded_image, kernel, stride=1):\n", + " # rotate kernel by 180 degrees\n", + " kernel = np.rot90(np.rot90(kernel))\n", + "\n", + " # note that kernel height // 2 is written as 'm'\n", + " # and kernel width // 2 as 'n' in the mathematical notation\n", + " m = kernel.shape[0] // 2\n", + " n = kernel.shape[1] // 2\n", + " \n", + " r = (kernel.shape[0] // 2) * 2\n", + " c = (kernel.shape[1] // 2) * 2\n", + " \n", + " # initialize output array\n", + " convolved_image = np.zeros(original_image.shape)\n", + " image_height = original_image.shape[0]\n", + " image_width = original_image.shape[1]\n", + "\n", + " # the convolution\n", + " for i in range(m, image_height + m, stride):\n", + " for j in range(n, image_width + n, stride):\n", + " convolved_image[i-m, j-n] = np.sum(\n", + " padded_image[i : i + m, j : j + n]\n", + " * kernel\n", + " )\n", + " \n", + " return convolved_image\n", + "\n", + "def convolve(image, kernel, stride=1):\n", + " for i in range(2):\n", + " kernel = np.rot90(kernel)\n", + "\n", + " k_half_height = kernel.shape[0] // 2\n", + " k_half_width = kernel.shape[0] // 2\n", + "\n", + " conv_image = np.zeros(image.shape)\n", + " pad_image = padding(image, kernel)\n", + "\n", + " for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):\n", + " for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):\n", + " conv_image[i - k_half_height, j - k_half_width] = np.sum(\n", + " pad_image[\n", + " i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1\n", + " ]\n", + " * kernel\n", + " )\n", + "\n", + " return conv_image" + ] + }, + { + "cell_type": "markdown", + "id": "57c2f880", + "metadata": {}, + "source": [ + "Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. \n", + "However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called \n", + "cross-correlation." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "629f5bab", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "original_image = np.array([[4, 1, 2, 9, 8, 6],\n", + " [9, 5, 9, 5, 8, 5],\n", + " [1, 5, 9, 7, 6, 4],\n", + " [2, 9, 8, 3, 7, 1],\n", + " [8, 1, 6, 4, 2, 2],\n", + " [1, 0, 5, 7, 8, 2]])\n", + "\n", + "kernel = (1/9)*np.ones((3,3))\n", + "\n", + "print(f\"{original_image.shape=}\")\n", + "\n", + "# note that convolve() performs padding\n", + "convolved_image = convolve(original_image, kernel, stride=1)\n", + "\n", + "print(f\"{convolved_image.shape=}\")" + ] + }, + { + "cell_type": "markdown", + "id": "589f42bc", + "metadata": {}, + "source": [ + "As you can see, the resulting image is of the same size as the\n", + "original image. To round of our demonstration of convolution, we will\n", + "present the results of convolution using commonly used kernels. In a\n", + "CNN, the values of the kernels are randomly initialized, and then\n", + "learned during training. These kernels will extract information\n", + "regarding the picture, such as for example the edge detection filter\n", + "demonstrated below extracts the edges present in the picture. Of\n", + "course, there is no guarantee that the CNN will learn an edge\n", + "detection filter, but this should provide some intuiton as to how the\n", + "CNN is able to use kernels to make better predictions than a regular\n", + "feed forward neural network." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "7addd2db", + "metadata": {}, + "outputs": [], + "source": [ + "# Now an example using a real image and first a gaussian low-pass filter and then a sobel filter\n", + "import numpy as np\n", + "import imageio.v3 as imageio\n", + "import matplotlib.pyplot as plt\n", + "import time\n", + "\n", + "def generate_gauss_mask(sigma, K=1):\n", + " side = np.ceil(1 + 8 * sigma)\n", + " y, x = np.mgrid[-side // 2 + 1 : (side // 2) + 1, -side // 2 + 1 : (side // 2) + 1]\n", + " ker_coef = K / (2 * np.pi * sigma**2)\n", + " g = np.exp(-((x**2 + y**2) / (2.0 * sigma**2)))\n", + "\n", + " return g, ker_coef\n", + "\n", + "\n", + "img_path = \"data/IMG-2167.JPG\"\n", + "image_of_cute_dog = imageio.imread(img_path, mode='L')\n", + "\n", + "plt.imshow(image_of_cute_dog, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.title(\"Original image\")\n", + "plt.show()\n", + "\n", + "gauss, kernel = generate_gauss_mask(sigma=6)\n", + "gauss_kernel = gauss*kernel\n", + "\n", + "filtered_image = convolve(image_of_cute_dog, gauss_kernel)\n", + "plt.imshow(filtered_image, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.title(\"Result of convolution with gauss kernel (blurring filter)\")\n", + "plt.show()\n", + "\n", + "sobel_kernel = np.array([[1, 2, 1],\n", + " [0, 0, 0], \n", + " [-1, -2, -1]])\n", + "\n", + "filtered_image = convolve(image_of_cute_dog, sobel_kernel)\n", + "\n", + "plt.imshow(filtered_image, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.title(\"Result of convolution with sobel kernel (edge detection filter)\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "5380e6ee", + "metadata": {}, + "source": [ + "### Layers\n", + "\n", + "The code below initialises global variables for readability and\n", + "describes the abstract class Layers. This is not important in order to\n", + "understand the CNN, but is benefitial for organizing the code neatly." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "45579a9f", + "metadata": {}, + "outputs": [], + "source": [ + "import math\n", + "import autograd.numpy as np\n", + "from copy import deepcopy, copy\n", + "from autograd import grad\n", + "from typing import Callable\n", + "\n", + "# global variables for index readability\n", + "input_index = 0\n", + "node_index = 1\n", + "bias_index = 1\n", + "input_channel_index = 1\n", + "feature_maps_index = 1\n", + "height_index = 2\n", + "width_index = 3\n", + "kernel_feature_maps_index = 1\n", + "kernel_input_channels_index = 0\n", + "\n", + "\n", + "class Layer:\n", + " def __init__(self, seed):\n", + " self.seed = seed\n", + "\n", + " def _feedforward(self):\n", + " raise NotImplementedError\n", + "\n", + " def _backpropagate(self):\n", + " raise NotImplementedError\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " raise NotImplementedError" + ] + }, + { + "cell_type": "markdown", + "id": "352938da", + "metadata": {}, + "source": [ + "### Convolution2DLayer: convolution in a hidden layer\n", + "\n", + "After establishing the foundational understanding of applying\n", + "convolution to spatial data, let us delve into the intricate workings\n", + "of a convolutional layer in a Convolutional Neural Network (CNN). The\n", + "primary function of convolution, as previously discussed, is to\n", + "extract pertinent information from images while simultaneously\n", + "decreasing the scale of our data. To initiate the image processing, we\n", + "shall begin by partitioning the images into color channels (unless the\n", + "image is grayscale), comprising three primary colors: red, green, and\n", + "blue. We will subsequently utilize trainable kernels to construct a\n", + "higher-dimensional encoding of each channel called feature\n", + "maps. Successive layers will receive these feature maps as inputs,\n", + "generating further encodings, albeit with reduced dimensions. The term\n", + "trainable kernels denotes the initialization of pre-defined\n", + "kernel-shaped weights, which we will then train via backpropagation,\n", + "similar to how weights are trained in a Feedforward Neural Network.\n", + "\n", + "To ensure seamless integration between our implementation of the\n", + "convolutional layer and popular machine learning frameworks like\n", + "Tensorflow (Keras) and PyTorch, we have adopted a design pattern that\n", + "mirrors the construction of models using these APIs. This involves\n", + "implementing our convolutional layer as a Python class or object,\n", + "which allows for a more modular and flexible approach to building\n", + "neural networks. By structuring our code in this way, users can easily\n", + "incorporate our implementation into their existing machine learning\n", + "pipelines without having to make significant changes to their\n", + "codebase. Additionally, this design pattern promotes code reusability\n", + "and makes it easier to maintain and update our convolutional layer\n", + "implementation over time.\n", + "\n", + "Note that the Convolution2DLayer takes in an activation function as a parameter, as it also performs non-linearity." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "67866434", + "metadata": {}, + "outputs": [], + "source": [ + "class Convolution2DLayer(Layer):\n", + " def __init__(\n", + " self,\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func: Callable,\n", + " seed=None,\n", + " reset_weights_independently=True,\n", + " ):\n", + " super().__init__(seed)\n", + " self.input_channels = input_channels\n", + " self.feature_maps = feature_maps\n", + " self.kernel_height = kernel_height\n", + " self.kernel_width = kernel_width\n", + " self.v_stride = v_stride\n", + " self.h_stride = h_stride\n", + " self.pad = pad\n", + " self.act_func = act_func\n", + "\n", + " # such that the layer can be used on its own\n", + " # outside of the CNN module\n", + " if reset_weights_independently == True:\n", + " self._reset_weights_independently()\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # note that the shape of X_batch = [inputs, input_maps, img_height, img_width]\n", + "\n", + " # pad the input batch\n", + " X_batch_padded = self._padding(X_batch)\n", + "\n", + " # calculate height_index and width_index after stride\n", + " strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))\n", + " strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))\n", + "\n", + " # create output array\n", + " output = np.ndarray(\n", + " (\n", + " X_batch.shape[input_index],\n", + " self.feature_maps,\n", + " strided_height,\n", + " strided_width,\n", + " )\n", + " )\n", + "\n", + " # save input and output for backpropagation\n", + " self.X_batch_feedforward = X_batch\n", + " self.output_shape = output.shape\n", + "\n", + " # checking for errors, no need to look here :)\n", + " self._check_for_errors()\n", + "\n", + " # convolve input with kernel\n", + " for img in range(X_batch.shape[input_index]):\n", + " for chin in range(self.input_channels):\n", + " for fmap in range(self.feature_maps):\n", + " out_h = 0\n", + " for h in range(0, X_batch.shape[height_index], self.v_stride):\n", + " out_w = 0\n", + " for w in range(0, X_batch.shape[width_index], self.h_stride):\n", + " output[img, fmap, out_h, out_w] = np.sum(\n", + " X_batch_padded[\n", + " img,\n", + " chin,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + " * self.kernel[chin, fmap, :, :]\n", + " )\n", + " out_w += 1\n", + " out_h += 1\n", + "\n", + " # Pay attention to the fact that we're not rotating the kernel by 180 degrees when filtering the image in\n", + " # the convolutional layer, as convolution in terms of Machine Learning is a procedure known as cross-correlation\n", + " # in image processing and signal processing\n", + "\n", + " # return a\n", + " return self.act_func(output / (self.kernel_height))\n", + "\n", + " def _backpropagate(self, delta_term_next):\n", + " # intiate matrices\n", + " delta_term = np.zeros((self.X_batch_feedforward.shape))\n", + " gradient_kernel = np.zeros((self.kernel.shape))\n", + "\n", + " # pad input for convolution\n", + " X_batch_padded = self._padding(self.X_batch_feedforward)\n", + "\n", + " # Since an activation function is used at the output of the convolution layer, its derivative\n", + " # has to be accounted for in the backpropagation -> as if ReLU was a layer on its own.\n", + " act_derivative = derivate(self.act_func)\n", + " delta_term_next = act_derivative(delta_term_next)\n", + "\n", + " # fill in 0's for values removed by vertical stride in feedforward\n", + " if self.v_stride > 1:\n", + " v_ind = 1\n", + " for i in range(delta_term_next.shape[height_index]):\n", + " for j in range(self.v_stride - 1):\n", + " delta_term_next = np.insert(\n", + " delta_term_next, v_ind, 0, axis=height_index\n", + " )\n", + " v_ind += self.v_stride\n", + "\n", + " # fill in 0's for values removed by horizontal stride in feedforward\n", + " if self.h_stride > 1:\n", + " h_ind = 1\n", + " for i in range(delta_term_next.shape[width_index]):\n", + " for k in range(self.h_stride - 1):\n", + " delta_term_next = np.insert(\n", + " delta_term_next, h_ind, 0, axis=width_index\n", + " )\n", + " h_ind += self.h_stride\n", + "\n", + " # crops out 0-rows and 0-columns\n", + " delta_term_next = delta_term_next[\n", + " :,\n", + " :,\n", + " : self.X_batch_feedforward.shape[height_index],\n", + " : self.X_batch_feedforward.shape[width_index],\n", + " ]\n", + "\n", + " # the gradient received from the next layer also needs to be padded\n", + " delta_term_next = self._padding(delta_term_next)\n", + "\n", + " # calculate delta term by convolving next delta term with kernel\n", + " for img in range(self.X_batch_feedforward.shape[input_index]):\n", + " for chin in range(self.input_channels):\n", + " for fmap in range(self.feature_maps):\n", + " for h in range(self.X_batch_feedforward.shape[height_index]):\n", + " for w in range(self.X_batch_feedforward.shape[width_index]):\n", + " delta_term[img, chin, h, w] = np.sum(\n", + " delta_term_next[\n", + " img,\n", + " fmap,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + " * np.rot90(np.rot90(self.kernel[chin, fmap, :, :]))\n", + " )\n", + "\n", + " # calculate gradient for kernel for weight update\n", + " # also via convolution\n", + " for chin in range(self.input_channels):\n", + " for fmap in range(self.feature_maps):\n", + " for k_x in range(self.kernel_height):\n", + " for k_y in range(self.kernel_width):\n", + " gradient_kernel[chin, fmap, k_x, k_y] = np.sum(\n", + " X_batch_padded[\n", + " img,\n", + " chin,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + " * delta_term_next[\n", + " img,\n", + " fmap,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + " )\n", + " # all kernels are updated with weight gradient of kernel\n", + " self.kernel -= gradient_kernel\n", + "\n", + " # return delta term\n", + " return delta_term\n", + "\n", + " def _padding(self, X_batch, batch_type=\"image\"):\n", + "\n", + " # same padding for images\n", + " if self.pad == \"same\" and batch_type == \"image\":\n", + " padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2\n", + " padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2\n", + " half_kernel_height = self.kernel_height // 2\n", + " half_kernel_width = self.kernel_width // 2\n", + "\n", + " # initialize padded array\n", + " X_batch_padded = np.ndarray(\n", + " (\n", + " X_batch.shape[input_index],\n", + " X_batch.shape[feature_maps_index],\n", + " padded_height,\n", + " padded_width,\n", + " )\n", + " )\n", + "\n", + " # zero pad all images in X_batch\n", + " for img in range(X_batch.shape[input_index]):\n", + " padded_img = np.zeros(\n", + " (X_batch.shape[feature_maps_index], padded_height, padded_width)\n", + " )\n", + " padded_img[\n", + " :,\n", + " half_kernel_height : padded_height - half_kernel_height,\n", + " half_kernel_width : padded_width - half_kernel_width,\n", + " ] = X_batch[img, :, :, :]\n", + " X_batch_padded[img, :, :, :] = padded_img[:, :, :]\n", + "\n", + " return X_batch_padded\n", + "\n", + " # same padding for gradients\n", + " elif self.pad == \"same\" and batch_type == \"grad\":\n", + " padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2\n", + " padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2\n", + " half_kernel_height = self.kernel_height // 2\n", + " half_kernel_width = self.kernel_width // 2\n", + "\n", + " # initialize padded array\n", + " delta_term_padded = np.zeros(\n", + " (\n", + " X_batch.shape[input_index],\n", + " X_batch.shape[feature_maps_index],\n", + " padded_height,\n", + " padded_width,\n", + " )\n", + " )\n", + "\n", + " # zero pad delta term\n", + " delta_term_padded[\n", + " :, :, : X_batch.shape[height_index], : X_batch.shape[width_index]\n", + " ] = X_batch[:, :, :, :]\n", + "\n", + " return delta_term_padded\n", + "\n", + " else:\n", + " return X_batch\n", + "\n", + " def _reset_weights_independently(self):\n", + " # sets seed to remove randomness inbetween runs\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " # initializes kernel matrix\n", + " self.kernel = np.ndarray(\n", + " (\n", + " self.input_channels,\n", + " self.feature_maps,\n", + " self.kernel_height,\n", + " self.kernel_width,\n", + " )\n", + " )\n", + "\n", + " # randomly initializes weights\n", + " for chin in range(self.kernel.shape[kernel_input_channels_index]):\n", + " for fmap in range(self.kernel.shape[kernel_feature_maps_index]):\n", + " self.kernel[chin, fmap, :, :] = np.random.rand(\n", + " self.kernel_height, self.kernel_width\n", + " )\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # sets weights\n", + " self._reset_weights_independently()\n", + "\n", + " # returns shape of output used for subsequent layer's weight initiation\n", + " strided_height = int(\n", + " np.ceil(previous_nodes.shape[height_index] / self.v_stride)\n", + " )\n", + " strided_width = int(np.ceil(previous_nodes.shape[width_index] / self.h_stride))\n", + " next_nodes = np.ones(\n", + " (\n", + " previous_nodes.shape[input_index],\n", + " self.feature_maps,\n", + " strided_height,\n", + " strided_width,\n", + " )\n", + " )\n", + " return next_nodes / self.kernel_height\n", + "\n", + " def _check_for_errors(self):\n", + " if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:\n", + " raise AssertionError(\n", + " f\"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal\"\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "904776a8", + "metadata": {}, + "source": [ + "### Backpropagation in the convolutional layer\n", + "\n", + "As you may have noticed, we have not yet explained how the\n", + "backpropagation algorithm works in a convolutional layer. However,\n", + "having covered all other major details about convolutional layers, we\n", + "are now prepared to do so. It should come as no surprise that the\n", + "calculation of delta terms at each convolutional layer takes the form\n", + "of convolution. After the gradient has been propagated backwards\n", + "through the flattening layer, where it was reshaped into an\n", + "appropriate form, calculating the update value for the kernel is\n", + "simply a matter of convolving the output gradient with the input of\n", + "the layer for which we are updating the weights. For more detail, this\n", + "article serves as an excellent resource, see\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "2bbce751", + "metadata": {}, + "source": [ + "### Demonstration\n", + "\n", + "We can use the convolutional layer above to perform a simple convolution on an image of the now familiar cute dog." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "78ea75c1", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import imageio.v3 as imageio\n", + "import matplotlib.pyplot as plt\n", + "\n", + "def plot_convolution_result(X, layer):\n", + " plt.imshow(X[0, 0, :, :], vmin=0, vmax=255, cmap=\"gray\")\n", + " plt.title(\"Original image\")\n", + " plt.colorbar()\n", + " plt.show()\n", + " conv_result = layer._feedforward(X)\n", + " plt.title(\"Result of convolutional layer\")\n", + " plt.imshow(conv_result[0, 0, :, :], vmin=0, vmax=255, cmap=\"gray\")\n", + " plt.colorbar()\n", + " plt.show()\n", + "\n", + "# create layer\n", + "layer = Convolution2DLayer(\n", + " input_channels=3,\n", + " feature_maps=1,\n", + " kernel_height=4,\n", + " kernel_width=4,\n", + " v_stride=2,\n", + " h_stride=2,\n", + " pad=\"same\",\n", + " act_func=identity,\n", + " seed=2023,\n", + " )\n", + "\n", + "# read in image path, make data correct format\n", + "img_path = img_path = \"data/IMG-2167.JPG\"\n", + "image_of_cute_dog = imageio.imread(img_path)\n", + "image_shape = image_of_cute_dog.shape\n", + "image_of_cute_dog = image_of_cute_dog.reshape(1, image_shape[0], image_shape[1], image_shape[2])\n", + "image_of_cute_dog = image_of_cute_dog.transpose(0, 3, 1, 2)\n", + "\n", + "# plot the result of the convolution\n", + "plot_convolution_result(image_of_cute_dog, layer)" + ] + }, + { + "cell_type": "markdown", + "id": "f6f0d049", + "metadata": {}, + "source": [ + "We cobserve that the result has half the pixels on each axis due to\n", + "the fact that we've used a horizontal and vertical stride of 2. The\n", + "result of this convolution is not very insightfull, as the kernel has\n", + "completely random values for the first feedforward pass. However, as\n", + "we perform multiple forward and backward passes, the results of the\n", + "convolution should provide identifying features of the image it uses\n", + "for classification.\n", + "\n", + "Note that image data usually comes in many different shapes and sizes,\n", + "but for our CNN we require the input data be formatted as \\[Number of\n", + "inputs, input channels, input height, input width\\]. Occasionally, the\n", + "data you come accross use will be formatted like this, but on many\n", + "occasions reshaping and transposing the dimensions is sadly necessary." + ] + }, + { + "cell_type": "markdown", + "id": "2ecb7763", + "metadata": {}, + "source": [ + "### Pooling Layer\n", + "\n", + "The pooling layer is another widely used type of layer in\n", + "convolutional neural networks that enables data downsampling to a more\n", + "manageable size. Despite recent technological advancements that allow\n", + "for convolution without excessive size reduction of the data, the\n", + "pooling layer still remains a fundamental component of convolutional\n", + "neural networks. It can be used before, after, or in between\n", + "convolutional layers, although finding the optimal placement of layers\n", + "and network depth requires experimentation to achieve the best\n", + "performance for a given problem. The code we provide allows you to\n", + "perform two types of pooling known as max pooling and average pooling." + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "1a180337", + "metadata": {}, + "outputs": [], + "source": [ + "class Pooling2DLayer(Layer):\n", + " def __init__(\n", + " self,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pooling=\"max\",\n", + " seed=None,\n", + " ):\n", + " super().__init__(seed)\n", + " self.kernel_height = kernel_height\n", + " self.kernel_width = kernel_width\n", + " self.v_stride = v_stride\n", + " self.h_stride = h_stride\n", + " self.pooling = pooling\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # Saving the input for use in the backwardpass\n", + " self.X_batch_feedforward = X_batch\n", + "\n", + " # check if user is silly\n", + " self._check_for_errors()\n", + "\n", + " # Computing the size of the feature maps based on kernel size and the stride parameter\n", + " strided_height = (\n", + " X_batch.shape[height_index] - self.kernel_height\n", + " ) // self.v_stride + 1\n", + " if X_batch.shape[height_index] == X_batch.shape[width_index]:\n", + " strided_width = strided_height\n", + " else:\n", + " strided_width = (\n", + " X_batch.shape[width_index] - self.kernel_width\n", + " ) // self.h_stride + 1\n", + "\n", + " # initialize output array\n", + " output = np.ndarray(\n", + " (\n", + " X_batch.shape[input_index],\n", + " X_batch.shape[feature_maps_index],\n", + " strided_height,\n", + " strided_width,\n", + " )\n", + " )\n", + "\n", + " # select pooling action, either max or average pooling\n", + " if self.pooling == \"max\":\n", + " self.pooling_action = np.max\n", + " elif self.pooling == \"average\":\n", + " self.pooling_action = np.mean\n", + "\n", + " # pool based on kernel size and stride\n", + " for img in range(output.shape[input_index]):\n", + " for fmap in range(output.shape[feature_maps_index]):\n", + " for h in range(strided_height):\n", + " for w in range(strided_width):\n", + " output[img, fmap, h, w] = self.pooling_action(\n", + " X_batch[\n", + " img,\n", + " fmap,\n", + " (h * self.v_stride) : (h * self.v_stride)\n", + " + self.kernel_height,\n", + " (w * self.h_stride) : (w * self.h_stride)\n", + " + self.kernel_width,\n", + " ]\n", + " )\n", + "\n", + " # output for feedforward in next layer\n", + " return output\n", + "\n", + " def _backpropagate(self, delta_term_next):\n", + " # initiate delta term array\n", + " delta_term = np.zeros((self.X_batch_feedforward.shape))\n", + "\n", + " for img in range(delta_term_next.shape[input_index]):\n", + " for fmap in range(delta_term_next.shape[feature_maps_index]):\n", + " for h in range(0, delta_term_next.shape[height_index], self.v_stride):\n", + " for w in range(\n", + " 0, delta_term_next.shape[width_index], self.h_stride\n", + " ):\n", + " # max pooling\n", + " if self.pooling == \"max\":\n", + " # get window\n", + " window = self.X_batch_feedforward[\n", + " img,\n", + " fmap,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + "\n", + " # find max values indices in window\n", + " max_h, max_w = np.unravel_index(\n", + " window.argmax(), window.shape\n", + " )\n", + "\n", + " # set values in new, upsampled delta term\n", + " delta_term[\n", + " img,\n", + " fmap,\n", + " (h + max_h),\n", + " (w + max_w),\n", + " ] += delta_term_next[img, fmap, h, w]\n", + "\n", + " # average pooling\n", + " if self.pooling == \"average\":\n", + " delta_term[\n", + " img,\n", + " fmap,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ] = (\n", + " delta_term_next[img, fmap, h, w]\n", + " / self.kernel_height\n", + " / self.kernel_width\n", + " )\n", + " # returns input to backpropagation in previous layer\n", + " return delta_term\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # calculate strided height, strided width\n", + " strided_height = (\n", + " previous_nodes.shape[height_index] - self.kernel_height\n", + " ) // self.v_stride + 1\n", + " if previous_nodes.shape[height_index] == previous_nodes.shape[width_index]:\n", + " strided_width = strided_height\n", + " else:\n", + " strided_width = (\n", + " previous_nodes.shape[width_index] - self.kernel_width\n", + " ) // self.h_stride + 1\n", + "\n", + " # initiate output array\n", + " output = np.ones(\n", + " (\n", + " previous_nodes.shape[input_index],\n", + " previous_nodes.shape[feature_maps_index],\n", + " strided_height,\n", + " strided_width,\n", + " )\n", + " )\n", + "\n", + " # returns output with shape used for reset weights in next layer\n", + " return output\n", + "\n", + " def _check_for_errors(self):\n", + " # check if input is smaller than kernel size -> error\n", + " assert (\n", + " self.X_batch_feedforward.shape[width_index] >= self.kernel_width\n", + " ), f\"ERROR: Pooling kernel width_index ({self.kernel_width}) larger than data width_index ({self.X_batch_feedforward.input.shape[2]}), please lower the kernel width_index of the Pooling2DLayer\"\n", + " assert (\n", + " self.X_batch_feedforward.shape[height_index] >= self.kernel_height\n", + " ), f\"ERROR: Pooling kernel height_index ({self.kernel_height}) larger than data height_index ({self.X_batch_feedforward.input.shape[3]}), please lower the kernel height_index of the Pooling2DLayer\"" + ] + }, + { + "cell_type": "markdown", + "id": "f4ab9ece", + "metadata": {}, + "source": [ + "### Flattening Layer\n", + "\n", + "Before we can begin building our first CNN model, we need to introduce\n", + "the flattening layer. As its name suggests, the flattening layer\n", + "transforms the data into a one-dimensional vector that can be fed into\n", + "the feedforward layers of our network. This layer plays a crucial role\n", + "in preparing the data for further processing in the\n", + "network. Additionally, the flattening layer is responsible for\n", + "reshaping the gradient to the proper shape during\n", + "backpropagation. This ensures that the kernels are correctly updated,\n", + "allowing for effective learning in the network." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "83d588e4", + "metadata": {}, + "outputs": [], + "source": [ + "class FlattenLayer(Layer):\n", + " def __init__(self, act_func=LRELU, seed=None):\n", + " super().__init__(seed)\n", + " self.act_func = act_func\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # save input for backpropagation\n", + " self.X_batch_feedforward_shape = X_batch.shape\n", + " # Remember, the data has the following shape: (I, FM, H, W, ) in the convolutional layers\n", + " # whilst the data has the shape (I, FM * H * W) in the fully connected layers\n", + " # I = Inputs, FM = Feature Maps, H = Height and W = Width.\n", + " X_batch = X_batch.reshape(\n", + " X_batch.shape[input_index],\n", + " X_batch.shape[feature_maps_index]\n", + " * X_batch.shape[height_index]\n", + " * X_batch.shape[width_index],\n", + " )\n", + "\n", + " # add bias to a\n", + " self.z_matrix = X_batch\n", + " bias = np.ones((X_batch.shape[input_index], 1)) * 0.01\n", + " self.a_matrix = np.hstack([bias, X_batch])\n", + "\n", + " # return a, the input to feedforward in next layer\n", + " return self.a_matrix\n", + "\n", + " def _backpropagate(self, weights_next, delta_term_next):\n", + " activation_derivative = derivate(self.act_func)\n", + "\n", + " # calculate delta term\n", + " delta_term = (\n", + " weights_next[bias_index:, :] @ delta_term_next.T\n", + " ).T * activation_derivative(self.z_matrix)\n", + "\n", + " # FlattenLayer does not update weights\n", + " # reshapes delta layer to convolutional layer data format [Input, Feature_Maps, Height, Width]\n", + " return delta_term.reshape(self.X_batch_feedforward_shape)\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # note that the previous nodes to the FlattenLayer are from the convolutional layers\n", + " previous_nodes = previous_nodes.reshape(\n", + " previous_nodes.shape[input_index],\n", + " previous_nodes.shape[feature_maps_index]\n", + " * previous_nodes.shape[height_index]\n", + " * previous_nodes.shape[width_index],\n", + " )\n", + "\n", + " # return shape used in reset_weights in next layer\n", + " return previous_nodes.shape[node_index]\n", + "\n", + " def get_prev_a(self):\n", + " return self.a_matrix" + ] + }, + { + "cell_type": "markdown", + "id": "922b6dfe", + "metadata": {}, + "source": [ + "### Fully Connected Layers\n", + "\n", + "Finally, the result from the flatten layer will pass to a series of\n", + "fully connected layers, which function as a normal feed forward neural\n", + "network. The fully connected layers are split into two classes;\n", + "FullyConnectedLayer which acts as a hidden layer, and OutputLayer,\n", + "which acts as the single output layer at the end of the CNN. If one\n", + "wishes to use this codebase to construct a normal feed forward neural\n", + "network, it must start with a FlattenLayer due to techincal details\n", + "regarding weight intitialization. However many FullyConnectedLayers\n", + "can be added to the CNN, and in each layer the amount of nodes, which\n", + "activation function and scheduler to use can be specified. In\n", + "practice, the scheduler will be specified in the CNN object\n", + "initialization, and inherited if no other scheduler is specified." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "85595198", + "metadata": {}, + "outputs": [], + "source": [ + "class FullyConnectedLayer(Layer):\n", + " # FullyConnectedLayer per default uses LRELU and Adam scheduler\n", + " # with an eta of 0.0001, rho of 0.9 and rho2 of 0.999\n", + " def __init__(\n", + " self,\n", + " nodes: int,\n", + " act_func: Callable = LRELU,\n", + " scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),\n", + " seed: int = None,\n", + " ):\n", + " super().__init__(seed)\n", + " self.nodes = nodes\n", + " self.act_func = act_func\n", + " self.scheduler_weight = copy(scheduler)\n", + " self.scheduler_bias = copy(scheduler)\n", + "\n", + " # initiate matrices for later\n", + " self.weights = None\n", + " self.a_matrix = None\n", + " self.z_matrix = None\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # calculate z\n", + " self.z_matrix = X_batch @ self.weights\n", + "\n", + " # calculate a, add bias\n", + " bias = np.ones((X_batch.shape[input_index], 1)) * 0.01\n", + " self.a_matrix = self.act_func(self.z_matrix)\n", + " self.a_matrix = np.hstack([bias, self.a_matrix])\n", + "\n", + " # return a, the input for feedforward in next layer\n", + " return self.a_matrix\n", + "\n", + " def _backpropagate(self, weights_next, delta_term_next, a_previous, lam):\n", + " # take the derivative of the activation function\n", + " activation_derivative = derivate(self.act_func)\n", + "\n", + " # calculate the delta term\n", + " delta_term = (\n", + " weights_next[bias_index:, :] @ delta_term_next.T\n", + " ).T * activation_derivative(self.z_matrix)\n", + "\n", + " # intitiate matrix to store gradient\n", + " # note that we exclude the bias term, which we will calculate later\n", + " gradient_weights = np.zeros(\n", + " (\n", + " a_previous.shape[input_index],\n", + " a_previous.shape[node_index] - bias_index,\n", + " delta_term.shape[node_index],\n", + " )\n", + " )\n", + "\n", + " # calculate gradient = delta term * previous a\n", + " for i in range(len(delta_term)):\n", + " gradient_weights[i, :, :] = np.outer(\n", + " a_previous[i, bias_index:], delta_term[i, :]\n", + " )\n", + "\n", + " # sum the gradient, divide by input_index\n", + " gradient_weights = np.mean(gradient_weights, axis=input_index)\n", + " # for the bias gradient we do not multiply by previous a\n", + " gradient_bias = np.mean(delta_term, axis=input_index).reshape(\n", + " 1, delta_term.shape[node_index]\n", + " )\n", + "\n", + " # regularization term\n", + " gradient_weights += self.weights[bias_index:, :] * lam\n", + "\n", + " # send gradients into scheduler\n", + " # returns update matrix which will be used to update the weights and bias\n", + " update_matrix = np.vstack(\n", + " [\n", + " self.scheduler_bias.update_change(gradient_bias),\n", + " self.scheduler_weight.update_change(gradient_weights),\n", + " ]\n", + " )\n", + "\n", + " # update weights\n", + " self.weights -= update_matrix\n", + "\n", + " # return weights and delta term, input for backpropagation in previous layer\n", + " return self.weights, delta_term\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # sets seed to remove randomness inbetween runs\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " # add bias, initiate random weights\n", + " bias = 1\n", + " self.weights = np.random.randn(previous_nodes + bias, self.nodes)\n", + "\n", + " # returns number of nodes, used for reset_weights in next layer\n", + " return self.nodes\n", + "\n", + " def _reset_scheduler(self):\n", + " # resets scheduler per epoch\n", + " self.scheduler_weight.reset()\n", + " self.scheduler_bias.reset()\n", + "\n", + " def get_prev_a(self):\n", + " # returns a matrix, used in backpropagation\n", + " return self.a_matrix\n", + "\n", + "\n", + "class OutputLayer(FullyConnectedLayer):\n", + " def __init__(\n", + " self,\n", + " nodes: int,\n", + " output_func: Callable = LRELU,\n", + " cost_func: Callable = CostCrossEntropy,\n", + " scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),\n", + " seed: int = None,\n", + " ):\n", + " super().__init__(nodes, output_func, copy(scheduler), seed)\n", + " self.cost_func = cost_func\n", + "\n", + " # initiate matrices for later\n", + " self.weights = None\n", + " self.a_matrix = None\n", + " self.z_matrix = None\n", + "\n", + " # decides if the output layer performs binary or multi-class classification\n", + " self._set_pred_format()\n", + "\n", + " def _feedforward(self, X_batch: np.ndarray):\n", + " # calculate a, z\n", + " # note that bias is not added as this would create an extra output class\n", + " self.z_matrix = X_batch @ self.weights\n", + " self.a_matrix = self.act_func(self.z_matrix)\n", + "\n", + " # returns prediction\n", + " return self.a_matrix\n", + "\n", + " def _backpropagate(self, target, a_previous, lam):\n", + " # note that in the OutputLayer the activation function is the output function\n", + " activation_derivative = derivate(self.act_func)\n", + "\n", + " # calculate output delta terms\n", + " # for multi-class or binary classification\n", + " if self.pred_format == \"Multi-class\":\n", + " delta_term = self.a_matrix - target\n", + " else:\n", + " cost_func_derivative = grad(self.cost_func(target))\n", + " delta_term = activation_derivative(self.z_matrix) * cost_func_derivative(\n", + " self.a_matrix\n", + " )\n", + "\n", + " # intiate matrix that stores gradient\n", + " gradient_weights = np.zeros(\n", + " (\n", + " a_previous.shape[input_index],\n", + " a_previous.shape[node_index] - bias_index,\n", + " delta_term.shape[node_index],\n", + " )\n", + " )\n", + "\n", + " # calculate gradient = delta term * previous a\n", + " for i in range(len(delta_term)):\n", + " gradient_weights[i, :, :] = np.outer(\n", + " a_previous[i, bias_index:], delta_term[i, :]\n", + " )\n", + "\n", + " # sum the gradient, divide by input_index\n", + " gradient_weights = np.mean(gradient_weights, axis=input_index)\n", + " # for the bias gradient we do not multiply by previous a\n", + " gradient_bias = np.mean(delta_term, axis=input_index).reshape(\n", + " 1, delta_term.shape[node_index]\n", + " )\n", + "\n", + " # regularization term\n", + " gradient_weights += self.weights[bias_index:, :] * lam\n", + "\n", + " # send gradients into scheduler\n", + " # returns update matrix which will be used to update the weights and bias\n", + " update_matrix = np.vstack(\n", + " [\n", + " self.scheduler_bias.update_change(gradient_bias),\n", + " self.scheduler_weight.update_change(gradient_weights),\n", + " ]\n", + " )\n", + "\n", + " # update weights\n", + " self.weights -= update_matrix\n", + "\n", + " # return weights and delta term, input for backpropagation in previous layer\n", + " return self.weights, delta_term\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # sets seed to remove randomness inbetween runs\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " # add bias, initiate random weights\n", + " bias = 1\n", + " self.weights = np.random.rand(previous_nodes + bias, self.nodes)\n", + "\n", + " # returns number of nodes, used for reset_weights in next layer\n", + " return self.nodes\n", + "\n", + " def _reset_scheduler(self):\n", + " # resets scheduler per epoch\n", + " self.scheduler_weight.reset()\n", + " self.scheduler_bias.reset()\n", + "\n", + " def _set_pred_format(self):\n", + " # sets prediction format to either regression, binary or multi-class classification\n", + " if self.act_func.__name__ is None or self.act_func.__name__ == \"identity\":\n", + " self.pred_format = \"Regression\"\n", + " elif self.act_func.__name__ == \"sigmoid\" or self.act_func.__name__ == \"tanh\":\n", + " self.pred_format = \"Binary\"\n", + " else:\n", + " self.pred_format = \"Multi-class\"\n", + "\n", + " def get_pred_format(self):\n", + " # returns format of prediction\n", + " return self.pred_format" + ] + }, + { + "cell_type": "markdown", + "id": "44351389", + "metadata": {}, + "source": [ + "### Optimized Convolution2DLayer\n", + "\n", + "For our CNN, we have also implemented an optimized version of the\n", + "Convolution2DLayer, Convolution2DLayerOPT, which runs much faster. See\n", + "VII. Remarks for discussion. This layer will per default be used by\n", + "the CNN due to its computational advantages, but is much less\n", + "readable. We've documented it such that specially interested students\n", + "can understand the principles behind it, but it is not recommended to\n", + "read. In short, we reshape and transpose parts of the image such that\n", + "the convolutional operation can be swapped out for a simple matrix\n", + "multiplication." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "f0e7aa82", + "metadata": {}, + "outputs": [], + "source": [ + "class Convolution2DLayerOPT(Convolution2DLayer):\n", + " \"\"\"\n", + " Am optimized version of the convolution layer above which\n", + " utilizes an approach of extracting windows of size equivalent\n", + " in size to the filter. The convoution is then performed on those\n", + " windows instead of a full feature map.\n", + " \"\"\"\n", + "\n", + " def __init__(\n", + " self,\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func: Callable,\n", + " seed=None,\n", + " reset_weights_independently=True,\n", + " ):\n", + " super().__init__(\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func,\n", + " seed,\n", + " )\n", + " # true if layer is used outside of CNN\n", + " if reset_weights_independently == True:\n", + " self._reset_weights_independently()\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # The optimized _feedforward method is difficult to understand but computationally more efficient\n", + " # for a more \"by the book\" approach, please look at the _feedforward method of Convolution2DLayer\n", + "\n", + " # save the input for backpropagation\n", + " self.X_batch_feedforward = X_batch\n", + "\n", + " # check that there are the correct amount of input channels\n", + " self._check_for_errors()\n", + "\n", + " # calculate new shape after stride\n", + " strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))\n", + " strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))\n", + "\n", + " # get windows of the image for more computationally efficient convolution\n", + " # the idea is that we want to align the dimensions that we wish to matrix\n", + " # multiply, then use a simple matrix multiplication instead of convolution.\n", + " # then, we reshape the size back to its intended shape\n", + " windows = self._extract_windows(X_batch)\n", + " windows = windows.transpose(1, 0, 2, 3, 4).reshape(\n", + " X_batch.shape[input_index],\n", + " strided_height * strided_width,\n", + " -1,\n", + " )\n", + "\n", + " # reshape the kernel for more computationally efficient convolution\n", + " kernel = self.kernel\n", + " kernel = kernel.transpose(0, 2, 3, 1).reshape(\n", + " kernel.shape[kernel_input_channels_index]\n", + " * kernel.shape[height_index]\n", + " * kernel.shape[width_index],\n", + " -1,\n", + " )\n", + "\n", + " # use simple matrix calculation to obtain output\n", + " output = (\n", + " (windows @ kernel)\n", + " .reshape(\n", + " X_batch.shape[input_index],\n", + " strided_height,\n", + " strided_width,\n", + " -1,\n", + " )\n", + " .transpose(0, 3, 1, 2)\n", + " )\n", + "\n", + " # The output is reshaped and rearranged to appropriate shape\n", + " return self.act_func(\n", + " output / (self.kernel_height * X_batch.shape[feature_maps_index])\n", + " )\n", + "\n", + " def _backpropagate(self, delta_term_next):\n", + " # The optimized _backpropagate method is difficult to understand but computationally more efficient\n", + " # for a more \"by the book\" approach, please look at the _backpropagate method of Convolution2DLayer\n", + " act_derivative = derivate(self.act_func)\n", + " delta_term_next = act_derivative(delta_term_next)\n", + "\n", + " # calculate strided dimensions\n", + " strided_height = int(\n", + " np.ceil(self.X_batch_feedforward.shape[height_index] / self.v_stride)\n", + " )\n", + " strided_width = int(\n", + " np.ceil(self.X_batch_feedforward.shape[width_index] / self.h_stride)\n", + " )\n", + "\n", + " # copy kernel\n", + " kernel = self.kernel\n", + "\n", + " # get windows, reshape for matrix multiplication\n", + " windows = self._extract_windows(self.X_batch_feedforward, \"image\").reshape(\n", + " self.X_batch_feedforward.shape[input_index]\n", + " * strided_height\n", + " * strided_width,\n", + " -1,\n", + " )\n", + "\n", + " # initialize output gradient, reshape and transpose into correct shape\n", + " # for matrix multiplication\n", + " output_grad_tr = delta_term_next.transpose(0, 2, 3, 1).reshape(\n", + " self.X_batch_feedforward.shape[input_index]\n", + " * strided_height\n", + " * strided_width,\n", + " -1,\n", + " )\n", + "\n", + " # calculate gradient kernel via simple matrix multiplication and reshaping\n", + " gradient_kernel = (\n", + " (windows.T @ output_grad_tr)\n", + " .reshape(\n", + " kernel.shape[kernel_input_channels_index],\n", + " kernel.shape[height_index],\n", + " kernel.shape[width_index],\n", + " kernel.shape[kernel_feature_maps_index],\n", + " )\n", + " .transpose(0, 3, 1, 2)\n", + " )\n", + "\n", + " # for computing the input gradient\n", + " windows_out, upsampled_height, upsampled_width = self._extract_windows(\n", + " delta_term_next, \"grad\"\n", + " )\n", + "\n", + " # calculate new window dimensions\n", + " new_windows_first_dim = (\n", + " self.X_batch_feedforward.shape[input_index]\n", + " * upsampled_height\n", + " * upsampled_width\n", + " )\n", + " # ceil allows for various asymmetric kernels\n", + " new_windows_sec_dim = int(np.ceil(windows_out.size / new_windows_first_dim))\n", + "\n", + " # reshape for matrix multiplication\n", + " windows_out = windows_out.transpose(1, 0, 2, 3, 4).reshape(\n", + " new_windows_first_dim, new_windows_sec_dim\n", + " )\n", + "\n", + " # reshape for matrix multiplication\n", + " kernel_reshaped = kernel.reshape(self.input_channels, -1)\n", + "\n", + " # calculating input gradient for next convolutional layer\n", + " input_grad = (windows_out @ kernel_reshaped.T).reshape(\n", + " self.X_batch_feedforward.shape[input_index],\n", + " upsampled_height,\n", + " upsampled_width,\n", + " kernel.shape[kernel_input_channels_index],\n", + " )\n", + " input_grad = input_grad.transpose(0, 3, 1, 2)\n", + "\n", + " # Update the weights in the kernel\n", + " self.kernel -= gradient_kernel\n", + "\n", + " # Output the gradient to propagate backwards\n", + " return input_grad\n", + "\n", + " def _extract_windows(self, X_batch, batch_type=\"image\"):\n", + " \"\"\"\n", + " Receives as input the X_batch with shape (inputs, feature_maps, image_height, image_width)\n", + " and extract windows of size kernel_height * kernel_width for every image and every feature_map.\n", + " It then returns an np.ndarray of shape (image_height * image_width, inputs, feature_maps, kernel_height, kernel_width)\n", + " which will be used either to filter the images in feedforward or to calculate the gradient.\n", + " \"\"\"\n", + "\n", + " # initialize list of windows\n", + " windows = []\n", + "\n", + " if batch_type == \"image\":\n", + " # pad the images\n", + " X_batch_padded = self._padding(X_batch, batch_type=\"image\")\n", + " img_height, img_width = X_batch_padded.shape[2:]\n", + " # For each location in the image...\n", + " for h in range(\n", + " 0,\n", + " X_batch.shape[height_index],\n", + " self.v_stride,\n", + " ):\n", + " for w in range(\n", + " 0,\n", + " X_batch.shape[width_index],\n", + " self.h_stride,\n", + " ):\n", + " # ...obtain an image patch of the original size (strided)\n", + "\n", + " # get window\n", + " window = X_batch_padded[\n", + " :,\n", + " :,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + "\n", + " # append to list of windows\n", + " windows.append(window)\n", + "\n", + " # return numpy array instead of list\n", + " return np.stack(windows)\n", + "\n", + " # In order to be able to perform backprogagation by the method of window extraction,\n", + " # here is a modified approach to extracting the windows which allow for the necessary\n", + " # upsampling of the gradient in case the on of the stride parameters is larger than one.\n", + "\n", + " if batch_type == \"grad\":\n", + "\n", + " # In the case of one of the stride parameters being odd, we have to take some\n", + " # extra care in calculating the upsampled size of X_batch. We solve this\n", + " # by simply flooring the result of dividing stride by 2.\n", + " if self.v_stride < 2 or self.v_stride % 2 == 0:\n", + " v_stride = 0\n", + " else:\n", + " v_stride = int(np.floor(self.v_stride / 2))\n", + "\n", + " if self.h_stride < 2 or self.h_stride % 2 == 0:\n", + " h_stride = 0\n", + " else:\n", + " h_stride = int(np.floor(self.h_stride / 2))\n", + "\n", + " upsampled_height = (X_batch.shape[height_index] * self.v_stride) - v_stride\n", + " upsampled_width = (X_batch.shape[width_index] * self.h_stride) - h_stride\n", + "\n", + " # When upsampling, we need to insert rows and columns filled with zeros\n", + " # into each feature map. How many of those we have to insert is purely\n", + " # dependant on the value of stride parameter in the vertical and horizontal\n", + " # direction.\n", + " if self.v_stride > 1:\n", + " v_ind = 1\n", + " for i in range(X_batch.shape[height_index]):\n", + " for j in range(self.v_stride - 1):\n", + " X_batch = np.insert(X_batch, v_ind, 0, axis=height_index)\n", + " v_ind += self.v_stride\n", + "\n", + " if self.h_stride > 1:\n", + " h_ind = 1\n", + " for i in range(X_batch.shape[width_index]):\n", + " for k in range(self.h_stride - 1):\n", + " X_batch = np.insert(X_batch, h_ind, 0, axis=width_index)\n", + " h_ind += self.h_stride\n", + "\n", + " # Since the insertion of zero-filled rows and columns isn't perfect, we have\n", + " # to assure that the resulting feature maps will have the expected upsampled height\n", + " # and width by cutting them og at desired dimensions.\n", + "\n", + " X_batch = X_batch[:, :, :upsampled_height, :upsampled_width]\n", + "\n", + " X_batch_padded = self._padding(X_batch, batch_type=\"grad\")\n", + "\n", + " # initialize list of windows\n", + " windows = []\n", + "\n", + " # For each location in the image...\n", + " for h in range(\n", + " 0,\n", + " X_batch.shape[height_index],\n", + " self.v_stride,\n", + " ):\n", + " for w in range(\n", + " 0,\n", + " X_batch.shape[width_index],\n", + " self.h_stride,\n", + " ):\n", + " # ...obtain an image patch of the original size (strided)\n", + "\n", + " # get window\n", + " window = X_batch_padded[\n", + " :, :, h : h + self.kernel_height, w : w + self.kernel_width\n", + " ]\n", + "\n", + " # append window to list\n", + " windows.append(window)\n", + "\n", + " # return numpy array, unsampled dimensions\n", + " return np.stack(windows), upsampled_height, upsampled_width\n", + "\n", + " def _check_for_errors(self):\n", + " # compares input channels of data to input channels of Convolution2DLayer\n", + " if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:\n", + " raise AssertionError(\n", + " f\"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal\"\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "76da2e3b", + "metadata": {}, + "source": [ + "### The Convolutional Neural Network (CNN)\n", + "\n", + "Finally, we present the code for the CNN. The CNN class organizes all the layers, and allows for training on image data." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "47fe6401", + "metadata": {}, + "outputs": [], + "source": [ + "import math\n", + "import autograd.numpy as np\n", + "import sys\n", + "import warnings\n", + "from autograd import grad, elementwise_grad\n", + "from random import random, seed\n", + "from copy import deepcopy\n", + "from typing import Tuple, Callable\n", + "from sklearn.utils import resample\n", + "\n", + "warnings.simplefilter(\"error\")\n", + "\n", + "\n", + "class CNN:\n", + " def __init__(\n", + " self,\n", + " cost_func: Callable = CostCrossEntropy,\n", + " scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),\n", + " seed: int = None,\n", + " ):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Instantiates CNN object\n", + "\n", + " Parameters:\n", + " ------------\n", + " I output_func (costFunctions) cost function for feed forward neural network part of CNN,\n", + " such as \"CostLogReg\", \"CostOLS\" or \"CostCrossEntropy\"\n", + "\n", + " II scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other\n", + " schedulers such as AdaGrad, Momentum, RMS_prop and Constant. Note that schedulers have\n", + " to be instantiated first with proper parameters (for example eta, rho and rho2 for Adam)\n", + "\n", + " III seed (int) used for seeding all random operations\n", + " \"\"\"\n", + " self.layers = list()\n", + " self.cost_func = cost_func\n", + " self.scheduler = scheduler\n", + " self.schedulers_weight = list()\n", + " self.schedulers_bias = list()\n", + " self.seed = seed\n", + " self.pred_format = None\n", + "\n", + " def add_FullyConnectedLayer(\n", + " self, nodes: int, act_func=LRELU, scheduler=None\n", + " ) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add a FullyConnectedLayer to the CNN, i.e. a hidden layer in the feed forward neural\n", + " network part of the CNN. Often called a Dense layer in literature\n", + "\n", + " Parameters:\n", + " ------------\n", + " I nodes (int) number of nodes in FullyConnectedLayer\n", + " II act_func (activationFunctions) activation function of FullyConnectedLayer,\n", + " such as \"sigmoid\", \"RELU\", \"LRELU\", \"softmax\" or \"identity\"\n", + " III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other\n", + " schedulers such as AdaGrad, Momentum, RMS_prop and Constant\n", + " \"\"\"\n", + " assert self.layers, \"FullyConnectedLayer should follow FlattenLayer in CNN\"\n", + "\n", + " if scheduler is None:\n", + " scheduler = self.scheduler\n", + "\n", + " layer = FullyConnectedLayer(nodes, act_func, scheduler, self.seed)\n", + " self.layers.append(layer)\n", + "\n", + " def add_OutputLayer(self, nodes: int, output_func=sigmoid, scheduler=None) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add an OutputLayer to the CNN, i.e. a the final layer in the feed forward neural\n", + " network part of the CNN\n", + "\n", + " Parameters:\n", + " ------------\n", + " I nodes (int) number of nodes in OutputLayer. Set nodes=1 for binary classification and\n", + " nodes = number of classes for multi-class classification\n", + " II output_func (activationFunctions) activation function for the output layer, such as\n", + " \"identity\" for regression, \"sigmoid\" for binary classification and \"softmax\" for multi-class\n", + " classification\n", + " III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other\n", + " schedulers such as AdaGrad, Momentum, RMS_prop and Constant\n", + " \"\"\"\n", + " assert self.layers, \"OutputLayer should follow FullyConnectedLayer in CNN\"\n", + "\n", + " if scheduler is None:\n", + " scheduler = self.scheduler\n", + "\n", + " output_layer = OutputLayer(\n", + " nodes, output_func, self.cost_func, scheduler, self.seed\n", + " )\n", + " self.layers.append(output_layer)\n", + " self.pred_format = output_layer.get_pred_format()\n", + "\n", + " def add_FlattenLayer(self, act_func=LRELU) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add a FlattenLayer to the CNN, which flattens the image data such that it is formatted to\n", + " be used in the feed forward neural network part of the CNN\n", + " \"\"\"\n", + " self.layers.append(FlattenLayer(act_func=act_func, seed=self.seed))\n", + "\n", + " def add_Convolution2DLayer(\n", + " self,\n", + " input_channels=1,\n", + " feature_maps=1,\n", + " kernel_height=3,\n", + " kernel_width=3,\n", + " v_stride=1,\n", + " h_stride=1,\n", + " pad=\"same\",\n", + " act_func=LRELU,\n", + " optimized=True,\n", + " ) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add a Convolution2DLayer to the CNN, i.e. a convolutional layer with a 2 dimensional kernel. Should be\n", + " the first layer added to the CNN\n", + "\n", + " Parameters:\n", + " ------------\n", + " I input_channels (int) specifies amount of input channels. For monochrome images, use input_channels\n", + " = 1, and input_channels = 3 for colored images, where each channel represents one of R, G and B\n", + " II feature_maps (int) amount of feature maps in CNN\n", + " III kernel_height (int) height of the kernel, also called 'convolutional filter' in literature\n", + " IV kernel_width (int) width of the kernel, also called 'convolutional filter' in literature\n", + " V v_stride (int) value of vertical stride for dimentionality reduction\n", + " VI h_stride (int) value of horizontal stride for dimentionality reduction\n", + " VII pad (str) default = \"same\" ensures output size is the same as input size (given stride=1)\n", + " VIII act_func (activationFunctions) default = \"LRELU\", nonlinear activation function\n", + " IX optimized (bool) default = True, uses Convolution2DLayerOPT if True which is much faster when\n", + " compared to Convolution2DLayer, which is a more straightforward, understandable implementation\n", + " \"\"\"\n", + " if optimized:\n", + " conv_layer = Convolution2DLayerOPT(\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func,\n", + " self.seed,\n", + " reset_weights_independently=False,\n", + " )\n", + " else:\n", + " conv_layer = Convolution2DLayer(\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func,\n", + " self.seed,\n", + " reset_weights_independently=False,\n", + " )\n", + " self.layers.append(conv_layer)\n", + "\n", + " def add_PoolingLayer(\n", + " self, kernel_height=2, kernel_width=2, v_stride=1, h_stride=1, pooling=\"max\"\n", + " ) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add a Pooling2DLayer to the CNN, i.e. a pooling layer that reduces the dimentionality of\n", + " the image data. It is not necessary to use a Pooling2DLayer when creating a CNN, but it\n", + " can be used to speed up the training\n", + "\n", + " Parameters:\n", + " ------------\n", + " I kernel_height (int) height of the kernel used for pooling\n", + " II kernel_width (int) width of the kernel used for pooling\n", + " III v_stride (int) value of vertical stride for dimentionality reduction\n", + " IV h_stride (int) value of horizontal stride for dimentionality reduction\n", + " V pooling (str) either \"max\" or \"average\", describes type of pooling performed\n", + " \"\"\"\n", + " pooling_layer = Pooling2DLayer(\n", + " kernel_height, kernel_width, v_stride, h_stride, pooling, self.seed\n", + " )\n", + " self.layers.append(pooling_layer)\n", + "\n", + " def fit(\n", + " self,\n", + " X: np.ndarray,\n", + " t: np.ndarray,\n", + " epochs: int = 100,\n", + " lam: float = 0,\n", + " batches: int = 1,\n", + " X_val: np.ndarray = None,\n", + " t_val: np.ndarray = None,\n", + " ) -> dict:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Fits the CNN to input X for a given amount of epochs. Performs feedforward and backpropagation passes,\n", + " can utilize batches, regulariziation and validation if desired.\n", + "\n", + " Parameters:\n", + " ------------\n", + " X (numpy array) with input data in format [images, input channels,\n", + " image height, image_width]\n", + " t (numpy array) target labels for input data\n", + " epochs (int) amount of epochs\n", + " lam (float) regulariziation term lambda\n", + " batches (int) amount of batches input data splits into\n", + " X_val (numpy array) validation data\n", + " t_val (numpy array) target labels for validation data\n", + "\n", + " Returns:\n", + " ------------\n", + " scores (dict) a dictionary with \"train_error\", \"train_acc\", \"val_error\", val_acc\" keys\n", + " that contain numpy arrays with float values of all accuracies/errors over all epochs.\n", + " Can be used to create plots. Also used to update the progress bar during training\n", + " \"\"\"\n", + "\n", + " # setup\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " # initialize weights\n", + " self._initialize_weights(X)\n", + "\n", + " # create arrays for score metrics\n", + " scores = self._initialize_scores(epochs)\n", + "\n", + " assert batches <= t.shape[0]\n", + " batch_size = X.shape[0] // batches\n", + "\n", + " try:\n", + " for epoch in range(epochs):\n", + " for batch in range(batches):\n", + " # minibatch gradient descent\n", + " # If the for loop has reached the last batch, take all thats left\n", + " if batch == batches - 1:\n", + " X_batch = X[batch * batch_size :, :, :, :]\n", + " t_batch = t[batch * batch_size :, :]\n", + " else:\n", + " X_batch = X[\n", + " batch * batch_size : (batch + 1) * batch_size, :, :, :\n", + " ]\n", + " t_batch = t[batch * batch_size : (batch + 1) * batch_size, :]\n", + "\n", + " self._feedforward(X_batch)\n", + " self._backpropagate(t_batch, lam)\n", + "\n", + " # reset schedulers for each epoch (some schedulers pass in this call)\n", + " for layer in self.layers:\n", + " if isinstance(layer, FullyConnectedLayer):\n", + " layer._reset_scheduler()\n", + "\n", + " # computing performance metrics\n", + " scores = self._compute_scores(scores, epoch, X, t, X_val, t_val)\n", + "\n", + " # printing progress bar\n", + " print_length = self._progress_bar(\n", + " epoch,\n", + " epochs,\n", + " scores,\n", + " )\n", + " # allows for stopping training at any point and seeing the result\n", + " except KeyboardInterrupt:\n", + " pass\n", + "\n", + " # visualization of training progression (similiar to tensorflow progression bar)\n", + " sys.stdout.write(\"\\r\" + \" \" * print_length)\n", + " sys.stdout.flush()\n", + " self._progress_bar(\n", + " epochs,\n", + " epochs,\n", + " scores,\n", + " )\n", + " sys.stdout.write(\"\")\n", + "\n", + " return scores\n", + "\n", + " def _feedforward(self, X_batch) -> np.ndarray:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Performs the feedforward pass for all layers in the CNN. Called from fit()\n", + " \"\"\"\n", + " a = X_batch\n", + " for layer in self.layers:\n", + " a = layer._feedforward(a)\n", + "\n", + " return a\n", + "\n", + " def _backpropagate(self, t_batch, lam) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Performs backpropagation for all layers in the CNN. Called from fit()\n", + " \"\"\"\n", + " assert len(self.layers) >= 2\n", + " reversed_layers = self.layers[::-1]\n", + "\n", + " # for every layer, backwards\n", + " for i in range(len(reversed_layers) - 1):\n", + " layer = reversed_layers[i]\n", + " prev_layer = reversed_layers[i + 1]\n", + "\n", + " # OutputLayer\n", + " if isinstance(layer, OutputLayer):\n", + " prev_a = prev_layer.get_prev_a()\n", + " weights_next, delta_next = layer._backpropagate(t_batch, prev_a, lam)\n", + "\n", + " # FullyConnectedLayer\n", + " elif isinstance(layer, FullyConnectedLayer):\n", + " assert (\n", + " delta_next is not None\n", + " ), \"No OutputLayer to follow FullyConnectedLayer\"\n", + " assert (\n", + " weights_next is not None\n", + " ), \"No OutputLayer to follow FullyConnectedLayer\"\n", + " prev_a = prev_layer.get_prev_a()\n", + " weights_next, delta_next = layer._backpropagate(\n", + " weights_next, delta_next, prev_a, lam\n", + " )\n", + "\n", + " # FlattenLayer\n", + " elif isinstance(layer, FlattenLayer):\n", + " assert (\n", + " delta_next is not None\n", + " ), \"No FullyConnectedLayer to follow FlattenLayer\"\n", + " assert (\n", + " weights_next is not None\n", + " ), \"No FullyConnectedLayer to follow FlattenLayer\"\n", + " delta_next = layer._backpropagate(weights_next, delta_next)\n", + "\n", + " # Convolution2DLayer and Convolution2DLayerOPT\n", + " elif isinstance(layer, Convolution2DLayer):\n", + " assert (\n", + " delta_next is not None\n", + " ), \"No FlattenLayer to follow Convolution2DLayer\"\n", + " delta_next = layer._backpropagate(delta_next)\n", + "\n", + " # Pooling2DLayer\n", + " elif isinstance(layer, Pooling2DLayer):\n", + " assert delta_next is not None, \"No Layer to follow Pooling2DLayer\"\n", + " delta_next = layer._backpropagate(delta_next)\n", + "\n", + " # Catch error\n", + " else:\n", + " raise NotImplementedError\n", + "\n", + " def _compute_scores(\n", + " self,\n", + " scores: dict,\n", + " epoch: int,\n", + " X: np.ndarray,\n", + " t: np.ndarray,\n", + " X_val: np.ndarray,\n", + " t_val: np.ndarray,\n", + " ) -> dict:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Computes scores such as training error, training accuracy, validation error\n", + " and validation accuracy for the CNN depending on if a validation set is used\n", + " and if the CNN performs classification or regression\n", + "\n", + " Returns:\n", + " ------------\n", + " scores (dict) a dictionary with \"train_error\", \"train_acc\", \"val_error\", val_acc\" keys\n", + " that contain numpy arrays with float values of all accuracies/errors over all epochs.\n", + " Can be used to create plots. Also used to update the progress bar during training\n", + " \"\"\"\n", + "\n", + " pred_train = self.predict(X)\n", + " cost_function_train = self.cost_func(t)\n", + " train_error = cost_function_train(pred_train)\n", + " scores[\"train_error\"][epoch] = train_error\n", + "\n", + " if X_val is not None and t_val is not None:\n", + " cost_function_val = self.cost_func(t_val)\n", + " pred_val = self.predict(X_val)\n", + " val_error = cost_function_val(pred_val)\n", + " scores[\"val_error\"][epoch] = val_error\n", + "\n", + " if self.pred_format != \"Regression\":\n", + " train_acc = self._accuracy(pred_train, t)\n", + " scores[\"train_acc\"][epoch] = train_acc\n", + " if X_val is not None and t_val is not None:\n", + " val_acc = self._accuracy(pred_val, t_val)\n", + " scores[\"val_acc\"][epoch] = val_acc\n", + "\n", + " return scores\n", + "\n", + " def _initialize_scores(self, epochs) -> dict:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Initializes scores such as training error, training accuracy, validation error\n", + " and validation accuracy for the CNN\n", + "\n", + " Returns:\n", + " ------------\n", + " A dictionary with \"train_error\", \"train_acc\", \"val_error\", val_acc\" keys that\n", + " will contain numpy arrays with float values of all accuracies/errors over all epochs\n", + " when passed through the _compute_scores() function during fit()\n", + " \"\"\"\n", + " scores = dict()\n", + "\n", + " train_errors = np.empty(epochs)\n", + " train_errors.fill(np.nan)\n", + " val_errors = np.empty(epochs)\n", + " val_errors.fill(np.nan)\n", + "\n", + " train_accs = np.empty(epochs)\n", + " train_accs.fill(np.nan)\n", + " val_accs = np.empty(epochs)\n", + " val_accs.fill(np.nan)\n", + "\n", + " scores[\"train_error\"] = train_errors\n", + " scores[\"val_error\"] = val_errors\n", + " scores[\"train_acc\"] = train_accs\n", + " scores[\"val_acc\"] = val_accs\n", + "\n", + " return scores\n", + "\n", + " def _initialize_weights(self, X: np.ndarray) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Initializes weights for all layers in CNN\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray) input of format [img, feature_maps, height, width]\n", + " \"\"\"\n", + " prev_nodes = X\n", + " for layer in self.layers:\n", + " prev_nodes = layer._reset_weights(prev_nodes)\n", + "\n", + " def predict(self, X: np.ndarray, *, threshold=0.5) -> np.ndarray:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Predicts output of input X\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray) input [img, feature_maps, height, width]\n", + " \"\"\"\n", + "\n", + " prediction = self._feedforward(X)\n", + "\n", + " if self.pred_format == \"Binary\":\n", + " return np.where(prediction > threshold, 1, 0)\n", + " elif self.pred_format == \"Multi-class\":\n", + " class_prediction = np.zeros(prediction.shape)\n", + " for i in range(prediction.shape[0]):\n", + " class_prediction[i, np.argmax(prediction[i, :])] = 1\n", + " return class_prediction\n", + " else:\n", + " return prediction\n", + "\n", + " def _accuracy(self, prediction: np.ndarray, target: np.ndarray) -> float:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Calculates accuracy of given prediction to target\n", + "\n", + " Parameters:\n", + " ------------\n", + " I prediction (np.ndarray): output of predict() fuction\n", + " (1s and 0s in case of classification, and real numbers in case of regression)\n", + " II target (np.ndarray): vector of true values (What the network should predict)\n", + "\n", + " Returns:\n", + " ------------\n", + " A floating point number representing the percentage of correctly classified instances.\n", + " \"\"\"\n", + " assert prediction.size == target.size\n", + " return np.average((target == prediction))\n", + "\n", + " def _progress_bar(self, epoch: int, epochs: int, scores: dict) -> int:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Displays progress of training\n", + " \"\"\"\n", + " progression = epoch / epochs\n", + " epoch -= 1\n", + " print_length = 40\n", + " num_equals = int(progression * print_length)\n", + " num_not = print_length - num_equals\n", + " arrow = \">\" if num_equals > 0 else \"\"\n", + " bar = \"[\" + \"=\" * (num_equals - 1) + arrow + \"-\" * num_not + \"]\"\n", + " perc_print = self._fmt(progression * 100, N=5)\n", + " line = f\" {bar} {perc_print}% \"\n", + "\n", + " for key, score in scores.items():\n", + " if np.isnan(score[epoch]) == False:\n", + " value = self._fmt(score[epoch], N=4)\n", + " line += f\"| {key}: {value} \"\n", + " print(line, end=\"\\r\")\n", + " return len(line)\n", + "\n", + " def _fmt(self, value: int, N=4) -> str:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Formats decimal numbers for progress bar\n", + " \"\"\"\n", + " if value > 0:\n", + " v = value\n", + " elif value < 0:\n", + " v = -10 * value\n", + " else:\n", + " v = 1\n", + " n = 1 + math.floor(math.log10(v))\n", + " if n >= N - 1:\n", + " return str(round(value))\n", + " # or overflow\n", + " return f\"{value:.{N-n-1}f}\"" + ] + }, + { + "cell_type": "markdown", + "id": "e941a3bc", + "metadata": {}, + "source": [ + "### Usage of CNN code\n", + "\n", + "Using the CNN codebase is very simple. We begin by initiating a CNN\n", + "object, which takes a cost function, a scheduler and a seed as its\n", + "arguments. If a scheduler is not provided, it will per default\n", + "initiate an Adam scheduler with eta=1e-4, and if a seed is not\n", + "provided, the CNN will not be seeded, meaning it will run with a\n", + "different random seed every run. Below we demonstrate an initiation of\n", + "our CNN." + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "d0f1de86", + "metadata": {}, + "outputs": [], + "source": [ + "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", + "cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)" + ] + }, + { + "cell_type": "markdown", + "id": "829d95eb", + "metadata": {}, + "source": [ + "Now that we have our CNN object, we can begin to add layers to it!\n", + "Many of the add_layer functions have default values, for example\n", + "add_Convolution2DLayer() has a default v_stride and h_stride of\n", + "1. However, these can of course be set to any value you please. Note\n", + "that the input channels of a subsequent convolutional layer must equal\n", + "the previous convolutional layer's feature maps." + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "4d56ff10", + "metadata": {}, + "outputs": [], + "source": [ + "cnn.add_Convolution2DLayer(\n", + " input_channels=1,\n", + " feature_maps=1,\n", + " kernel_height=3,\n", + " kernel_width=3,\n", + " act_func=LRELU,\n", + ")\n", + "\n", + "cnn.add_FlattenLayer()\n", + "\n", + "cnn.add_FullyConnectedLayer(30, LRELU)\n", + "\n", + "cnn.add_FullyConnectedLayer(20, LRELU)\n", + "\n", + "cnn.add_OutputLayer(10, softmax)" + ] + }, + { + "cell_type": "markdown", + "id": "bc89efc7", + "metadata": {}, + "source": [ + "Here we have created a CNN with the following architecture:\n", + "\n", + "1. A convolutional layer with 1 input channel, with a kernel height of 2 and a width of 2, which uses LRELU as its non-linearity function. This layer outputs 1 feature map, which feed into the subsequent layer.\n", + "\n", + "2. A flatten layer\n", + "\n", + "3. A hidden layer with 30 nodes, with LRELU as its activation function\n", + "\n", + "4. Another hidden layer but with 20 nodes\n", + "\n", + "5. The output layer, with softmax as its activation function and 10 nodes. We use 10 nodes because we will be using a dataset with 10 classes.\n", + "\n", + "Now, before we can train the model, we need to load in our data. We\n", + "will use the MNIST dataset and use 10000 $28 \\times 28 images$." + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "b51beb67", + "metadata": {}, + "outputs": [], + "source": [ + "from sklearn.datasets import fetch_openml\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "def onehot(target: np.ndarray):\n", + " onehot = np.zeros((target.size, target.max() + 1))\n", + " onehot[np.arange(target.size), target] = 1\n", + " return onehot\n", + "\n", + "# get dataset\n", + "dataset = fetch_openml(\"mnist_784\", parser=\"auto\")\n", + "mnist = dataset.data.to_numpy(dtype=\"float\")[:10000, :]\n", + "\n", + "# scale data\n", + "for i in range(mnist.shape[1]):\n", + " mnist[:, i] /= 255\n", + " \n", + "# reshape to add single input channel to data shape [inputs, input_channels, height, width]\n", + "mnist = mnist.reshape(mnist.shape[0], 1, 28, 28)\n", + "\n", + "# one hot encode target as we are doing multi-class classification\n", + "target = onehot(np.array([int(i) for i in dataset.target.to_numpy()[:10000]]))\n", + "\n", + "# split into training and validation data\n", + "x_train, x_val, y_train, y_val = train_test_split(mnist, target)" + ] + }, + { + "cell_type": "markdown", + "id": "0a876ad7", + "metadata": {}, + "source": [ + "Now we may train our model. Note that we can utilize regularization in\n", + "the CNN by using the lam (lambda) parameter in fit(), and utilize\n", + "different types of gradient descent by specifying the amount of\n", + "batches via the batches parameter as shown below.\n", + "\n", + "The functionfit() returns a score dictionary of the training error and\n", + "accuracy (and validation error and accuracy if a validation set is\n", + "provided) which can be used to plot the error and accuracy of the\n", + "model over epochs." + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "94770f35", + "metadata": {}, + "outputs": [], + "source": [ + "scores = cnn.fit(\n", + " x_train,\n", + " y_train,\n", + " lam=1e-5,\n", + " batches=10,\n", + " epochs=100,\n", + " X_val=x_val,\n", + " t_val=y_val,\n", + ")\n", + "\n", + "plt.plot(scores[\"train_acc\"], label=\"Training\")\n", + "plt.plot(scores[\"val_acc\"], label=\"Validation\")\n", + "plt.ylim([0.8,1])\n", + "plt.xlabel(\"Epochs\")\n", + "plt.ylabel(\"Accuracy\")\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "938a273d", + "metadata": {}, + "source": [ + "Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good.\n", + "\n", + "The codebase allows for great flexibility in CNN\n", + "architectures. Pooling layers can be added before, inbetween or after\n", + "convolutional layers, but due to the great optimizations made within\n", + "Convolution2DLayerOPT, we recommend using the v_stride and h_stride\n", + "parameters in add_Convolution2DLayer() to reduce the dimentionality of\n", + "the problem as the pooling layer is slow in comparison. To use the\n", + "unoptimized version of Convolution2DLayer, simply pass optimized=False\n", + "as an argument in add_Convolution2DLayer().\n", + "\n", + "If one wishes to perform binary classification using the CNN, simply\n", + "use the cost function 'CostLogReg' when initializing the CNN and use 1\n", + "node at the OutputLayer.\n", + "\n", + "Below we have created another, more untraditional architecture using\n", + "our code to demonstrate its flexibility and different attributes such\n", + "as asymmetric stride that might become useful when constructing your\n", + "own CNN." + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "7d7dc9ff", + "metadata": {}, + "outputs": [], + "source": [ + "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", + "cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)\n", + "\n", + "cnn.add_Convolution2DLayer(\n", + " input_channels=1,\n", + " feature_maps=7,\n", + " kernel_height=7,\n", + " kernel_width=1,\n", + " act_func=LRELU,\n", + ")\n", + "\n", + "cnn.add_PoolingLayer(\n", + " kernel_height=2,\n", + " kernel_width=2,\n", + " pooling=\"average\",\n", + ")\n", + "\n", + "cnn.add_PoolingLayer(\n", + " kernel_height=2,\n", + " kernel_width=2,\n", + " pooling=\"max\",\n", + ")\n", + "\n", + "cnn.add_Convolution2DLayer(\n", + " input_channels=7,\n", + " feature_maps=1,\n", + " kernel_height=4,\n", + " kernel_width=4,\n", + " v_stride=2,\n", + " h_stride=3,\n", + " act_func=LRELU,\n", + " optimized=False,\n", + ")\n", + "\n", + "cnn.add_Convolution2DLayer(\n", + " input_channels=1,\n", + " feature_maps=1,\n", + " kernel_height=2,\n", + " kernel_width=2,\n", + " act_func=sigmoid,\n", + " optimized=True,\n", + ")\n", + "\n", + "cnn.add_PoolingLayer(\n", + " kernel_height=2,\n", + " kernel_width=2,\n", + " pooling=\"max\"\n", + ")\n", + "\n", + "cnn.add_FlattenLayer()\n", + "\n", + "cnn.add_FullyConnectedLayer(100, LRELU)\n", + "\n", + "cnn.add_FullyConnectedLayer(10, sigmoid)\n", + "\n", + "cnn.add_FullyConnectedLayer(101, identity)\n", + "\n", + "cnn.add_OutputLayer(10, softmax)" + ] + }, + { + "cell_type": "markdown", + "id": "0c290246", + "metadata": {}, + "source": [ + "Here we see the use of asymmetrical 1D kernels such as the $7 \\times\n", + "1$ kernel in the first convolutional layer, both max and average\n", + "pooling, asymmetric stride in the unoptimized convolutional layer,\n", + "more pooling, a flatten layer, a hidden layer with 100 nodes using\n", + "LRELU, another hidden layer with 10 hidden nodes that uses the sigmoid\n", + "activation function, and another hidden layer with 101 nodes which\n", + "utilizes no activation function (identity). Finally, we arrive at the\n", + "output layer with 10 nodes, which uses softmax as its activation\n", + "function." + ] + }, + { + "cell_type": "markdown", + "id": "71e78b12", + "metadata": {}, + "source": [ + "### Additional Remarks\n", + "\n", + "The stride parameter controls the distance between each convolution\n", + "and the kernel/filter. If our image is padded, stride is the only\n", + "parameter that determines the size of the output from a convolutional\n", + "layer. However, if we decide not to perform any padding, the size of\n", + "the output feature map depends on both the stride and kernel size. It\n", + "is important to note that neither the stride nor the kernel has to be\n", + "symmetrical. This means that we can use a rectangular filter if we\n", + "choose, and the stride in the vertical direction (axis=0 in Python)\n", + "does not need to be the same as the stride in the horizontal direction\n", + "(axis=1 in Python). It may even be the case that asymmetric\n", + "combinations of stride or kernel dimensions, or both, yield better\n", + "results than symmetric values for these parameters." + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "cb88fdfd", + "metadata": {}, + "outputs": [], + "source": [ + "def convolve(image, kernel, stride=1):\n", + " for i in range(2):\n", + " kernel = np.rot90(kernel)\n", + "\n", + " k_half_height = kernel.shape[0] // 2\n", + " k_half_width = kernel.shape[0] // 2\n", + "\n", + " conv_image = np.zeros(image.shape)\n", + " pad_image = padding(image, kernel)\n", + "\n", + " for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):\n", + " for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):\n", + " conv_image[i - k_half_height, j - k_half_width] = np.sum(\n", + " pad_image[\n", + " i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1\n", + " ]\n", + " * kernel\n", + " )\n", + "\n", + " return conv_image" + ] + }, + { + "cell_type": "markdown", + "id": "b3c1ca97", + "metadata": {}, + "source": [ + "### Remarks on the speed\n", + "\n", + "Despite the naive convolution algorithm shown above working finely, it\n", + "is extremely slow, requiring approximately 20-30 seconds to process a\n", + "single image. The time complexity of 2D convolution, which is O(NMnm),\n", + "rapidly becomes a constraint and may, at worst, make computations\n", + "infeasible. Consequently, optimizing the naive 2D convolution\n", + "algorithm is a necessity, as the execution time of the algorithm\n", + "significantly increases as the input data size expands. This can pose\n", + "a bottleneck in applications that necessitate real-time processing of\n", + "large data volumes, such as image and video processing, deep learning,\n", + "and scientific simulations.\n", + "\n", + "To address this issue, we shall present two widely used optimization\n", + "techniques: the separable kernel approach and Fast Fourier Transform\n", + "(FFT). Both of these methods can drastically reduce the computational\n", + "complexity of convolution and enhance the overall efficiency of\n", + "processing substantial data quantities. While we shall refrain from\n", + "delving into the intricacies of these algorithms, we strongly\n", + "encourage you to examine at least the application of FFT to optimize\n", + "computations." + ] + }, + { + "cell_type": "markdown", + "id": "976d307c", + "metadata": {}, + "source": [ + "### Convolution using separable kernels" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "89647600", + "metadata": {}, + "outputs": [], + "source": [ + "def conv2DSep(image, kernel, coef, stride=1, pad=\"zero\"):\n", + " for i in range(2):\n", + " kernel = np.rot90(kernel)\n", + "\n", + " # The kernel is quadratic, thus we only need one of its dimensions\n", + " half_dim = kernel.shape[0] // 2\n", + "\n", + " ker1 = np.array(kernel[0, :])\n", + " ker2 = np.array(kernel[:, 0])\n", + "\n", + " if pad == \"zero\":\n", + " conv_image = np.zeros(image.shape)\n", + " pad_image = padding(image, kernel)\n", + " else:\n", + " conv_image = np.zeros(\n", + " (image.shape[0] - kernel.shape[0], image.shape[1] - kernel.shape[1])\n", + " )\n", + " pad_image = image[:, :]\n", + "\n", + " for i in range(half_dim, conv_image.shape[0] + half_dim, stride):\n", + " for j in range(half_dim, conv_image.shape[1] + half_dim, stride):\n", + " conv_image[i - half_dim, j - half_dim] = (\n", + " pad_image[\n", + " i - half_dim : i + half_dim + 1, j - half_dim : j + half_dim + 1\n", + " ]\n", + " @ ker1\n", + " @ ker2.T\n", + " * coef\n", + " )\n", + "\n", + " return conv_image\n", + "\n", + "img_path = img_path = \"data/IMG-2167.JPG\"\n", + "image_of_cute_dog = imageio.imread(img_path, mode=\"L\")\n", + "start_time = time.time()\n", + "filtered_image = conv2DSep(image_of_cute_dog, kernel=sobel_kernel, coef=1)\n", + "print(f'Time taken for convolution with seperated kernel on 128x128 image {time.time() - start_time}')\n", + "plt.imshow(filtered_image, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "f4baf26f", + "metadata": {}, + "source": [ + "By taking advantage of the capabilities of separable kernels, we can\n", + "effectively cut the computational expense of filtering an image in\n", + "half. Yet, if we seek even more rapid processing, we can turn to the\n", + "Fast Fourier Transform (FFT) algorithm provided by the numpy\n", + "library. By utilizing FFT to transform the input image and filter into\n", + "the frequency domain, we can perform convolution in this domain. This\n", + "approach significantly reduces the number of operations needed and\n", + "results in a marked speedup relative to other convolution\n", + "techniques. In addition, it is worth noting that the FFT is widely\n", + "regarded as one of the most critical algorithms developed to date,\n", + "with applications ranging from digital signal processing to scientific\n", + "computing." + ] + }, + { + "cell_type": "markdown", + "id": "81180d52", + "metadata": {}, + "source": [ + "### Convolution in the Fourier domain" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "8ae65bb6", + "metadata": {}, + "outputs": [], + "source": [ + "start_time = time.time()\n", + "img_fft = np.fft.fft2(image_of_cute_dog)\n", + "kernel_fft = np.fft.fft2(sobel_kernel, s=image_of_cute_dog.shape)\n", + "\n", + "conv_image = img_fft * kernel_fft\n", + "\n", + "filtered_image = np.fft.ifft2(conv_image)\n", + "print(f'Time take for convolution in the fourier domain: {time.time() - start_time}')\n", + "plt.imshow(filtered_image.real, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "78e3becb", + "metadata": {}, + "source": [ + "It is evident that executing convolution in the Fourier domain yields\n", + "the quickest computation time. Nonetheless, one should exercise\n", + "caution, particularly when dealing with images of relatively small\n", + "dimensions, as one of the other methods may prove to be more\n", + "expeditious than FFT-enhanced convolution. The overhead involved in\n", + "transferring both the image and filter into the Fourier domain,\n", + "followed by their subsequent transformation back into the spatial\n", + "domain, results in a minor inconvenience. Therefore, it is imperative\n", + "to remain cognizant of this fact when utilizing FFT as the primary\n", + "optimization technique." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.10" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/LectureNotes/exercisesweek43.ipynb b/doc/LectureNotes/exercisesweek43.ipynb index 96c3390e4..eda98ac3a 100644 --- a/doc/LectureNotes/exercisesweek43.ipynb +++ b/doc/LectureNotes/exercisesweek43.ipynb @@ -3,9 +3,7 @@ { "cell_type": "markdown", "id": "d5ebb4c0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", @@ -15,9 +13,7 @@ { "cell_type": "markdown", "id": "812b4e46", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "# Exercises weeks 43 and 44 \n", "**October 23-27, 2023**\n", @@ -30,9 +26,7 @@ { "cell_type": "markdown", "id": "3230cd2f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "# Overarching aims of the exercises weeks 43 and 44\n", "\n", @@ -70,9 +64,7 @@ { "cell_type": "markdown", "id": "e3617d4e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The AND and XOR Gates\n", "\n", @@ -108,9 +100,7 @@ { "cell_type": "markdown", "id": "54e1e7fc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Representing the Data Sets\n", "\n", @@ -120,9 +110,7 @@ { "cell_type": "markdown", "id": "6b3c15cb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", @@ -135,9 +123,7 @@ { "cell_type": "markdown", "id": "acc25271", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate.\n", "\n", @@ -165,9 +151,7 @@ { "cell_type": "markdown", "id": "ffe0a840", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up dimensionalities by hand\n", "\n", @@ -177,9 +161,7 @@ { "cell_type": "markdown", "id": "46abf545", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{W_h}=\\begin{bmatrix} 1 & 1 \\\\\n", @@ -190,9 +172,7 @@ { "cell_type": "markdown", "id": "86e105cc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Multiplying $\\boldsymbol{X}$ and $\\boldsymbol{W}$ gives" ] @@ -200,9 +180,7 @@ { "cell_type": "markdown", "id": "5e1d21f1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}{W}_h=\\begin{bmatrix} 0 & 0 \\\\\n", @@ -215,9 +193,7 @@ { "cell_type": "markdown", "id": "692c6cbf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Assume also that the bias vector for the hidden layer is" ] @@ -225,9 +201,7 @@ { "cell_type": "markdown", "id": "5d81e641", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{b}_h=\\begin{bmatrix} 0 \\\\\n", @@ -238,9 +212,7 @@ { "cell_type": "markdown", "id": "a42bdee4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Adding it gives us the input to the activation function of the hidden layer" ] @@ -248,9 +220,7 @@ { "cell_type": "markdown", "id": "5116b854", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{z}_h=\\boldsymbol{X}\\boldsymbol{W}_h+\\boldsymbol{b}_h=\\begin{bmatrix} 0 & -1 \\\\\n", @@ -263,9 +233,7 @@ { "cell_type": "markdown", "id": "8dd26d09", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Let us then assume that our activation function is the RELU function, which simply means that we take the max of $0$ and the elements of the input argument $\\boldsymbol{z}_h$, that is we have" ] @@ -273,9 +241,7 @@ { "cell_type": "markdown", "id": "ebf97c03", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{a}_h=\\mathrm{RELU}(\\boldsymbol{z}_h=\\boldsymbol{X}\\boldsymbol{W}_h+\\boldsymbol{b}_h)=\\begin{bmatrix} 0 & 0 \\\\\n", @@ -288,9 +254,7 @@ { "cell_type": "markdown", "id": "262a4a3a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Assume also that the bias of the output layer is zero and that the weights of the output layer are" ] @@ -298,9 +262,7 @@ { "cell_type": "markdown", "id": "f03ad8e7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{w}_o=\\begin{bmatrix} 1 \\\\\n", @@ -311,9 +273,7 @@ { "cell_type": "markdown", "id": "36fe00c0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and multiplying with $\\boldsymbol{a}_h$ gives the output" ] @@ -321,9 +281,7 @@ { "cell_type": "markdown", "id": "80ab43ac", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{a}_o=\\begin{bmatrix} 0 & 0 \\\\\n", @@ -337,9 +295,7 @@ { "cell_type": "markdown", "id": "86bcfe49", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "the wanted result. Pay attention to the dimensionalities as well." ] @@ -347,9 +303,7 @@ { "cell_type": "markdown", "id": "f19a899e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up the Neural Network\n", "\n", @@ -360,10 +314,7 @@ "cell_type": "code", "execution_count": 1, "id": "901ddca7", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", @@ -430,9 +381,7 @@ { "cell_type": "markdown", "id": "53f22266", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." ] @@ -440,9 +389,7 @@ { "cell_type": "markdown", "id": "5f665ac6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The Code using Scikit-Learn" ] @@ -451,10 +398,7 @@ "cell_type": "code", "execution_count": 2, "id": "cb396cda", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# import necessary packages\n", @@ -516,9 +460,7 @@ { "cell_type": "markdown", "id": "c5978471", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Building a neural network code\n", "\n", @@ -535,9 +477,7 @@ { "cell_type": "markdown", "id": "7b82dc46", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Learning rate methods\n", "\n", @@ -557,10 +497,7 @@ "cell_type": "code", "execution_count": 3, "id": "de4dedfb", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -698,9 +635,7 @@ { "cell_type": "markdown", "id": "bb621fce", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Usage of the above learning rate schedulers\n", "\n", @@ -714,10 +649,7 @@ "cell_type": "code", "execution_count": 4, "id": "34ddb829", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", @@ -727,9 +659,7 @@ { "cell_type": "markdown", "id": "e43498d4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Here is a small example for how a segment of code using schedulers\n", "could look. Switching out the schedulers is simple." @@ -739,10 +669,7 @@ "cell_type": "code", "execution_count": 5, "id": "f05b9625", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "weights = np.ones((3,3))\n", @@ -761,9 +688,7 @@ { "cell_type": "markdown", "id": "19cf9841", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Cost functions\n", "\n", @@ -777,10 +702,7 @@ "cell_type": "code", "execution_count": 6, "id": "993efa8d", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -815,9 +737,7 @@ { "cell_type": "markdown", "id": "011c734c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Below we give a short example of how these cost function may be used\n", "to obtain results if you wish to test them out on your own using\n", @@ -828,10 +748,7 @@ "cell_type": "code", "execution_count": 7, "id": "9e1b97f5", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from autograd import grad\n", @@ -849,9 +766,7 @@ { "cell_type": "markdown", "id": "4acd87b2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Activation functions\n", "\n", @@ -865,10 +780,7 @@ "cell_type": "code", "execution_count": 8, "id": "befa86ae", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -923,9 +835,7 @@ { "cell_type": "markdown", "id": "c20aa75e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Below follows a short demonstration of how to use an activation\n", "function. The derivative of the activation function will be important\n", @@ -938,10 +848,7 @@ "cell_type": "code", "execution_count": 9, "id": "e209f9e5", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "z = np.array([[4, 5, 6]]).T\n", @@ -959,9 +866,7 @@ { "cell_type": "markdown", "id": "524b409b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### The Neural Network\n", "\n", @@ -983,10 +888,7 @@ "cell_type": "code", "execution_count": 10, "id": "083116d3", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import math\n", @@ -1455,9 +1357,7 @@ { "cell_type": "markdown", "id": "e4ba55d0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Before we make a model, we will quickly generate a dataset we can use\n", "for our linear regression problem as shown below" @@ -1467,10 +1367,7 @@ "cell_type": "code", "execution_count": 11, "id": "c72a22c6", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1511,9 +1408,7 @@ { "cell_type": "markdown", "id": "25b63b47", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Now that we have our dataset ready for the regression, we can create\n", "our regressor. Note that with the seed parameter, we can make sure our\n", @@ -1527,10 +1422,7 @@ "cell_type": "code", "execution_count": 12, "id": "b6b4e461", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "input_nodes = X_train.shape[1]\n", @@ -1542,9 +1434,7 @@ { "cell_type": "markdown", "id": "d7860b74", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We then fit our model with our training data using the scheduler of our choice." ] @@ -1553,10 +1443,7 @@ "cell_type": "code", "execution_count": 13, "id": "00522c73", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", @@ -1568,9 +1455,7 @@ { "cell_type": "markdown", "id": "a57bfb12", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Due to the progress bar we can see the MSE (train_error) throughout\n", "the FFNN's training. Note that the fit() function has some optional\n", @@ -1584,10 +1469,7 @@ "cell_type": "code", "execution_count": 14, "id": "35259e41", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", @@ -1598,9 +1480,7 @@ { "cell_type": "markdown", "id": "4a403370", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We see that given more epochs to train on, the regressor reaches a lower MSE.\n", "\n", @@ -1613,10 +1493,7 @@ "cell_type": "code", "execution_count": 15, "id": "6c791130", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from sklearn.datasets import load_breast_cancer\n", @@ -1639,10 +1516,7 @@ "cell_type": "code", "execution_count": 16, "id": "0ac0258d", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "input_nodes = X_train.shape[1]\n", @@ -1654,9 +1528,7 @@ { "cell_type": "markdown", "id": "a9c74baa", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We will now make use of our validation data by passing it into our fit function as a keyword argument" ] @@ -1665,10 +1537,7 @@ "cell_type": "code", "execution_count": 17, "id": "e5021bbf", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", @@ -1680,9 +1549,7 @@ { "cell_type": "markdown", "id": "ae0148bb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Finally, we will create a neural network with 2 hidden layers with activation functions." ] @@ -1691,10 +1558,7 @@ "cell_type": "code", "execution_count": 18, "id": "bb7e4340", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "input_nodes = X_train.shape[1]\n", @@ -1711,10 +1575,7 @@ "cell_type": "code", "execution_count": 19, "id": "d0655afb", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", @@ -1726,9 +1587,7 @@ { "cell_type": "markdown", "id": "dc8a90af", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Multiclass classification\n", "\n", @@ -1741,10 +1600,7 @@ "cell_type": "code", "execution_count": 20, "id": "9305c08a", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from sklearn.datasets import load_digits\n", @@ -1778,9 +1634,7 @@ { "cell_type": "markdown", "id": "8e208051", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Testing the XOR gate and other gates\n", "\n", @@ -1791,10 +1645,7 @@ "cell_type": "code", "execution_count": 21, "id": "db016d41", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", @@ -1814,15 +1665,31 @@ { "cell_type": "markdown", "id": "d1384449", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Not bad, but the results depend strongly on the learning reate. Try different learning rates." ] } ], - "metadata": {}, + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.10" + } + }, "nbformat": 4, "nbformat_minor": 5 } diff --git a/doc/LectureNotes/week41.ipynb b/doc/LectureNotes/week41.ipynb index e7bdb5237..7c1e7c629 100644 --- a/doc/LectureNotes/week41.ipynb +++ b/doc/LectureNotes/week41.ipynb @@ -3,9 +3,7 @@ { "cell_type": "markdown", "id": "9a4eccc2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", @@ -15,9 +13,7 @@ { "cell_type": "markdown", "id": "243c5d47", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "# Week 41 Neural networks and constructing a neural network code\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", @@ -28,9 +24,7 @@ { "cell_type": "markdown", "id": "0cae636e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Plan for week 41\n", "\n", @@ -76,9 +70,7 @@ { "cell_type": "markdown", "id": "51ff64f7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Lecture Thursday October 12" ] @@ -86,9 +78,7 @@ { "cell_type": "markdown", "id": "07ff4601", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Introduction to Neural networks\n", "\n", @@ -104,9 +94,7 @@ { "cell_type": "markdown", "id": "4806cddf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Artificial neurons\n", "\n", @@ -128,9 +116,7 @@ { "cell_type": "markdown", "id": "ccfdcf2b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -146,9 +132,7 @@ { "cell_type": "markdown", "id": "900fd38b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Here, the output $y$ of the neuron is the value of its activation function, which have as input\n", "a weighted sum of signals $x_i, \\dots ,x_n$ received by $n$ other neurons.\n", @@ -186,9 +170,7 @@ { "cell_type": "markdown", "id": "15e0098f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Neural network types\n", "\n", @@ -215,9 +197,7 @@ { "cell_type": "markdown", "id": "70d3fe5d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Feed-forward neural networks\n", "\n", @@ -236,9 +216,7 @@ { "cell_type": "markdown", "id": "838210ba", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Convolutional Neural Network\n", "\n", @@ -265,9 +243,7 @@ { "cell_type": "markdown", "id": "8a78d22d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Recurrent neural networks\n", "\n", @@ -286,9 +262,7 @@ { "cell_type": "markdown", "id": "4ca0b479", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Other types of networks\n", "\n", @@ -307,9 +281,7 @@ { "cell_type": "markdown", "id": "b80ebf1a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Multilayer perceptrons\n", "\n", @@ -324,9 +296,7 @@ { "cell_type": "markdown", "id": "749545b4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Why multilayer perceptrons?\n", "\n", @@ -345,9 +315,7 @@ { "cell_type": "markdown", "id": "f524768e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Illustration of a single perceptron model and a multi-perceptron model\n", "\n", @@ -361,9 +329,7 @@ { "cell_type": "markdown", "id": "6c2f8b44", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Examples of XOR, OR and AND gates\n", "\n", @@ -378,10 +344,7 @@ "cell_type": "code", "execution_count": 1, "id": "8dfb9c06", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", @@ -419,9 +382,7 @@ { "cell_type": "markdown", "id": "b0033599", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "What is happening here?" ] @@ -429,9 +390,7 @@ { "cell_type": "markdown", "id": "4663d22e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Does Logistic Regression do a better Job?" ] @@ -440,10 +399,7 @@ "cell_type": "code", "execution_count": 2, "id": "846ae942", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", @@ -502,9 +458,7 @@ { "cell_type": "markdown", "id": "22786e56", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Not exactly impressive, but somewhat better." ] @@ -512,9 +466,7 @@ { "cell_type": "markdown", "id": "b6bdebe1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Adding Neural Networks" ] @@ -523,10 +475,7 @@ "cell_type": "code", "execution_count": 3, "id": "fdfb8244", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "\n", @@ -543,9 +492,7 @@ { "cell_type": "markdown", "id": "13c5155d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Mathematical model\n", "\n", @@ -555,9 +502,7 @@ { "cell_type": "markdown", "id": "47b4c719", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "y = f\\left(\\sum_{i=1}^n w_ix_i + b_i\\right) = f(z),\n", @@ -567,9 +512,7 @@ { "cell_type": "markdown", "id": "d65d78c7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "This function receives $x_i$ as inputs.\n", "Here the activation $z=(\\sum_{i=1}^n w_ix_i+b_i)$. \n", @@ -582,9 +525,7 @@ { "cell_type": "markdown", "id": "b8605d0d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Mathematical model\n", "\n", @@ -594,9 +535,7 @@ { "cell_type": "markdown", "id": "be0a2d56", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -611,9 +550,7 @@ { "cell_type": "markdown", "id": "8a8ec932", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Here $b_i$ is the so-called bias which is normally needed in\n", "case of zero activation weights or inputs. How to fix the biases and\n", @@ -626,9 +563,7 @@ { "cell_type": "markdown", "id": "30b5df75", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -644,9 +579,7 @@ { "cell_type": "markdown", "id": "9906f339", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where we assume that all nodes in the same layer have identical\n", "activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.\n", @@ -656,9 +589,7 @@ { "cell_type": "markdown", "id": "705c18d2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -674,9 +605,7 @@ { "cell_type": "markdown", "id": "c0779fc6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $N_l$ is the number of nodes in layer $l$. When the output of\n", "all the nodes in the first hidden layer are computed, the values of\n", @@ -687,9 +616,7 @@ { "cell_type": "markdown", "id": "128a41e3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Mathematical model\n", "\n", @@ -699,9 +626,7 @@ { "cell_type": "markdown", "id": "e8efb8a6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -717,9 +642,7 @@ { "cell_type": "markdown", "id": "f975dcc6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -735,9 +658,7 @@ { "cell_type": "markdown", "id": "7c3843f7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads" ] @@ -745,9 +666,7 @@ { "cell_type": "markdown", "id": "0008d41a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -763,9 +682,7 @@ { "cell_type": "markdown", "id": "e8dc6d51", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -782,9 +699,7 @@ { "cell_type": "markdown", "id": "1455a093", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Mathematical model\n", "\n", @@ -795,9 +710,7 @@ { "cell_type": "markdown", "id": "c2affab6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -813,9 +726,7 @@ { "cell_type": "markdown", "id": "c7910d23", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which illustrates a basic property of MLPs: The only independent\n", "variables are the input values $x_n$." @@ -824,9 +735,7 @@ { "cell_type": "markdown", "id": "ec9e660d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Mathematical model\n", "\n", @@ -843,9 +752,7 @@ { "cell_type": "markdown", "id": "29c77377", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -861,9 +768,7 @@ { "cell_type": "markdown", "id": "f52146ef", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where the parameters $c_i$ are weights and biases. By adjusting these\n", "parameters, the activation functions can be shifted up and down or\n", @@ -874,9 +779,7 @@ { "cell_type": "markdown", "id": "7f9f65ce", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Matrix-vector notation\n", "\n", @@ -894,9 +797,7 @@ { "cell_type": "markdown", "id": "7aec05b7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -927,9 +828,7 @@ { "cell_type": "markdown", "id": "524f3145", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Matrix-vector notation and activation\n", "\n", @@ -939,9 +838,7 @@ { "cell_type": "markdown", "id": "67ea322c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -958,9 +855,7 @@ { "cell_type": "markdown", "id": "fb2a1836", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "This is not just a convenient and compact notation, but also a useful\n", "and intuitive way to think about MLPs: The output is calculated by a\n", @@ -972,9 +867,7 @@ { "cell_type": "markdown", "id": "c6e37074", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Activation functions\n", "\n", @@ -995,9 +888,7 @@ { "cell_type": "markdown", "id": "516427eb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Activation functions, Logistic and Hyperbolic ones\n", "\n", @@ -1014,9 +905,7 @@ { "cell_type": "markdown", "id": "607e0e1f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f(x) = \\frac{1}{1 + e^{-x}},\n", @@ -1026,9 +915,7 @@ { "cell_type": "markdown", "id": "4147fa7c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and the *hyperbolic tangent* function" ] @@ -1036,9 +923,7 @@ { "cell_type": "markdown", "id": "4c880e2a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f(x) = \\tanh(x)\n", @@ -1048,9 +933,7 @@ { "cell_type": "markdown", "id": "56c9cd1b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Relevance\n", "\n", @@ -1065,10 +948,7 @@ "cell_type": "code", "execution_count": 4, "id": "187aa1c5", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "\"\"\"The sigmoid function (or the logistic curve) is a \n", @@ -1147,9 +1027,7 @@ { "cell_type": "markdown", "id": "e3195fd0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The multilayer perceptron (MLP)\n", "\n", @@ -1185,9 +1063,7 @@ { "cell_type": "markdown", "id": "f15de9c4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## From one to many layers, the universal approximation theorem\n", "\n", @@ -1215,9 +1091,7 @@ { "cell_type": "markdown", "id": "9d79d680", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Deriving the back propagation code for a multilayer perceptron model\n", "\n", @@ -1236,9 +1110,7 @@ { "cell_type": "markdown", "id": "31e1a9b1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "{\\cal C}(\\hat{W}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2,\n", @@ -1248,9 +1120,7 @@ { "cell_type": "markdown", "id": "890921b9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where the $t_i$s are our $n$ targets (the values we want to\n", "reproduce), while the outputs of the network after having propagated\n", @@ -1263,9 +1133,7 @@ { "cell_type": "markdown", "id": "fe55dffb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Definitions\n", "\n", @@ -1280,9 +1148,7 @@ { "cell_type": "markdown", "id": "61548fd5", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "z_j^l = \\sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,\n", @@ -1292,9 +1158,7 @@ { "cell_type": "markdown", "id": "7b437827", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$\n", "represents the total number of nodes/neurons/units of layer $l-1$. The\n", @@ -1305,9 +1169,7 @@ { "cell_type": "markdown", "id": "88aeaf0f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\hat{z}^l = \\left(\\hat{W}^l\\right)^T\\hat{a}^{l-1}+\\hat{b}^l.\n", @@ -1317,9 +1179,7 @@ { "cell_type": "markdown", "id": "d81878b1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "With the activation values $\\hat{z}^l$ we can in turn define the\n", "output of layer $l$ as $\\hat{a}^l = f(\\hat{z}^l)$ where $f$ is our\n", @@ -1331,9 +1191,7 @@ { "cell_type": "markdown", "id": "aa3e6b55", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "a_j^l = f(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n", @@ -1343,9 +1201,7 @@ { "cell_type": "markdown", "id": "282fc0f1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Derivatives and the chain rule\n", "\n", @@ -1355,9 +1211,7 @@ { "cell_type": "markdown", "id": "5007c640", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n", @@ -1367,9 +1221,7 @@ { "cell_type": "markdown", "id": "ed8b0010", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -1377,9 +1229,7 @@ { "cell_type": "markdown", "id": "3174619f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n", @@ -1389,9 +1239,7 @@ { "cell_type": "markdown", "id": "448a714d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "With our definition of the activation function we have that (note that this function depends only on $z_j^l$)" ] @@ -1399,9 +1247,7 @@ { "cell_type": "markdown", "id": "862da704", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial a_j^l}{\\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)).\n", @@ -1411,9 +1257,7 @@ { "cell_type": "markdown", "id": "9958b437", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Derivative of the cost function\n", "\n", @@ -1425,9 +1269,7 @@ { "cell_type": "markdown", "id": "be3a329b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "{\\cal C}(\\hat{W^L}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2=\\frac{1}{2}\\sum_{i=1}^n\\left(a_i^L - t_i\\right)^2,\n", @@ -1437,9 +1279,7 @@ { "cell_type": "markdown", "id": "2237bf2b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The derivative of this function with respect to the weights is" ] @@ -1447,9 +1287,7 @@ { "cell_type": "markdown", "id": "74e6185e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}},\n", @@ -1459,9 +1297,7 @@ { "cell_type": "markdown", "id": "462a7694", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The last partial derivative can easily be computed and reads (by applying the chain rule)" ] @@ -1469,9 +1305,7 @@ { "cell_type": "markdown", "id": "cde99728", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}} = \\frac{\\partial a_j^L}{\\partial z_{j}^{L}}\\frac{\\partial z_j^L}{\\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1},\n", @@ -1481,9 +1315,7 @@ { "cell_type": "markdown", "id": "11c5d932", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Bringing it together, first back propagation equation\n", "\n", @@ -1493,9 +1325,7 @@ { "cell_type": "markdown", "id": "d46a1cc5", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)a_j^L(1-a_j^L)a_k^{L-1},\n", @@ -1505,9 +1335,7 @@ { "cell_type": "markdown", "id": "7f634831", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Defining" ] @@ -1515,9 +1343,7 @@ { "cell_type": "markdown", "id": "c2245dab", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^L = a_j^L(1-a_j^L)\\left(a_j^L - t_j\\right) = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", @@ -1527,9 +1353,7 @@ { "cell_type": "markdown", "id": "fbda1939", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and using the Hadamard product of two vectors we can write this as" ] @@ -1537,9 +1361,7 @@ { "cell_type": "markdown", "id": "54e8fb49", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\hat{\\delta}^L = f'(\\hat{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\hat{a}^L)}.\n", @@ -1549,9 +1371,7 @@ { "cell_type": "markdown", "id": "0fa8b43d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "This is an important expression. The second term on the right handside\n", "measures how fast the cost function is changing as a function of the $j$th\n", @@ -1573,9 +1393,7 @@ { "cell_type": "markdown", "id": "00455d1e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n", @@ -1585,9 +1403,7 @@ { "cell_type": "markdown", "id": "8a503b44", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "With the definition of $\\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely" ] @@ -1595,9 +1411,7 @@ { "cell_type": "markdown", "id": "28aaa847", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1}.\n", @@ -1607,9 +1421,7 @@ { "cell_type": "markdown", "id": "ca7f309e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Derivatives in terms of $z_j^L$\n", "\n", @@ -1619,9 +1431,7 @@ { "cell_type": "markdown", "id": "79b5d957", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^L =\\frac{\\partial {\\cal C}}{\\partial z_j^L}= \\frac{\\partial {\\cal C}}{\\partial a_j^L}\\frac{\\partial a_j^L}{\\partial z_j^L},\n", @@ -1631,9 +1441,7 @@ { "cell_type": "markdown", "id": "ba24b0ba", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely" ] @@ -1641,9 +1449,7 @@ { "cell_type": "markdown", "id": "2f98d5ae", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L}\\frac{\\partial b_j^L}{\\partial z_j^L}=\\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", @@ -1653,9 +1459,7 @@ { "cell_type": "markdown", "id": "596bd7eb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "That is, the error $\\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias." ] @@ -1663,9 +1467,7 @@ { "cell_type": "markdown", "id": "9144dcb7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Bringing it together\n", "\n", @@ -1677,9 +1479,7 @@ { "cell_type": "markdown", "id": "4f2e52cb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -1695,9 +1495,7 @@ { "cell_type": "markdown", "id": "3b94d154", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -1705,9 +1503,7 @@ { "cell_type": "markdown", "id": "18f353fd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -1723,9 +1519,7 @@ { "cell_type": "markdown", "id": "631f4feb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -1733,9 +1527,7 @@ { "cell_type": "markdown", "id": "1793bcd7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -1751,9 +1543,7 @@ { "cell_type": "markdown", "id": "0cc3885e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "An interesting consequence of the above equations is that when the\n", "activation $a_k^{L-1}$ is small, the gradient term, that is the\n", @@ -1778,9 +1568,7 @@ { "cell_type": "markdown", "id": "7f697fec", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Final back propagating equation\n", "\n", @@ -1790,9 +1578,7 @@ { "cell_type": "markdown", "id": "42a9acc8", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n", @@ -1802,9 +1588,7 @@ { "cell_type": "markdown", "id": "ac01943b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have" ] @@ -1812,9 +1596,7 @@ { "cell_type": "markdown", "id": "a6ec5df0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^l =\\sum_k \\frac{\\partial {\\cal C}}{\\partial z_k^{l+1}}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}}=\\sum_k \\delta_k^{l+1}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}},\n", @@ -1824,9 +1606,7 @@ { "cell_type": "markdown", "id": "8b0f324a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and recalling that" ] @@ -1834,9 +1614,7 @@ { "cell_type": "markdown", "id": "4ae4c890", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "z_j^{l+1} = \\sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},\n", @@ -1846,9 +1624,7 @@ { "cell_type": "markdown", "id": "b8af6a3b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "with $M_l$ being the number of nodes in layer $l$, we obtain" ] @@ -1856,9 +1632,7 @@ { "cell_type": "markdown", "id": "c5a36652", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^l =\\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),\n", @@ -1868,9 +1642,7 @@ { "cell_type": "markdown", "id": "eb9f0a42", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "This is our final equation.\n", "\n", @@ -1880,9 +1652,7 @@ { "cell_type": "markdown", "id": "cd78653c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up the Back propagation algorithm\n", "\n", @@ -1903,9 +1673,7 @@ { "cell_type": "markdown", "id": "adab4f13", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", @@ -1915,9 +1683,7 @@ { "cell_type": "markdown", "id": "9091074a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" ] @@ -1925,9 +1691,7 @@ { "cell_type": "markdown", "id": "da04b8a8", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", @@ -1937,9 +1701,7 @@ { "cell_type": "markdown", "id": "d707b6e0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" ] @@ -1947,9 +1709,7 @@ { "cell_type": "markdown", "id": "f26ac396", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", @@ -1959,9 +1719,7 @@ { "cell_type": "markdown", "id": "1d5d1ed0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", @@ -1971,9 +1729,7 @@ { "cell_type": "markdown", "id": "d686cbb0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." @@ -1982,9 +1738,7 @@ { "cell_type": "markdown", "id": "31554688", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up the Back propagation algorithm\n", "\n", @@ -2005,9 +1759,7 @@ { "cell_type": "markdown", "id": "a34466dc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", @@ -2017,9 +1769,7 @@ { "cell_type": "markdown", "id": "742b0899", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" ] @@ -2027,9 +1777,7 @@ { "cell_type": "markdown", "id": "813c7f07", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", @@ -2039,9 +1787,7 @@ { "cell_type": "markdown", "id": "88fccb02", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" ] @@ -2049,9 +1795,7 @@ { "cell_type": "markdown", "id": "a5d5593c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", @@ -2061,9 +1805,7 @@ { "cell_type": "markdown", "id": "1b5aeaa8", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", @@ -2073,9 +1815,7 @@ { "cell_type": "markdown", "id": "29156297", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." @@ -2084,9 +1824,7 @@ { "cell_type": "markdown", "id": "752b2b7a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up the Back propagation algorithm\n", "\n", @@ -2107,9 +1845,7 @@ { "cell_type": "markdown", "id": "29bb348b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", @@ -2119,9 +1855,7 @@ { "cell_type": "markdown", "id": "2cbb4812", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" ] @@ -2129,9 +1863,7 @@ { "cell_type": "markdown", "id": "73fa8d95", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", @@ -2141,9 +1873,7 @@ { "cell_type": "markdown", "id": "d815b24a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" ] @@ -2151,9 +1881,7 @@ { "cell_type": "markdown", "id": "43d2f617", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", @@ -2163,9 +1891,7 @@ { "cell_type": "markdown", "id": "bf7af7f5", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", @@ -2175,9 +1901,7 @@ { "cell_type": "markdown", "id": "9a5e5eaf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." @@ -2186,9 +1910,7 @@ { "cell_type": "markdown", "id": "e62f23f4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up a Multi-layer perceptron model for classification\n", "\n", @@ -2214,9 +1936,7 @@ { "cell_type": "markdown", "id": "42d7a94e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = \\frac{1}{1 + \\exp{(- \\boldsymbol{x}})} ,\n", @@ -2226,9 +1946,7 @@ { "cell_type": "markdown", "id": "5bfea505", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -2236,9 +1954,7 @@ { "cell_type": "markdown", "id": "9f6b8143", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "P(y = 1 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = 1 - P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) ,\n", @@ -2248,9 +1964,7 @@ { "cell_type": "markdown", "id": "194f2cbe", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $y \\in \\{0, 1\\}$ and $\\boldsymbol{\\theta}$ represents the weights and biases\n", "of our network." @@ -2259,9 +1973,7 @@ { "cell_type": "markdown", "id": "20cd18e6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Defining the cost function\n", "\n", @@ -2271,9 +1983,7 @@ { "cell_type": "markdown", "id": "b3e52796", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = - \\sum_{i=1}^n\n", @@ -2284,9 +1994,7 @@ { "cell_type": "markdown", "id": "7cb68d89", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", "for each point in the dataset $\\mathcal{L}_i(\\boldsymbol{\\theta})$. \n", @@ -2309,9 +2017,7 @@ { "cell_type": "markdown", "id": "0a98f80a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "P(y_{ic} = 1 \\mid \\boldsymbol{x}_i, \\boldsymbol{\\theta}) = \\frac{\\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_c)}}\n", @@ -2322,9 +2028,7 @@ { "cell_type": "markdown", "id": "b86447a6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which reduces to the logistic function in the binary case. \n", "The likelihood of this $C$-class classifier\n", @@ -2334,9 +2038,7 @@ { "cell_type": "markdown", "id": "942e0060", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", @@ -2346,9 +2048,7 @@ { "cell_type": "markdown", "id": "99eae6f4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Again we take the negative log-likelihood to define our cost function:" ] @@ -2356,9 +2056,7 @@ { "cell_type": "markdown", "id": "872017e1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\boldsymbol{\\theta})}.\n", @@ -2368,9 +2066,7 @@ { "cell_type": "markdown", "id": "f55259c0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "See the logistic regression lectures for a full definition of the cost function.\n", "\n", @@ -2380,9 +2076,7 @@ { "cell_type": "markdown", "id": "db983bc4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Example: binary classification problem\n", "\n", @@ -2392,9 +2086,7 @@ { "cell_type": "markdown", "id": "165881cf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\boldsymbol{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\boldsymbol{\\beta})}+(1-y_i)\\log{1-p(y_i \\vert x_i,\\boldsymbol{\\beta})}\\right),\n", @@ -2404,9 +2096,7 @@ { "cell_type": "markdown", "id": "50ecaa83", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where we had defined the logistic (sigmoid) function" ] @@ -2414,9 +2104,7 @@ { "cell_type": "markdown", "id": "b16d30f7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "p(y_i =1\\vert x_i,\\boldsymbol{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", @@ -2426,9 +2114,7 @@ { "cell_type": "markdown", "id": "2d4c1829", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -2436,9 +2122,7 @@ { "cell_type": "markdown", "id": "4d7a8c79", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "p(y_i =0\\vert x_i,\\boldsymbol{\\beta})=1-p(y_i =1\\vert x_i,\\boldsymbol{\\beta}).\n", @@ -2448,9 +2132,7 @@ { "cell_type": "markdown", "id": "7c4a0d89", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The parameters $\\boldsymbol{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", "\n", @@ -2461,9 +2143,7 @@ { "cell_type": "markdown", "id": "96bccb9e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", @@ -2473,9 +2153,7 @@ { "cell_type": "markdown", "id": "01f9ae68", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "with" ] @@ -2483,9 +2161,7 @@ { "cell_type": "markdown", "id": "590fc8bd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", @@ -2495,9 +2171,7 @@ { "cell_type": "markdown", "id": "f3dc3a43", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", "Our cost function at the final layer $l=L$ is now" @@ -2506,9 +2180,7 @@ { "cell_type": "markdown", "id": "7dd1bbaa", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\boldsymbol{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(1-t_i)\\log{(1-a_i^L)}\\right),\n", @@ -2518,9 +2190,7 @@ { "cell_type": "markdown", "id": "dc472c94", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" ] @@ -2528,9 +2198,7 @@ { "cell_type": "markdown", "id": "372c5019", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\mathcal{C}(\\boldsymbol{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", @@ -2540,9 +2208,7 @@ { "cell_type": "markdown", "id": "783cc2c1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "In case we use another activation function than the logistic one, we need to evaluate other derivatives." ] @@ -2550,9 +2216,7 @@ { "cell_type": "markdown", "id": "d37a48b8", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The Softmax function\n", "In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need" @@ -2561,9 +2225,7 @@ { "cell_type": "markdown", "id": "e6790133", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", @@ -2574,9 +2236,7 @@ { "cell_type": "markdown", "id": "97578009", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "For the Softmax function we have" ] @@ -2584,9 +2244,7 @@ { "cell_type": "markdown", "id": "13822f62", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", @@ -2596,9 +2254,7 @@ { "cell_type": "markdown", "id": "10bf9fb7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Its derivative with respect to $z_j^l$ gives" ] @@ -2606,9 +2262,7 @@ { "cell_type": "markdown", "id": "cf59a594", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", @@ -2618,9 +2272,7 @@ { "cell_type": "markdown", "id": "80a4d3d7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which in case of the simply binary model reduces to having $i=j$." ] @@ -2628,9 +2280,7 @@ { "cell_type": "markdown", "id": "91baac68", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Developing a code for doing neural networks with back propagation\n", "\n", @@ -2652,9 +2302,7 @@ { "cell_type": "markdown", "id": "b4d8a71e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Collect and pre-process data\n", "\n", @@ -2702,10 +2350,7 @@ "cell_type": "code", "execution_count": 5, "id": "ad941e6f", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# import necessary packages\n", @@ -2755,9 +2400,7 @@ { "cell_type": "markdown", "id": "c2f821dc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Train and test datasets\n", "\n", @@ -2776,10 +2419,7 @@ "cell_type": "code", "execution_count": 6, "id": "d368bcd4", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split\n", @@ -2814,9 +2454,7 @@ { "cell_type": "markdown", "id": "c0e21c2d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Define model and architecture\n", "\n", @@ -2858,9 +2496,7 @@ { "cell_type": "markdown", "id": "ba8404a4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Layers\n", "\n", @@ -2898,9 +2534,7 @@ { "cell_type": "markdown", "id": "5ea9e948", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Weights and biases\n", "\n", @@ -2919,10 +2553,7 @@ "cell_type": "code", "execution_count": 7, "id": "890bc8b7", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# building our neural network\n", @@ -2945,9 +2576,7 @@ { "cell_type": "markdown", "id": "1acc9cfe", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Feed-forward pass\n", "\n", @@ -2973,9 +2602,7 @@ { "cell_type": "markdown", "id": "e13f966a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Matrix multiplications\n", "\n", @@ -3010,10 +2637,7 @@ "cell_type": "code", "execution_count": 8, "id": "8df5db3a", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# setup the feed-forward pass, subscript h = hidden layer\n", @@ -3056,9 +2680,7 @@ { "cell_type": "markdown", "id": "aa73fc1e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Choose cost function and optimizer\n", "\n", @@ -3087,9 +2709,7 @@ { "cell_type": "markdown", "id": "74081e44", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Optimizing the cost function\n", "\n", @@ -3125,9 +2745,7 @@ { "cell_type": "markdown", "id": "1e1c4fe3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Regularization\n", "\n", @@ -3159,9 +2777,7 @@ { "cell_type": "markdown", "id": "6f66a9ad", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Matrix multiplication\n", "\n", @@ -3200,10 +2816,7 @@ "cell_type": "code", "execution_count": 9, "id": "b4ba72fe", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# to categorical turns our integer vector into a onehot representation\n", @@ -3279,9 +2892,7 @@ { "cell_type": "markdown", "id": "1bf824b2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Improving performance\n", "\n", @@ -3300,9 +2911,7 @@ { "cell_type": "markdown", "id": "c98cec8d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Full object-oriented implementation\n", "\n", @@ -3314,10 +2923,7 @@ "cell_type": "code", "execution_count": 10, "id": "26d4691e", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "class NeuralNetwork:\n", @@ -3424,9 +3030,7 @@ { "cell_type": "markdown", "id": "24f75613", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Evaluate model performance on test data\n", "\n", @@ -3443,10 +3047,7 @@ "cell_type": "code", "execution_count": 11, "id": "52a987ae", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "epochs = 100\n", @@ -3470,9 +3071,7 @@ { "cell_type": "markdown", "id": "1605eb14", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Adjust hyperparameters\n", "\n", @@ -3484,10 +3083,7 @@ "cell_type": "code", "execution_count": 12, "id": "952131d2", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "eta_vals = np.logspace(-5, 1, 7)\n", @@ -3515,9 +3111,7 @@ { "cell_type": "markdown", "id": "182a8a49", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Visualization" ] @@ -3526,10 +3120,7 @@ "cell_type": "code", "execution_count": 13, "id": "d3d1b7d5", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# visual representation of grid search\n", @@ -3570,9 +3161,7 @@ { "cell_type": "markdown", "id": "aa705900", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## scikit-learn implementation\n", "\n", @@ -3593,10 +3182,7 @@ "cell_type": "code", "execution_count": 14, "id": "09c32314", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from sklearn.neural_network import MLPClassifier\n", @@ -3620,9 +3206,7 @@ { "cell_type": "markdown", "id": "fde4721e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Visualization" ] @@ -3631,10 +3215,7 @@ "cell_type": "code", "execution_count": 15, "id": "e855729e", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# optional\n", @@ -3676,9 +3257,7 @@ { "cell_type": "markdown", "id": "765ac227", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Testing our code for the XOR, OR and AND gates\n", "\n", @@ -3703,9 +3282,7 @@ { "cell_type": "markdown", "id": "02d395cd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The AND and XOR Gates\n", "\n", @@ -3741,9 +3318,7 @@ { "cell_type": "markdown", "id": "0fba1e7d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Representing the Data Sets\n", "\n", @@ -3753,9 +3328,7 @@ { "cell_type": "markdown", "id": "9a3c4e68", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", @@ -3768,9 +3341,7 @@ { "cell_type": "markdown", "id": "545fccde", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate." ] @@ -3778,9 +3349,7 @@ { "cell_type": "markdown", "id": "678395d0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up the Neural Network\n", "\n", @@ -3791,10 +3360,7 @@ "cell_type": "code", "execution_count": 16, "id": "7c64daef", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", @@ -3867,9 +3433,7 @@ { "cell_type": "markdown", "id": "c35ff8f2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." ] @@ -3877,9 +3441,7 @@ { "cell_type": "markdown", "id": "3b5396c0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The Code using Scikit-Learn" ] @@ -3888,10 +3450,7 @@ "cell_type": "code", "execution_count": 17, "id": "3d4e508b", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# import necessary packages\n", @@ -3954,7 +3513,25 @@ ] } ], - "metadata": {}, + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.10" + } + }, "nbformat": 4, "nbformat_minor": 5 } diff --git a/doc/LectureNotes/week42.ipynb b/doc/LectureNotes/week42.ipynb index 99df66e64..8d7906a77 100644 --- a/doc/LectureNotes/week42.ipynb +++ b/doc/LectureNotes/week42.ipynb @@ -3,9 +3,7 @@ { "cell_type": "markdown", "id": "bbaa1aec", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", @@ -15,9 +13,7 @@ { "cell_type": "markdown", "id": "d981139a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "# Week 42 Constructing a Neural Network code with introduction to Tensor flow\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", @@ -28,9 +24,7 @@ { "cell_type": "markdown", "id": "d3d2fdcb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Plan for week 42\n", "\n", @@ -74,9 +68,7 @@ { "cell_type": "markdown", "id": "8e0c0ad3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Lecture Thursday October 19" ] @@ -84,9 +76,7 @@ { "cell_type": "markdown", "id": "6d072b79", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Review of the back propagation algorithm\n", "\n", @@ -99,9 +89,7 @@ { "cell_type": "markdown", "id": "6a5894d2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up the Back propagation algorithm\n", "\n", @@ -122,9 +110,7 @@ { "cell_type": "markdown", "id": "47296efd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", @@ -134,9 +120,7 @@ { "cell_type": "markdown", "id": "598d3a19", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" ] @@ -144,9 +128,7 @@ { "cell_type": "markdown", "id": "7077d9c2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", @@ -156,9 +138,7 @@ { "cell_type": "markdown", "id": "c62043b3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" ] @@ -166,9 +146,7 @@ { "cell_type": "markdown", "id": "3307a4bc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", @@ -178,9 +156,7 @@ { "cell_type": "markdown", "id": "50db23f1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", @@ -190,9 +166,7 @@ { "cell_type": "markdown", "id": "0cf89ca4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." @@ -201,9 +175,7 @@ { "cell_type": "markdown", "id": "d5374d6f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up a Multi-layer perceptron model for classification\n", "\n", @@ -229,9 +201,7 @@ { "cell_type": "markdown", "id": "fc8ce130", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = \\frac{1}{1 + \\exp{(- \\boldsymbol{x}})} ,\n", @@ -241,9 +211,7 @@ { "cell_type": "markdown", "id": "8eaf0c3c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -251,9 +219,7 @@ { "cell_type": "markdown", "id": "3caeb6b3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "P(y = 1 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = 1 - P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) ,\n", @@ -263,9 +229,7 @@ { "cell_type": "markdown", "id": "cb5b4f3d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $y \\in \\{0, 1\\}$ and $\\boldsymbol{\\theta}$ represents the weights and biases\n", "of our network." @@ -274,9 +238,7 @@ { "cell_type": "markdown", "id": "6edbd945", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Defining the cost function\n", "\n", @@ -286,9 +248,7 @@ { "cell_type": "markdown", "id": "3e039295", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = - \\sum_{i=1}^n\n", @@ -299,9 +259,7 @@ { "cell_type": "markdown", "id": "60d3b57c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", "for each point in the dataset $\\mathcal{L}_i(\\boldsymbol{\\theta})$. \n", @@ -324,9 +282,7 @@ { "cell_type": "markdown", "id": "9045875f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "P(y_{ic} = 1 \\mid \\boldsymbol{x}_i, \\boldsymbol{\\theta}) = \\frac{\\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_c)}}\n", @@ -337,9 +293,7 @@ { "cell_type": "markdown", "id": "1d37a3a2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which reduces to the logistic function in the binary case. \n", "The likelihood of this $C$-class classifier\n", @@ -349,9 +303,7 @@ { "cell_type": "markdown", "id": "429c3549", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", @@ -361,9 +313,7 @@ { "cell_type": "markdown", "id": "cde118d9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Again we take the negative log-likelihood to define our cost function:" ] @@ -371,9 +321,7 @@ { "cell_type": "markdown", "id": "16740280", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\boldsymbol{\\theta})}.\n", @@ -383,9 +331,7 @@ { "cell_type": "markdown", "id": "a4b60c6f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "See the logistic regression lectures for a full definition of the cost function.\n", "\n", @@ -395,9 +341,7 @@ { "cell_type": "markdown", "id": "36cce044", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Example: binary classification problem\n", "\n", @@ -407,9 +351,7 @@ { "cell_type": "markdown", "id": "d2cc5185", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\boldsymbol{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\boldsymbol{\\beta})}+(1-y_i)\\log{1-p(y_i \\vert x_i,\\boldsymbol{\\beta})}\\right),\n", @@ -419,9 +361,7 @@ { "cell_type": "markdown", "id": "6f62ac34", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where we had defined the logistic (sigmoid) function" ] @@ -429,9 +369,7 @@ { "cell_type": "markdown", "id": "980d2595", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "p(y_i =1\\vert x_i,\\boldsymbol{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", @@ -441,9 +379,7 @@ { "cell_type": "markdown", "id": "07f96bba", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -451,9 +387,7 @@ { "cell_type": "markdown", "id": "ab7ef463", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "p(y_i =0\\vert x_i,\\boldsymbol{\\beta})=1-p(y_i =1\\vert x_i,\\boldsymbol{\\beta}).\n", @@ -463,9 +397,7 @@ { "cell_type": "markdown", "id": "712f14c5", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The parameters $\\boldsymbol{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", "\n", @@ -476,9 +408,7 @@ { "cell_type": "markdown", "id": "efb3f21c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", @@ -488,9 +418,7 @@ { "cell_type": "markdown", "id": "661dd5e4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "with" ] @@ -498,9 +426,7 @@ { "cell_type": "markdown", "id": "545879f3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", @@ -510,9 +436,7 @@ { "cell_type": "markdown", "id": "20187a39", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", "Our cost function at the final layer $l=L$ is now" @@ -521,9 +445,7 @@ { "cell_type": "markdown", "id": "ecd3c551", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\boldsymbol{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(1-t_i)\\log{(1-a_i^L)}\\right),\n", @@ -533,9 +455,7 @@ { "cell_type": "markdown", "id": "03d1bd2b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" ] @@ -543,9 +463,7 @@ { "cell_type": "markdown", "id": "1baaf3b0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\mathcal{C}(\\boldsymbol{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", @@ -555,9 +473,7 @@ { "cell_type": "markdown", "id": "9114b454", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "In case we use another activation function than the logistic one, we need to evaluate other derivatives." ] @@ -565,9 +481,7 @@ { "cell_type": "markdown", "id": "19b41dd4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The Softmax function\n", "In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need" @@ -576,9 +490,7 @@ { "cell_type": "markdown", "id": "bc1b97c5", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", @@ -589,9 +501,7 @@ { "cell_type": "markdown", "id": "52f2e768", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "For the Softmax function we have" ] @@ -599,9 +509,7 @@ { "cell_type": "markdown", "id": "1a60c363", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", @@ -611,9 +519,7 @@ { "cell_type": "markdown", "id": "93eb34b6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Its derivative with respect to $z_j^l$ gives" ] @@ -621,9 +527,7 @@ { "cell_type": "markdown", "id": "aa26229f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", @@ -633,9 +537,7 @@ { "cell_type": "markdown", "id": "1f075e8c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which in case of the simply binary model reduces to having $i=j$." ] @@ -643,9 +545,7 @@ { "cell_type": "markdown", "id": "b0cb8b0e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Developing a code for doing neural networks with back propagation\n", "\n", @@ -667,9 +567,7 @@ { "cell_type": "markdown", "id": "c4cd71b6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Collect and pre-process data\n", "\n", @@ -717,10 +615,7 @@ "cell_type": "code", "execution_count": 1, "id": "ca43227b", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", @@ -772,9 +667,7 @@ { "cell_type": "markdown", "id": "79f4798f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Train and test datasets\n", "\n", @@ -793,10 +686,7 @@ "cell_type": "code", "execution_count": 2, "id": "38e01634", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split\n", @@ -831,9 +721,7 @@ { "cell_type": "markdown", "id": "faca5ec2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Define model and architecture\n", "\n", @@ -875,9 +763,7 @@ { "cell_type": "markdown", "id": "e720f042", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Layers\n", "\n", @@ -915,9 +801,7 @@ { "cell_type": "markdown", "id": "b4a3815d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Weights and biases\n", "\n", @@ -936,10 +820,7 @@ "cell_type": "code", "execution_count": 3, "id": "5c7ae6ce", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# building our neural network\n", @@ -962,9 +843,7 @@ { "cell_type": "markdown", "id": "bc289dbd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Feed-forward pass\n", "\n", @@ -990,9 +869,7 @@ { "cell_type": "markdown", "id": "3e93f012", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Matrix multiplications\n", "\n", @@ -1027,10 +904,7 @@ "cell_type": "code", "execution_count": 4, "id": "31084597", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# setup the feed-forward pass, subscript h = hidden layer\n", @@ -1073,9 +947,7 @@ { "cell_type": "markdown", "id": "93ca9a82", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Choose cost function and optimizer\n", "\n", @@ -1104,9 +976,7 @@ { "cell_type": "markdown", "id": "59ad4e01", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Optimizing the cost function\n", "\n", @@ -1142,9 +1012,7 @@ { "cell_type": "markdown", "id": "d017d149", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Regularization\n", "\n", @@ -1176,9 +1044,7 @@ { "cell_type": "markdown", "id": "3b624b6e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Matrix multiplication\n", "\n", @@ -1217,10 +1083,7 @@ "cell_type": "code", "execution_count": 5, "id": "39eabb7a", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# to categorical turns our integer vector into a onehot representation\n", @@ -1296,9 +1159,7 @@ { "cell_type": "markdown", "id": "22c14a38", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Improving performance\n", "\n", @@ -1317,9 +1178,7 @@ { "cell_type": "markdown", "id": "33d33cf6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Full object-oriented implementation\n", "\n", @@ -1331,10 +1190,7 @@ "cell_type": "code", "execution_count": 6, "id": "a5009498", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "class NeuralNetwork:\n", @@ -1441,9 +1297,7 @@ { "cell_type": "markdown", "id": "68639daa", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Evaluate model performance on test data\n", "\n", @@ -1460,10 +1314,7 @@ "cell_type": "code", "execution_count": 7, "id": "487c6612", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "epochs = 100\n", @@ -1487,9 +1338,7 @@ { "cell_type": "markdown", "id": "c3b10024", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Adjust hyperparameters\n", "\n", @@ -1501,10 +1350,7 @@ "cell_type": "code", "execution_count": 8, "id": "7ab55f7a", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "eta_vals = np.logspace(-5, 1, 7)\n", @@ -1532,9 +1378,7 @@ { "cell_type": "markdown", "id": "aa9d91e2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Visualization" ] @@ -1543,10 +1387,7 @@ "cell_type": "code", "execution_count": 9, "id": "ce6b84ae", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# visual representation of grid search\n", @@ -1587,9 +1428,7 @@ { "cell_type": "markdown", "id": "1d50ccf4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## scikit-learn implementation\n", "\n", @@ -1610,10 +1449,7 @@ "cell_type": "code", "execution_count": 10, "id": "05cc9271", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from sklearn.neural_network import MLPClassifier\n", @@ -1637,9 +1473,7 @@ { "cell_type": "markdown", "id": "9f51a74d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Visualization" ] @@ -1648,10 +1482,7 @@ "cell_type": "code", "execution_count": 11, "id": "38a896b8", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# optional\n", @@ -1693,9 +1524,7 @@ { "cell_type": "markdown", "id": "f8ee3eb3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Testing our code for the XOR, OR and AND gates\n", "\n", @@ -1720,9 +1549,7 @@ { "cell_type": "markdown", "id": "5c0e406c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The AND and XOR Gates\n", "\n", @@ -1758,9 +1585,7 @@ { "cell_type": "markdown", "id": "f52ee7dd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Representing the Data Sets\n", "\n", @@ -1770,9 +1595,7 @@ { "cell_type": "markdown", "id": "f2634e6f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", @@ -1785,9 +1608,7 @@ { "cell_type": "markdown", "id": "a39715fe", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate." ] @@ -1795,9 +1616,7 @@ { "cell_type": "markdown", "id": "8bff01b2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting up the Neural Network\n", "\n", @@ -1808,10 +1627,7 @@ "cell_type": "code", "execution_count": 12, "id": "9d94da1e", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", @@ -1884,9 +1700,7 @@ { "cell_type": "markdown", "id": "fdbce6ba", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." ] @@ -1894,9 +1708,7 @@ { "cell_type": "markdown", "id": "f5cbb06d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The Code using Scikit-Learn" ] @@ -1905,10 +1717,7 @@ "cell_type": "code", "execution_count": 13, "id": "edf69ad3", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# import necessary packages\n", @@ -1973,9 +1782,7 @@ { "cell_type": "markdown", "id": "d5e5d8a0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Building neural networks in Tensorflow and Keras\n", "\n", @@ -1991,9 +1798,7 @@ { "cell_type": "markdown", "id": "8326a878", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Tensorflow\n", "\n", @@ -2026,10 +1831,7 @@ "cell_type": "code", "execution_count": 14, "id": "dd988cfc", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "pip3 install tensorflow" @@ -2038,9 +1840,7 @@ { "cell_type": "markdown", "id": "d2f8d6f3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and/or if you use **anaconda**, just write (or install from the graphical user interface)\n", "(current release of CPU-only TensorFlow)" @@ -2050,10 +1850,7 @@ "cell_type": "code", "execution_count": 15, "id": "fdaffccc", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "conda create -n tf tensorflow\n", @@ -2063,9 +1860,7 @@ { "cell_type": "markdown", "id": "80db034a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "To install the current release of GPU TensorFlow" ] @@ -2074,10 +1869,7 @@ "cell_type": "code", "execution_count": 16, "id": "e632c541", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "conda create -n tf-gpu tensorflow-gpu\n", @@ -2087,9 +1879,7 @@ { "cell_type": "markdown", "id": "605ac1fd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Using Keras\n", "\n", @@ -2102,10 +1892,7 @@ "cell_type": "code", "execution_count": 17, "id": "11e69ce0", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "conda install keras" @@ -2114,9 +1901,7 @@ { "cell_type": "markdown", "id": "176bf3ac", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "You can look up the [instructions here](https://keras.io/) for more information.\n", "\n", @@ -2126,9 +1911,7 @@ { "cell_type": "markdown", "id": "7a085449", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Collect and pre-process data\n", "\n", @@ -2139,10 +1922,7 @@ "cell_type": "code", "execution_count": 18, "id": "d8bae540", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# import necessary packages\n", @@ -2194,10 +1974,7 @@ "cell_type": "code", "execution_count": 19, "id": "5608d691", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from tensorflow.keras.layers import Input\n", @@ -2223,10 +2000,7 @@ "cell_type": "code", "execution_count": 20, "id": "7bce7422", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "\n", @@ -2253,10 +2027,7 @@ "cell_type": "code", "execution_count": 21, "id": "65a68468", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", @@ -2280,10 +2051,7 @@ "cell_type": "code", "execution_count": 22, "id": "45ae200f", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# optional\n", @@ -2322,9 +2090,7 @@ { "cell_type": "markdown", "id": "b955ad39", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The Breast Cancer Data, now with Keras" ] @@ -2333,10 +2099,7 @@ "cell_type": "code", "execution_count": 23, "id": "8ed2e257", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "\n", @@ -2510,9 +2273,7 @@ { "cell_type": "markdown", "id": "107bab25", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Fine-tuning neural network hyperparameters\n", "\n", @@ -2538,9 +2299,7 @@ { "cell_type": "markdown", "id": "53ad43ce", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Hidden layers\n", "\n", @@ -2561,9 +2320,7 @@ { "cell_type": "markdown", "id": "6f613497", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Which activation function should I use?\n", "\n", @@ -2592,9 +2349,7 @@ { "cell_type": "markdown", "id": "91843fee", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Is the Logistic activation function (Sigmoid) our choice?\n", "\n", @@ -2624,9 +2379,7 @@ { "cell_type": "markdown", "id": "83535426", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The derivative of the Logistic funtion\n", "\n", @@ -2662,9 +2415,7 @@ { "cell_type": "markdown", "id": "37bdca60", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The RELU function family\n", "\n", @@ -2687,9 +2438,7 @@ { "cell_type": "markdown", "id": "11ae19d2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", @@ -2699,9 +2448,7 @@ { "cell_type": "markdown", "id": "f3a54f08", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Which activation function should we use?\n", "\n", @@ -2722,9 +2469,7 @@ { "cell_type": "markdown", "id": "4dd226db", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## More on activation functions, output layers\n", "\n", @@ -2742,9 +2487,7 @@ { "cell_type": "markdown", "id": "f9521d8f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Batch Normalization\n", "\n", @@ -2764,9 +2507,7 @@ { "cell_type": "markdown", "id": "080c7f12", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Dropout\n", "\n", @@ -2782,9 +2523,7 @@ { "cell_type": "markdown", "id": "963e7d21", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Gradient Clipping\n", "\n", @@ -2801,9 +2540,7 @@ { "cell_type": "markdown", "id": "0b69f45e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## A very nice website on Neural Networks\n", "\n", @@ -2813,9 +2550,7 @@ { "cell_type": "markdown", "id": "3585dfbf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## A top-down perspective on Neural networks\n", "\n", @@ -2858,9 +2593,7 @@ { "cell_type": "markdown", "id": "dd7c4575", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Limitations of supervised learning with deep networks\n", "\n", @@ -2886,7 +2619,25 @@ ] } ], - "metadata": {}, + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.10" + } + }, "nbformat": 4, "nbformat_minor": 5 } diff --git a/doc/LectureNotes/week44.ipynb b/doc/LectureNotes/week44.ipynb index ad54b59cc..b188679e4 100644 --- a/doc/LectureNotes/week44.ipynb +++ b/doc/LectureNotes/week44.ipynb @@ -3,9 +3,7 @@ { "cell_type": "markdown", "id": "ba617ce1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", @@ -15,9 +13,7 @@ { "cell_type": "markdown", "id": "0aef8b39", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "# Week 44, Convolutional Neural Networks (CNN)\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", @@ -28,9 +24,7 @@ { "cell_type": "markdown", "id": "963a2f0d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Plan for week 44\n", "\n", @@ -72,9 +66,7 @@ { "cell_type": "markdown", "id": "55d065ae", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Material for Lecture Thursday November 2" ] @@ -82,9 +74,7 @@ { "cell_type": "markdown", "id": "59207a59", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Convolutional Neural Networks (recognizing images)\n", "\n", @@ -109,9 +99,7 @@ { "cell_type": "markdown", "id": "5dbf2651", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## What is the Difference\n", "\n", @@ -125,9 +113,7 @@ { "cell_type": "markdown", "id": "805d6ec9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Neural Networks vs CNNs\n", "\n", @@ -143,9 +129,7 @@ { "cell_type": "markdown", "id": "040f7963", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Why CNNS for images, sound files, medical images from CT scans etc?\n", "\n", @@ -173,9 +157,7 @@ { "cell_type": "markdown", "id": "0b2761a4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Regular NNs don’t scale well to full images\n", "\n", @@ -203,9 +185,7 @@ { "cell_type": "markdown", "id": "148c281c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## 3D volumes of neurons\n", "\n", @@ -243,9 +223,7 @@ { "cell_type": "markdown", "id": "a8cd3791", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Layers used to build CNNs\n", "\n", @@ -272,9 +250,7 @@ { "cell_type": "markdown", "id": "dbfdb1bb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Transforming images\n", "\n", @@ -294,9 +270,7 @@ { "cell_type": "markdown", "id": "ef624344", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## CNNs in brief\n", "\n", @@ -322,9 +296,7 @@ { "cell_type": "markdown", "id": "222c06f9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Key Idea\n", "\n", @@ -339,9 +311,7 @@ { "cell_type": "markdown", "id": "a16255ff", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Mathematics of CNNs\n", "\n", @@ -359,9 +329,7 @@ { "cell_type": "markdown", "id": "8e7516b9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "y(t) = \\int x(a) w(t-a) da,\n", @@ -371,9 +339,7 @@ { "cell_type": "markdown", "id": "9e141e69", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $x(a)$ represents a so-called input and $w(t-a)$ is normally called the weight function or kernel.\n", "\n", @@ -383,9 +349,7 @@ { "cell_type": "markdown", "id": "3b5e0f3e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "y(t) = \\left(x * w\\right)(t).\n", @@ -395,9 +359,7 @@ { "cell_type": "markdown", "id": "94239c1e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The discretized version reads" ] @@ -405,9 +367,7 @@ { "cell_type": "markdown", "id": "4c025970", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "y(t) = \\sum_{a=-\\infty}^{a=\\infty}x(a)w(t-a).\n", @@ -417,9 +377,7 @@ { "cell_type": "markdown", "id": "f957e92b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Computing the inverse of the above convolution operations is known as deconvolution.\n", "\n", @@ -429,9 +387,7 @@ { "cell_type": "markdown", "id": "c1c2091a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Convolution Examples: Polynomial multiplication\n", "\n", @@ -444,9 +400,7 @@ { "cell_type": "markdown", "id": "4d4c8d1a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "p(t) = \\alpha_0+\\alpha_1 t+\\alpha_2 t^2,\n", @@ -456,9 +410,7 @@ { "cell_type": "markdown", "id": "05c9d6b9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -466,9 +418,7 @@ { "cell_type": "markdown", "id": "97f48245", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "s(t) = \\beta_0+\\beta_1 t+\\beta_2 t^2+\\beta_3 t^3.\n", @@ -478,9 +428,7 @@ { "cell_type": "markdown", "id": "5166255e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The polynomial multiplication gives us a new polynomial of degree $5$" ] @@ -488,9 +436,7 @@ { "cell_type": "markdown", "id": "295382a6", - "metadata": { - "editable": true - }, + "metadata": {}, "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", @@ -500,9 +446,7 @@ { "cell_type": "markdown", "id": "5eaf190d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Efficient Polynomial Multiplication\n", "\n", @@ -513,9 +457,7 @@ { "cell_type": "markdown", "id": "0f92301f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\begin{split}\n", @@ -532,9 +474,7 @@ { "cell_type": "markdown", "id": "0199fc42", - "metadata": { - "editable": true - }, + "metadata": {}, "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", @@ -544,9 +484,7 @@ { "cell_type": "markdown", "id": "3b34d0b1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_j = \\sum_{i=-\\infty}^{i=\\infty}\\alpha_i\\beta_{j-i}=(\\alpha * \\beta)_j,\n", @@ -556,9 +494,7 @@ { "cell_type": "markdown", "id": "4796ab01", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "or as a double sum with restriction $l=i+j$" ] @@ -566,9 +502,7 @@ { "cell_type": "markdown", "id": "b2d1bf1d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\delta_l = \\sum_{ij}\\alpha_i\\beta_{j}.\n", @@ -578,9 +512,7 @@ { "cell_type": "markdown", "id": "0aa6a56e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Do you see a potential drawback with these equations?" ] @@ -588,9 +520,7 @@ { "cell_type": "markdown", "id": "b1063211", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## A more efficient way of coding the above Convolution\n", "\n", @@ -602,9 +532,7 @@ { "cell_type": "markdown", "id": "65bff227", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\delta}=\\begin{bmatrix}\\alpha_0 & 0 & 0 & 0 \\\\\n", @@ -620,9 +548,7 @@ { "cell_type": "markdown", "id": "19c391a4", - "metadata": { - "editable": true - }, + "metadata": {}, "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" @@ -631,9 +557,7 @@ { "cell_type": "markdown", "id": "35aa0736", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\delta}=\\begin{bmatrix}\\beta_0 & 0 & 0 \\\\\n", @@ -649,9 +573,7 @@ { "cell_type": "markdown", "id": "f30929d8", - "metadata": { - "editable": true - }, + "metadata": {}, "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", @@ -669,9 +591,7 @@ { "cell_type": "markdown", "id": "b92c89bf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{A}=\\begin{bmatrix}a_0 & 0 & 0 \\\\\n", @@ -687,9 +607,7 @@ { "cell_type": "markdown", "id": "58677db5", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "with elements $a_{ii}=a_{i+1,j+1}=a_{i-j}$ is an example of a Toeplitz\n", "matrix. Such a matrix does not need to be a square matrix. Toeplitz\n", @@ -704,9 +622,7 @@ { "cell_type": "markdown", "id": "51de5ea3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms)\n", "\n", @@ -716,9 +632,7 @@ { "cell_type": "markdown", "id": "8fa65373", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "m\\frac{d^2x}{dt^2}+\\eta\\frac{dx}{dt}+x(t)=F(t),\n", @@ -728,9 +642,7 @@ { "cell_type": "markdown", "id": "ca8f7fbb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $F(t)$ is an applied external force acting on the system (often\n", "called a driving force), one can use the theory of Fourier\n", @@ -744,9 +656,7 @@ { "cell_type": "markdown", "id": "d8afff8f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -762,9 +672,7 @@ { "cell_type": "markdown", "id": "cfe7c6cb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "This is known as the principle of superposition. It only applies when\n", "the homogenous equation is linear. \n", @@ -779,9 +687,7 @@ { "cell_type": "markdown", "id": "e4cb68fd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\begin{eqnarray}\n", @@ -793,9 +699,7 @@ { "cell_type": "markdown", "id": "9668712e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "One example of a non-sinusoidal periodic force is a square wave. Many\n", "components in electric circuits are non-linear, for example diodes. This \n", @@ -806,9 +710,7 @@ { "cell_type": "markdown", "id": "a47455dc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Simple Code Example\n", "\n", @@ -821,10 +723,7 @@ "cell_type": "code", "execution_count": 1, "id": "ea14d21d", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", @@ -851,9 +750,7 @@ { "cell_type": "markdown", "id": "d12e3c32", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "For the sinusoidal example the\n", "period is $\\tau=2\\pi/\\omega$. However, higher harmonics can also\n", @@ -865,9 +762,7 @@ { "cell_type": "markdown", "id": "c4304af6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -883,9 +778,7 @@ { "cell_type": "markdown", "id": "626f9f6d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Wrapping up Fourier transforms\n", "\n", @@ -898,9 +791,7 @@ { "cell_type": "markdown", "id": "2f563405", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -916,9 +807,7 @@ { "cell_type": "markdown", "id": "f99c330a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The solutions for $x(t)$ then come from replacing $\\omega$ with\n", "$n\\omega$ for each term in the particular solution," @@ -927,9 +816,7 @@ { "cell_type": "markdown", "id": "b240e4ec", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\begin{eqnarray}\n", @@ -947,9 +834,7 @@ { "cell_type": "markdown", "id": "905cc057", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Finding the Coefficients\n", "\n", @@ -966,9 +851,7 @@ { "cell_type": "markdown", "id": "5841f5ce", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -986,9 +869,7 @@ { "cell_type": "markdown", "id": "03e7ed50", - "metadata": { - "editable": true - }, + "metadata": {}, "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", @@ -999,9 +880,7 @@ { "cell_type": "markdown", "id": "0397e306", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "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).\n", @@ -1011,9 +890,7 @@ { "cell_type": "markdown", "id": "fed2b29e", - "metadata": { - "editable": true - }, + "metadata": {}, "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", @@ -1028,9 +905,7 @@ { "cell_type": "markdown", "id": "4db87a94", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -1046,9 +921,7 @@ { "cell_type": "markdown", "id": "c34b0353", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -1056,9 +929,7 @@ { "cell_type": "markdown", "id": "3cb68d87", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f_n=\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~f_n/2=f_n.\n", @@ -1068,9 +939,7 @@ { "cell_type": "markdown", "id": "09cc733e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The same method can be used to check for the consistency of $g_n$." ] @@ -1078,9 +947,7 @@ { "cell_type": "markdown", "id": "14d8af81", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Final words on Fourier Transforms\n", "\n", @@ -1097,10 +964,7 @@ "cell_type": "code", "execution_count": 2, "id": "99fc76a1", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -1137,9 +1001,7 @@ { "cell_type": "markdown", "id": "1340474e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Fourier transforms and convolution\n", "\n", @@ -1149,9 +1011,7 @@ { "cell_type": "markdown", "id": "5b1c005a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\hat{f}(y)=\\boldsymbol{F}[f(y)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{-i\\omega y} f(\\omega),\n", @@ -1161,9 +1021,7 @@ { "cell_type": "markdown", "id": "0ca09d82", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and similarly we have" ] @@ -1171,9 +1029,7 @@ { "cell_type": "markdown", "id": "d49b6997", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\hat{g}(y)=\\boldsymbol{F}[g(y)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{-i\\omega y} g(\\omega).\n", @@ -1183,9 +1039,7 @@ { "cell_type": "markdown", "id": "75795dd4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The inverse Fourier transform is given by" ] @@ -1193,9 +1047,7 @@ { "cell_type": "markdown", "id": "bc49fd47", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{F}^{-1}[g(y)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{i\\omega y} g(\\omega).\n", @@ -1205,9 +1057,7 @@ { "cell_type": "markdown", "id": "ff256a0d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The inverse Fourier transform of the product of the two functions $\\hat{f}\\hat{g}$ can be written as" ] @@ -1215,9 +1065,7 @@ { "cell_type": "markdown", "id": "a334082e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{F}^{-1}[(\\hat{f}\\hat{g})(x)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{i\\omega x} \\hat{f}(\\omega)\\hat{g}(\\omega).\n", @@ -1227,9 +1075,7 @@ { "cell_type": "markdown", "id": "35b63bfc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We can rewrite the latter as" ] @@ -1237,9 +1083,7 @@ { "cell_type": "markdown", "id": "ea83e607", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{F}^{-1}[(\\hat{f}\\hat{g})(x)]=\\int_{-\\infty}^{\\infty} d\\omega \\exp{i\\omega x} \\hat{f}(\\omega)\\left[\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}g(y)dy \\exp{-i\\omega y}\\right]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}dy g(y)\\int_{-\\infty}^{\\infty} d\\omega \\hat{f}(\\omega) \\exp{i\\omega(x- y)},\n", @@ -1249,9 +1093,7 @@ { "cell_type": "markdown", "id": "835bdbbd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which is simply" ] @@ -1259,9 +1101,7 @@ { "cell_type": "markdown", "id": "79d2b70c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{F}^{-1}[(\\hat{f}\\hat{g})(x)]=\\int_{-\\infty}^{\\infty}dy g(y)f(x-y)=(f*g)(x),\n", @@ -1271,9 +1111,7 @@ { "cell_type": "markdown", "id": "25fc980c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "the convolution of the functions $f$ and $g$." ] @@ -1281,9 +1119,7 @@ { "cell_type": "markdown", "id": "9d47efce", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Two-dimensional Objects\n", "\n", @@ -1296,9 +1132,7 @@ { "cell_type": "markdown", "id": "b96e8fa0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "S_(i,j)=(I * K)(i,j) = \\sum_m\\sum_n I(m,n)K(i-m,j-n).\n", @@ -1308,9 +1142,7 @@ { "cell_type": "markdown", "id": "90817709", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Convolution is a commutatitave process, which means we can rewrite this equation as" ] @@ -1318,9 +1150,7 @@ { "cell_type": "markdown", "id": "ef889e3f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "S_(i,j)=(I * K)(i,j) = \\sum_m\\sum_n I(i-m,j-n)K(m,n).\n", @@ -1330,9 +1160,7 @@ { "cell_type": "markdown", "id": "ad86a022", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Normally the latter is more straightforward to implement in a machine larning library since there is less variation in the range of values of $m$ and $n$.\n", "\n", @@ -1342,9 +1170,7 @@ { "cell_type": "markdown", "id": "379561b4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "S_(i,j)=(I * K)(i,j) = \\sum_m\\sum_n I(i+m,j+n)K(m,n).\n", @@ -1354,9 +1180,7 @@ { "cell_type": "markdown", "id": "0c7b6540", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## More on Dimensionalities\n", "\n", @@ -1381,9 +1205,7 @@ { "cell_type": "markdown", "id": "47d923f0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \\approx 10^{10},\n", @@ -1393,9 +1215,7 @@ { "cell_type": "markdown", "id": "f51762c0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "that is ten billion parameters to determine." ] @@ -1403,9 +1223,7 @@ { "cell_type": "markdown", "id": "e9f8618d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Further Dimensionality Remarks\n", "\n", @@ -1429,9 +1247,7 @@ { "cell_type": "markdown", "id": "14066a55", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## CNNs in more detail\n", "\n", @@ -1442,9 +1258,7 @@ { "cell_type": "markdown", "id": "9cc57063", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{I}=\\begin{bmatrix}i_{00} & i_{01} & i_{02} \\\\\n", @@ -1456,9 +1270,7 @@ { "cell_type": "markdown", "id": "40d9c084", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] @@ -1466,9 +1278,7 @@ { "cell_type": "markdown", "id": "814a3e68", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{W}=\\begin{bmatrix}w_{00} & w_{01} \\\\\n", @@ -1479,9 +1289,7 @@ { "cell_type": "markdown", "id": "3014dcb3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We introduce now the hyperparameter $S$ **stride**. Stride represents how the filter $W$ moves the convolution process on the matrix $I$.\n", "We strongly recommend the repository on [Arithmetic of deep learning by Dumoulin and Visin](https://github.com/vdumoulin/conv_arithmetic) \n", @@ -1494,9 +1302,7 @@ { "cell_type": "markdown", "id": "47a57310", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "S_(i,j)=(I * W)(i,j) = \\sum_m\\sum_n I(i-m,j-n)W(m,n),\n", @@ -1506,9 +1312,7 @@ { "cell_type": "markdown", "id": "780c3b94", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and obtain" ] @@ -1516,9 +1320,7 @@ { "cell_type": "markdown", "id": "6ad3ca13", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{S}=\\begin{bmatrix}i_{00}w_{00}+i_{01}w_{01}+i_{10}w_{10}+i_{11}w_{11} & i_{01}w_{00}+i_{02}w_{01}+i_{11}w_{10}+i_{12}w_{11} \\\\\n", @@ -1529,9 +1331,7 @@ { "cell_type": "markdown", "id": "cf2dec6f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We can rewrite this operation in terms of a matrix-vector multiplication by defining a new vector where we flatten out the inputs as a vector $\\boldsymbol{I}'$ of length $9$ and\n", "a matrix $\\boldsymbol{W}'$ with dimension $4\\times 9$ as" @@ -1540,9 +1340,7 @@ { "cell_type": "markdown", "id": "f6b654b4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{I}'=\\begin{bmatrix}i_{00} \\\\ i_{01} \\\\ i_{02} \\\\ i_{10} \\\\ i_{11} \\\\ i_{12} \\\\ i_{20} \\\\ i_{21} \\\\ i_{22} \\end{bmatrix},\n", @@ -1552,9 +1350,7 @@ { "cell_type": "markdown", "id": "54b5f04e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and the new matrix" ] @@ -1562,9 +1358,7 @@ { "cell_type": "markdown", "id": "053dd929", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{W}'=\\begin{bmatrix} w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 & 0 & 0 & 0 \\\\\n", @@ -1577,9 +1371,7 @@ { "cell_type": "markdown", "id": "8afc19f4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We see easily that performing the matrix-vector multiplication $\\boldsymbol{W}'\\boldsymbol{I}'$ is the same as the above convolution with stride $S=1$, that is" ] @@ -1587,9 +1379,7 @@ { "cell_type": "markdown", "id": "e8f84c8a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "S=(\\boldsymbol{W}*\\boldsymbol{I}),\n", @@ -1599,9 +1389,7 @@ { "cell_type": "markdown", "id": "1c04d062", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "is now given by $\\boldsymbol{W}'\\boldsymbol{I}'$ which is a vector of length $4$ instead of the originally resulting $2\\times 2$ output matrix.\n", "\n", @@ -1612,9 +1400,7 @@ { "cell_type": "markdown", "id": "2c10c4d1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\begin{split}\n", @@ -1628,9 +1414,7 @@ { "cell_type": "markdown", "id": "edf2c021", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The following properties affect the output size $o_j$ of a convolutional layer\n", "along axis $j$:\n", @@ -1656,9 +1440,7 @@ { "cell_type": "markdown", "id": "5956ab9e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Pooling\n", "\n", @@ -1706,9 +1488,7 @@ { "cell_type": "markdown", "id": "1291dcfc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## No zero padding, unit strides\n", "\n", @@ -1721,9 +1501,7 @@ { "cell_type": "markdown", "id": "36403adf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "o = (i - k) + 1.\n", @@ -1733,9 +1511,7 @@ { "cell_type": "markdown", "id": "5baecc1a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Zero padding, unit strides\n", "\n", @@ -1750,9 +1526,7 @@ { "cell_type": "markdown", "id": "5f87df6c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "o = (i - k) + 2p + 1.\n", @@ -1762,9 +1536,7 @@ { "cell_type": "markdown", "id": "cdaece55", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Half (same) padding\n", "\n", @@ -1778,9 +1550,7 @@ { "cell_type": "markdown", "id": "a126c99f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\begin{split}\n", @@ -1794,9 +1564,7 @@ { "cell_type": "markdown", "id": "f0882225", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Full padding\n", "\n", @@ -1810,9 +1578,7 @@ { "cell_type": "markdown", "id": "ec5ea353", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\begin{split}\n", @@ -1825,9 +1591,7 @@ { "cell_type": "markdown", "id": "ff523888", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "This is sometimes referred to as full padding, because in this\n", "setting every possible partial or complete superimposition of the kernel on the\n", @@ -1837,9 +1601,7 @@ { "cell_type": "markdown", "id": "7fc1dd60", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Pooling arithmetic\n", "\n", @@ -1859,9 +1621,7 @@ { "cell_type": "markdown", "id": "3ef94f77", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "o = \\left\\lfloor \\frac{i - k}{s} \\right\\rfloor + 1.\n", @@ -1871,9 +1631,7 @@ { "cell_type": "markdown", "id": "551b830f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n", "\n", @@ -1890,9 +1648,7 @@ { "cell_type": "markdown", "id": "c9f41dea", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Setting it up\n", "\n", @@ -1903,9 +1659,7 @@ { "cell_type": "markdown", "id": "3d199bb5", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n", @@ -1915,9 +1669,7 @@ { "cell_type": "markdown", "id": "92ec055c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The MNIST dataset again\n", "\n", @@ -1936,9 +1688,7 @@ { "cell_type": "markdown", "id": "eb0031a2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Strong correlations\n", "\n", @@ -1957,9 +1707,7 @@ { "cell_type": "markdown", "id": "c7ce376c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Layers of a CNN\n", "The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n", @@ -1982,9 +1730,7 @@ { "cell_type": "markdown", "id": "92c06244", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Systematic reduction\n", "\n", @@ -2001,9 +1747,7 @@ { "cell_type": "markdown", "id": "48038c16", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Prerequisites: Collect and pre-process data" ] @@ -2012,10 +1756,7 @@ "cell_type": "code", "execution_count": 3, "id": "69c8a363", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# import necessary packages\n", @@ -2063,9 +1804,7 @@ { "cell_type": "markdown", "id": "d2f311c1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Importing Keras and Tensorflow" ] @@ -2074,10 +1813,7 @@ "cell_type": "code", "execution_count": 4, "id": "42abafc8", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from tensorflow.keras import datasets, layers, models\n", @@ -2107,9 +1843,7 @@ { "cell_type": "markdown", "id": "fbf5e9da", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Running with Keras" ] @@ -2118,10 +1852,7 @@ "cell_type": "code", "execution_count": 5, "id": "40605ae2", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "def create_convolutional_neural_network_keras(input_shape, receptive_field,\n", @@ -2155,9 +1886,7 @@ { "cell_type": "markdown", "id": "60a23dcf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Final part" ] @@ -2166,10 +1895,7 @@ "cell_type": "code", "execution_count": 6, "id": "032146fe", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", @@ -2193,9 +1919,7 @@ { "cell_type": "markdown", "id": "51a2dbec", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Final visualization" ] @@ -2204,10 +1928,7 @@ "cell_type": "code", "execution_count": 7, "id": "f5b791f0", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# visual representation of grid search\n", @@ -2245,9 +1966,7 @@ { "cell_type": "markdown", "id": "7f997c83", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## The CIFAR01 data set\n", "\n", @@ -2261,10 +1980,7 @@ "cell_type": "code", "execution_count": 8, "id": "0a1859fe", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import tensorflow as tf\n", @@ -2282,9 +1998,7 @@ { "cell_type": "markdown", "id": "d21fdb8b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Verifying the data set\n", "\n", @@ -2295,10 +2009,7 @@ "cell_type": "code", "execution_count": 9, "id": "d873925c", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n", @@ -2320,9 +2031,7 @@ { "cell_type": "markdown", "id": "4c1d4824", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Set up the model\n", "\n", @@ -2335,10 +2044,7 @@ "cell_type": "code", "execution_count": 10, "id": "cf685009", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "model = models.Sequential()\n", @@ -2356,9 +2062,7 @@ { "cell_type": "markdown", "id": "8a6c0580", - "metadata": { - "editable": true - }, + "metadata": {}, "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." ] @@ -2366,9 +2070,7 @@ { "cell_type": "markdown", "id": "b2e5625a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Add Dense layers on top\n", "\n", @@ -2385,10 +2087,7 @@ "cell_type": "code", "execution_count": 11, "id": "32424489", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "model.add(layers.Flatten())\n", @@ -2402,9 +2101,7 @@ { "cell_type": "markdown", "id": "832d8c60", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers." ] @@ -2412,9 +2109,7 @@ { "cell_type": "markdown", "id": "b72ea4e9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Compile and train the model" ] @@ -2423,10 +2118,7 @@ "cell_type": "code", "execution_count": 12, "id": "ef7e9721", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "model.compile(optimizer='adam',\n", @@ -2440,9 +2132,7 @@ { "cell_type": "markdown", "id": "2d93dc5e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Finally, evaluate the model" ] @@ -2451,10 +2141,7 @@ "cell_type": "code", "execution_count": 13, "id": "286d29cd", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "plt.plot(history.history['accuracy'], label='accuracy')\n", @@ -2472,9 +2159,7 @@ { "cell_type": "markdown", "id": "8eaa01af", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Building our own CNN code\n", "\n", @@ -2503,9 +2188,7 @@ { "cell_type": "markdown", "id": "b13efbbf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### List of contents:\n", "\n", @@ -2527,9 +2210,7 @@ { "cell_type": "markdown", "id": "d4bf9acd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Schedulers\n", "\n", @@ -2550,10 +2231,7 @@ "cell_type": "code", "execution_count": 14, "id": "731fe634", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -2691,9 +2369,7 @@ { "cell_type": "markdown", "id": "51a4758d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Usage of schedulers\n", "\n", @@ -2704,10 +2380,7 @@ "cell_type": "code", "execution_count": 15, "id": "cbe83098", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", @@ -2717,9 +2390,7 @@ { "cell_type": "markdown", "id": "c180fcec", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple." ] @@ -2728,10 +2399,7 @@ "cell_type": "code", "execution_count": 16, "id": "5469f02b", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "weights = np.ones((3,3))\n", @@ -2750,9 +2418,7 @@ { "cell_type": "markdown", "id": "87d59625", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Cost functions\n", "\n", @@ -2766,10 +2432,7 @@ "cell_type": "code", "execution_count": 17, "id": "dd9d99c0", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "def CostOLS(target):\n", @@ -2813,9 +2476,7 @@ { "cell_type": "markdown", "id": "ea50c429", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Usage of cost functions\n", "\n", @@ -2828,10 +2489,7 @@ "cell_type": "code", "execution_count": 18, "id": "438d0249", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from autograd import grad\n", @@ -2849,9 +2507,7 @@ { "cell_type": "markdown", "id": "6060ed74", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Activation functions\n", "\n", @@ -2866,10 +2522,7 @@ "cell_type": "code", "execution_count": 19, "id": "962289b4", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "\n", @@ -2925,9 +2578,7 @@ { "cell_type": "markdown", "id": "e10ea31a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Usage of activation functions\n", "\n", @@ -2942,10 +2593,7 @@ "cell_type": "code", "execution_count": 20, "id": "b374bde5", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "z = np.array([[4, 5, 6]]).T\n", @@ -2963,9 +2611,7 @@ { "cell_type": "markdown", "id": "a67f2032", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Convolution\n", "\n", @@ -2980,9 +2626,7 @@ { "cell_type": "markdown", "id": "70c5cf9f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(f \\ast g)(t):=\\int_{-\\infty}^{\\infty} f(\\tau) g(t-\\tau) d \\tau.\n", @@ -2992,9 +2636,7 @@ { "cell_type": "markdown", "id": "a0738da9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Here, f and g are the two functions on which we want to perform an\n", "operation. The outcome of the convolution operation is represented by\n", @@ -3008,9 +2650,7 @@ { "cell_type": "markdown", "id": "fa290f29", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(f \\ast g)[n]=\\sum_{m=0}^{n-1} f[m] g[n-m].\n", @@ -3020,9 +2660,7 @@ { "cell_type": "markdown", "id": "78ece2fc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The key idea we utilize to extract the information contained in an\n", "image is to slide an $m \\times n$ matrix *g* over an $m \\times n$\n", @@ -3035,9 +2673,7 @@ { "cell_type": "markdown", "id": "b19ddb5e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(f \\ast g)[i, j]\\sum_{m=0}^{M-1}\\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n].\n", @@ -3047,9 +2683,7 @@ { "cell_type": "markdown", "id": "3a97d8af", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "It is imperative to note that the size of the kernel g is\n", "significantly smaller than the size of the input image f, thereby\n", @@ -3065,9 +2699,7 @@ { "cell_type": "markdown", "id": "1a5462e2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f = \\begin{bmatrix}\n", @@ -3084,9 +2716,7 @@ { "cell_type": "markdown", "id": "2e904e3d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and a $3 \\times 3$ kernel *g* called a low-pass filter. Note that the\n", "kernel is usually rotated by 180 degrees during convolution, however\n", @@ -3096,9 +2726,7 @@ { "cell_type": "markdown", "id": "65c5e545", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "g = \\frac{1}{9}\n", @@ -3113,9 +2741,7 @@ { "cell_type": "markdown", "id": "6fedef15", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "In order to filter the image, we have to extract a $3 \\times 3$\n", "element from the upper left corner of *f*, and perform element-wise\n", @@ -3126,9 +2752,7 @@ { "cell_type": "markdown", "id": "e0abec0e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\begin{bmatrix}\n", @@ -3155,9 +2779,7 @@ { "cell_type": "markdown", "id": "aef3b0ae", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Then, following the multiplication, we summarize all the elements of the resulting matrix A:" ] @@ -3165,9 +2787,7 @@ { "cell_type": "markdown", "id": "b9ce4351", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(f \\ast g)[0, 0]= \\sum_{i=0}^{2} \\sum_{j=0}^{2} a_{i,j} = 5\n", @@ -3177,9 +2797,7 @@ { "cell_type": "markdown", "id": "e58be5c7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Which corresponds to the first element of the filtered image $(f \\ast g)$.\n", "\n", @@ -3198,9 +2816,7 @@ { "cell_type": "markdown", "id": "68d7caf4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(f \\ast g) =\n", @@ -3216,9 +2832,7 @@ { "cell_type": "markdown", "id": "67df8548", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image.\n", "How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with *r* additional rows and *c* additional columns." @@ -3227,9 +2841,7 @@ { "cell_type": "markdown", "id": "ca837258", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "r =\\lfloor \\frac{kernel\\ height}{2} \\rfloor \\cdot 2 \\\\\n", @@ -3240,9 +2852,7 @@ { "cell_type": "markdown", "id": "9013a50e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Note the notation $\\lfloor \\frac{kernel width}{2} \\rfloor$ means that\n", "we floor the result of the division, meaning we round down to a whole\n", @@ -3264,9 +2874,7 @@ { "cell_type": "markdown", "id": "27ab00a4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\begin{bmatrix}\n", @@ -3286,9 +2894,7 @@ { "cell_type": "markdown", "id": "dedb1313", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding.~" ] @@ -3297,10 +2903,7 @@ "cell_type": "code", "execution_count": 21, "id": "76641906", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -3379,9 +2982,7 @@ { "cell_type": "markdown", "id": "57c2f880", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. \n", "However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called \n", @@ -3392,10 +2993,7 @@ "cell_type": "code", "execution_count": 22, "id": "629f5bab", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "\n", @@ -3419,9 +3017,7 @@ { "cell_type": "markdown", "id": "589f42bc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "As you can see, the resulting image is of the same size as the\n", "original image. To round of our demonstration of convolution, we will\n", @@ -3440,10 +3036,7 @@ "cell_type": "code", "execution_count": 23, "id": "7addd2db", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# Now an example using a real image and first a gaussian low-pass filter and then a sobel filter\n", @@ -3490,9 +3083,7 @@ { "cell_type": "markdown", "id": "5380e6ee", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Layers\n", "\n", @@ -3505,10 +3096,7 @@ "cell_type": "code", "execution_count": 24, "id": "45579a9f", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import math\n", @@ -3546,9 +3134,7 @@ { "cell_type": "markdown", "id": "352938da", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Convolution2DLayer: convolution in a hidden layer\n", "\n", @@ -3588,10 +3174,7 @@ "cell_type": "code", "execution_count": 25, "id": "67866434", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "class Convolution2DLayer(Layer):\n", @@ -3874,9 +3457,7 @@ { "cell_type": "markdown", "id": "904776a8", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Backpropagation in the convolutional layer\n", "\n", @@ -3897,9 +3478,7 @@ { "cell_type": "markdown", "id": "2bbce751", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Demonstration\n", "\n", @@ -3910,10 +3489,7 @@ "cell_type": "code", "execution_count": 26, "id": "78ea75c1", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", @@ -3958,9 +3534,7 @@ { "cell_type": "markdown", "id": "f6f0d049", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We cobserve that the result has half the pixels on each axis due to\n", "the fact that we've used a horizontal and vertical stride of 2. The\n", @@ -3980,9 +3554,7 @@ { "cell_type": "markdown", "id": "2ecb7763", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Pooling Layer\n", "\n", @@ -4002,10 +3574,7 @@ "cell_type": "code", "execution_count": 27, "id": "1a180337", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "class Pooling2DLayer(Layer):\n", @@ -4164,9 +3733,7 @@ { "cell_type": "markdown", "id": "f4ab9ece", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Flattening Layer\n", "\n", @@ -4185,10 +3752,7 @@ "cell_type": "code", "execution_count": 28, "id": "83d588e4", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "class FlattenLayer(Layer):\n", @@ -4248,9 +3812,7 @@ { "cell_type": "markdown", "id": "922b6dfe", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Fully Connected Layers\n", "\n", @@ -4272,10 +3834,7 @@ "cell_type": "code", "execution_count": 29, "id": "85595198", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "class FullyConnectedLayer(Layer):\n", @@ -4500,9 +4059,7 @@ { "cell_type": "markdown", "id": "44351389", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Optimized Convolution2DLayer\n", "\n", @@ -4521,10 +4078,7 @@ "cell_type": "code", "execution_count": 30, "id": "f0e7aa82", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "class Convolution2DLayerOPT(Convolution2DLayer):\n", @@ -4825,9 +4379,7 @@ { "cell_type": "markdown", "id": "76da2e3b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### The Convolutional Neural Network (CNN)\n", "\n", @@ -4838,10 +4390,7 @@ "cell_type": "code", "execution_count": 31, "id": "47fe6401", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import math\n", @@ -5373,9 +4922,7 @@ { "cell_type": "markdown", "id": "e941a3bc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Usage of CNN code\n", "\n", @@ -5392,10 +4939,7 @@ "cell_type": "code", "execution_count": 32, "id": "d0f1de86", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", @@ -5405,9 +4949,7 @@ { "cell_type": "markdown", "id": "829d95eb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Now that we have our CNN object, we can begin to add layers to it!\n", "Many of the add_layer functions have default values, for example\n", @@ -5421,10 +4963,7 @@ "cell_type": "code", "execution_count": 33, "id": "4d56ff10", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "cnn.add_Convolution2DLayer(\n", @@ -5447,9 +4986,7 @@ { "cell_type": "markdown", "id": "bc89efc7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Here we have created a CNN with the following architecture:\n", "\n", @@ -5471,10 +5008,7 @@ "cell_type": "code", "execution_count": 34, "id": "b51beb67", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "from sklearn.datasets import fetch_openml\n", @@ -5506,9 +5040,7 @@ { "cell_type": "markdown", "id": "0a876ad7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Now we may train our model. Note that we can utilize regularization in\n", "the CNN by using the lam (lambda) parameter in fit(), and utilize\n", @@ -5525,10 +5057,7 @@ "cell_type": "code", "execution_count": 35, "id": "94770f35", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "scores = cnn.fit(\n", @@ -5553,9 +5082,7 @@ { "cell_type": "markdown", "id": "938a273d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good.\n", "\n", @@ -5582,10 +5109,7 @@ "cell_type": "code", "execution_count": 36, "id": "7d7dc9ff", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", @@ -5651,9 +5175,7 @@ { "cell_type": "markdown", "id": "0c290246", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Here we see the use of asymmetrical 1D kernels such as the $7 \\times\n", "1$ kernel in the first convolutional layer, both max and average\n", @@ -5669,9 +5191,7 @@ { "cell_type": "markdown", "id": "71e78b12", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Additional Remarks\n", "\n", @@ -5693,10 +5213,7 @@ "cell_type": "code", "execution_count": 37, "id": "cb88fdfd", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "def convolve(image, kernel, stride=1):\n", @@ -5724,9 +5241,7 @@ { "cell_type": "markdown", "id": "b3c1ca97", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Remarks on the speed\n", "\n", @@ -5754,9 +5269,7 @@ { "cell_type": "markdown", "id": "976d307c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Convolution using separable kernels" ] @@ -5765,10 +5278,7 @@ "cell_type": "code", "execution_count": 38, "id": "89647600", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "def conv2DSep(image, kernel, coef, stride=1, pad=\"zero\"):\n", @@ -5815,9 +5325,7 @@ { "cell_type": "markdown", "id": "f4baf26f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "By taking advantage of the capabilities of separable kernels, we can\n", "effectively cut the computational expense of filtering an image in\n", @@ -5836,9 +5344,7 @@ { "cell_type": "markdown", "id": "81180d52", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Convolution in the Fourier domain" ] @@ -5847,10 +5353,7 @@ "cell_type": "code", "execution_count": 39, "id": "8ae65bb6", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "start_time = time.time()\n", @@ -5868,9 +5371,7 @@ { "cell_type": "markdown", "id": "78e3becb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "It is evident that executing convolution in the Fourier domain yields\n", "the quickest computation time. Nonetheless, one should exercise\n", @@ -5885,7 +5386,25 @@ ] } ], - "metadata": {}, + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.10" + } + }, "nbformat": 4, "nbformat_minor": 5 }