diff --git a/doc/LectureNotes/week42.ipynb b/doc/LectureNotes/week42.ipynb index 8699e7c79..fdfeb303f 100644 --- a/doc/LectureNotes/week42.ipynb +++ b/doc/LectureNotes/week42.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "474b773e", + "id": "71674611", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "a8ac8249", + "id": "65b3502e", "metadata": { "editable": true }, @@ -27,7 +27,7 @@ }, { "cell_type": "markdown", - "id": "c8760378", + "id": "1d840be4", "metadata": { "editable": true }, @@ -56,7 +56,7 @@ }, { "cell_type": "markdown", - "id": "76c6895d", + "id": "8c43f62c", "metadata": { "editable": true }, @@ -73,7 +73,7 @@ }, { "cell_type": "markdown", - "id": "ebb39354", + "id": "bb52c881", "metadata": { "editable": true }, @@ -92,7 +92,7 @@ }, { "cell_type": "markdown", - "id": "cfb26b1b", + "id": "e53a998a", "metadata": { "editable": true }, @@ -108,7 +108,7 @@ }, { "cell_type": "markdown", - "id": "28f60678", + "id": "2be1dbc1", "metadata": { "editable": true }, @@ -119,7 +119,7 @@ }, { "cell_type": "markdown", - "id": "3c7f8f61", + "id": "d81e5954", "metadata": { "editable": true }, @@ -133,7 +133,7 @@ }, { "cell_type": "markdown", - "id": "9ee5faa5", + "id": "bf67ca94", "metadata": { "editable": true }, @@ -148,7 +148,7 @@ }, { "cell_type": "markdown", - "id": "e82fbb01", + "id": "ea5ccdfd", "metadata": { "editable": true }, @@ -160,7 +160,7 @@ }, { "cell_type": "markdown", - "id": "e1b4862d", + "id": "a67526dc", "metadata": { "editable": true }, @@ -174,7 +174,7 @@ }, { "cell_type": "markdown", - "id": "f7b41bcb", + "id": "004f244e", "metadata": { "editable": true }, @@ -186,7 +186,7 @@ }, { "cell_type": "markdown", - "id": "2825a689", + "id": "d5019705", "metadata": { "editable": true }, @@ -202,7 +202,7 @@ }, { "cell_type": "markdown", - "id": "1853d23c", + "id": "b28a1451", "metadata": { "editable": true }, @@ -218,7 +218,7 @@ }, { "cell_type": "markdown", - "id": "1625a8c3", + "id": "bb9e817a", "metadata": { "editable": true }, @@ -230,7 +230,7 @@ }, { "cell_type": "markdown", - "id": "7427a24a", + "id": "cb070b5e", "metadata": { "editable": true }, @@ -240,7 +240,7 @@ }, { "cell_type": "markdown", - "id": "d4911a64", + "id": "f68d4801", "metadata": { "editable": true }, @@ -252,7 +252,7 @@ }, { "cell_type": "markdown", - "id": "0f290988", + "id": "fffa97bd", "metadata": { "editable": true }, @@ -262,7 +262,7 @@ }, { "cell_type": "markdown", - "id": "4cbbad95", + "id": "7f751c77", "metadata": { "editable": true }, @@ -274,7 +274,7 @@ }, { "cell_type": "markdown", - "id": "cc8122a6", + "id": "e8f8479b", "metadata": { "editable": true }, @@ -284,7 +284,7 @@ }, { "cell_type": "markdown", - "id": "39f03825", + "id": "9d52f786", "metadata": { "editable": true }, @@ -296,7 +296,7 @@ }, { "cell_type": "markdown", - "id": "3eeb7a29", + "id": "cdb55ad0", "metadata": { "editable": true }, @@ -312,7 +312,7 @@ }, { "cell_type": "markdown", - "id": "33e1d35f", + "id": "ece1a1cc", "metadata": { "editable": true }, @@ -324,7 +324,7 @@ }, { "cell_type": "markdown", - "id": "e846a441", + "id": "e2af50fb", "metadata": { "editable": true }, @@ -336,7 +336,7 @@ }, { "cell_type": "markdown", - "id": "fbb3f1ff", + "id": "c883f2ef", "metadata": { "editable": true }, @@ -346,7 +346,7 @@ }, { "cell_type": "markdown", - "id": "40200643", + "id": "f1129306", "metadata": { "editable": true }, @@ -358,7 +358,7 @@ }, { "cell_type": "markdown", - "id": "a2e96689", + "id": "1d14bedd", "metadata": { "editable": true }, @@ -368,7 +368,7 @@ }, { "cell_type": "markdown", - "id": "1a014316", + "id": "84378f69", "metadata": { "editable": true }, @@ -384,7 +384,7 @@ }, { "cell_type": "markdown", - "id": "06a0b720", + "id": "7f6f41e3", "metadata": { "editable": true }, @@ -396,7 +396,7 @@ }, { "cell_type": "markdown", - "id": "48581ce4", + "id": "f38cb151", "metadata": { "editable": true }, @@ -408,7 +408,7 @@ }, { "cell_type": "markdown", - "id": "58f46792", + "id": "d7f60566", "metadata": { "editable": true }, @@ -420,7 +420,7 @@ }, { "cell_type": "markdown", - "id": "dc5aa924", + "id": "81219134", "metadata": { "editable": true }, @@ -432,7 +432,7 @@ }, { "cell_type": "markdown", - "id": "407690af", + "id": "8f0f27a7", "metadata": { "editable": true }, @@ -444,7 +444,7 @@ }, { "cell_type": "markdown", - "id": "8f5cacad", + "id": "aa9974f2", "metadata": { "editable": true }, @@ -454,7 +454,7 @@ }, { "cell_type": "markdown", - "id": "79f592c1", + "id": "02021c85", "metadata": { "editable": true }, @@ -470,7 +470,7 @@ }, { "cell_type": "markdown", - "id": "412247f9", + "id": "d5b4c3d8", "metadata": { "editable": true }, @@ -482,7 +482,7 @@ }, { "cell_type": "markdown", - "id": "83c09361", + "id": "0c0f2d45", "metadata": { "editable": true }, @@ -494,7 +494,7 @@ }, { "cell_type": "markdown", - "id": "d341a3c7", + "id": "9f8b567b", "metadata": { "editable": true }, @@ -504,7 +504,7 @@ }, { "cell_type": "markdown", - "id": "2bb5b78f", + "id": "6afa5b0f", "metadata": { "editable": true }, @@ -516,7 +516,7 @@ }, { "cell_type": "markdown", - "id": "3d6558a8", + "id": "a8447e5f", "metadata": { "editable": true }, @@ -530,7 +530,7 @@ }, { "cell_type": "markdown", - "id": "f55c404e", + "id": "0262d1c4", "metadata": { "editable": true }, @@ -548,7 +548,7 @@ { "cell_type": "code", "execution_count": 1, - "id": "076950d8", + "id": "91932727", "metadata": { "collapsed": false, "editable": true @@ -621,7 +621,7 @@ }, { "cell_type": "markdown", - "id": "b5a2150f", + "id": "6695945c", "metadata": { "editable": true }, @@ -631,7 +631,7 @@ }, { "cell_type": "markdown", - "id": "cb93f2d2", + "id": "30bd4411", "metadata": { "editable": true }, @@ -643,51 +643,51 @@ "layer with two hidden nodes and one output layer with one output node/neuron only (see graph)..\n", "\n", "We need to define the following parameters and variables with the input layer (layer $(0)$) \n", - "where we label the nodes $x_0$ and $x_1$" + "where we label the nodes $x_1$ and $x_2$" ] }, { "cell_type": "markdown", - "id": "893b1b33", + "id": "03303707", "metadata": { "editable": true }, "source": [ "$$\n", - "x_0 = a_0^{(0)} \\wedge x_1 = a_1^{(0)}.\n", + "x_1 = a_1^{(0)} \\wedge x_2 = a_2^{(0)}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "f1554902", + "id": "24dc6874", "metadata": { "editable": true }, "source": [ - "The hidden layer (layer $(1)$) has nodes which yield the outputs $a_0^{(1)}$ and $a_1^{(1)}$) with weight $\\boldsymbol{w}$ and bias $\\boldsymbol{b}$ parameters" + "The hidden layer (layer $(1)$) has nodes which yield the outputs $a_1^{(1)}$ and $a_2^{(1)}$) with weight $\\boldsymbol{w}$ and bias $\\boldsymbol{b}$ parameters" ] }, { "cell_type": "markdown", - "id": "e01cd011", + "id": "9229190d", "metadata": { "editable": true }, "source": [ "$$\n", - "w_{ij}^{(1)}=\\left\\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\\right\\} \\wedge b^{(1)}=\\left\\{b_0^{(1)},b_1^{(1)}\\right\\}.\n", + "w_{ij}^{(1)}=\\left\\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)}\\right\\} \\wedge b^{(1)}=\\left\\{b_1^{(1)},b_2^{(1)}\\right\\}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "691e42c5", + "id": "db21c4eb", "metadata": { "editable": true }, "source": [ - "## Layout of a simple neural network with two input nodes, one hidden layer and one output node\n", + "## Layout of a simple neural network with two input nodes, one hidden layer with two hidden noeds and one output node\n", "\n", "\n", "\n", @@ -698,31 +698,31 @@ }, { "cell_type": "markdown", - "id": "57573a8a", + "id": "cf9b69e8", "metadata": { "editable": true }, "source": [ "## The ouput layer\n", "\n", - "Finally, we have the ouput layer given by layer label $(2)$ with output $a^{(2)}$ and weights and biases to be determined given by the variables" + "We have the ouput layer given by layer label $(2)$ with output $a^{(2)}$ and weights and biases to be determined given by the variables" ] }, { "cell_type": "markdown", - "id": "91ff8dfb", + "id": "53130107", "metadata": { "editable": true }, "source": [ "$$\n", - "w_{i}^{(2)}=\\left\\{w_{0}^{(2)},w_{1}^{(2)}\\right\\} \\wedge b^{(2)}.\n", + "w_{i}^{(2)}=\\left\\{w_{1}^{(2)},w_{2}^{(2)}\\right\\} \\wedge b^{(2)}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "315f787f", + "id": "5835245c", "metadata": { "editable": true }, @@ -733,19 +733,19 @@ }, { "cell_type": "markdown", - "id": "612ebd67", + "id": "dd31d181", "metadata": { "editable": true }, "source": [ "$$\n", - "\\boldsymbol{\\Theta}=\\left\\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)},w_{0}^{(2)},w_{1}^{(2)},b_0^{(1)},b_1^{(1)},b^{(2)}\\right\\}.\n", + "\\boldsymbol{\\Theta}=\\left\\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)},w_{1}^{(2)},w_{2}^{(2)},b_1^{(1)},b_2^{(1)},b^{(2)}\\right\\}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "c28762dc", + "id": "36a9d52a", "metadata": { "editable": true }, @@ -758,19 +758,19 @@ }, { "cell_type": "markdown", - "id": "b4d0309d", + "id": "3af3b240", "metadata": { "editable": true }, "source": [ "$$\n", - "\\begin{bmatrix}z_0^{(1)} \\\\ z_1^{(1)} \\end{bmatrix}=\\left(\\begin{bmatrix}w_{00}^{(1)} & w_{01}^{(1)}\\\\ w_{10}^{(1)} &w_{11}^{(1)} \\end{bmatrix}\\right)^{T}\\begin{bmatrix}a_0^{(0)} \\\\ a_1^{(0)} \\end{bmatrix}+\\begin{bmatrix}b_0^{(1)} \\\\ b_1^{(1)} \\end{bmatrix},\n", + "\\begin{bmatrix}z_1^{(1)} \\\\ z_2^{(1)} \\end{bmatrix}=\\left(\\begin{bmatrix}w_{11}^{(1)} & w_{12}^{(1)}\\\\ w_{21}^{(1)} &w_{22}^{(1)} \\end{bmatrix}\\right)^{T}\\begin{bmatrix}a_1^{(0)} \\\\ a_2^{(0)} \\end{bmatrix}+\\begin{bmatrix}b_1^{(1)} \\\\ b_2^{(1)} \\end{bmatrix},\n", "$$" ] }, { "cell_type": "markdown", - "id": "f3c715f1", + "id": "3ef7b15b", "metadata": { "editable": true }, @@ -780,19 +780,19 @@ }, { "cell_type": "markdown", - "id": "5db82289", + "id": "31e47e2c", "metadata": { "editable": true }, "source": [ "$$\n", - "\\begin{bmatrix}a_0^{(1)} \\\\ a_1^{(1)} \\end{bmatrix}=\\begin{bmatrix}\\sigma^{(1)}(z_0^{(1)}) \\\\ \\sigma^{(1)}(z_1^{(1)}) \\end{bmatrix}.\n", + "\\begin{bmatrix}a_1^{(1)} \\\\ a_2^{(1)} \\end{bmatrix}=\\begin{bmatrix}\\sigma^{(1)}(z_1^{(1)}) \\\\ \\sigma^{(1)}(z_2^{(1)}) \\end{bmatrix}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "b6b2ad78", + "id": "c5690e76", "metadata": { "editable": true }, @@ -804,19 +804,19 @@ }, { "cell_type": "markdown", - "id": "dcefdba1", + "id": "919ce153", "metadata": { "editable": true }, "source": [ "$$\n", - "z^{(2)} = w_{0}^{(2)}a_0^{(1)} +w_{1}^{(2)}a_1^{(1)}+b^{(2)},\n", + "z^{(2)} = w_{1}^{(2)}a_1^{(1)} +w_{2}^{(2)}a_2^{(1)}+b^{(2)},\n", "$$" ] }, { "cell_type": "markdown", - "id": "d554c6ce", + "id": "69df1f30", "metadata": { "editable": true }, @@ -826,7 +826,7 @@ }, { "cell_type": "markdown", - "id": "651ff447", + "id": "42ea9246", "metadata": { "editable": true }, @@ -838,7 +838,7 @@ }, { "cell_type": "markdown", - "id": "f171ceaa", + "id": "af203af1", "metadata": { "editable": true }, @@ -854,7 +854,7 @@ }, { "cell_type": "markdown", - "id": "609bb2dd", + "id": "fd36e08b", "metadata": { "editable": true }, @@ -866,7 +866,7 @@ }, { "cell_type": "markdown", - "id": "da1d696b", + "id": "997bddf7", "metadata": { "editable": true }, @@ -876,7 +876,7 @@ }, { "cell_type": "markdown", - "id": "d21d62cc", + "id": "ba4380bd", "metadata": { "editable": true }, @@ -888,7 +888,7 @@ }, { "cell_type": "markdown", - "id": "fb9dd90f", + "id": "13be072b", "metadata": { "editable": true }, @@ -898,7 +898,7 @@ }, { "cell_type": "markdown", - "id": "9026fb2d", + "id": "2c6bcc22", "metadata": { "editable": true }, @@ -910,7 +910,7 @@ }, { "cell_type": "markdown", - "id": "2d20d5d1", + "id": "a50dfdeb", "metadata": { "editable": true }, @@ -922,20 +922,20 @@ }, { "cell_type": "markdown", - "id": "e6fbb9b5", + "id": "0d50cd56", "metadata": { "editable": true }, "source": [ "$$\n", - "\\frac{\\partial C}{\\partial w_{00}^{(1)}}=\\frac{\\partial C}{\\partial a^{(2)}}\\frac{\\partial a^{(2)}}{\\partial z^{(2)}}\n", - "\\frac{\\partial z^{(2)}}{\\partial z_0^{(1)}}\\frac{\\partial z_0^{(1)}}{\\partial w_{00}^{(1)}}= \\delta^{(2)}\\frac{\\partial z^{(2)}}{\\partial z_0^{(1)}}\\frac{\\partial z_0^{(1)}}{\\partial w_{00}^{(1)}},\n", + "\\frac{\\partial C}{\\partial w_{11}^{(1)}}=\\frac{\\partial C}{\\partial a^{(2)}}\\frac{\\partial a^{(2)}}{\\partial z^{(2)}}\n", + "\\frac{\\partial z^{(2)}}{\\partial z_1^{(1)}}\\frac{\\partial z_1^{(1)}}{\\partial w_{11}^{(1)}}= \\delta^{(2)}\\frac{\\partial z^{(2)}}{\\partial z_1^{(1)}}\\frac{\\partial z_1^{(1)}}{\\partial w_{11}^{(1)}},\n", "$$" ] }, { "cell_type": "markdown", - "id": "781a7ac8", + "id": "4fc9436b", "metadata": { "editable": true }, @@ -945,19 +945,19 @@ }, { "cell_type": "markdown", - "id": "3ee09d8f", + "id": "7545f5c9", "metadata": { "editable": true }, "source": [ "$$\n", - "z^{(2)} =w_0^{(2)}a_0^{(1)}+w_1^{(2)}a_1^{(1)}+b^{(2)},\n", + "z^{(2)} =w_1^{(2)}a_1^{(1)}+w_2^{(2)}a_2^{(1)}+b^{(2)},\n", "$$" ] }, { "cell_type": "markdown", - "id": "65f44692", + "id": "bcbea03f", "metadata": { "editable": true }, @@ -967,19 +967,19 @@ }, { "cell_type": "markdown", - "id": "0b84b7af", + "id": "ee05da6d", "metadata": { "editable": true }, "source": [ "$$\n", - "\\frac{\\partial z^{(2)}}{\\partial z_0^{(1)}}\\frac{\\partial z_0^{(1)}}{\\partial w_{00}^{(1)}}=w_0^{(2)}\\frac{\\partial a_0^{(1)}}{\\partial z_0^{(1)}}a_0^{(1)}.\n", + "\\frac{\\partial z^{(2)}}{\\partial z_1^{(1)}}\\frac{\\partial z_1^{(1)}}{\\partial w_{11}^{(1)}}=w_1^{(2)}\\frac{\\partial a_1^{(1)}}{\\partial z_1^{(1)}}a_1^{(1)}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "53c138bd", + "id": "1f9491ce", "metadata": { "editable": true }, @@ -990,19 +990,19 @@ }, { "cell_type": "markdown", - "id": "3f81bb3f", + "id": "07772fef", "metadata": { "editable": true }, "source": [ "$$\n", - "\\delta_0^{(1)}=w_0^{(2)}\\frac{\\partial a_0^{(1)}}{\\partial z_0^{(1)}}\\delta^{(2)},\n", + "\\delta_1^{(1)}=w_1^{(2)}\\frac{\\partial a_1^{(1)}}{\\partial z_1^{(1)}}\\delta^{(2)},\n", "$$" ] }, { "cell_type": "markdown", - "id": "eb6783b2", + "id": "c432668f", "metadata": { "editable": true }, @@ -1012,19 +1012,19 @@ }, { "cell_type": "markdown", - "id": "1c754dbb", + "id": "4274417c", "metadata": { "editable": true }, "source": [ "$$\n", - "\\frac{\\partial C}{\\partial w_{00}^{(1)}}=\\delta_0^{(1)}a_0^{(1)}.\n", + "\\frac{\\partial C}{\\partial w_{11}^{(1)}}=\\delta_1^{(1)}a_1^{(1)}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "e0b9760c", + "id": "b615718d", "metadata": { "editable": true }, @@ -1034,19 +1034,19 @@ }, { "cell_type": "markdown", - "id": "b1efb446", + "id": "c541b15f", "metadata": { "editable": true }, "source": [ "$$\n", - "\\frac{\\partial C}{\\partial w_{01}^{(1)}}=\\delta_0^{(1)}a_1^{(1)}.\n", + "\\frac{\\partial C}{\\partial w_{12}^{(1)}}=\\delta_1^{(1)}a_2^{(1)}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "2cf7b43f", + "id": "6b741552", "metadata": { "editable": true }, @@ -1058,19 +1058,19 @@ }, { "cell_type": "markdown", - "id": "262b517f", + "id": "d564e7a9", "metadata": { "editable": true }, "source": [ "$$\n", - "\\frac{\\partial C}{\\partial w_{10}^{(1)}}=\\delta_1^{(1)}a_0^{(1)},\n", + "\\frac{\\partial C}{\\partial w_{21}^{(1)}}=\\delta_2^{(1)}a_1^{(1)},\n", "$$" ] }, { "cell_type": "markdown", - "id": "59285e3f", + "id": "927894b5", "metadata": { "editable": true }, @@ -1080,19 +1080,19 @@ }, { "cell_type": "markdown", - "id": "2813790f", + "id": "75624550", "metadata": { "editable": true }, "source": [ "$$\n", - "\\frac{\\partial C}{\\partial w_{11}^{(1)}}=\\delta_1^{(1)}a_1^{(1)},\n", + "\\frac{\\partial C}{\\partial w_{22}^{(1)}}=\\delta_2^{(1)}a_2^{(1)},\n", "$$" ] }, { "cell_type": "markdown", - "id": "a56b94b4", + "id": "9252c078", "metadata": { "editable": true }, @@ -1102,19 +1102,19 @@ }, { "cell_type": "markdown", - "id": "a3ed9010", + "id": "10c7da6e", "metadata": { "editable": true }, "source": [ "$$\n", - "\\delta_1^{(1)}=w_1^{(2)}\\frac{\\partial a_1^{(1)}}{\\partial z_1^{(1)}}\\delta^{(2)}.\n", + "\\delta_2^{(1)}=w_2^{(2)}\\frac{\\partial a_2^{(1)}}{\\partial z_2^{(1)}}\\delta^{(2)}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "03a5562c", + "id": "0fe640a9", "metadata": { "editable": true }, @@ -1126,19 +1126,19 @@ }, { "cell_type": "markdown", - "id": "025bd04f", + "id": "01ff9a38", "metadata": { "editable": true }, "source": [ "$$\n", - "\\frac{\\partial C}{\\partial b_{0}^{(1)}}=\\delta_0^{(1)},\n", + "\\frac{\\partial C}{\\partial b_{1}^{(1)}}=\\delta_1^{(1)},\n", "$$" ] }, { "cell_type": "markdown", - "id": "e1ef6c2f", + "id": "37fda9de", "metadata": { "editable": true }, @@ -1148,19 +1148,19 @@ }, { "cell_type": "markdown", - "id": "157d7580", + "id": "861af2b9", "metadata": { "editable": true }, "source": [ "$$\n", - "\\frac{\\partial C}{\\partial b_{1}^{(1)}}=\\delta_1^{(1)}.\n", + "\\frac{\\partial C}{\\partial b_{2}^{(1)}}=\\delta_2^{(1)}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "389a7e2d", + "id": "f9cea8b7", "metadata": { "editable": true }, @@ -1170,7 +1170,7 @@ }, { "cell_type": "markdown", - "id": "bccf9918", + "id": "12e3298b", "metadata": { "editable": true }, @@ -1183,7 +1183,7 @@ }, { "cell_type": "markdown", - "id": "ab05945c", + "id": "a104df98", "metadata": { "editable": true }, @@ -1195,7 +1195,7 @@ }, { "cell_type": "markdown", - "id": "cb2ef195", + "id": "9bc2f036", "metadata": { "editable": true }, @@ -1205,7 +1205,7 @@ }, { "cell_type": "markdown", - "id": "da672f61", + "id": "568ced5c", "metadata": { "editable": true }, @@ -1217,7 +1217,7 @@ }, { "cell_type": "markdown", - "id": "95dd3d2b", + "id": "906d2bd9", "metadata": { "editable": true }, @@ -1227,7 +1227,7 @@ }, { "cell_type": "markdown", - "id": "532b99a2", + "id": "79992e6f", "metadata": { "editable": true }, @@ -1239,7 +1239,7 @@ }, { "cell_type": "markdown", - "id": "5d5f45cc", + "id": "0745b6ba", "metadata": { "editable": true }, @@ -1249,7 +1249,7 @@ }, { "cell_type": "markdown", - "id": "2333cfb1", + "id": "4fb2781f", "metadata": { "editable": true }, @@ -1261,7 +1261,7 @@ }, { "cell_type": "markdown", - "id": "4b555f81", + "id": "57576b6e", "metadata": { "editable": true }, @@ -1271,7 +1271,7 @@ }, { "cell_type": "markdown", - "id": "20c0952f", + "id": "d1f38053", "metadata": { "editable": true }, @@ -1288,7 +1288,7 @@ }, { "cell_type": "markdown", - "id": "5a155f81", + "id": "6f6f31e8", "metadata": { "editable": true }, @@ -1300,7 +1300,7 @@ }, { "cell_type": "markdown", - "id": "ff1fc071", + "id": "f206ae2b", "metadata": { "editable": true }, @@ -1312,7 +1312,7 @@ }, { "cell_type": "markdown", - "id": "63576478", + "id": "5e7af877", "metadata": { "editable": true }, @@ -1328,7 +1328,7 @@ }, { "cell_type": "markdown", - "id": "3410ad89", + "id": "96c13dab", "metadata": { "editable": true }, @@ -1345,7 +1345,7 @@ }, { "cell_type": "markdown", - "id": "c71d887c", + "id": "a6781c7d", "metadata": { "editable": true }, @@ -1357,7 +1357,7 @@ }, { "cell_type": "markdown", - "id": "ffeae21c", + "id": "4db58da4", "metadata": { "editable": true }, @@ -1370,7 +1370,7 @@ }, { "cell_type": "markdown", - "id": "2fe917a4", + "id": "b4458c55", "metadata": { "editable": true }, @@ -1382,7 +1382,7 @@ }, { "cell_type": "markdown", - "id": "65404bec", + "id": "b32e0714", "metadata": { "editable": true }, @@ -1398,7 +1398,7 @@ }, { "cell_type": "markdown", - "id": "a6c0c8b6", + "id": "fffb7785", "metadata": { "editable": true }, @@ -1410,7 +1410,7 @@ }, { "cell_type": "markdown", - "id": "2454faec", + "id": "08bff16c", "metadata": { "editable": true }, @@ -1426,7 +1426,7 @@ }, { "cell_type": "markdown", - "id": "e5b67040", + "id": "fb907bb3", "metadata": { "editable": true }, @@ -1438,7 +1438,7 @@ }, { "cell_type": "markdown", - "id": "aaec49a4", + "id": "f97ed7ef", "metadata": { "editable": true }, @@ -1450,7 +1450,7 @@ }, { "cell_type": "markdown", - "id": "e8ad40d3", + "id": "136c2230", "metadata": { "editable": true }, @@ -1460,7 +1460,7 @@ }, { "cell_type": "markdown", - "id": "e04a4d28", + "id": "4b2344b6", "metadata": { "editable": true }, @@ -1472,7 +1472,7 @@ }, { "cell_type": "markdown", - "id": "9b121a33", + "id": "52a4e7a7", "metadata": { "editable": true }, @@ -1482,7 +1482,7 @@ }, { "cell_type": "markdown", - "id": "3bf7d884", + "id": "163ee2e5", "metadata": { "editable": true }, @@ -1494,7 +1494,7 @@ }, { "cell_type": "markdown", - "id": "7d58918c", + "id": "5aa607a5", "metadata": { "editable": true }, @@ -1508,7 +1508,7 @@ }, { "cell_type": "markdown", - "id": "d21dce97", + "id": "da13c77b", "metadata": { "editable": true }, @@ -1520,7 +1520,7 @@ }, { "cell_type": "markdown", - "id": "dc143bea", + "id": "7bf944d0", "metadata": { "editable": true }, @@ -1530,7 +1530,7 @@ }, { "cell_type": "markdown", - "id": "49415a06", + "id": "ea130e95", "metadata": { "editable": true }, @@ -1542,7 +1542,7 @@ }, { "cell_type": "markdown", - "id": "4398e11e", + "id": "2fba64b7", "metadata": { "editable": true }, @@ -1552,7 +1552,7 @@ }, { "cell_type": "markdown", - "id": "da3fca7e", + "id": "5904a528", "metadata": { "editable": true }, @@ -1564,7 +1564,7 @@ }, { "cell_type": "markdown", - "id": "9055bc57", + "id": "86f8199b", "metadata": { "editable": true }, @@ -1576,7 +1576,7 @@ }, { "cell_type": "markdown", - "id": "c7995e73", + "id": "e4370f9f", "metadata": { "editable": true }, @@ -1588,7 +1588,7 @@ }, { "cell_type": "markdown", - "id": "d142f966", + "id": "f60e1730", "metadata": { "editable": true }, @@ -1598,7 +1598,7 @@ }, { "cell_type": "markdown", - "id": "d5dc5f9f", + "id": "e282d002", "metadata": { "editable": true }, @@ -1610,7 +1610,7 @@ }, { "cell_type": "markdown", - "id": "5f598e3e", + "id": "5de6d59f", "metadata": { "editable": true }, @@ -1620,7 +1620,7 @@ }, { "cell_type": "markdown", - "id": "9769b50e", + "id": "97c35e7d", "metadata": { "editable": true }, @@ -1632,7 +1632,7 @@ }, { "cell_type": "markdown", - "id": "5a8851ae", + "id": "c4754c54", "metadata": { "editable": true }, @@ -1650,7 +1650,7 @@ }, { "cell_type": "markdown", - "id": "b455efff", + "id": "0b03f12b", "metadata": { "editable": true }, @@ -1668,7 +1668,7 @@ }, { "cell_type": "markdown", - "id": "8b430778", + "id": "ad079735", "metadata": { "editable": true }, @@ -1680,7 +1680,7 @@ }, { "cell_type": "markdown", - "id": "7fb2cea5", + "id": "0bf757b6", "metadata": { "editable": true }, @@ -1690,7 +1690,7 @@ }, { "cell_type": "markdown", - "id": "6c77ac74", + "id": "b6246783", "metadata": { "editable": true }, @@ -1702,7 +1702,7 @@ }, { "cell_type": "markdown", - "id": "708f42bb", + "id": "b7575d50", "metadata": { "editable": true }, @@ -1714,7 +1714,7 @@ }, { "cell_type": "markdown", - "id": "40f66bf5", + "id": "e6c93f95", "metadata": { "editable": true }, @@ -1726,7 +1726,7 @@ }, { "cell_type": "markdown", - "id": "21b9ebbe", + "id": "b52b78ac", "metadata": { "editable": true }, @@ -1736,7 +1736,7 @@ }, { "cell_type": "markdown", - "id": "665ad548", + "id": "a5fdfb9c", "metadata": { "editable": true }, @@ -1748,7 +1748,7 @@ }, { "cell_type": "markdown", - "id": "c182abd9", + "id": "8bd7f846", "metadata": { "editable": true }, @@ -1758,7 +1758,7 @@ }, { "cell_type": "markdown", - "id": "aa70c6cf", + "id": "550334c8", "metadata": { "editable": true }, @@ -1770,7 +1770,7 @@ }, { "cell_type": "markdown", - "id": "db460a07", + "id": "ac298c05", "metadata": { "editable": true }, @@ -1788,7 +1788,7 @@ }, { "cell_type": "markdown", - "id": "3af036d6", + "id": "6609cbf5", "metadata": { "editable": true }, @@ -1798,7 +1798,7 @@ }, { "cell_type": "markdown", - "id": "5662288a", + "id": "64741262", "metadata": { "editable": true }, @@ -1816,7 +1816,7 @@ }, { "cell_type": "markdown", - "id": "b6a8a1ac", + "id": "76c4610d", "metadata": { "editable": true }, @@ -1826,7 +1826,7 @@ }, { "cell_type": "markdown", - "id": "dda8fce0", + "id": "efd0ba93", "metadata": { "editable": true }, @@ -1844,7 +1844,7 @@ }, { "cell_type": "markdown", - "id": "f1957ab0", + "id": "98e88435", "metadata": { "editable": true }, @@ -1856,7 +1856,7 @@ }, { "cell_type": "markdown", - "id": "31c8f2c9", + "id": "08bdbdff", "metadata": { "editable": true }, @@ -1868,7 +1868,7 @@ }, { "cell_type": "markdown", - "id": "bba8d29e", + "id": "e234c8a6", "metadata": { "editable": true }, @@ -1878,7 +1878,7 @@ }, { "cell_type": "markdown", - "id": "af4922ec", + "id": "6a4118be", "metadata": { "editable": true }, @@ -1890,7 +1890,7 @@ }, { "cell_type": "markdown", - "id": "f43f0f87", + "id": "d211df4b", "metadata": { "editable": true }, @@ -1902,7 +1902,7 @@ }, { "cell_type": "markdown", - "id": "eba489e4", + "id": "bf0c2817", "metadata": { "editable": true }, @@ -1912,7 +1912,7 @@ }, { "cell_type": "markdown", - "id": "82610f92", + "id": "2de9333a", "metadata": { "editable": true }, @@ -1924,7 +1924,7 @@ }, { "cell_type": "markdown", - "id": "62513d62", + "id": "00d82ece", "metadata": { "editable": true }, @@ -1934,7 +1934,7 @@ }, { "cell_type": "markdown", - "id": "ca381ec8", + "id": "19f78643", "metadata": { "editable": true }, @@ -1946,7 +1946,7 @@ }, { "cell_type": "markdown", - "id": "bdf32ad4", + "id": "1424f687", "metadata": { "editable": true }, @@ -1958,14 +1958,40 @@ }, { "cell_type": "markdown", - "id": "764448ea", + "id": "9d7c23b2", "metadata": { "editable": true }, "source": [ - "## Setting up the back propagation algorithm\n", + "## Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations\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", + "**The architecture (our model).**\n", + "\n", + "1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)\n", + "\n", + "2. Define the number of hidden layers and hidden nodes\n", + "\n", + "3. Define activation functions for hidden layers and output layers\n", + "\n", + "4. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates\n", + "\n", + "5. Define cost function and possible regularization terms with hyperparameters\n", + "\n", + "6. Initialize weights and biases\n", + "\n", + "7. Fix number of iterations for the feed forward part and back propagation part" + ] + }, + { + "cell_type": "markdown", + "id": "1decfbef", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the back propagation algorithm, part 1\n", + "\n", + "The four equations provide us with a way of computing the gradients 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", @@ -1981,7 +2007,7 @@ }, { "cell_type": "markdown", - "id": "989c3082", + "id": "7f237d52", "metadata": { "editable": true }, @@ -1993,7 +2019,7 @@ }, { "cell_type": "markdown", - "id": "9d14949a", + "id": "d37fa1b5", "metadata": { "editable": true }, @@ -2005,7 +2031,7 @@ }, { "cell_type": "markdown", - "id": "4ee118b1", + "id": "213b757d", "metadata": { "editable": true }, @@ -2015,7 +2041,7 @@ }, { "cell_type": "markdown", - "id": "ba89ad67", + "id": "3137751d", "metadata": { "editable": true }, @@ -2027,7 +2053,7 @@ }, { "cell_type": "markdown", - "id": "e1f840c5", + "id": "da1cf61b", "metadata": { "editable": true }, @@ -2041,7 +2067,7 @@ }, { "cell_type": "markdown", - "id": "9f06bcfc", + "id": "3b57ef97", "metadata": { "editable": true }, @@ -2053,7 +2079,7 @@ }, { "cell_type": "markdown", - "id": "7063f2be", + "id": "bb0c4d59", "metadata": { "editable": true }, @@ -2065,7 +2091,7 @@ }, { "cell_type": "markdown", - "id": "3e299445", + "id": "a9483fc9", "metadata": { "editable": true }, @@ -2075,7 +2101,7 @@ }, { "cell_type": "markdown", - "id": "28921878", + "id": "49c7c2f3", "metadata": { "editable": true }, @@ -2087,7 +2113,7 @@ }, { "cell_type": "markdown", - "id": "90f5404c", + "id": "734ef014", "metadata": { "editable": true }, @@ -2099,7 +2125,7 @@ }, { "cell_type": "markdown", - "id": "53c2dfbd", + "id": "ac393c38", "metadata": { "editable": true }, @@ -2109,7 +2135,7 @@ }, { "cell_type": "markdown", - "id": "03805799", + "id": "c38ed8eb", "metadata": { "editable": true }, @@ -2121,7 +2147,7 @@ }, { "cell_type": "markdown", - "id": "4f8f9c02", + "id": "d097bbf6", "metadata": { "editable": true }, @@ -2133,17 +2159,17 @@ }, { "cell_type": "markdown", - "id": "9bf86f9c", + "id": "56e28349", "metadata": { "editable": true }, "source": [ - "### Activation functions\n", + "## 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", + "connectivity, is the choice of activation function(s). The following\n", + "restrictions are imposed on an activation function for an FFNN to\n", + "fulfill the universal approximation theorem\n", "\n", " * Non-constant\n", "\n", @@ -2156,7 +2182,7 @@ }, { "cell_type": "markdown", - "id": "eeaed73c", + "id": "0f764f08", "metadata": { "editable": true }, @@ -2175,7 +2201,7 @@ }, { "cell_type": "markdown", - "id": "0786aaf0", + "id": "697fbd9c", "metadata": { "editable": true }, @@ -2187,7 +2213,7 @@ }, { "cell_type": "markdown", - "id": "aa76601b", + "id": "e9f79c9b", "metadata": { "editable": true }, @@ -2197,7 +2223,7 @@ }, { "cell_type": "markdown", - "id": "e1bca915", + "id": "8285a58e", "metadata": { "editable": true }, @@ -2209,12 +2235,12 @@ }, { "cell_type": "markdown", - "id": "1832a8c4", + "id": "eba13151", "metadata": { "editable": true }, "source": [ - "### Relevance\n", + "## Relevance\n", "\n", "The *sigmoid* function are more biologically plausible because the\n", "output of inactive neurons are zero. Such activation function are\n", @@ -2226,7 +2252,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "5c689736", + "id": "d5693cd0", "metadata": { "collapsed": false, "editable": true @@ -2310,7 +2336,228 @@ }, { "cell_type": "markdown", - "id": "0b3a4c95", + "id": "b0e28a6b", + "metadata": { + "editable": true + }, + "source": [ + "## Vanishing gradients\n", + "\n", + "The Back propagation algorithm we derived above works by going from\n", + "the output layer to the input layer, propagating the error gradient on\n", + "the way. Once the algorithm has computed the gradient of the cost\n", + "function with regards to each parameter in the network, it uses these\n", + "gradients to update each parameter with a Gradient Descent (GD) step.\n", + "\n", + "Unfortunately for us, the gradients often get smaller and smaller as\n", + "the algorithm progresses down to the first hidden layers. As a result,\n", + "the GD update leaves the lower layer connection weights virtually\n", + "unchanged, and training never converges to a good solution. This is\n", + "known in the literature as **the vanishing gradients problem**." + ] + }, + { + "cell_type": "markdown", + "id": "436fb27b", + "metadata": { + "editable": true + }, + "source": [ + "## Exploding gradients\n", + "\n", + "In other cases, the opposite can happen, namely the the gradients can\n", + "grow bigger and bigger. The result is that many of the layers get\n", + "large updates of the weights the algorithm diverges. This is the\n", + "**exploding gradients problem**, which is mostly encountered in\n", + "recurrent neural networks. More generally, deep neural networks suffer\n", + "from unstable gradients, different layers may learn at widely\n", + "different speeds" + ] + }, + { + "cell_type": "markdown", + "id": "9319de67", + "metadata": { + "editable": true + }, + "source": [ + "## Is the Logistic activation function (Sigmoid) our choice?\n", + "\n", + "Although this unfortunate behavior has been empirically observed for\n", + "quite a while (it was one of the reasons why deep neural networks were\n", + "mostly abandoned for a long time), it is only around 2010 that\n", + "significant progress was made in understanding it.\n", + "\n", + "A paper titled [Understanding the Difficulty of Training Deep\n", + "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n", + "the problems with the popular logistic\n", + "sigmoid activation function and the weight initialization technique\n", + "that was most popular at the time, namely random initialization using\n", + "a normal distribution with a mean of 0 and a standard deviation of\n", + "1." + ] + }, + { + "cell_type": "markdown", + "id": "e90fbb0a", + "metadata": { + "editable": true + }, + "source": [ + "## Logistic function as the root of problems\n", + "\n", + "They showed that with this activation function and this\n", + "initialization scheme, the variance of the outputs of each layer is\n", + "much greater than the variance of its inputs. Going forward in the\n", + "network, the variance keeps increasing after each layer until the\n", + "activation function saturates at the top layers. This is actually made\n", + "worse by the fact that the logistic function has a mean of 0.5, not 0\n", + "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n", + "better than the logistic function in deep networks)." + ] + }, + { + "cell_type": "markdown", + "id": "7a18427f", + "metadata": { + "editable": true + }, + "source": [ + "## The derivative of the Logistic funtion\n", + "\n", + "Looking at the logistic activation function, when inputs become large\n", + "(negative or positive), the function saturates at 0 or 1, with a\n", + "derivative extremely close to 0. Thus when backpropagation kicks in,\n", + "it has virtually no gradient to propagate back through the network,\n", + "and what little gradient exists keeps getting diluted as\n", + "backpropagation progresses down through the top layers, so there is\n", + "really nothing left for the lower layers.\n", + "\n", + "In their paper, Glorot and Bengio propose a way to significantly\n", + "alleviate this problem. We need the signal to flow properly in both\n", + "directions: in the forward direction when making predictions, and in\n", + "the reverse direction when backpropagating gradients. We don’t want\n", + "the signal to die out, nor do we want it to explode and saturate. For\n", + "the signal to flow properly, the authors argue that we need the\n", + "variance of the outputs of each layer to be equal to the variance of\n", + "its inputs, and we also need the gradients to have equal variance\n", + "before and after flowing through a layer in the reverse direction." + ] + }, + { + "cell_type": "markdown", + "id": "ac352aa1", + "metadata": { + "editable": true + }, + "source": [ + "## Insights from the paper by Glorot and Bengio\n", + "\n", + "One of the insights in the 2010 paper by Glorot and Bengio was that\n", + "the vanishing/exploding gradients problems were in part due to a poor\n", + "choice of activation function. Until then most people had assumed that\n", + "if Nature had chosen to use roughly sigmoid activation functions in\n", + "biological neurons, they must be an excellent choice. But it turns out\n", + "that other activation functions behave much better in deep neural\n", + "networks, in particular the ReLU activation function, mostly because\n", + "it does not saturate for positive values (and also because it is quite\n", + "fast to compute)." + ] + }, + { + "cell_type": "markdown", + "id": "67a8bef0", + "metadata": { + "editable": true + }, + "source": [ + "## The RELU function family\n", + "\n", + "The ReLU activation function suffers from a problem known as the dying\n", + "ReLUs: during training, some neurons effectively die, meaning they\n", + "stop outputting anything other than 0.\n", + "\n", + "In some cases, you may find that half of your network’s neurons are\n", + "dead, especially if you used a large learning rate. During training,\n", + "if a neuron’s weights get updated such that the weighted sum of the\n", + "neuron’s inputs is negative, it will start outputting 0. When this\n", + "happen, the neuron is unlikely to come back to life since the gradient\n", + "of the ReLU function is 0 when its input is negative." + ] + }, + { + "cell_type": "markdown", + "id": "76de2016", + "metadata": { + "editable": true + }, + "source": [ + "## ELU function\n", + "\n", + "To solve this problem, nowadays practitioners use a variant of the\n", + "ReLU function, such as the leaky ReLU discussed above or the so-called\n", + "exponential linear unit (ELU) function" + ] + }, + { + "cell_type": "markdown", + "id": "e798fa5d", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6f33abb9", + "metadata": { + "editable": true + }, + "source": [ + "## Which activation function should we use?\n", + "\n", + "In general it seems that the ELU activation function is better than\n", + "the leaky ReLU function (and its variants), which is better than\n", + "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", + "than the logistic function.\n", + "\n", + "If runtime performance is an issue, then you may opt for the leaky\n", + "ReLU function over the ELU function If you don’t want to tweak yet\n", + "another hyperparameter, you may just use the default $\\alpha$ of\n", + "$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and\n", + "computing power, you can use cross-validation or bootstrap to evaluate\n", + "other activation functions." + ] + }, + { + "cell_type": "markdown", + "id": "ad76ab9d", + "metadata": { + "editable": true + }, + "source": [ + "## More on activation functions, output layers\n", + "\n", + "In most cases you can use the ReLU activation function in the hidden\n", + "layers (or one of its variants).\n", + "\n", + "It is a bit faster to compute than other activation functions, and the\n", + "gradient descent optimization does in general not get stuck.\n", + "\n", + "**For the output layer:**\n", + "\n", + "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n", + "\n", + "* For regression tasks, you can simply use no activation function at all." + ] + }, + { + "cell_type": "markdown", + "id": "4d0588bb", "metadata": { "editable": true }, @@ -2339,7 +2586,7 @@ }, { "cell_type": "markdown", - "id": "9955a636", + "id": "cb5679f8", "metadata": { "editable": true }, @@ -2347,7 +2594,7 @@ "## Hidden layers\n", "\n", "For many problems you can start with just one or two hidden layers and\n", - "it will work just fine. For the MNIST data set you ca easily get a\n", + "it will work just fine. For the MNIST data set discussed below you can easily get a\n", "high accuracy using just one hidden layer with a few hundred neurons.\n", "You can reach for this data set above 98% accuracy using two hidden\n", "layers with the same total amount of neurons, in roughly the same\n", @@ -2365,228 +2612,7 @@ }, { "cell_type": "markdown", - "id": "f1aa77e9", - "metadata": { - "editable": true - }, - "source": [ - "## Vanishing gradients\n", - "\n", - "The Back propagation algorithm we derived above works by going from\n", - "the output layer to the input layer, propagating the error gradient on\n", - "the way. Once the algorithm has computed the gradient of the cost\n", - "function with regards to each parameter in the network, it uses these\n", - "gradients to update each parameter with a Gradient Descent (GD) step.\n", - "\n", - "Unfortunately for us, the gradients often get smaller and smaller as\n", - "the algorithm progresses down to the first hidden layers. As a result,\n", - "the GD update leaves the lower layer connection weights virtually\n", - "unchanged, and training never converges to a good solution. This is\n", - "known in the literature as **the vanishing gradients problem**." - ] - }, - { - "cell_type": "markdown", - "id": "3703bb33", - "metadata": { - "editable": true - }, - "source": [ - "## Exploding gradients\n", - "\n", - "In other cases, the opposite can happen, namely the the gradients can\n", - "grow bigger and bigger. The result is that many of the layers get\n", - "large updates of the weights the algorithm diverges. This is the\n", - "**exploding gradients problem**, which is mostly encountered in\n", - "recurrent neural networks. More generally, deep neural networks suffer\n", - "from unstable gradients, different layers may learn at widely\n", - "different speeds" - ] - }, - { - "cell_type": "markdown", - "id": "43b1aa26", - "metadata": { - "editable": true - }, - "source": [ - "## Is the Logistic activation function (Sigmoid) our choice?\n", - "\n", - "Although this unfortunate behavior has been empirically observed for\n", - "quite a while (it was one of the reasons why deep neural networks were\n", - "mostly abandoned for a long time), it is only around 2010 that\n", - "significant progress was made in understanding it.\n", - "\n", - "A paper titled [Understanding the Difficulty of Training Deep\n", - "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n", - "the problems with the popular logistic\n", - "sigmoid activation function and the weight initialization technique\n", - "that was most popular at the time, namely random initialization using\n", - "a normal distribution with a mean of 0 and a standard deviation of\n", - "1." - ] - }, - { - "cell_type": "markdown", - "id": "463f4f64", - "metadata": { - "editable": true - }, - "source": [ - "## Logistic function as the root of problems\n", - "\n", - "They showed that with this activation function and this\n", - "initialization scheme, the variance of the outputs of each layer is\n", - "much greater than the variance of its inputs. Going forward in the\n", - "network, the variance keeps increasing after each layer until the\n", - "activation function saturates at the top layers. This is actually made\n", - "worse by the fact that the logistic function has a mean of 0.5, not 0\n", - "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n", - "better than the logistic function in deep networks)." - ] - }, - { - "cell_type": "markdown", - "id": "6c9ea582", - "metadata": { - "editable": true - }, - "source": [ - "## The derivative of the Logistic funtion\n", - "\n", - "Looking at the logistic activation function, when inputs become large\n", - "(negative or positive), the function saturates at 0 or 1, with a\n", - "derivative extremely close to 0. Thus when backpropagation kicks in,\n", - "it has virtually no gradient to propagate back through the network,\n", - "and what little gradient exists keeps getting diluted as\n", - "backpropagation progresses down through the top layers, so there is\n", - "really nothing left for the lower layers.\n", - "\n", - "In their paper, Glorot and Bengio propose a way to significantly\n", - "alleviate this problem. We need the signal to flow properly in both\n", - "directions: in the forward direction when making predictions, and in\n", - "the reverse direction when backpropagating gradients. We don’t want\n", - "the signal to die out, nor do we want it to explode and saturate. For\n", - "the signal to flow properly, the authors argue that we need the\n", - "variance of the outputs of each layer to be equal to the variance of\n", - "its inputs, and we also need the gradients to have equal variance\n", - "before and after flowing through a layer in the reverse direction." - ] - }, - { - "cell_type": "markdown", - "id": "80c83d2c", - "metadata": { - "editable": true - }, - "source": [ - "## Insights from the paper by Glorot and Bengio\n", - "\n", - "One of the insights in the 2010 paper by Glorot and Bengio was that\n", - "the vanishing/exploding gradients problems were in part due to a poor\n", - "choice of activation function. Until then most people had assumed that\n", - "if Nature had chosen to use roughly sigmoid activation functions in\n", - "biological neurons, they must be an excellent choice. But it turns out\n", - "that other activation functions behave much better in deep neural\n", - "networks, in particular the ReLU activation function, mostly because\n", - "it does not saturate for positive values (and also because it is quite\n", - "fast to compute)." - ] - }, - { - "cell_type": "markdown", - "id": "55a1ad5d", - "metadata": { - "editable": true - }, - "source": [ - "## The RELU function family\n", - "\n", - "The ReLU activation function suffers from a problem known as the dying\n", - "ReLUs: during training, some neurons effectively die, meaning they\n", - "stop outputting anything other than 0.\n", - "\n", - "In some cases, you may find that half of your network’s neurons are\n", - "dead, especially if you used a large learning rate. During training,\n", - "if a neuron’s weights get updated such that the weighted sum of the\n", - "neuron’s inputs is negative, it will start outputting 0. When this\n", - "happen, the neuron is unlikely to come back to life since the gradient\n", - "of the ReLU function is 0 when its input is negative." - ] - }, - { - "cell_type": "markdown", - "id": "b7fafe4a", - "metadata": { - "editable": true - }, - "source": [ - "## ELU function\n", - "\n", - "To solve this problem, nowadays practitioners use a variant of the\n", - "ReLU function, such as the leaky ReLU discussed above or the so-called\n", - "exponential linear unit (ELU) function" - ] - }, - { - "cell_type": "markdown", - "id": "46e10153", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0930ba50", - "metadata": { - "editable": true - }, - "source": [ - "## Which activation function should we use?\n", - "\n", - "In general it seems that the ELU activation function is better than\n", - "the leaky ReLU function (and its variants), which is better than\n", - "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", - "than the logistic function.\n", - "\n", - "If runtime performance is an issue, then you may opt for the leaky\n", - "ReLU function over the ELU function If you don’t want to tweak yet\n", - "another hyperparameter, you may just use the default $\\alpha$ of\n", - "$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and\n", - "computing power, you can use cross-validation or bootstrap to evaluate\n", - "other activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "5c0c59af", - "metadata": { - "editable": true - }, - "source": [ - "## More on activation functions, output layers\n", - "\n", - "In most cases you can use the ReLU activation function in the hidden\n", - "layers (or one of its variants).\n", - "\n", - "It is a bit faster to compute than other activation functions, and the\n", - "gradient descent optimization does in general not get stuck.\n", - "\n", - "**For the output layer:**\n", - "\n", - "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n", - "\n", - "* For regression tasks, you can simply use no activation function at all." - ] - }, - { - "cell_type": "markdown", - "id": "582e4df4", + "id": "fa928c9b", "metadata": { "editable": true }, @@ -2612,7 +2638,7 @@ }, { "cell_type": "markdown", - "id": "ea360013", + "id": "4a9462ce", "metadata": { "editable": true }, @@ -2632,7 +2658,7 @@ }, { "cell_type": "markdown", - "id": "fee98b12", + "id": "e523997a", "metadata": { "editable": true }, @@ -2652,7 +2678,7 @@ }, { "cell_type": "markdown", - "id": "c9f175b0", + "id": "19bba5e1", "metadata": { "editable": true }, @@ -2678,7 +2704,7 @@ }, { "cell_type": "markdown", - "id": "f6f04fbb", + "id": "ff6b5f13", "metadata": { "editable": true }, @@ -2707,7 +2733,7 @@ }, { "cell_type": "markdown", - "id": "d4184eee", + "id": "df905d9f", "metadata": { "editable": true }, @@ -2725,7 +2751,7 @@ }, { "cell_type": "markdown", - "id": "82d314da", + "id": "233e93d6", "metadata": { "editable": true }, @@ -2741,7 +2767,7 @@ }, { "cell_type": "markdown", - "id": "abc6640b", + "id": "0034168c", "metadata": { "editable": true }, @@ -2753,7 +2779,7 @@ }, { "cell_type": "markdown", - "id": "bb7d1f89", + "id": "cd701f7d", "metadata": { "editable": true }, @@ -2767,109 +2793,7 @@ }, { "cell_type": "markdown", - "id": "442b1b5e", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the back-propagation algorithm\n", - "\n", - "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": "0005e340", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2b27751b", - "metadata": { - "editable": true - }, - "source": [ - "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" - ] - }, - { - "cell_type": "markdown", - "id": "dd544b4b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "57a7d213", - "metadata": { - "editable": true - }, - "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": "932510f4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{ij}^l\\leftarrow = w_{ij}^l- \\eta \\delta_j^la_i^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bf80ed99", - "metadata": { - "editable": true - }, - "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": "f682bf76", - "metadata": { - "editable": true - }, - "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": "ad2b26a4", + "id": "84048fb0", "metadata": { "editable": true }, @@ -2897,7 +2821,7 @@ }, { "cell_type": "markdown", - "id": "a08331b2", + "id": "61ea03ed", "metadata": { "editable": true }, @@ -2909,7 +2833,7 @@ }, { "cell_type": "markdown", - "id": "9ebfde52", + "id": "abd0c817", "metadata": { "editable": true }, @@ -2919,7 +2843,7 @@ }, { "cell_type": "markdown", - "id": "531dfa25", + "id": "2e0379cc", "metadata": { "editable": true }, @@ -2931,7 +2855,7 @@ }, { "cell_type": "markdown", - "id": "8941d38c", + "id": "59290cf7", "metadata": { "editable": true }, @@ -2942,7 +2866,7 @@ }, { "cell_type": "markdown", - "id": "7ae7e222", + "id": "6bc256eb", "metadata": { "editable": true }, @@ -2954,7 +2878,7 @@ }, { "cell_type": "markdown", - "id": "cbb157cc", + "id": "831eee08", "metadata": { "editable": true }, @@ -2967,7 +2891,7 @@ }, { "cell_type": "markdown", - "id": "0178770c", + "id": "ba46bcc0", "metadata": { "editable": true }, @@ -2992,7 +2916,7 @@ }, { "cell_type": "markdown", - "id": "cb69f3df", + "id": "a475ed33", "metadata": { "editable": true }, @@ -3005,7 +2929,7 @@ }, { "cell_type": "markdown", - "id": "11aa1335", + "id": "378895ce", "metadata": { "editable": true }, @@ -3017,7 +2941,7 @@ }, { "cell_type": "markdown", - "id": "a225e57a", + "id": "268989a6", "metadata": { "editable": true }, @@ -3029,7 +2953,7 @@ }, { "cell_type": "markdown", - "id": "569dd3f2", + "id": "1ac5dfe0", "metadata": { "editable": true }, @@ -3039,7 +2963,7 @@ }, { "cell_type": "markdown", - "id": "f8e84cae", + "id": "4d3d6bb7", "metadata": { "editable": true }, @@ -3051,7 +2975,7 @@ }, { "cell_type": "markdown", - "id": "1dd303e8", + "id": "bc4e4a53", "metadata": { "editable": true }, @@ -3063,7 +2987,7 @@ }, { "cell_type": "markdown", - "id": "33494270", + "id": "4cc000a1", "metadata": { "editable": true }, @@ -3075,7 +2999,7 @@ }, { "cell_type": "markdown", - "id": "01bd6a05", + "id": "7f5ea691", "metadata": { "editable": true }, @@ -3087,7 +3011,7 @@ }, { "cell_type": "markdown", - "id": "60f16a47", + "id": "a7f4fc8e", "metadata": { "editable": true }, @@ -3097,7 +3021,7 @@ }, { "cell_type": "markdown", - "id": "ab0c42b3", + "id": "acdecb39", "metadata": { "editable": true }, @@ -3109,7 +3033,7 @@ }, { "cell_type": "markdown", - "id": "dcfb2e28", + "id": "b0c3e8c7", "metadata": { "editable": true }, @@ -3119,7 +3043,7 @@ }, { "cell_type": "markdown", - "id": "5076b392", + "id": "6e130deb", "metadata": { "editable": true }, @@ -3131,7 +3055,7 @@ }, { "cell_type": "markdown", - "id": "9d6001f4", + "id": "23e83ce8", "metadata": { "editable": true }, @@ -3144,7 +3068,7 @@ }, { "cell_type": "markdown", - "id": "d0245c18", + "id": "67c77893", "metadata": { "editable": true }, @@ -3156,7 +3080,7 @@ }, { "cell_type": "markdown", - "id": "030ac014", + "id": "36ede636", "metadata": { "editable": true }, @@ -3166,7 +3090,7 @@ }, { "cell_type": "markdown", - "id": "bdc01c83", + "id": "4008b26c", "metadata": { "editable": true }, @@ -3178,7 +3102,7 @@ }, { "cell_type": "markdown", - "id": "1a77b25c", + "id": "258ae1d4", "metadata": { "editable": true }, @@ -3189,7 +3113,7 @@ }, { "cell_type": "markdown", - "id": "1f169ed1", + "id": "b9c648be", "metadata": { "editable": true }, @@ -3201,7 +3125,7 @@ }, { "cell_type": "markdown", - "id": "6bc460e2", + "id": "615f1fce", "metadata": { "editable": true }, @@ -3211,7 +3135,7 @@ }, { "cell_type": "markdown", - "id": "fe1f92c0", + "id": "620b34cb", "metadata": { "editable": true }, @@ -3223,7 +3147,7 @@ }, { "cell_type": "markdown", - "id": "78cf6843", + "id": "7d09dc1a", "metadata": { "editable": true }, @@ -3233,7 +3157,7 @@ }, { "cell_type": "markdown", - "id": "81ed1ccc", + "id": "8589b8ee", "metadata": { "editable": true }, @@ -3244,7 +3168,7 @@ }, { "cell_type": "markdown", - "id": "2a16cf53", + "id": "63160327", "metadata": { "editable": true }, @@ -3257,7 +3181,7 @@ }, { "cell_type": "markdown", - "id": "21988141", + "id": "98614055", "metadata": { "editable": true }, @@ -3267,7 +3191,7 @@ }, { "cell_type": "markdown", - "id": "b37cc0cd", + "id": "37435d7c", "metadata": { "editable": true }, @@ -3279,7 +3203,7 @@ }, { "cell_type": "markdown", - "id": "259618c5", + "id": "64a4d79f", "metadata": { "editable": true }, @@ -3289,7 +3213,7 @@ }, { "cell_type": "markdown", - "id": "af5a331e", + "id": "7e3891af", "metadata": { "editable": true }, @@ -3301,7 +3225,7 @@ }, { "cell_type": "markdown", - "id": "208ab286", + "id": "7205e781", "metadata": { "editable": true }, @@ -3311,7 +3235,7 @@ }, { "cell_type": "markdown", - "id": "8f30fbc3", + "id": "a5645092", "metadata": { "editable": true }, @@ -3335,7 +3259,7 @@ }, { "cell_type": "markdown", - "id": "09538ef9", + "id": "09e9b12d", "metadata": { "editable": true }, @@ -3385,7 +3309,7 @@ { "cell_type": "code", "execution_count": 3, - "id": "ced37e42", + "id": "84fd1480", "metadata": { "collapsed": false, "editable": true @@ -3438,7 +3362,7 @@ }, { "cell_type": "markdown", - "id": "ebabb274", + "id": "e671e2a8", "metadata": { "editable": true }, @@ -3459,7 +3383,7 @@ { "cell_type": "code", "execution_count": 4, - "id": "2c87b9f9", + "id": "5d1c4624", "metadata": { "collapsed": false, "editable": true @@ -3497,7 +3421,7 @@ }, { "cell_type": "markdown", - "id": "0c186fec", + "id": "b397d4ee", "metadata": { "editable": true }, @@ -3541,7 +3465,7 @@ }, { "cell_type": "markdown", - "id": "2cbece98", + "id": "1fce534f", "metadata": { "editable": true }, @@ -3581,7 +3505,7 @@ }, { "cell_type": "markdown", - "id": "442935af", + "id": "9c50a158", "metadata": { "editable": true }, @@ -3602,7 +3526,7 @@ { "cell_type": "code", "execution_count": 5, - "id": "07fbb18c", + "id": "4daeba9a", "metadata": { "collapsed": false, "editable": true @@ -3628,7 +3552,7 @@ }, { "cell_type": "markdown", - "id": "6a3ea326", + "id": "f26a835c", "metadata": { "editable": true }, @@ -3656,7 +3580,7 @@ }, { "cell_type": "markdown", - "id": "525624c4", + "id": "09f1187b", "metadata": { "editable": true }, @@ -3693,7 +3617,7 @@ { "cell_type": "code", "execution_count": 6, - "id": "32d0a43f", + "id": "35d71f0e", "metadata": { "collapsed": false, "editable": true @@ -3739,7 +3663,7 @@ }, { "cell_type": "markdown", - "id": "da2ede88", + "id": "e318575f", "metadata": { "editable": true }, @@ -3770,7 +3694,7 @@ }, { "cell_type": "markdown", - "id": "069a250d", + "id": "788f45d2", "metadata": { "editable": true }, @@ -3808,7 +3732,7 @@ }, { "cell_type": "markdown", - "id": "29ab6ee7", + "id": "599a7b8f", "metadata": { "editable": true }, @@ -3842,7 +3766,7 @@ }, { "cell_type": "markdown", - "id": "b7c4a178", + "id": "cc694849", "metadata": { "editable": true }, @@ -3883,7 +3807,7 @@ { "cell_type": "code", "execution_count": 7, - "id": "4142969e", + "id": "e3607c66", "metadata": { "collapsed": false, "editable": true @@ -3962,7 +3886,7 @@ }, { "cell_type": "markdown", - "id": "4d79c3b3", + "id": "0a70cdcf", "metadata": { "editable": true }, @@ -3983,7 +3907,7 @@ }, { "cell_type": "markdown", - "id": "58012d93", + "id": "b0600212", "metadata": { "editable": true }, @@ -3997,7 +3921,7 @@ { "cell_type": "code", "execution_count": 8, - "id": "ea4b7741", + "id": "4e0c1326", "metadata": { "collapsed": false, "editable": true @@ -4107,7 +4031,7 @@ }, { "cell_type": "markdown", - "id": "04860b2c", + "id": "125f8eca", "metadata": { "editable": true }, @@ -4126,7 +4050,7 @@ { "cell_type": "code", "execution_count": 9, - "id": "b52d4df3", + "id": "cef0e788", "metadata": { "collapsed": false, "editable": true @@ -4153,7 +4077,7 @@ }, { "cell_type": "markdown", - "id": "6dce68ff", + "id": "b12d6f86", "metadata": { "editable": true }, @@ -4167,7 +4091,7 @@ { "cell_type": "code", "execution_count": 10, - "id": "65caeb78", + "id": "974faa4e", "metadata": { "collapsed": false, "editable": true @@ -4198,7 +4122,7 @@ }, { "cell_type": "markdown", - "id": "0c44c38e", + "id": "3bb19122", "metadata": { "editable": true }, @@ -4209,7 +4133,7 @@ { "cell_type": "code", "execution_count": 11, - "id": "fbdc64f1", + "id": "baeb1ea3", "metadata": { "collapsed": false, "editable": true @@ -4253,7 +4177,7 @@ }, { "cell_type": "markdown", - "id": "e07e69e3", + "id": "d75dad8e", "metadata": { "editable": true }, @@ -4276,7 +4200,7 @@ { "cell_type": "code", "execution_count": 12, - "id": "f48eaa77", + "id": "d55fae28", "metadata": { "collapsed": false, "editable": true @@ -4303,7 +4227,7 @@ }, { "cell_type": "markdown", - "id": "ac3c7bcb", + "id": "276badf8", "metadata": { "editable": true }, @@ -4314,7 +4238,7 @@ { "cell_type": "code", "execution_count": 13, - "id": "2d81262e", + "id": "7d6c714e", "metadata": { "collapsed": false, "editable": true @@ -4359,7 +4283,7 @@ }, { "cell_type": "markdown", - "id": "8f5f8f4b", + "id": "0d45b429", "metadata": { "editable": true }, @@ -4377,7 +4301,7 @@ }, { "cell_type": "markdown", - "id": "6ec638b9", + "id": "67aec670", "metadata": { "editable": true }, @@ -4412,7 +4336,7 @@ { "cell_type": "code", "execution_count": 14, - "id": "6443ca72", + "id": "0ab38a83", "metadata": { "collapsed": false, "editable": true @@ -4424,7 +4348,7 @@ }, { "cell_type": "markdown", - "id": "a8918d58", + "id": "8f53f5b9", "metadata": { "editable": true }, @@ -4436,7 +4360,7 @@ { "cell_type": "code", "execution_count": 15, - "id": "20e9a0f5", + "id": "5190c7ff", "metadata": { "collapsed": false, "editable": true @@ -4449,7 +4373,7 @@ }, { "cell_type": "markdown", - "id": "1381a34b", + "id": "676ff9d7", "metadata": { "editable": true }, @@ -4460,7 +4384,7 @@ { "cell_type": "code", "execution_count": 16, - "id": "80e92af9", + "id": "479149f7", "metadata": { "collapsed": false, "editable": true @@ -4473,7 +4397,7 @@ }, { "cell_type": "markdown", - "id": "074ac69f", + "id": "62d1b789", "metadata": { "editable": true }, @@ -4488,7 +4412,7 @@ { "cell_type": "code", "execution_count": 17, - "id": "0d710bd3", + "id": "4a11035a", "metadata": { "collapsed": false, "editable": true @@ -4500,7 +4424,7 @@ }, { "cell_type": "markdown", - "id": "7adbcab8", + "id": "abf44b70", "metadata": { "editable": true }, @@ -4512,7 +4436,7 @@ }, { "cell_type": "markdown", - "id": "e17c7253", + "id": "3f163559", "metadata": { "editable": true }, @@ -4525,7 +4449,7 @@ { "cell_type": "code", "execution_count": 18, - "id": "5ae741f5", + "id": "f7418c1e", "metadata": { "collapsed": false, "editable": true @@ -4580,7 +4504,7 @@ { "cell_type": "code", "execution_count": 19, - "id": "4f7ef6bb", + "id": "49ec0156", "metadata": { "collapsed": false, "editable": true @@ -4609,7 +4533,7 @@ { "cell_type": "code", "execution_count": 20, - "id": "7b74e049", + "id": "302ad127", "metadata": { "collapsed": false, "editable": true @@ -4639,7 +4563,7 @@ { "cell_type": "code", "execution_count": 21, - "id": "eaa25983", + "id": "436a3e0a", "metadata": { "collapsed": false, "editable": true @@ -4666,7 +4590,7 @@ { "cell_type": "code", "execution_count": 22, - "id": "949eca1f", + "id": "a26e83e0", "metadata": { "collapsed": false, "editable": true @@ -4708,7 +4632,7 @@ }, { "cell_type": "markdown", - "id": "bb8b8ac1", + "id": "8d69b494", "metadata": { "editable": true }, @@ -4719,7 +4643,7 @@ { "cell_type": "code", "execution_count": 23, - "id": "9d5ebbb2", + "id": "cad16bbe", "metadata": { "collapsed": false, "editable": true @@ -4896,7 +4820,7 @@ }, { "cell_type": "markdown", - "id": "f1baeb0b", + "id": "61624838", "metadata": { "editable": true }, @@ -4915,7 +4839,7 @@ }, { "cell_type": "markdown", - "id": "6549fa13", + "id": "f825f2da", "metadata": { "editable": true }, @@ -4937,7 +4861,7 @@ { "cell_type": "code", "execution_count": 24, - "id": "21062ebc", + "id": "409b4250", "metadata": { "collapsed": false, "editable": true @@ -5078,7 +5002,7 @@ }, { "cell_type": "markdown", - "id": "f965b277", + "id": "c6830d86", "metadata": { "editable": true }, @@ -5094,7 +5018,7 @@ { "cell_type": "code", "execution_count": 25, - "id": "35ab935b", + "id": "041fc0bf", "metadata": { "collapsed": false, "editable": true @@ -5107,7 +5031,7 @@ }, { "cell_type": "markdown", - "id": "b26972b4", + "id": "0e18ef84", "metadata": { "editable": true }, @@ -5119,7 +5043,7 @@ { "cell_type": "code", "execution_count": 26, - "id": "3df9caac", + "id": "8be0e7fd", "metadata": { "collapsed": false, "editable": true @@ -5141,7 +5065,7 @@ }, { "cell_type": "markdown", - "id": "1c07f6da", + "id": "2d2bc7a5", "metadata": { "editable": true }, @@ -5157,7 +5081,7 @@ { "cell_type": "code", "execution_count": 27, - "id": "743aa0bd", + "id": "f5cb107e", "metadata": { "collapsed": false, "editable": true @@ -5195,7 +5119,7 @@ }, { "cell_type": "markdown", - "id": "c78bdc16", + "id": "beb4f622", "metadata": { "editable": true }, @@ -5208,7 +5132,7 @@ { "cell_type": "code", "execution_count": 28, - "id": "4ec3a28c", + "id": "1b508839", "metadata": { "collapsed": false, "editable": true @@ -5229,7 +5153,7 @@ }, { "cell_type": "markdown", - "id": "5c924e11", + "id": "afb2e0af", "metadata": { "editable": true }, @@ -5245,7 +5169,7 @@ { "cell_type": "code", "execution_count": 29, - "id": "87402ee9", + "id": "b96d6c89", "metadata": { "collapsed": false, "editable": true @@ -5303,7 +5227,7 @@ }, { "cell_type": "markdown", - "id": "45ddd0bc", + "id": "0be588f8", "metadata": { "editable": true }, @@ -5318,7 +5242,7 @@ { "cell_type": "code", "execution_count": 30, - "id": "77034679", + "id": "49b8531e", "metadata": { "collapsed": false, "editable": true @@ -5339,7 +5263,7 @@ }, { "cell_type": "markdown", - "id": "9fd8140f", + "id": "874d306a", "metadata": { "editable": true }, @@ -5363,7 +5287,7 @@ { "cell_type": "code", "execution_count": 31, - "id": "7540d755", + "id": "c25e9955", "metadata": { "collapsed": false, "editable": true @@ -5835,7 +5759,7 @@ }, { "cell_type": "markdown", - "id": "5ee996ef", + "id": "86746540", "metadata": { "editable": true }, @@ -5847,7 +5771,7 @@ { "cell_type": "code", "execution_count": 32, - "id": "183b180b", + "id": "6f232f0a", "metadata": { "collapsed": false, "editable": true @@ -5891,7 +5815,7 @@ }, { "cell_type": "markdown", - "id": "21a48508", + "id": "7227f21d", "metadata": { "editable": true }, @@ -5907,7 +5831,7 @@ { "cell_type": "code", "execution_count": 33, - "id": "37eba90c", + "id": "944ba89b", "metadata": { "collapsed": false, "editable": true @@ -5922,7 +5846,7 @@ }, { "cell_type": "markdown", - "id": "58a6b726", + "id": "3cef110a", "metadata": { "editable": true }, @@ -5933,7 +5857,7 @@ { "cell_type": "code", "execution_count": 34, - "id": "046d7076", + "id": "8eb39d5e", "metadata": { "collapsed": false, "editable": true @@ -5948,7 +5872,7 @@ }, { "cell_type": "markdown", - "id": "981e95ce", + "id": "4c0ab092", "metadata": { "editable": true }, @@ -5964,7 +5888,7 @@ { "cell_type": "code", "execution_count": 35, - "id": "6da23296", + "id": "af77a32b", "metadata": { "collapsed": false, "editable": true @@ -5978,7 +5902,7 @@ }, { "cell_type": "markdown", - "id": "ba0fea41", + "id": "dfdb722f", "metadata": { "editable": true }, @@ -5993,7 +5917,7 @@ { "cell_type": "code", "execution_count": 36, - "id": "1bd5c3e5", + "id": "d740dbad", "metadata": { "collapsed": false, "editable": true @@ -6019,7 +5943,7 @@ { "cell_type": "code", "execution_count": 37, - "id": "9923ffbf", + "id": "bfb7c28b", "metadata": { "collapsed": false, "editable": true @@ -6034,7 +5958,7 @@ }, { "cell_type": "markdown", - "id": "95431510", + "id": "17a8dc93", "metadata": { "editable": true }, @@ -6045,7 +5969,7 @@ { "cell_type": "code", "execution_count": 38, - "id": "9d71cef9", + "id": "7efc0180", "metadata": { "collapsed": false, "editable": true @@ -6060,7 +5984,7 @@ }, { "cell_type": "markdown", - "id": "acfee190", + "id": "8255133c", "metadata": { "editable": true }, @@ -6071,7 +5995,7 @@ { "cell_type": "code", "execution_count": 39, - "id": "c834fb60", + "id": "4fa47196", "metadata": { "collapsed": false, "editable": true @@ -6091,7 +6015,7 @@ { "cell_type": "code", "execution_count": 40, - "id": "0c557301", + "id": "b7b5ed9f", "metadata": { "collapsed": false, "editable": true @@ -6106,7 +6030,7 @@ }, { "cell_type": "markdown", - "id": "750490a3", + "id": "bc0fc41e", "metadata": { "editable": true }, @@ -6121,7 +6045,7 @@ { "cell_type": "code", "execution_count": 41, - "id": "5318d06b", + "id": "4ccf32f6", "metadata": { "collapsed": false, "editable": true @@ -6158,7 +6082,7 @@ }, { "cell_type": "markdown", - "id": "ff519831", + "id": "382301fa", "metadata": { "editable": true }, @@ -6171,7 +6095,7 @@ { "cell_type": "code", "execution_count": 42, - "id": "57e3fb33", + "id": "0feb8f2a", "metadata": { "collapsed": false, "editable": true @@ -6194,7 +6118,7 @@ }, { "cell_type": "markdown", - "id": "e4c08bad", + "id": "3f48285b", "metadata": { "editable": true }, diff --git a/doc/pub/week42/html/._week42-bs016.html b/doc/pub/week42/html/._week42-bs016.html index 4a9ec98ed..21cee57db 100644 --- a/doc/pub/week42/html/._week42-bs016.html +++ b/doc/pub/week42/html/._week42-bs016.html @@ -473,15 +473,15 @@ layer with two hidden nodes and one output layer with one output node/neuron onl

We need to define the following parameters and variables with the input layer (layer \( (0) \)) -where we label the nodes \( x_0 \) and \( x_1 \) +where we label the nodes \( x_1 \) and \( x_2 \)

$$ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. +x_1 = a_1^{(0)} \wedge x_2 = a_2^{(0)}. $$ -

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_0^{(1)} \) and \( a_1^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

+

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_1^{(1)} \) and \( a_2^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

$$ -w_{ij}^{(1)}=\left\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\right\} \wedge b^{(1)}=\left\{b_0^{(1)},b_1^{(1)}\right\}. +w_{ij}^{(1)}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)}\right\} \wedge b^{(1)}=\left\{b_1^{(1)},b_2^{(1)}\right\}. $$ diff --git a/doc/pub/week42/html/week42-reveal.html b/doc/pub/week42/html/week42-reveal.html index 88db3fbfa..0e2e44853 100644 --- a/doc/pub/week42/html/week42-reveal.html +++ b/doc/pub/week42/html/week42-reveal.html @@ -584,18 +584,18 @@ layer with two hidden nodes and one output layer with one output node/neuron onl

We need to define the following parameters and variables with the input layer (layer \( (0) \)) -where we label the nodes \( x_0 \) and \( x_1 \) +where we label the nodes \( x_1 \) and \( x_2 \)

 
$$ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. +x_1 = a_1^{(0)} \wedge x_2 = a_2^{(0)}. $$

 
-

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_0^{(1)} \) and \( a_1^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

+

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_1^{(1)} \) and \( a_2^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

 
$$ -w_{ij}^{(1)}=\left\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\right\} \wedge b^{(1)}=\left\{b_0^{(1)},b_1^{(1)}\right\}. +w_{ij}^{(1)}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)}\right\} \wedge b^{(1)}=\left\{b_1^{(1)},b_2^{(1)}\right\}. $$

 
diff --git a/doc/pub/week42/html/week42-solarized.html b/doc/pub/week42/html/week42-solarized.html index 09a6aa095..ee3e75686 100644 --- a/doc/pub/week42/html/week42-solarized.html +++ b/doc/pub/week42/html/week42-solarized.html @@ -730,15 +730,15 @@ layer with two hidden nodes and one output layer with one output node/neuron onl

We need to define the following parameters and variables with the input layer (layer \( (0) \)) -where we label the nodes \( x_0 \) and \( x_1 \) +where we label the nodes \( x_1 \) and \( x_2 \)

$$ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. +x_1 = a_1^{(0)} \wedge x_2 = a_2^{(0)}. $$ -

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_0^{(1)} \) and \( a_1^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

+

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_1^{(1)} \) and \( a_2^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

$$ -w_{ij}^{(1)}=\left\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\right\} \wedge b^{(1)}=\left\{b_0^{(1)},b_1^{(1)}\right\}. +w_{ij}^{(1)}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)}\right\} \wedge b^{(1)}=\left\{b_1^{(1)},b_2^{(1)}\right\}. $$ diff --git a/doc/pub/week42/html/week42.html b/doc/pub/week42/html/week42.html index 10fd5c21b..53d75e1db 100644 --- a/doc/pub/week42/html/week42.html +++ b/doc/pub/week42/html/week42.html @@ -807,15 +807,15 @@ layer with two hidden nodes and one output layer with one output node/neuron onl

We need to define the following parameters and variables with the input layer (layer \( (0) \)) -where we label the nodes \( x_0 \) and \( x_1 \) +where we label the nodes \( x_1 \) and \( x_2 \)

$$ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. +x_1 = a_1^{(0)} \wedge x_2 = a_2^{(0)}. $$ -

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_0^{(1)} \) and \( a_1^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

+

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_1^{(1)} \) and \( a_2^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

$$ -w_{ij}^{(1)}=\left\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\right\} \wedge b^{(1)}=\left\{b_0^{(1)},b_1^{(1)}\right\}. +w_{ij}^{(1)}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)}\right\} \wedge b^{(1)}=\left\{b_1^{(1)},b_2^{(1)}\right\}. $$ diff --git a/doc/pub/week42/ipynb/ipynb-week42-src.tar.gz b/doc/pub/week42/ipynb/ipynb-week42-src.tar.gz index 126c04428..3c9edfc0b 100644 Binary files a/doc/pub/week42/ipynb/ipynb-week42-src.tar.gz and b/doc/pub/week42/ipynb/ipynb-week42-src.tar.gz differ diff --git a/doc/pub/week42/ipynb/week42.ipynb b/doc/pub/week42/ipynb/week42.ipynb index ff791c9a6..fdfeb303f 100644 --- a/doc/pub/week42/ipynb/week42.ipynb +++ b/doc/pub/week42/ipynb/week42.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "eeb3000a", + "id": "71674611", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "c5c0c27f", + "id": "65b3502e", "metadata": { "editable": true }, @@ -27,7 +27,7 @@ }, { "cell_type": "markdown", - "id": "af228a9b", + "id": "1d840be4", "metadata": { "editable": true }, @@ -56,7 +56,7 @@ }, { "cell_type": "markdown", - "id": "750557ba", + "id": "8c43f62c", "metadata": { "editable": true }, @@ -73,7 +73,7 @@ }, { "cell_type": "markdown", - "id": "35c84973", + "id": "bb52c881", "metadata": { "editable": true }, @@ -92,7 +92,7 @@ }, { "cell_type": "markdown", - "id": "ddc4c89d", + "id": "e53a998a", "metadata": { "editable": true }, @@ -108,7 +108,7 @@ }, { "cell_type": "markdown", - "id": "ac3c5024", + "id": "2be1dbc1", "metadata": { "editable": true }, @@ -119,7 +119,7 @@ }, { "cell_type": "markdown", - "id": "11b95652", + "id": "d81e5954", "metadata": { "editable": true }, @@ -133,7 +133,7 @@ }, { "cell_type": "markdown", - "id": "b6e2e459", + "id": "bf67ca94", "metadata": { "editable": true }, @@ -148,7 +148,7 @@ }, { "cell_type": "markdown", - "id": "1409dab2", + "id": "ea5ccdfd", "metadata": { "editable": true }, @@ -160,7 +160,7 @@ }, { "cell_type": "markdown", - "id": "9a1cfa21", + "id": "a67526dc", "metadata": { "editable": true }, @@ -174,7 +174,7 @@ }, { "cell_type": "markdown", - "id": "745f5eb1", + "id": "004f244e", "metadata": { "editable": true }, @@ -186,7 +186,7 @@ }, { "cell_type": "markdown", - "id": "44b74d07", + "id": "d5019705", "metadata": { "editable": true }, @@ -202,7 +202,7 @@ }, { "cell_type": "markdown", - "id": "5a549fa5", + "id": "b28a1451", "metadata": { "editable": true }, @@ -218,7 +218,7 @@ }, { "cell_type": "markdown", - "id": "c2276f01", + "id": "bb9e817a", "metadata": { "editable": true }, @@ -230,7 +230,7 @@ }, { "cell_type": "markdown", - "id": "961fdf59", + "id": "cb070b5e", "metadata": { "editable": true }, @@ -240,7 +240,7 @@ }, { "cell_type": "markdown", - "id": "fbbebd7f", + "id": "f68d4801", "metadata": { "editable": true }, @@ -252,7 +252,7 @@ }, { "cell_type": "markdown", - "id": "ad4d526c", + "id": "fffa97bd", "metadata": { "editable": true }, @@ -262,7 +262,7 @@ }, { "cell_type": "markdown", - "id": "950ff3dc", + "id": "7f751c77", "metadata": { "editable": true }, @@ -274,7 +274,7 @@ }, { "cell_type": "markdown", - "id": "c1fc8822", + "id": "e8f8479b", "metadata": { "editable": true }, @@ -284,7 +284,7 @@ }, { "cell_type": "markdown", - "id": "4a04f7f7", + "id": "9d52f786", "metadata": { "editable": true }, @@ -296,7 +296,7 @@ }, { "cell_type": "markdown", - "id": "26430ee8", + "id": "cdb55ad0", "metadata": { "editable": true }, @@ -312,7 +312,7 @@ }, { "cell_type": "markdown", - "id": "cb0b0c94", + "id": "ece1a1cc", "metadata": { "editable": true }, @@ -324,7 +324,7 @@ }, { "cell_type": "markdown", - "id": "0288d581", + "id": "e2af50fb", "metadata": { "editable": true }, @@ -336,7 +336,7 @@ }, { "cell_type": "markdown", - "id": "b1e21087", + "id": "c883f2ef", "metadata": { "editable": true }, @@ -346,7 +346,7 @@ }, { "cell_type": "markdown", - "id": "81523a1c", + "id": "f1129306", "metadata": { "editable": true }, @@ -358,7 +358,7 @@ }, { "cell_type": "markdown", - "id": "b2f1a06b", + "id": "1d14bedd", "metadata": { "editable": true }, @@ -368,7 +368,7 @@ }, { "cell_type": "markdown", - "id": "a769001e", + "id": "84378f69", "metadata": { "editable": true }, @@ -384,7 +384,7 @@ }, { "cell_type": "markdown", - "id": "c84fadb6", + "id": "7f6f41e3", "metadata": { "editable": true }, @@ -396,7 +396,7 @@ }, { "cell_type": "markdown", - "id": "481d95b7", + "id": "f38cb151", "metadata": { "editable": true }, @@ -408,7 +408,7 @@ }, { "cell_type": "markdown", - "id": "5f75ab21", + "id": "d7f60566", "metadata": { "editable": true }, @@ -420,7 +420,7 @@ }, { "cell_type": "markdown", - "id": "587d754d", + "id": "81219134", "metadata": { "editable": true }, @@ -432,7 +432,7 @@ }, { "cell_type": "markdown", - "id": "2fb1fdf5", + "id": "8f0f27a7", "metadata": { "editable": true }, @@ -444,7 +444,7 @@ }, { "cell_type": "markdown", - "id": "7a5e05db", + "id": "aa9974f2", "metadata": { "editable": true }, @@ -454,7 +454,7 @@ }, { "cell_type": "markdown", - "id": "01ca79e1", + "id": "02021c85", "metadata": { "editable": true }, @@ -470,7 +470,7 @@ }, { "cell_type": "markdown", - "id": "3fcd5865", + "id": "d5b4c3d8", "metadata": { "editable": true }, @@ -482,7 +482,7 @@ }, { "cell_type": "markdown", - "id": "c4fea209", + "id": "0c0f2d45", "metadata": { "editable": true }, @@ -494,7 +494,7 @@ }, { "cell_type": "markdown", - "id": "a1347ae3", + "id": "9f8b567b", "metadata": { "editable": true }, @@ -504,7 +504,7 @@ }, { "cell_type": "markdown", - "id": "7dcd110f", + "id": "6afa5b0f", "metadata": { "editable": true }, @@ -516,7 +516,7 @@ }, { "cell_type": "markdown", - "id": "81d126e1", + "id": "a8447e5f", "metadata": { "editable": true }, @@ -530,7 +530,7 @@ }, { "cell_type": "markdown", - "id": "9a53fc82", + "id": "0262d1c4", "metadata": { "editable": true }, @@ -548,7 +548,7 @@ { "cell_type": "code", "execution_count": 1, - "id": "0f334c42", + "id": "91932727", "metadata": { "collapsed": false, "editable": true @@ -621,7 +621,7 @@ }, { "cell_type": "markdown", - "id": "da20ec8b", + "id": "6695945c", "metadata": { "editable": true }, @@ -631,7 +631,7 @@ }, { "cell_type": "markdown", - "id": "fe320615", + "id": "30bd4411", "metadata": { "editable": true }, @@ -643,46 +643,46 @@ "layer with two hidden nodes and one output layer with one output node/neuron only (see graph)..\n", "\n", "We need to define the following parameters and variables with the input layer (layer $(0)$) \n", - "where we label the nodes $x_0$ and $x_1$" + "where we label the nodes $x_1$ and $x_2$" ] }, { "cell_type": "markdown", - "id": "ec803247", + "id": "03303707", "metadata": { "editable": true }, "source": [ "$$\n", - "x_0 = a_0^{(0)} \\wedge x_1 = a_1^{(0)}.\n", + "x_1 = a_1^{(0)} \\wedge x_2 = a_2^{(0)}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "a5188847", + "id": "24dc6874", "metadata": { "editable": true }, "source": [ - "The hidden layer (layer $(1)$) has nodes which yield the outputs $a_0^{(1)}$ and $a_1^{(1)}$) with weight $\\boldsymbol{w}$ and bias $\\boldsymbol{b}$ parameters" + "The hidden layer (layer $(1)$) has nodes which yield the outputs $a_1^{(1)}$ and $a_2^{(1)}$) with weight $\\boldsymbol{w}$ and bias $\\boldsymbol{b}$ parameters" ] }, { "cell_type": "markdown", - "id": "dbc0051b", + "id": "9229190d", "metadata": { "editable": true }, "source": [ "$$\n", - "w_{ij}^{(1)}=\\left\\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\\right\\} \\wedge b^{(1)}=\\left\\{b_0^{(1)},b_1^{(1)}\\right\\}.\n", + "w_{ij}^{(1)}=\\left\\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)}\\right\\} \\wedge b^{(1)}=\\left\\{b_1^{(1)},b_2^{(1)}\\right\\}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "9a086cbe", + "id": "db21c4eb", "metadata": { "editable": true }, @@ -698,7 +698,7 @@ }, { "cell_type": "markdown", - "id": "55691e04", + "id": "cf9b69e8", "metadata": { "editable": true }, @@ -710,7 +710,7 @@ }, { "cell_type": "markdown", - "id": "1aa3e85c", + "id": "53130107", "metadata": { "editable": true }, @@ -722,7 +722,7 @@ }, { "cell_type": "markdown", - "id": "04fd1c47", + "id": "5835245c", "metadata": { "editable": true }, @@ -733,7 +733,7 @@ }, { "cell_type": "markdown", - "id": "628a64e0", + "id": "dd31d181", "metadata": { "editable": true }, @@ -745,7 +745,7 @@ }, { "cell_type": "markdown", - "id": "3856c61f", + "id": "36a9d52a", "metadata": { "editable": true }, @@ -758,7 +758,7 @@ }, { "cell_type": "markdown", - "id": "bf06c970", + "id": "3af3b240", "metadata": { "editable": true }, @@ -770,7 +770,7 @@ }, { "cell_type": "markdown", - "id": "15c61190", + "id": "3ef7b15b", "metadata": { "editable": true }, @@ -780,7 +780,7 @@ }, { "cell_type": "markdown", - "id": "d675d2b5", + "id": "31e47e2c", "metadata": { "editable": true }, @@ -792,7 +792,7 @@ }, { "cell_type": "markdown", - "id": "ed858ea7", + "id": "c5690e76", "metadata": { "editable": true }, @@ -804,7 +804,7 @@ }, { "cell_type": "markdown", - "id": "151b4f5e", + "id": "919ce153", "metadata": { "editable": true }, @@ -816,7 +816,7 @@ }, { "cell_type": "markdown", - "id": "3ea32b93", + "id": "69df1f30", "metadata": { "editable": true }, @@ -826,7 +826,7 @@ }, { "cell_type": "markdown", - "id": "257efa71", + "id": "42ea9246", "metadata": { "editable": true }, @@ -838,7 +838,7 @@ }, { "cell_type": "markdown", - "id": "e97f52ba", + "id": "af203af1", "metadata": { "editable": true }, @@ -854,7 +854,7 @@ }, { "cell_type": "markdown", - "id": "c48537ec", + "id": "fd36e08b", "metadata": { "editable": true }, @@ -866,7 +866,7 @@ }, { "cell_type": "markdown", - "id": "132f1c81", + "id": "997bddf7", "metadata": { "editable": true }, @@ -876,7 +876,7 @@ }, { "cell_type": "markdown", - "id": "5bca9598", + "id": "ba4380bd", "metadata": { "editable": true }, @@ -888,7 +888,7 @@ }, { "cell_type": "markdown", - "id": "c8065eb2", + "id": "13be072b", "metadata": { "editable": true }, @@ -898,7 +898,7 @@ }, { "cell_type": "markdown", - "id": "e14472e4", + "id": "2c6bcc22", "metadata": { "editable": true }, @@ -910,7 +910,7 @@ }, { "cell_type": "markdown", - "id": "e6a4b016", + "id": "a50dfdeb", "metadata": { "editable": true }, @@ -922,7 +922,7 @@ }, { "cell_type": "markdown", - "id": "1b2a2eb8", + "id": "0d50cd56", "metadata": { "editable": true }, @@ -935,7 +935,7 @@ }, { "cell_type": "markdown", - "id": "bfe4686c", + "id": "4fc9436b", "metadata": { "editable": true }, @@ -945,7 +945,7 @@ }, { "cell_type": "markdown", - "id": "26e1d8dc", + "id": "7545f5c9", "metadata": { "editable": true }, @@ -957,7 +957,7 @@ }, { "cell_type": "markdown", - "id": "3b1c1b35", + "id": "bcbea03f", "metadata": { "editable": true }, @@ -967,7 +967,7 @@ }, { "cell_type": "markdown", - "id": "4e24a907", + "id": "ee05da6d", "metadata": { "editable": true }, @@ -979,7 +979,7 @@ }, { "cell_type": "markdown", - "id": "674e3b94", + "id": "1f9491ce", "metadata": { "editable": true }, @@ -990,7 +990,7 @@ }, { "cell_type": "markdown", - "id": "5da27439", + "id": "07772fef", "metadata": { "editable": true }, @@ -1002,7 +1002,7 @@ }, { "cell_type": "markdown", - "id": "145df32f", + "id": "c432668f", "metadata": { "editable": true }, @@ -1012,7 +1012,7 @@ }, { "cell_type": "markdown", - "id": "e2b358af", + "id": "4274417c", "metadata": { "editable": true }, @@ -1024,7 +1024,7 @@ }, { "cell_type": "markdown", - "id": "36176956", + "id": "b615718d", "metadata": { "editable": true }, @@ -1034,7 +1034,7 @@ }, { "cell_type": "markdown", - "id": "622c2850", + "id": "c541b15f", "metadata": { "editable": true }, @@ -1046,7 +1046,7 @@ }, { "cell_type": "markdown", - "id": "c4f7f75a", + "id": "6b741552", "metadata": { "editable": true }, @@ -1058,7 +1058,7 @@ }, { "cell_type": "markdown", - "id": "5b9e0d5b", + "id": "d564e7a9", "metadata": { "editable": true }, @@ -1070,7 +1070,7 @@ }, { "cell_type": "markdown", - "id": "ea608c40", + "id": "927894b5", "metadata": { "editable": true }, @@ -1080,7 +1080,7 @@ }, { "cell_type": "markdown", - "id": "6d8ca0aa", + "id": "75624550", "metadata": { "editable": true }, @@ -1092,7 +1092,7 @@ }, { "cell_type": "markdown", - "id": "69f842d7", + "id": "9252c078", "metadata": { "editable": true }, @@ -1102,7 +1102,7 @@ }, { "cell_type": "markdown", - "id": "1d6268de", + "id": "10c7da6e", "metadata": { "editable": true }, @@ -1114,7 +1114,7 @@ }, { "cell_type": "markdown", - "id": "dbfc1af0", + "id": "0fe640a9", "metadata": { "editable": true }, @@ -1126,7 +1126,7 @@ }, { "cell_type": "markdown", - "id": "7efc04c4", + "id": "01ff9a38", "metadata": { "editable": true }, @@ -1138,7 +1138,7 @@ }, { "cell_type": "markdown", - "id": "0233ba94", + "id": "37fda9de", "metadata": { "editable": true }, @@ -1148,7 +1148,7 @@ }, { "cell_type": "markdown", - "id": "07b0c80c", + "id": "861af2b9", "metadata": { "editable": true }, @@ -1160,7 +1160,7 @@ }, { "cell_type": "markdown", - "id": "d1064240", + "id": "f9cea8b7", "metadata": { "editable": true }, @@ -1170,7 +1170,7 @@ }, { "cell_type": "markdown", - "id": "f69fc276", + "id": "12e3298b", "metadata": { "editable": true }, @@ -1183,7 +1183,7 @@ }, { "cell_type": "markdown", - "id": "f35ac459", + "id": "a104df98", "metadata": { "editable": true }, @@ -1195,7 +1195,7 @@ }, { "cell_type": "markdown", - "id": "f4cee470", + "id": "9bc2f036", "metadata": { "editable": true }, @@ -1205,7 +1205,7 @@ }, { "cell_type": "markdown", - "id": "6f416b41", + "id": "568ced5c", "metadata": { "editable": true }, @@ -1217,7 +1217,7 @@ }, { "cell_type": "markdown", - "id": "3de1cb99", + "id": "906d2bd9", "metadata": { "editable": true }, @@ -1227,7 +1227,7 @@ }, { "cell_type": "markdown", - "id": "109542b5", + "id": "79992e6f", "metadata": { "editable": true }, @@ -1239,7 +1239,7 @@ }, { "cell_type": "markdown", - "id": "bd937e5b", + "id": "0745b6ba", "metadata": { "editable": true }, @@ -1249,7 +1249,7 @@ }, { "cell_type": "markdown", - "id": "f91328b7", + "id": "4fb2781f", "metadata": { "editable": true }, @@ -1261,7 +1261,7 @@ }, { "cell_type": "markdown", - "id": "d00bddec", + "id": "57576b6e", "metadata": { "editable": true }, @@ -1271,7 +1271,7 @@ }, { "cell_type": "markdown", - "id": "872c3ff1", + "id": "d1f38053", "metadata": { "editable": true }, @@ -1288,7 +1288,7 @@ }, { "cell_type": "markdown", - "id": "6d2ff831", + "id": "6f6f31e8", "metadata": { "editable": true }, @@ -1300,7 +1300,7 @@ }, { "cell_type": "markdown", - "id": "f1ef66e0", + "id": "f206ae2b", "metadata": { "editable": true }, @@ -1312,7 +1312,7 @@ }, { "cell_type": "markdown", - "id": "83c547c3", + "id": "5e7af877", "metadata": { "editable": true }, @@ -1328,7 +1328,7 @@ }, { "cell_type": "markdown", - "id": "895eb8e2", + "id": "96c13dab", "metadata": { "editable": true }, @@ -1345,7 +1345,7 @@ }, { "cell_type": "markdown", - "id": "32c90a46", + "id": "a6781c7d", "metadata": { "editable": true }, @@ -1357,7 +1357,7 @@ }, { "cell_type": "markdown", - "id": "a2f5143d", + "id": "4db58da4", "metadata": { "editable": true }, @@ -1370,7 +1370,7 @@ }, { "cell_type": "markdown", - "id": "aeb197f1", + "id": "b4458c55", "metadata": { "editable": true }, @@ -1382,7 +1382,7 @@ }, { "cell_type": "markdown", - "id": "18771f50", + "id": "b32e0714", "metadata": { "editable": true }, @@ -1398,7 +1398,7 @@ }, { "cell_type": "markdown", - "id": "ecb1436d", + "id": "fffb7785", "metadata": { "editable": true }, @@ -1410,7 +1410,7 @@ }, { "cell_type": "markdown", - "id": "9677173f", + "id": "08bff16c", "metadata": { "editable": true }, @@ -1426,7 +1426,7 @@ }, { "cell_type": "markdown", - "id": "dfbd401d", + "id": "fb907bb3", "metadata": { "editable": true }, @@ -1438,7 +1438,7 @@ }, { "cell_type": "markdown", - "id": "0e5b891e", + "id": "f97ed7ef", "metadata": { "editable": true }, @@ -1450,7 +1450,7 @@ }, { "cell_type": "markdown", - "id": "75554797", + "id": "136c2230", "metadata": { "editable": true }, @@ -1460,7 +1460,7 @@ }, { "cell_type": "markdown", - "id": "71553e68", + "id": "4b2344b6", "metadata": { "editable": true }, @@ -1472,7 +1472,7 @@ }, { "cell_type": "markdown", - "id": "a3761904", + "id": "52a4e7a7", "metadata": { "editable": true }, @@ -1482,7 +1482,7 @@ }, { "cell_type": "markdown", - "id": "1a5221dc", + "id": "163ee2e5", "metadata": { "editable": true }, @@ -1494,7 +1494,7 @@ }, { "cell_type": "markdown", - "id": "a18b7cd9", + "id": "5aa607a5", "metadata": { "editable": true }, @@ -1508,7 +1508,7 @@ }, { "cell_type": "markdown", - "id": "252a444e", + "id": "da13c77b", "metadata": { "editable": true }, @@ -1520,7 +1520,7 @@ }, { "cell_type": "markdown", - "id": "6f7b45e3", + "id": "7bf944d0", "metadata": { "editable": true }, @@ -1530,7 +1530,7 @@ }, { "cell_type": "markdown", - "id": "d4cc4b41", + "id": "ea130e95", "metadata": { "editable": true }, @@ -1542,7 +1542,7 @@ }, { "cell_type": "markdown", - "id": "d3411c54", + "id": "2fba64b7", "metadata": { "editable": true }, @@ -1552,7 +1552,7 @@ }, { "cell_type": "markdown", - "id": "3d01d63a", + "id": "5904a528", "metadata": { "editable": true }, @@ -1564,7 +1564,7 @@ }, { "cell_type": "markdown", - "id": "8ef8b814", + "id": "86f8199b", "metadata": { "editable": true }, @@ -1576,7 +1576,7 @@ }, { "cell_type": "markdown", - "id": "14a70a29", + "id": "e4370f9f", "metadata": { "editable": true }, @@ -1588,7 +1588,7 @@ }, { "cell_type": "markdown", - "id": "905ac02a", + "id": "f60e1730", "metadata": { "editable": true }, @@ -1598,7 +1598,7 @@ }, { "cell_type": "markdown", - "id": "a13234b9", + "id": "e282d002", "metadata": { "editable": true }, @@ -1610,7 +1610,7 @@ }, { "cell_type": "markdown", - "id": "a3a48110", + "id": "5de6d59f", "metadata": { "editable": true }, @@ -1620,7 +1620,7 @@ }, { "cell_type": "markdown", - "id": "aa50c29e", + "id": "97c35e7d", "metadata": { "editable": true }, @@ -1632,7 +1632,7 @@ }, { "cell_type": "markdown", - "id": "87104468", + "id": "c4754c54", "metadata": { "editable": true }, @@ -1650,7 +1650,7 @@ }, { "cell_type": "markdown", - "id": "8a9aec64", + "id": "0b03f12b", "metadata": { "editable": true }, @@ -1668,7 +1668,7 @@ }, { "cell_type": "markdown", - "id": "425a6241", + "id": "ad079735", "metadata": { "editable": true }, @@ -1680,7 +1680,7 @@ }, { "cell_type": "markdown", - "id": "f0b54a14", + "id": "0bf757b6", "metadata": { "editable": true }, @@ -1690,7 +1690,7 @@ }, { "cell_type": "markdown", - "id": "56ecf740", + "id": "b6246783", "metadata": { "editable": true }, @@ -1702,7 +1702,7 @@ }, { "cell_type": "markdown", - "id": "12008dc0", + "id": "b7575d50", "metadata": { "editable": true }, @@ -1714,7 +1714,7 @@ }, { "cell_type": "markdown", - "id": "fb92f522", + "id": "e6c93f95", "metadata": { "editable": true }, @@ -1726,7 +1726,7 @@ }, { "cell_type": "markdown", - "id": "3ec8475f", + "id": "b52b78ac", "metadata": { "editable": true }, @@ -1736,7 +1736,7 @@ }, { "cell_type": "markdown", - "id": "f45052da", + "id": "a5fdfb9c", "metadata": { "editable": true }, @@ -1748,7 +1748,7 @@ }, { "cell_type": "markdown", - "id": "927e0716", + "id": "8bd7f846", "metadata": { "editable": true }, @@ -1758,7 +1758,7 @@ }, { "cell_type": "markdown", - "id": "6ce4a56f", + "id": "550334c8", "metadata": { "editable": true }, @@ -1770,7 +1770,7 @@ }, { "cell_type": "markdown", - "id": "0ace7815", + "id": "ac298c05", "metadata": { "editable": true }, @@ -1788,7 +1788,7 @@ }, { "cell_type": "markdown", - "id": "56b08cf1", + "id": "6609cbf5", "metadata": { "editable": true }, @@ -1798,7 +1798,7 @@ }, { "cell_type": "markdown", - "id": "5230a333", + "id": "64741262", "metadata": { "editable": true }, @@ -1816,7 +1816,7 @@ }, { "cell_type": "markdown", - "id": "6deeed25", + "id": "76c4610d", "metadata": { "editable": true }, @@ -1826,7 +1826,7 @@ }, { "cell_type": "markdown", - "id": "20f2b16b", + "id": "efd0ba93", "metadata": { "editable": true }, @@ -1844,7 +1844,7 @@ }, { "cell_type": "markdown", - "id": "05d1f509", + "id": "98e88435", "metadata": { "editable": true }, @@ -1856,7 +1856,7 @@ }, { "cell_type": "markdown", - "id": "78aa987f", + "id": "08bdbdff", "metadata": { "editable": true }, @@ -1868,7 +1868,7 @@ }, { "cell_type": "markdown", - "id": "cfec91fb", + "id": "e234c8a6", "metadata": { "editable": true }, @@ -1878,7 +1878,7 @@ }, { "cell_type": "markdown", - "id": "0b9f61b7", + "id": "6a4118be", "metadata": { "editable": true }, @@ -1890,7 +1890,7 @@ }, { "cell_type": "markdown", - "id": "7bf04564", + "id": "d211df4b", "metadata": { "editable": true }, @@ -1902,7 +1902,7 @@ }, { "cell_type": "markdown", - "id": "ca86cf07", + "id": "bf0c2817", "metadata": { "editable": true }, @@ -1912,7 +1912,7 @@ }, { "cell_type": "markdown", - "id": "3a0f1b25", + "id": "2de9333a", "metadata": { "editable": true }, @@ -1924,7 +1924,7 @@ }, { "cell_type": "markdown", - "id": "632562ae", + "id": "00d82ece", "metadata": { "editable": true }, @@ -1934,7 +1934,7 @@ }, { "cell_type": "markdown", - "id": "12ea4e17", + "id": "19f78643", "metadata": { "editable": true }, @@ -1946,7 +1946,7 @@ }, { "cell_type": "markdown", - "id": "4b8b66a0", + "id": "1424f687", "metadata": { "editable": true }, @@ -1958,7 +1958,7 @@ }, { "cell_type": "markdown", - "id": "403e4837", + "id": "9d7c23b2", "metadata": { "editable": true }, @@ -1984,7 +1984,7 @@ }, { "cell_type": "markdown", - "id": "651cc192", + "id": "1decfbef", "metadata": { "editable": true }, @@ -2007,7 +2007,7 @@ }, { "cell_type": "markdown", - "id": "8480c1cd", + "id": "7f237d52", "metadata": { "editable": true }, @@ -2019,7 +2019,7 @@ }, { "cell_type": "markdown", - "id": "f0a2c0b3", + "id": "d37fa1b5", "metadata": { "editable": true }, @@ -2031,7 +2031,7 @@ }, { "cell_type": "markdown", - "id": "bc0b65ac", + "id": "213b757d", "metadata": { "editable": true }, @@ -2041,7 +2041,7 @@ }, { "cell_type": "markdown", - "id": "7e70f36c", + "id": "3137751d", "metadata": { "editable": true }, @@ -2053,7 +2053,7 @@ }, { "cell_type": "markdown", - "id": "1e77d7c3", + "id": "da1cf61b", "metadata": { "editable": true }, @@ -2067,7 +2067,7 @@ }, { "cell_type": "markdown", - "id": "2d0867fe", + "id": "3b57ef97", "metadata": { "editable": true }, @@ -2079,7 +2079,7 @@ }, { "cell_type": "markdown", - "id": "fcedd3da", + "id": "bb0c4d59", "metadata": { "editable": true }, @@ -2091,7 +2091,7 @@ }, { "cell_type": "markdown", - "id": "7b61d89e", + "id": "a9483fc9", "metadata": { "editable": true }, @@ -2101,7 +2101,7 @@ }, { "cell_type": "markdown", - "id": "001fbe19", + "id": "49c7c2f3", "metadata": { "editable": true }, @@ -2113,7 +2113,7 @@ }, { "cell_type": "markdown", - "id": "4069ec72", + "id": "734ef014", "metadata": { "editable": true }, @@ -2125,7 +2125,7 @@ }, { "cell_type": "markdown", - "id": "43911e1b", + "id": "ac393c38", "metadata": { "editable": true }, @@ -2135,7 +2135,7 @@ }, { "cell_type": "markdown", - "id": "b1dbae91", + "id": "c38ed8eb", "metadata": { "editable": true }, @@ -2147,7 +2147,7 @@ }, { "cell_type": "markdown", - "id": "93839b4c", + "id": "d097bbf6", "metadata": { "editable": true }, @@ -2159,7 +2159,7 @@ }, { "cell_type": "markdown", - "id": "aecfea5f", + "id": "56e28349", "metadata": { "editable": true }, @@ -2182,7 +2182,7 @@ }, { "cell_type": "markdown", - "id": "99e7343d", + "id": "0f764f08", "metadata": { "editable": true }, @@ -2201,7 +2201,7 @@ }, { "cell_type": "markdown", - "id": "2505f9b3", + "id": "697fbd9c", "metadata": { "editable": true }, @@ -2213,7 +2213,7 @@ }, { "cell_type": "markdown", - "id": "66dd8f27", + "id": "e9f79c9b", "metadata": { "editable": true }, @@ -2223,7 +2223,7 @@ }, { "cell_type": "markdown", - "id": "4ee0dfc6", + "id": "8285a58e", "metadata": { "editable": true }, @@ -2235,7 +2235,7 @@ }, { "cell_type": "markdown", - "id": "3a306198", + "id": "eba13151", "metadata": { "editable": true }, @@ -2252,7 +2252,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "cc546550", + "id": "d5693cd0", "metadata": { "collapsed": false, "editable": true @@ -2336,7 +2336,7 @@ }, { "cell_type": "markdown", - "id": "4ced1878", + "id": "b0e28a6b", "metadata": { "editable": true }, @@ -2358,7 +2358,7 @@ }, { "cell_type": "markdown", - "id": "7ea86243", + "id": "436fb27b", "metadata": { "editable": true }, @@ -2376,7 +2376,7 @@ }, { "cell_type": "markdown", - "id": "511380e2", + "id": "9319de67", "metadata": { "editable": true }, @@ -2399,7 +2399,7 @@ }, { "cell_type": "markdown", - "id": "22b40132", + "id": "e90fbb0a", "metadata": { "editable": true }, @@ -2418,7 +2418,7 @@ }, { "cell_type": "markdown", - "id": "ee4c79cc", + "id": "7a18427f", "metadata": { "editable": true }, @@ -2446,7 +2446,7 @@ }, { "cell_type": "markdown", - "id": "27f52200", + "id": "ac352aa1", "metadata": { "editable": true }, @@ -2466,7 +2466,7 @@ }, { "cell_type": "markdown", - "id": "b8b9d46c", + "id": "67a8bef0", "metadata": { "editable": true }, @@ -2487,7 +2487,7 @@ }, { "cell_type": "markdown", - "id": "3d0c5b2b", + "id": "76de2016", "metadata": { "editable": true }, @@ -2501,7 +2501,7 @@ }, { "cell_type": "markdown", - "id": "a1ae341a", + "id": "e798fa5d", "metadata": { "editable": true }, @@ -2513,7 +2513,7 @@ }, { "cell_type": "markdown", - "id": "cc1fca15", + "id": "6f33abb9", "metadata": { "editable": true }, @@ -2535,7 +2535,7 @@ }, { "cell_type": "markdown", - "id": "53768e88", + "id": "ad76ab9d", "metadata": { "editable": true }, @@ -2557,7 +2557,7 @@ }, { "cell_type": "markdown", - "id": "82acd79b", + "id": "4d0588bb", "metadata": { "editable": true }, @@ -2586,7 +2586,7 @@ }, { "cell_type": "markdown", - "id": "a75c544a", + "id": "cb5679f8", "metadata": { "editable": true }, @@ -2612,7 +2612,7 @@ }, { "cell_type": "markdown", - "id": "db855fb4", + "id": "fa928c9b", "metadata": { "editable": true }, @@ -2638,7 +2638,7 @@ }, { "cell_type": "markdown", - "id": "7d9639b2", + "id": "4a9462ce", "metadata": { "editable": true }, @@ -2658,7 +2658,7 @@ }, { "cell_type": "markdown", - "id": "4a509ed7", + "id": "e523997a", "metadata": { "editable": true }, @@ -2678,7 +2678,7 @@ }, { "cell_type": "markdown", - "id": "db3b3c93", + "id": "19bba5e1", "metadata": { "editable": true }, @@ -2704,7 +2704,7 @@ }, { "cell_type": "markdown", - "id": "98a721de", + "id": "ff6b5f13", "metadata": { "editable": true }, @@ -2733,7 +2733,7 @@ }, { "cell_type": "markdown", - "id": "6edf83c0", + "id": "df905d9f", "metadata": { "editable": true }, @@ -2751,7 +2751,7 @@ }, { "cell_type": "markdown", - "id": "175a12ef", + "id": "233e93d6", "metadata": { "editable": true }, @@ -2767,7 +2767,7 @@ }, { "cell_type": "markdown", - "id": "32058465", + "id": "0034168c", "metadata": { "editable": true }, @@ -2779,7 +2779,7 @@ }, { "cell_type": "markdown", - "id": "93409885", + "id": "cd701f7d", "metadata": { "editable": true }, @@ -2793,7 +2793,7 @@ }, { "cell_type": "markdown", - "id": "6008f899", + "id": "84048fb0", "metadata": { "editable": true }, @@ -2821,7 +2821,7 @@ }, { "cell_type": "markdown", - "id": "95440f53", + "id": "61ea03ed", "metadata": { "editable": true }, @@ -2833,7 +2833,7 @@ }, { "cell_type": "markdown", - "id": "0702b971", + "id": "abd0c817", "metadata": { "editable": true }, @@ -2843,7 +2843,7 @@ }, { "cell_type": "markdown", - "id": "a6f77a09", + "id": "2e0379cc", "metadata": { "editable": true }, @@ -2855,7 +2855,7 @@ }, { "cell_type": "markdown", - "id": "1ca3e1b7", + "id": "59290cf7", "metadata": { "editable": true }, @@ -2866,7 +2866,7 @@ }, { "cell_type": "markdown", - "id": "32065169", + "id": "6bc256eb", "metadata": { "editable": true }, @@ -2878,7 +2878,7 @@ }, { "cell_type": "markdown", - "id": "cbbd02a7", + "id": "831eee08", "metadata": { "editable": true }, @@ -2891,7 +2891,7 @@ }, { "cell_type": "markdown", - "id": "41c433a4", + "id": "ba46bcc0", "metadata": { "editable": true }, @@ -2916,7 +2916,7 @@ }, { "cell_type": "markdown", - "id": "651f5b04", + "id": "a475ed33", "metadata": { "editable": true }, @@ -2929,7 +2929,7 @@ }, { "cell_type": "markdown", - "id": "1effdc88", + "id": "378895ce", "metadata": { "editable": true }, @@ -2941,7 +2941,7 @@ }, { "cell_type": "markdown", - "id": "11fca2c0", + "id": "268989a6", "metadata": { "editable": true }, @@ -2953,7 +2953,7 @@ }, { "cell_type": "markdown", - "id": "a99bf23b", + "id": "1ac5dfe0", "metadata": { "editable": true }, @@ -2963,7 +2963,7 @@ }, { "cell_type": "markdown", - "id": "e78b0dba", + "id": "4d3d6bb7", "metadata": { "editable": true }, @@ -2975,7 +2975,7 @@ }, { "cell_type": "markdown", - "id": "d9ae883b", + "id": "bc4e4a53", "metadata": { "editable": true }, @@ -2987,7 +2987,7 @@ }, { "cell_type": "markdown", - "id": "792b7d30", + "id": "4cc000a1", "metadata": { "editable": true }, @@ -2999,7 +2999,7 @@ }, { "cell_type": "markdown", - "id": "94a824ec", + "id": "7f5ea691", "metadata": { "editable": true }, @@ -3011,7 +3011,7 @@ }, { "cell_type": "markdown", - "id": "03fc0202", + "id": "a7f4fc8e", "metadata": { "editable": true }, @@ -3021,7 +3021,7 @@ }, { "cell_type": "markdown", - "id": "d22d0454", + "id": "acdecb39", "metadata": { "editable": true }, @@ -3033,7 +3033,7 @@ }, { "cell_type": "markdown", - "id": "05b6e8f3", + "id": "b0c3e8c7", "metadata": { "editable": true }, @@ -3043,7 +3043,7 @@ }, { "cell_type": "markdown", - "id": "b27f84e2", + "id": "6e130deb", "metadata": { "editable": true }, @@ -3055,7 +3055,7 @@ }, { "cell_type": "markdown", - "id": "6713cccf", + "id": "23e83ce8", "metadata": { "editable": true }, @@ -3068,7 +3068,7 @@ }, { "cell_type": "markdown", - "id": "5613ad7a", + "id": "67c77893", "metadata": { "editable": true }, @@ -3080,7 +3080,7 @@ }, { "cell_type": "markdown", - "id": "ff5f4e47", + "id": "36ede636", "metadata": { "editable": true }, @@ -3090,7 +3090,7 @@ }, { "cell_type": "markdown", - "id": "addea11c", + "id": "4008b26c", "metadata": { "editable": true }, @@ -3102,7 +3102,7 @@ }, { "cell_type": "markdown", - "id": "6abca84d", + "id": "258ae1d4", "metadata": { "editable": true }, @@ -3113,7 +3113,7 @@ }, { "cell_type": "markdown", - "id": "d3a1b69c", + "id": "b9c648be", "metadata": { "editable": true }, @@ -3125,7 +3125,7 @@ }, { "cell_type": "markdown", - "id": "918afb75", + "id": "615f1fce", "metadata": { "editable": true }, @@ -3135,7 +3135,7 @@ }, { "cell_type": "markdown", - "id": "64c9a4f5", + "id": "620b34cb", "metadata": { "editable": true }, @@ -3147,7 +3147,7 @@ }, { "cell_type": "markdown", - "id": "9f1923dc", + "id": "7d09dc1a", "metadata": { "editable": true }, @@ -3157,7 +3157,7 @@ }, { "cell_type": "markdown", - "id": "8f270399", + "id": "8589b8ee", "metadata": { "editable": true }, @@ -3168,7 +3168,7 @@ }, { "cell_type": "markdown", - "id": "8de704ac", + "id": "63160327", "metadata": { "editable": true }, @@ -3181,7 +3181,7 @@ }, { "cell_type": "markdown", - "id": "59087524", + "id": "98614055", "metadata": { "editable": true }, @@ -3191,7 +3191,7 @@ }, { "cell_type": "markdown", - "id": "7f665678", + "id": "37435d7c", "metadata": { "editable": true }, @@ -3203,7 +3203,7 @@ }, { "cell_type": "markdown", - "id": "2d2c4d5d", + "id": "64a4d79f", "metadata": { "editable": true }, @@ -3213,7 +3213,7 @@ }, { "cell_type": "markdown", - "id": "b0fcad75", + "id": "7e3891af", "metadata": { "editable": true }, @@ -3225,7 +3225,7 @@ }, { "cell_type": "markdown", - "id": "1ffab0fd", + "id": "7205e781", "metadata": { "editable": true }, @@ -3235,7 +3235,7 @@ }, { "cell_type": "markdown", - "id": "2d93613f", + "id": "a5645092", "metadata": { "editable": true }, @@ -3259,7 +3259,7 @@ }, { "cell_type": "markdown", - "id": "67a188b1", + "id": "09e9b12d", "metadata": { "editable": true }, @@ -3309,7 +3309,7 @@ { "cell_type": "code", "execution_count": 3, - "id": "2d2dca8e", + "id": "84fd1480", "metadata": { "collapsed": false, "editable": true @@ -3362,7 +3362,7 @@ }, { "cell_type": "markdown", - "id": "c309c653", + "id": "e671e2a8", "metadata": { "editable": true }, @@ -3383,7 +3383,7 @@ { "cell_type": "code", "execution_count": 4, - "id": "7a7b60e2", + "id": "5d1c4624", "metadata": { "collapsed": false, "editable": true @@ -3421,7 +3421,7 @@ }, { "cell_type": "markdown", - "id": "4f9ea146", + "id": "b397d4ee", "metadata": { "editable": true }, @@ -3465,7 +3465,7 @@ }, { "cell_type": "markdown", - "id": "1ac702f1", + "id": "1fce534f", "metadata": { "editable": true }, @@ -3505,7 +3505,7 @@ }, { "cell_type": "markdown", - "id": "8e01b66f", + "id": "9c50a158", "metadata": { "editable": true }, @@ -3526,7 +3526,7 @@ { "cell_type": "code", "execution_count": 5, - "id": "89e89f6b", + "id": "4daeba9a", "metadata": { "collapsed": false, "editable": true @@ -3552,7 +3552,7 @@ }, { "cell_type": "markdown", - "id": "c8263d0b", + "id": "f26a835c", "metadata": { "editable": true }, @@ -3580,7 +3580,7 @@ }, { "cell_type": "markdown", - "id": "fe4e2d27", + "id": "09f1187b", "metadata": { "editable": true }, @@ -3617,7 +3617,7 @@ { "cell_type": "code", "execution_count": 6, - "id": "441d2f83", + "id": "35d71f0e", "metadata": { "collapsed": false, "editable": true @@ -3663,7 +3663,7 @@ }, { "cell_type": "markdown", - "id": "d3b6dfd7", + "id": "e318575f", "metadata": { "editable": true }, @@ -3694,7 +3694,7 @@ }, { "cell_type": "markdown", - "id": "e72cf1e3", + "id": "788f45d2", "metadata": { "editable": true }, @@ -3732,7 +3732,7 @@ }, { "cell_type": "markdown", - "id": "eb188032", + "id": "599a7b8f", "metadata": { "editable": true }, @@ -3766,7 +3766,7 @@ }, { "cell_type": "markdown", - "id": "a728bad0", + "id": "cc694849", "metadata": { "editable": true }, @@ -3807,7 +3807,7 @@ { "cell_type": "code", "execution_count": 7, - "id": "e0c7221a", + "id": "e3607c66", "metadata": { "collapsed": false, "editable": true @@ -3886,7 +3886,7 @@ }, { "cell_type": "markdown", - "id": "78be309a", + "id": "0a70cdcf", "metadata": { "editable": true }, @@ -3907,7 +3907,7 @@ }, { "cell_type": "markdown", - "id": "e58fe912", + "id": "b0600212", "metadata": { "editable": true }, @@ -3921,7 +3921,7 @@ { "cell_type": "code", "execution_count": 8, - "id": "264331ef", + "id": "4e0c1326", "metadata": { "collapsed": false, "editable": true @@ -4031,7 +4031,7 @@ }, { "cell_type": "markdown", - "id": "89119105", + "id": "125f8eca", "metadata": { "editable": true }, @@ -4050,7 +4050,7 @@ { "cell_type": "code", "execution_count": 9, - "id": "84f5192d", + "id": "cef0e788", "metadata": { "collapsed": false, "editable": true @@ -4077,7 +4077,7 @@ }, { "cell_type": "markdown", - "id": "62ccfca8", + "id": "b12d6f86", "metadata": { "editable": true }, @@ -4091,7 +4091,7 @@ { "cell_type": "code", "execution_count": 10, - "id": "d7836d26", + "id": "974faa4e", "metadata": { "collapsed": false, "editable": true @@ -4122,7 +4122,7 @@ }, { "cell_type": "markdown", - "id": "0f12323a", + "id": "3bb19122", "metadata": { "editable": true }, @@ -4133,7 +4133,7 @@ { "cell_type": "code", "execution_count": 11, - "id": "e7e0fd6b", + "id": "baeb1ea3", "metadata": { "collapsed": false, "editable": true @@ -4177,7 +4177,7 @@ }, { "cell_type": "markdown", - "id": "e497e447", + "id": "d75dad8e", "metadata": { "editable": true }, @@ -4200,7 +4200,7 @@ { "cell_type": "code", "execution_count": 12, - "id": "d50de16a", + "id": "d55fae28", "metadata": { "collapsed": false, "editable": true @@ -4227,7 +4227,7 @@ }, { "cell_type": "markdown", - "id": "7994d203", + "id": "276badf8", "metadata": { "editable": true }, @@ -4238,7 +4238,7 @@ { "cell_type": "code", "execution_count": 13, - "id": "7403a1d9", + "id": "7d6c714e", "metadata": { "collapsed": false, "editable": true @@ -4283,7 +4283,7 @@ }, { "cell_type": "markdown", - "id": "c91fafb3", + "id": "0d45b429", "metadata": { "editable": true }, @@ -4301,7 +4301,7 @@ }, { "cell_type": "markdown", - "id": "de877dec", + "id": "67aec670", "metadata": { "editable": true }, @@ -4336,7 +4336,7 @@ { "cell_type": "code", "execution_count": 14, - "id": "174b34a1", + "id": "0ab38a83", "metadata": { "collapsed": false, "editable": true @@ -4348,7 +4348,7 @@ }, { "cell_type": "markdown", - "id": "b24e37a3", + "id": "8f53f5b9", "metadata": { "editable": true }, @@ -4360,7 +4360,7 @@ { "cell_type": "code", "execution_count": 15, - "id": "120502b3", + "id": "5190c7ff", "metadata": { "collapsed": false, "editable": true @@ -4373,7 +4373,7 @@ }, { "cell_type": "markdown", - "id": "f315598a", + "id": "676ff9d7", "metadata": { "editable": true }, @@ -4384,7 +4384,7 @@ { "cell_type": "code", "execution_count": 16, - "id": "30c4aecf", + "id": "479149f7", "metadata": { "collapsed": false, "editable": true @@ -4397,7 +4397,7 @@ }, { "cell_type": "markdown", - "id": "80c81210", + "id": "62d1b789", "metadata": { "editable": true }, @@ -4412,7 +4412,7 @@ { "cell_type": "code", "execution_count": 17, - "id": "9273bbaa", + "id": "4a11035a", "metadata": { "collapsed": false, "editable": true @@ -4424,7 +4424,7 @@ }, { "cell_type": "markdown", - "id": "470fb33d", + "id": "abf44b70", "metadata": { "editable": true }, @@ -4436,7 +4436,7 @@ }, { "cell_type": "markdown", - "id": "534f68d4", + "id": "3f163559", "metadata": { "editable": true }, @@ -4449,7 +4449,7 @@ { "cell_type": "code", "execution_count": 18, - "id": "00ce07a1", + "id": "f7418c1e", "metadata": { "collapsed": false, "editable": true @@ -4504,7 +4504,7 @@ { "cell_type": "code", "execution_count": 19, - "id": "e3a94eef", + "id": "49ec0156", "metadata": { "collapsed": false, "editable": true @@ -4533,7 +4533,7 @@ { "cell_type": "code", "execution_count": 20, - "id": "8ebd406f", + "id": "302ad127", "metadata": { "collapsed": false, "editable": true @@ -4563,7 +4563,7 @@ { "cell_type": "code", "execution_count": 21, - "id": "1c44ca1b", + "id": "436a3e0a", "metadata": { "collapsed": false, "editable": true @@ -4590,7 +4590,7 @@ { "cell_type": "code", "execution_count": 22, - "id": "547bb452", + "id": "a26e83e0", "metadata": { "collapsed": false, "editable": true @@ -4632,7 +4632,7 @@ }, { "cell_type": "markdown", - "id": "75957f82", + "id": "8d69b494", "metadata": { "editable": true }, @@ -4643,7 +4643,7 @@ { "cell_type": "code", "execution_count": 23, - "id": "94525555", + "id": "cad16bbe", "metadata": { "collapsed": false, "editable": true @@ -4820,7 +4820,7 @@ }, { "cell_type": "markdown", - "id": "a1785215", + "id": "61624838", "metadata": { "editable": true }, @@ -4839,7 +4839,7 @@ }, { "cell_type": "markdown", - "id": "9c17c7d6", + "id": "f825f2da", "metadata": { "editable": true }, @@ -4861,7 +4861,7 @@ { "cell_type": "code", "execution_count": 24, - "id": "f9227a16", + "id": "409b4250", "metadata": { "collapsed": false, "editable": true @@ -5002,7 +5002,7 @@ }, { "cell_type": "markdown", - "id": "131c32f5", + "id": "c6830d86", "metadata": { "editable": true }, @@ -5018,7 +5018,7 @@ { "cell_type": "code", "execution_count": 25, - "id": "1d9eeefd", + "id": "041fc0bf", "metadata": { "collapsed": false, "editable": true @@ -5031,7 +5031,7 @@ }, { "cell_type": "markdown", - "id": "33286bbb", + "id": "0e18ef84", "metadata": { "editable": true }, @@ -5043,7 +5043,7 @@ { "cell_type": "code", "execution_count": 26, - "id": "6a604d44", + "id": "8be0e7fd", "metadata": { "collapsed": false, "editable": true @@ -5065,7 +5065,7 @@ }, { "cell_type": "markdown", - "id": "a3da1579", + "id": "2d2bc7a5", "metadata": { "editable": true }, @@ -5081,7 +5081,7 @@ { "cell_type": "code", "execution_count": 27, - "id": "3252d0f9", + "id": "f5cb107e", "metadata": { "collapsed": false, "editable": true @@ -5119,7 +5119,7 @@ }, { "cell_type": "markdown", - "id": "4b975b6f", + "id": "beb4f622", "metadata": { "editable": true }, @@ -5132,7 +5132,7 @@ { "cell_type": "code", "execution_count": 28, - "id": "8766a22e", + "id": "1b508839", "metadata": { "collapsed": false, "editable": true @@ -5153,7 +5153,7 @@ }, { "cell_type": "markdown", - "id": "f066034a", + "id": "afb2e0af", "metadata": { "editable": true }, @@ -5169,7 +5169,7 @@ { "cell_type": "code", "execution_count": 29, - "id": "a83127b5", + "id": "b96d6c89", "metadata": { "collapsed": false, "editable": true @@ -5227,7 +5227,7 @@ }, { "cell_type": "markdown", - "id": "9e044132", + "id": "0be588f8", "metadata": { "editable": true }, @@ -5242,7 +5242,7 @@ { "cell_type": "code", "execution_count": 30, - "id": "ee834194", + "id": "49b8531e", "metadata": { "collapsed": false, "editable": true @@ -5263,7 +5263,7 @@ }, { "cell_type": "markdown", - "id": "cbe89495", + "id": "874d306a", "metadata": { "editable": true }, @@ -5287,7 +5287,7 @@ { "cell_type": "code", "execution_count": 31, - "id": "0b542b4f", + "id": "c25e9955", "metadata": { "collapsed": false, "editable": true @@ -5759,7 +5759,7 @@ }, { "cell_type": "markdown", - "id": "d1a70256", + "id": "86746540", "metadata": { "editable": true }, @@ -5771,7 +5771,7 @@ { "cell_type": "code", "execution_count": 32, - "id": "6065cbb1", + "id": "6f232f0a", "metadata": { "collapsed": false, "editable": true @@ -5815,7 +5815,7 @@ }, { "cell_type": "markdown", - "id": "079f4466", + "id": "7227f21d", "metadata": { "editable": true }, @@ -5831,7 +5831,7 @@ { "cell_type": "code", "execution_count": 33, - "id": "3d0cbbdc", + "id": "944ba89b", "metadata": { "collapsed": false, "editable": true @@ -5846,7 +5846,7 @@ }, { "cell_type": "markdown", - "id": "3b2c61b3", + "id": "3cef110a", "metadata": { "editable": true }, @@ -5857,7 +5857,7 @@ { "cell_type": "code", "execution_count": 34, - "id": "7b0a3f82", + "id": "8eb39d5e", "metadata": { "collapsed": false, "editable": true @@ -5872,7 +5872,7 @@ }, { "cell_type": "markdown", - "id": "3b3643a5", + "id": "4c0ab092", "metadata": { "editable": true }, @@ -5888,7 +5888,7 @@ { "cell_type": "code", "execution_count": 35, - "id": "86c8aae2", + "id": "af77a32b", "metadata": { "collapsed": false, "editable": true @@ -5902,7 +5902,7 @@ }, { "cell_type": "markdown", - "id": "4e8f19e1", + "id": "dfdb722f", "metadata": { "editable": true }, @@ -5917,7 +5917,7 @@ { "cell_type": "code", "execution_count": 36, - "id": "dda49b53", + "id": "d740dbad", "metadata": { "collapsed": false, "editable": true @@ -5943,7 +5943,7 @@ { "cell_type": "code", "execution_count": 37, - "id": "a5816f25", + "id": "bfb7c28b", "metadata": { "collapsed": false, "editable": true @@ -5958,7 +5958,7 @@ }, { "cell_type": "markdown", - "id": "a51f22b7", + "id": "17a8dc93", "metadata": { "editable": true }, @@ -5969,7 +5969,7 @@ { "cell_type": "code", "execution_count": 38, - "id": "7d8852f0", + "id": "7efc0180", "metadata": { "collapsed": false, "editable": true @@ -5984,7 +5984,7 @@ }, { "cell_type": "markdown", - "id": "6675f462", + "id": "8255133c", "metadata": { "editable": true }, @@ -5995,7 +5995,7 @@ { "cell_type": "code", "execution_count": 39, - "id": "55a4e205", + "id": "4fa47196", "metadata": { "collapsed": false, "editable": true @@ -6015,7 +6015,7 @@ { "cell_type": "code", "execution_count": 40, - "id": "d29aef95", + "id": "b7b5ed9f", "metadata": { "collapsed": false, "editable": true @@ -6030,7 +6030,7 @@ }, { "cell_type": "markdown", - "id": "4816b115", + "id": "bc0fc41e", "metadata": { "editable": true }, @@ -6045,7 +6045,7 @@ { "cell_type": "code", "execution_count": 41, - "id": "2ce1d25b", + "id": "4ccf32f6", "metadata": { "collapsed": false, "editable": true @@ -6082,7 +6082,7 @@ }, { "cell_type": "markdown", - "id": "c9b9150b", + "id": "382301fa", "metadata": { "editable": true }, @@ -6095,7 +6095,7 @@ { "cell_type": "code", "execution_count": 42, - "id": "0e8eea1f", + "id": "0feb8f2a", "metadata": { "collapsed": false, "editable": true @@ -6118,7 +6118,7 @@ }, { "cell_type": "markdown", - "id": "55edaac4", + "id": "3f48285b", "metadata": { "editable": true }, diff --git a/doc/src/week42/._week42-bs000.html b/doc/src/week42/._week42-bs000.html deleted file mode 100644 index 01e8a9642..000000000 --- a/doc/src/week42/._week42-bs000.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -
-
-

Week 42 Constructing a Neural Network code with examples

-
- - -
-Morten Hjorth-Jensen [1, 2] -
- -
-[1] Department of Physics, University of Oslo -
-
-[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University -
-
-
-

October 14-18, 2024

-
-
- - - -

Read »

- - -
- -

- -

- -
- - - - -
- © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - diff --git a/doc/src/week42/._week42-bs001.html b/doc/src/week42/._week42-bs001.html deleted file mode 100644 index 59127ba6d..000000000 --- a/doc/src/week42/._week42-bs001.html +++ /dev/null @@ -1,530 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Lecture October 14, 2024

-
-
- -
    -
  1. Building our own Feed-forward Neural Network and discussion of project 2
  2. -
-
-
- -
-
- -
    -
  1. These lecture notes - -
  2. -
  3. For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7.
  4. -
  5. Neural Networks demystified at https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs
  6. -
  7. Building Neural Networks from scratch at https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex
  8. -
  9. Video on Neural Networks at https://www.youtube.com/watch?v=CqOfi41LfDw
  10. -
  11. Video on the back propagation algorithm at https://www.youtube.com/watch?v=Ilg3gGewQ5U
  12. -
-

I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at http://neuralnetworksanddeeplearning.com/chap4.html.

-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs002.html b/doc/src/week42/._week42-bs002.html deleted file mode 100644 index c6623ae0b..000000000 --- a/doc/src/week42/._week42-bs002.html +++ /dev/null @@ -1,517 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Material for the active learning sessions on Tuesday and Wednesday

-
-
- -
    -
  • Exercise on starting to write a code for neural networks, feed forward part. We will also continue ur discussions of gradient descent methods from last week. If you have time, start considering the back-propagation part as well (exercises for next week)
  • -
  • Discussion of project 2
  • -
-
-
- - -

Note: some of the codes will also be discussed next week in connection with the solution of differential equations.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs003.html b/doc/src/week42/._week42-bs003.html deleted file mode 100644 index dcd01d0d6..000000000 --- a/doc/src/week42/._week42-bs003.html +++ /dev/null @@ -1,517 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Writing a code which implements a feed-forward neural network

- -

Last week we discussed the basics of neural networks and deep learning -and the basics of automatic differentiation. We looked also at -examples on how compute the parameters of a simple network with scalar -inputs and ouputs and no or just one hidden layers. -

- -

We ended our discussions with the derivation of the equations for a -neural network with one hidden layers and two input variables and two -hidden nodes but only one output node. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs004.html b/doc/src/week42/._week42-bs004.html deleted file mode 100644 index 37db78730..000000000 --- a/doc/src/week42/._week42-bs004.html +++ /dev/null @@ -1,518 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Mathematics of deep learning

- -
- -
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs005.html b/doc/src/week42/._week42-bs005.html deleted file mode 100644 index 62f983273..000000000 --- a/doc/src/week42/._week42-bs005.html +++ /dev/null @@ -1,517 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Reminder on books with hands-on material and codes

-
- -
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs006.html b/doc/src/week42/._week42-bs006.html deleted file mode 100644 index f10997788..000000000 --- a/doc/src/week42/._week42-bs006.html +++ /dev/null @@ -1,513 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Reading recommendations

- -
    -
  1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub
  2. -
  3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
  4. -
-

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs007.html b/doc/src/week42/._week42-bs007.html deleted file mode 100644 index f36029253..000000000 --- a/doc/src/week42/._week42-bs007.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

First network example, simple percepetron with one input

- -

As yet another example we define now a simple perceptron model with -all quantities given by scalars. We consider only one input variable -\( x \) and one target value \( y \). We define an activation function -\( \sigma_1 \) which takes as input -

- -$$ -z_1 = w_1x+b_1, -$$ - -

where \( w_1 \) is the weight and \( b_1 \) is the bias. These are the -parameters we want to optimize. The output is \( a_1=\sigma(z_1) \) (see -graph from whiteboard notes). This output is then fed into the -cost/loss function, which we here for the sake of simplicity just -define as the squared error -

- -$$ -C(x;w_1,b_1)=\frac{1}{2}(a_1-y)^2. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs008.html b/doc/src/week42/._week42-bs008.html deleted file mode 100644 index 9966971d8..000000000 --- a/doc/src/week42/._week42-bs008.html +++ /dev/null @@ -1,517 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Layout of a simple neural network with no hidden layer

- -

-
-

-
-

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs009.html b/doc/src/week42/._week42-bs009.html deleted file mode 100644 index accfdbc6b..000000000 --- a/doc/src/week42/._week42-bs009.html +++ /dev/null @@ -1,538 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Optimizing the parameters

- -

In setting up the feed forward and back propagation parts of the -algorithm, we need now the derivative of the various variables we want -to train. -

- -

We need

-$$ -\frac{\partial C}{\partial w_1} \hspace{0.1cm}\mathrm{and}\hspace{0.1cm}\frac{\partial C}{\partial b_1}. -$$ - -

Using the chain rule we find

-$$ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_1-y)\sigma_1'x, -$$ - -

and

-$$ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_1-y)\sigma_1', -$$ - -

which we later will just define as

-$$ -\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}=\delta_1. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs010.html b/doc/src/week42/._week42-bs010.html deleted file mode 100644 index 1cd03effb..000000000 --- a/doc/src/week42/._week42-bs010.html +++ /dev/null @@ -1,535 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Adding a hidden layer

- -

We change our simple model to (see graph) -a network with just one hidden layer but with scalar variables only. -

- -

Our output variable changes to \( a_2 \) and \( a_1 \) is now the output from the hidden node and \( a_0=x \). -We have then -

-$$ -z_1 = w_1a_0+b_1 \hspace{0.1cm} \wedge a_1 = \sigma_1(z_1), -$$ - -$$ -z_2 = w_2a_1+b_2 \hspace{0.1cm} \wedge a_2 = \sigma_2(z_2), -$$ - -

and the cost function

-$$ -C(x;\boldsymbol{\Theta})=\frac{1}{2}(a_2-y)^2, -$$ - -

with \( \boldsymbol{\Theta}=[w_1,w_2,b_1,b_2] \).

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs011.html b/doc/src/week42/._week42-bs011.html deleted file mode 100644 index bdb721fe0..000000000 --- a/doc/src/week42/._week42-bs011.html +++ /dev/null @@ -1,519 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Layout of a simple neural network with one hidden layer

- -

-
-

-
-

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs012.html b/doc/src/week42/._week42-bs012.html deleted file mode 100644 index 1876d220c..000000000 --- a/doc/src/week42/._week42-bs012.html +++ /dev/null @@ -1,533 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

The derivatives

- -

The derivatives are now, using the chain rule again

- -$$ -\frac{\partial C}{\partial w_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial w_2}=(a_2-y)\sigma_2'a_1=\delta_2a_1, -$$ - -$$ -\frac{\partial C}{\partial b_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial b_2}=(a_2-y)\sigma_2'=\delta_2, -$$ - -$$ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_2-y)\sigma_2'a_1\sigma_1'a_0, -$$ - -$$ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_2-y)\sigma_2'\sigma_1'=\delta_1. -$$ - -

Can you generalize this to more than one hidden layer?

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs013.html b/doc/src/week42/._week42-bs013.html deleted file mode 100644 index b446fcd88..000000000 --- a/doc/src/week42/._week42-bs013.html +++ /dev/null @@ -1,526 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Important observations

- -
-
- -

From the above equations we see that the derivatives of the activation -functions play a central role. If they vanish, the training may -stop. This is called the vanishing gradient problem, see discussions below. If they become -large, the parameters \( w_i \) and \( b_i \) may simply go to infinity. This -is referenced as the exploding gradient problem. -

-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs014.html b/doc/src/week42/._week42-bs014.html deleted file mode 100644 index 8abe55087..000000000 --- a/doc/src/week42/._week42-bs014.html +++ /dev/null @@ -1,530 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

The training

- -

The training of the parameters is done through various gradient descent approximations with

- -$$ -w_{i}\leftarrow w_{i}- \eta \delta_i a_{i-1}, -$$ - -

and

-$$ -b_i \leftarrow b_i-\eta \delta_i, -$$ - -

with \( \eta \) is the learning rate.

- -

One iteration consists of one feed forward step and one back-propagation step. Each back-propagation step does one update of the parameters \( \boldsymbol{\Theta} \).

- -

For the first hidden layer \( a_{i-1}=a_0=x \) for this simple model.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs015.html b/doc/src/week42/._week42-bs015.html deleted file mode 100644 index 1746be476..000000000 --- a/doc/src/week42/._week42-bs015.html +++ /dev/null @@ -1,607 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Code example

- -

The code here implements the above model with one hidden layer and -scalar variables for the same function we studied in the previous -example. The code is however set up so that we can add multiple -inputs \( x \) and target values \( y \). Note also that we have the -possibility of defining a feature matrix \( \boldsymbol{X} \) with more than just -one column for the input values. This will turn useful in our next example. We have also defined matrices and vectors for all of our operations although it is not necessary here. -

- - - -
-
-
-
-
-
import numpy as np
-# We use the Sigmoid function as activation function
-def sigmoid(z):
-    return 1.0/(1.0+np.exp(-z))
-
-def forwardpropagation(x):
-    # weighted sum of inputs to the hidden layer
-    z_1 = np.matmul(x, w_1) + b_1
-    # activation in the hidden layer
-    a_1 = sigmoid(z_1)
-    # weighted sum of inputs to the output layer
-    z_2 = np.matmul(a_1, w_2) + b_2
-    a_2 = z_2
-    return a_1, a_2
-
-def backpropagation(x, y):
-    a_1, a_2 = forwardpropagation(x)
-    # parameter delta for the output layer, note that a_2=z_2 and its derivative wrt z_2 is just 1
-    delta_2 = a_2 - y
-    print(0.5*((a_2-y)**2))
-    # delta for  the hidden layer
-    delta_1 = np.matmul(delta_2, w_2.T) * a_1 * (1 - a_1)
-    # gradients for the output layer
-    output_weights_gradient = np.matmul(a_1.T, delta_2)
-    output_bias_gradient = np.sum(delta_2, axis=0)
-    # gradient for the hidden layer
-    hidden_weights_gradient = np.matmul(x.T, delta_1)
-    hidden_bias_gradient = np.sum(delta_1, axis=0)
-    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-# Input variable
-x = np.array([4.0],dtype=np.float64)
-# Target values
-y = 2*x+1.0 
-
-# Defining the neural network, only scalars here
-n_inputs = x.shape
-n_features = 1
-n_hidden_neurons = 1
-n_outputs = 1
-
-# Initialize the network
-# weights and bias in the hidden layer
-w_1 = np.random.randn(n_features, n_hidden_neurons)
-b_1 = np.zeros(n_hidden_neurons) + 0.01
-
-# weights and bias in the output layer
-w_2 = np.random.randn(n_hidden_neurons, n_outputs)
-b_2 = np.zeros(n_outputs) + 0.01
-
-eta = 0.1
-for i in range(50):
-    # calculate gradients
-    derivW2, derivB2, derivW1, derivB1 = backpropagation(x, y)
-    # update weights and biases
-    w_2 -= eta * derivW2
-    b_2 -= eta * derivB2
-    w_1 -= eta * derivW1
-    b_1 -= eta * derivB1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that after some few iterations (the results do depend on the learning rate however), we get an error which is rather small.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs016.html b/doc/src/week42/._week42-bs016.html deleted file mode 100644 index 4a9ec98ed..000000000 --- a/doc/src/week42/._week42-bs016.html +++ /dev/null @@ -1,531 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Simple neural network and the back propagation equations

- -

Let us now try to increase our level of ambition and attempt at setting -up the equations for a neural network with two input nodes, one hidden -layer with two hidden nodes and one output layer with one output node/neuron only (see graph).. -

- -

We need to define the following parameters and variables with the input layer (layer \( (0) \)) -where we label the nodes \( x_0 \) and \( x_1 \) -

-$$ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. -$$ - -

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_0^{(1)} \) and \( a_1^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

-$$ -w_{ij}^{(1)}=\left\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\right\} \wedge b^{(1)}=\left\{b_0^{(1)},b_1^{(1)}\right\}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs017.html b/doc/src/week42/._week42-bs017.html deleted file mode 100644 index 31544c02e..000000000 --- a/doc/src/week42/._week42-bs017.html +++ /dev/null @@ -1,519 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Layout of a simple neural network with two input nodes, one hidden layer with two hidden noeds and one output node

- -

-
-

-
-

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs018.html b/doc/src/week42/._week42-bs018.html deleted file mode 100644 index 84b0b581a..000000000 --- a/doc/src/week42/._week42-bs018.html +++ /dev/null @@ -1,526 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

The ouput layer

- -

We have the ouput layer given by layer label \( (2) \) with output \( a^{(2)} \) and weights and biases to be determined given by the variables

-$$ -w_{i}^{(2)}=\left\{w_{1}^{(2)},w_{2}^{(2)}\right\} \wedge b^{(2)}. -$$ - -

Our output is \( \tilde{y}=a^{(2)} \) and we define a generic cost function \( C(a^{(2)},y;\boldsymbol{\Theta}) \) where \( y \) is the target value (a scalar here). -The parameters we need to optimize are given by -

-$$ -\boldsymbol{\Theta}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)},w_{1}^{(2)},w_{2}^{(2)},b_1^{(1)},b_2^{(1)},b^{(2)}\right\}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs019.html b/doc/src/week42/._week42-bs019.html deleted file mode 100644 index c41632cb4..000000000 --- a/doc/src/week42/._week42-bs019.html +++ /dev/null @@ -1,526 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Compact expressions

- -

We can define the inputs to the activation functions for the various layers in terms of various matrix-vector multiplications and vector additions. -The inputs to the first hidden layer are -

-$$ -\begin{bmatrix}z_1^{(1)} \\ z_2^{(1)} \end{bmatrix}=\left(\begin{bmatrix}w_{11}^{(1)} & w_{12}^{(1)}\\ w_{21}^{(1)} &w_{22}^{(1)} \end{bmatrix}\right)^{T}\begin{bmatrix}a_1^{(0)} \\ a_2^{(0)} \end{bmatrix}+\begin{bmatrix}b_1^{(1)} \\ b_2^{(1)} \end{bmatrix}, -$$ - -

with outputs

-$$ -\begin{bmatrix}a_1^{(1)} \\ a_2^{(1)} \end{bmatrix}=\begin{bmatrix}\sigma^{(1)}(z_1^{(1)}) \\ \sigma^{(1)}(z_2^{(1)}) \end{bmatrix}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs020.html b/doc/src/week42/._week42-bs020.html deleted file mode 100644 index f193ffed7..000000000 --- a/doc/src/week42/._week42-bs020.html +++ /dev/null @@ -1,524 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Output layer

- -

For the final output layer we have the inputs to the final activation function

-$$ -z^{(2)} = w_{1}^{(2)}a_1^{(1)} +w_{2}^{(2)}a_2^{(1)}+b^{(2)}, -$$ - -

resulting in the output

-$$ -a^{(2)}=\sigma^{(2)}(z^{(2)}). -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs021.html b/doc/src/week42/._week42-bs021.html deleted file mode 100644 index e401afcfc..000000000 --- a/doc/src/week42/._week42-bs021.html +++ /dev/null @@ -1,535 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Explicit derivatives

- -

In total we have nine parameters which we need to train. Using the -chain rule (or just the back-propagation algorithm) we can find all -derivatives. Since we will use automatic differentiation in reverse -mode, we start with the derivatives of the cost function with respect -to the parameters of the output layer, namely -

- -$$ -\frac{\partial C}{\partial w_{i}^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial w_{i}^{(2)}}=\delta^{(2)}a_i^{(1)}, -$$ - -

with

-$$ -\delta^{(2)}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -$$ - -

and finally

-$$ -\frac{\partial C}{\partial b^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial b^{(2)}}=\delta^{(2)}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs022.html b/doc/src/week42/._week42-bs022.html deleted file mode 100644 index 7af775cf9..000000000 --- a/doc/src/week42/._week42-bs022.html +++ /dev/null @@ -1,530 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Derivatives of the hidden layer

- -

Using the chain rule we have the following expressions for say one of the weight parameters (it is easy to generalize to the other weight parameters)

-$$ -\frac{\partial C}{\partial w_{11}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}= \delta^{(2)}\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}, -$$ - -

which, noting that

-$$ -z^{(2)} =w_1^{(2)}a_1^{(1)}+w_2^{(2)}a_2^{(1)}+b^{(2)}, -$$ - -

allows us to rewrite

-$$ -\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}a_1^{(1)}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs023.html b/doc/src/week42/._week42-bs023.html deleted file mode 100644 index 595d824e0..000000000 --- a/doc/src/week42/._week42-bs023.html +++ /dev/null @@ -1,528 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Final expression

-

Defining

-$$ -\delta_1^{(1)}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}\delta^{(2)}, -$$ - -

we have

-$$ -\frac{\partial C}{\partial w_{11}^{(1)}}=\delta_1^{(1)}a_1^{(1)}. -$$ - -

Similarly, we obtain

-$$ -\frac{\partial C}{\partial w_{12}^{(1)}}=\delta_1^{(1)}a_2^{(1)}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs024.html b/doc/src/week42/._week42-bs024.html deleted file mode 100644 index ea63e4fc7..000000000 --- a/doc/src/week42/._week42-bs024.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Completing the list

- -

Similarly, we find

-$$ -\frac{\partial C}{\partial w_{21}^{(1)}}=\delta_2^{(1)}a_1^{(1)}, -$$ - -

and

-$$ -\frac{\partial C}{\partial w_{22}^{(1)}}=\delta_2^{(1)}a_2^{(1)}, -$$ - -

where we have defined

-$$ -\delta_2^{(1)}=w_2^{(2)}\frac{\partial a_2^{(1)}}{\partial z_2^{(1)}}\delta^{(2)}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs025.html b/doc/src/week42/._week42-bs025.html deleted file mode 100644 index 1a39902ee..000000000 --- a/doc/src/week42/._week42-bs025.html +++ /dev/null @@ -1,525 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Final expressions for the biases of the hidden layer

- -

For the sake of completeness, we list the derivatives of the biases, which are

-$$ -\frac{\partial C}{\partial b_{1}^{(1)}}=\delta_1^{(1)}, -$$ - -

and

-$$ -\frac{\partial C}{\partial b_{2}^{(1)}}=\delta_2^{(1)}. -$$ - -

As we will see below, these expressions can be generalized in a more compact form.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs026.html b/doc/src/week42/._week42-bs026.html deleted file mode 100644 index f00c2656b..000000000 --- a/doc/src/week42/._week42-bs026.html +++ /dev/null @@ -1,537 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Gradient expressions

- -

For this specific model, with just one output node and two hidden -nodes, the gradient descent equations take the following form for output layer -

-$$ -w_{i}^{(2)}\leftarrow w_{i}^{(2)}- \eta \delta^{(2)} a_{i}^{(1)}, -$$ - -

and

-$$ -b^{(2)} \leftarrow b^{(2)}-\eta \delta^{(2)}, -$$ - -

and

-$$ -w_{ij}^{(1)}\leftarrow w_{ij}^{(1)}- \eta \delta_{i}^{(1)} a_{j}^{(0)}, -$$ - -

and

-$$ -b_{i}^{(1)} \leftarrow b_{i}^{(1)}-\eta \delta_{i}^{(1)}, -$$ - -

where \( \eta \) is the learning rate.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs027.html b/doc/src/week42/._week42-bs027.html deleted file mode 100644 index 89668d155..000000000 --- a/doc/src/week42/._week42-bs027.html +++ /dev/null @@ -1,531 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Setting up the equations for a neural network

- -

The questions we want to ask are how do changes in the biases and the -weights in our network change the cost function and how can we use the -final output to modify the weights and biases? -

- -

To derive these equations let us start with a plain regression problem -and define our cost function as -

- -$$ -{\cal C}(\boldsymbol{\Theta}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2, -$$ - -

where the $y_i$s are our \( n \) targets (the values we want to -reproduce), while the outputs of the network after having propagated -all inputs \( \boldsymbol{x} \) are given by \( \boldsymbol{\tilde{y}}_i \). -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs028.html b/doc/src/week42/._week42-bs028.html deleted file mode 100644 index c2b11af09..000000000 --- a/doc/src/week42/._week42-bs028.html +++ /dev/null @@ -1,519 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Layout of a neural network with three hidden layers (last later = \( l=L=4 \), first layer \( l=0 \))

- -

-
-

-
-

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs029.html b/doc/src/week42/._week42-bs029.html deleted file mode 100644 index 45bfd2bbd..000000000 --- a/doc/src/week42/._week42-bs029.html +++ /dev/null @@ -1,536 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Definitions

- -

With our definition of the targets \( \boldsymbol{y} \), the outputs of the -network \( \boldsymbol{\tilde{y}} \) and the inputs \( \boldsymbol{x} \) we -define now the activation \( z_j^l \) of node/neuron/unit \( j \) of the -\( l \)-th layer as a function of the bias, the weights which add up from -the previous layer \( l-1 \) and the forward passes/outputs -\( \boldsymbol{a}^{l-1} \) from the previous layer as -

- -$$ -z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, -$$ - -

where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) -represents the total number of nodes/neurons/units of layer \( l-1 \). The -figure in the whiteboard notes illustrates this equation. We can rewrite this in a more -compact form as the matrix-vector products we discussed earlier, -

- -$$ -\boldsymbol{z}^l = \left(\boldsymbol{W}^l\right)^T\boldsymbol{a}^{l-1}+\boldsymbol{b}^l. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs030.html b/doc/src/week42/._week42-bs030.html deleted file mode 100644 index 04978b68b..000000000 --- a/doc/src/week42/._week42-bs030.html +++ /dev/null @@ -1,525 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Inputs to the activation function

- -

With the activation values \( \boldsymbol{z}^l \) we can in turn define the -output of layer \( l \) as \( \boldsymbol{a}^l = \sigma(\boldsymbol{z}^l) \) where \( \sigma \) is our -activation function. In the examples here we will use the sigmoid -function discussed in our logistic regression lectures. We will also use the same activation function \( \sigma \) for all layers -and their nodes. It means we have -

- -$$ -a_j^l = \sigma(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs031.html b/doc/src/week42/._week42-bs031.html deleted file mode 100644 index 40e18abe1..000000000 --- a/doc/src/week42/._week42-bs031.html +++ /dev/null @@ -1,519 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Layout of input to first hidden layer \( l=1 \) from input layer \( l=0 \)

- -

-
-

-
-

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs032.html b/doc/src/week42/._week42-bs032.html deleted file mode 100644 index 4090147f3..000000000 --- a/doc/src/week42/._week42-bs032.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Derivatives and the chain rule

- -

From the definition of the input variable to the activation function, that is \( z_j^l \) we have

-$$ -\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, -$$ - -

and

-$$ -\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. -$$ - -

With our definition of the activation function we have that (note that this function depends only on \( z_j^l \))

-$$ -\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=\sigma(z_j^l)(1-\sigma(z_j^l)). -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs033.html b/doc/src/week42/._week42-bs033.html deleted file mode 100644 index ae79e8047..000000000 --- a/doc/src/week42/._week42-bs033.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Derivative of the cost function

- -

With these definitions we can now compute the derivative of the cost function in terms of the weights.

- -

Let us specialize to the output layer \( l=L \). Our cost function is

-$$ -{\cal C}(\boldsymbol{\Theta}^L) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - y_i\right)^2, -$$ - -

The derivative of this function with respect to the weights is

- -$$ -\frac{\partial{\cal C}(\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)\frac{\partial a_j^L}{\partial w_{ij}^{L}}, -$$ - -

The last partial derivative can easily be computed and reads (by applying the chain rule)

-$$ -\frac{\partial a_j^L}{\partial w_{ij}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{ij}^{L}}=a_j^L(1-a_j^L)a_i^{L-1}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs034.html b/doc/src/week42/._week42-bs034.html deleted file mode 100644 index 76f262307..000000000 --- a/doc/src/week42/._week42-bs034.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

The back propagation equations for a neural network

- -

We have thus

-$$ -\frac{\partial{\cal C}((\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)a_j^L(1-a_j^L)a_i^{L-1}, -$$ - -

Defining

-$$ -\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - y_j\right) = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -$$ - -

and using the Hadamard product of two vectors we can write this as

-$$ -\boldsymbol{\delta}^L = \sigma'(\boldsymbol{z}^L)\circ\frac{\partial {\cal C}}{\partial (\boldsymbol{a}^L)}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs035.html b/doc/src/week42/._week42-bs035.html deleted file mode 100644 index b2d367ad6..000000000 --- a/doc/src/week42/._week42-bs035.html +++ /dev/null @@ -1,522 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Analyzing the last results

- -

This is an important expression. The second term on the right handside -measures how fast the cost function is changing as a function of the $j$th -output activation. If, for example, the cost function doesn't depend -much on a particular output node \( j \), then \( \delta_j^L \) will be small, -which is what we would expect. The first term on the right, measures -how fast the activation function \( f \) is changing at a given activation -value \( z_j^L \). -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs036.html b/doc/src/week42/._week42-bs036.html deleted file mode 100644 index 6d921843a..000000000 --- a/doc/src/week42/._week42-bs036.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

More considerations

- -

Notice that everything in the above equations is easily computed. In -particular, we compute \( z_j^L \) while computing the behaviour of the -network, and it is only a small additional overhead to compute -\( \sigma'(z^L_j) \). The exact form of the derivative with respect to the -output depends on the form of the cost function. -However, provided the cost function is known there should be little -trouble in calculating -

- -$$ -\frac{\partial {\cal C}}{\partial (a_j^L)} -$$ - -

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

-$$ -\frac{\partial{\cal C}}{\partial w_{ij}^L} = \delta_j^La_i^{L-1}. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs037.html b/doc/src/week42/._week42-bs037.html deleted file mode 100644 index d1fe17793..000000000 --- a/doc/src/week42/._week42-bs037.html +++ /dev/null @@ -1,526 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Derivatives in terms of \( z_j^L \)

- -

It is also easy to see that our previous equation can be written as

- -$$ -\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}, -$$ - -

which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely

-$$ -\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}, -$$ - -

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.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs038.html b/doc/src/week42/._week42-bs038.html deleted file mode 100644 index 2e20d7b0d..000000000 --- a/doc/src/week42/._week42-bs038.html +++ /dev/null @@ -1,540 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Bringing it together

- -

We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are

- -$$ -\begin{equation} -\frac{\partial{\cal C}(\boldsymbol{W^L})}{\partial w_{ij}^L} = \delta_j^La_i^{L-1}, -\tag{1} -\end{equation} -$$ - -

and

-$$ -\begin{equation} -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\tag{2} -\end{equation} -$$ - -

and

- -$$ -\begin{equation} -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}, -\tag{3} -\end{equation} -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs039.html b/doc/src/week42/._week42-bs039.html deleted file mode 100644 index e4d3d3833..000000000 --- a/doc/src/week42/._week42-bs039.html +++ /dev/null @@ -1,520 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Final back propagating equation

- -

We have that (replacing \( L \) with a general layer \( l \))

-$$ -\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. -$$ - -

We want to express this in terms of the equations for layer \( l+1 \).

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs040.html b/doc/src/week42/._week42-bs040.html deleted file mode 100644 index 298d6005a..000000000 --- a/doc/src/week42/._week42-bs040.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Using the chain rule and summing over all \( k \) entries

- -

We obtain

-$$ -\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}}, -$$ - -

and recalling that

-$$ -z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, -$$ - -

with \( M_l \) being the number of nodes in layer \( l \), we obtain

-$$ -\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -$$ - -

This is our final equation.

- -

We are now ready to set up the algorithm for back propagation and learning the weights and biases.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs041.html b/doc/src/week42/._week42-bs041.html deleted file mode 100644 index 4c0d90908..000000000 --- a/doc/src/week42/._week42-bs041.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

- -
-
- -
    -
  1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)
  2. -
  3. Define the number of hidden layers and hidden nodes
  4. -
  5. Define activation functions for hidden layers and output layers
  6. -
  7. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates
  8. -
  9. Define cost function and possible regularization terms with hyperparameters
  10. -
  11. Initialize weights and biases
  12. -
  13. Fix number of iterations for the feed forward part and back propagation part
  14. -
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs042.html b/doc/src/week42/._week42-bs042.html deleted file mode 100644 index 51b2a3657..000000000 --- a/doc/src/week42/._week42-bs042.html +++ /dev/null @@ -1,528 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Setting up the back propagation algorithm, part 1

- -

The four equations provide us with a way of computing the gradients of the cost function. Let us write this out in the form of an algorithm.

- -

First, we set up the input data \( \boldsymbol{x} \) and the activations -\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and -the pertinent outputs \( \boldsymbol{a}^1 \). -

- -

Secondly, we perform then the feed forward till we reach the output -layer and compute all \( \boldsymbol{z}_l \) of the input layer and compute the -activation function and the pertinent outputs \( \boldsymbol{a}^l \) for -\( l=1,2,3,\dots,L \). -

- -

Notation: The first hidden layer has \( l=1 \) as label and the final output layer has \( l=L \).

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs043.html b/doc/src/week42/._week42-bs043.html deleted file mode 100644 index 416827e4a..000000000 --- a/doc/src/week42/._week42-bs043.html +++ /dev/null @@ -1,524 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Setting up the back propagation algorithm, part 2

- -

Thereafter we compute the ouput error \( \boldsymbol{\delta}^L \) by computing all

-$$ -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. -$$ - -

Then we compute the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

-$$ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs044.html b/doc/src/week42/._week42-bs044.html deleted file mode 100644 index 612fa717b..000000000 --- a/doc/src/week42/._week42-bs044.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Setting up the Back propagation algorithm, part 3

- -

Finally, we update the weights and the biases using gradient descent -for each \( l=L-1,L-2,\dots,1 \) (the first hidden layer) and update the weights and biases -according to the rules -

- -$$ -w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, -$$ - - -$$ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -$$ - -

with \( \eta \) being the learning rate.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs045.html b/doc/src/week42/._week42-bs045.html deleted file mode 100644 index 2a9abcd83..000000000 --- a/doc/src/week42/._week42-bs045.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Updating the gradients

- -

With the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

-$$ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -$$ - -

we update the weights and the biases using gradient descent for each \( l=L-1,L-2,\dots,1 \) and update the weights and biases according to the rules

-$$ -w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, -$$ - - -$$ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs046.html b/doc/src/week42/._week42-bs046.html deleted file mode 100644 index 1d172d997..000000000 --- a/doc/src/week42/._week42-bs046.html +++ /dev/null @@ -1,525 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Activation functions

- -

A property that characterizes a neural network, other than its -connectivity, is the choice of activation function(s). The following -restrictions are imposed on an activation function for an FFNN to -fulfill the universal approximation theorem -

- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs047.html b/doc/src/week42/._week42-bs047.html deleted file mode 100644 index bb022d2bb..000000000 --- a/doc/src/week42/._week42-bs047.html +++ /dev/null @@ -1,534 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Activation functions, Logistic and Hyperbolic ones

- -

The second requirement excludes all linear functions. Furthermore, in -a MLP with only linear activation functions, each layer simply -performs a linear transformation of its inputs. -

- -

Regardless of the number of layers, the output of the NN will be -nothing but a linear function of the inputs. Thus we need to introduce -some kind of non-linearity to the NN to be able to fit non-linear -functions Typical examples are the logistic Sigmoid -

- -$$ - \sigma(x) = \frac{1}{1 + e^{-x}}, -$$ - -

and the hyperbolic tangent function

-$$ - \sigma(x) = \tanh(x) -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs048.html b/doc/src/week42/._week42-bs048.html deleted file mode 100644 index 1e420e2c0..000000000 --- a/doc/src/week42/._week42-bs048.html +++ /dev/null @@ -1,614 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Relevance

- -

The sigmoid function are more biologically plausible because the -output of inactive neurons are zero. Such activation function are -called one-sided. However, it has been shown that the hyperbolic -tangent performs better than the sigmoid for training MLPs. has -become the most popular for deep neural networks -

- - - -
-
-
-
-
-
"""The sigmoid function (or the logistic curve) is a 
-function that takes any real number, z, and outputs a number (0,1).
-It is useful in neural networks for assigning weights on a relative scale.
-The value z is the weighted sum of parameters involved in the learning algorithm."""
-
-import numpy
-import matplotlib.pyplot as plt
-import math as mt
-
-z = numpy.arange(-5, 5, .1)
-sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
-sigma = sigma_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, sigma)
-ax.set_ylim([-0.1, 1.1])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sigmoid function')
-
-plt.show()
-
-"""Step Function"""
-z = numpy.arange(-5, 5, .02)
-step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
-step = step_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, step)
-ax.set_ylim([-0.5, 1.5])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('step function')
-
-plt.show()
-
-"""Sine Function"""
-z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
-t = numpy.sin(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, t)
-ax.set_ylim([-1.0, 1.0])
-ax.set_xlim([-2*mt.pi,2*mt.pi])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sine function')
-
-plt.show()
-
-"""Plots a graph of the squashing function used by a rectified linear
-unit"""
-z = numpy.arange(-2, 2, .1)
-zero = numpy.zeros(len(z))
-y = numpy.max([zero, z], axis=0)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, y)
-ax.set_ylim([-2.0, 2.0])
-ax.set_xlim([-2.0, 2.0])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('Rectified linear unit')
-
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs049.html b/doc/src/week42/._week42-bs049.html deleted file mode 100644 index d7d92c221..000000000 --- a/doc/src/week42/._week42-bs049.html +++ /dev/null @@ -1,527 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Vanishing gradients

- -

The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. -

- -

Unfortunately for us, the gradients often get smaller and smaller as -the algorithm progresses down to the first hidden layers. As a result, -the GD update leaves the lower layer connection weights virtually -unchanged, and training never converges to a good solution. This is -known in the literature as the vanishing gradients problem. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs050.html b/doc/src/week42/._week42-bs050.html deleted file mode 100644 index 770a888d2..000000000 --- a/doc/src/week42/._week42-bs050.html +++ /dev/null @@ -1,522 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Exploding gradients

- -

In other cases, the opposite can happen, namely the the gradients can -grow bigger and bigger. The result is that many of the layers get -large updates of the weights the algorithm diverges. This is the -exploding gradients problem, which is mostly encountered in -recurrent neural networks. More generally, deep neural networks suffer -from unstable gradients, different layers may learn at widely -different speeds -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs051.html b/doc/src/week42/._week42-bs051.html deleted file mode 100644 index 0ea94a198..000000000 --- a/doc/src/week42/._week42-bs051.html +++ /dev/null @@ -1,528 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Is the Logistic activation function (Sigmoid) our choice?

- -

Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. -

- -

A paper titled Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs052.html b/doc/src/week42/._week42-bs052.html deleted file mode 100644 index 3a76e948a..000000000 --- a/doc/src/week42/._week42-bs052.html +++ /dev/null @@ -1,523 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Logistic function as the root of problems

- -

They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs053.html b/doc/src/week42/._week42-bs053.html deleted file mode 100644 index 6baeafbb9..000000000 --- a/doc/src/week42/._week42-bs053.html +++ /dev/null @@ -1,533 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

The derivative of the Logistic funtion

- -

Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. -

- -

In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs054.html b/doc/src/week42/._week42-bs054.html deleted file mode 100644 index fbad8c238..000000000 --- a/doc/src/week42/._week42-bs054.html +++ /dev/null @@ -1,524 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Insights from the paper by Glorot and Bengio

- -

One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs055.html b/doc/src/week42/._week42-bs055.html deleted file mode 100644 index ab7dd5029..000000000 --- a/doc/src/week42/._week42-bs055.html +++ /dev/null @@ -1,526 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

The RELU function family

- -

The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. -

- -

In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs056.html b/doc/src/week42/._week42-bs056.html deleted file mode 100644 index 0c01e85e0..000000000 --- a/doc/src/week42/._week42-bs056.html +++ /dev/null @@ -1,523 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

ELU function

- -

To solve this problem, nowadays practitioners use a variant of the -ReLU function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function -

- -$$ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -$$ - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs057.html b/doc/src/week42/._week42-bs057.html deleted file mode 100644 index e3de53cde..000000000 --- a/doc/src/week42/._week42-bs057.html +++ /dev/null @@ -1,527 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Which activation function should we use?

- -

In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than \( \tanh \) which in turn performs better -than the logistic function. -

- -

If runtime performance is an issue, then you may opt for the leaky -ReLU function over the ELU function If you don’t want to tweak yet -another hyperparameter, you may just use the default \( \alpha \) of -\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and -computing power, you can use cross-validation or bootstrap to evaluate -other activation functions. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs058.html b/doc/src/week42/._week42-bs058.html deleted file mode 100644 index 17ef0bdb2..000000000 --- a/doc/src/week42/._week42-bs058.html +++ /dev/null @@ -1,527 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

More on activation functions, output layers

- -

In most cases you can use the ReLU activation function in the hidden -layers (or one of its variants). -

- -

It is a bit faster to compute than other activation functions, and the -gradient descent optimization does in general not get stuck. -

- -For the output layer: - - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs059.html b/doc/src/week42/._week42-bs059.html deleted file mode 100644 index 1be16c029..000000000 --- a/doc/src/week42/._week42-bs059.html +++ /dev/null @@ -1,535 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Fine-tuning neural network hyperparameters

- -

The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are -interconnected), but even in a simple FFNN you can change the number -of layers, the number of neurons per layer, the type of activation -function to use in each layer, the weight initialization logic, the -stochastic gradient optmized and much more. How do you know what -combination of hyperparameters is the best for your task? -

- - -

However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. -

- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs060.html b/doc/src/week42/._week42-bs060.html deleted file mode 100644 index 4fce7ed10..000000000 --- a/doc/src/week42/._week42-bs060.html +++ /dev/null @@ -1,531 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Hidden layers

- -

For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set discussed below you can easily get a -high accuracy using just one hidden layer with a few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden -layers with the same total amount of neurons, in roughly the same -amount of training time. -

- -

For more complex problems, you can gradually ramp up the number of -hidden layers, until you start overfitting the training set. Very -complex tasks, such as large image classification or speech -recognition, typically require networks with dozens of layers and they -need a huge amount of training data. However, you will rarely have to -train such networks from scratch: it is much more common to reuse -parts of a pretrained state-of-the-art network that performs a similar -task. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs061.html b/doc/src/week42/._week42-bs061.html deleted file mode 100644 index 17c93e9fa..000000000 --- a/doc/src/week42/._week42-bs061.html +++ /dev/null @@ -1,531 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Batch Normalization

- -

Batch Normalization aims to address the vanishing/exploding gradients -problems, and more generally the problem that the distribution of each -layer’s inputs changes during training, as the parameters of the -previous layers change. -

- -

The technique consists of adding an operation in the model just before -the activation function of each layer, simply zero-centering and -normalizing the inputs, then scaling and shifting the result using two -new parameters per layer (one for scaling, the other for shifting). In -other words, this operation lets the model learn the optimal scale and -mean of the inputs for each layer. In order to zero-center and -normalize the inputs, the algorithm needs to estimate the inputs’ mean -and standard deviation. It does so by evaluating the mean and standard -deviation of the inputs over the current mini-batch, from this the -name batch normalization. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs062.html b/doc/src/week42/._week42-bs062.html deleted file mode 100644 index de92bf6e6..000000000 --- a/doc/src/week42/._week42-bs062.html +++ /dev/null @@ -1,525 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Dropout

- -

It is a fairly simple algorithm: at every training step, every neuron -(including the input neurons but excluding the output neurons) has a -probability \( p \) of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active -during the next step. -

- -

The hyperparameter \( p \) is called the dropout rate, and it is typically -set to 50%. After training, the neurons are not dropped anymore. It -is viewed as one of the most popular regularization techniques. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs063.html b/doc/src/week42/._week42-bs063.html deleted file mode 100644 index cb91698d3..000000000 --- a/doc/src/week42/._week42-bs063.html +++ /dev/null @@ -1,525 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Gradient Clipping

- -

A popular technique to lessen the exploding gradients problem is to -simply clip the gradients during backpropagation so that they never -exceed some threshold (this is mostly useful for recurrent neural -networks). -

- -

This technique is called Gradient Clipping.

- -

In general however, Batch -Normalization is preferred. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs064.html b/doc/src/week42/._week42-bs064.html deleted file mode 100644 index 7feaa88b6..000000000 --- a/doc/src/week42/._week42-bs064.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

A top-down perspective on Neural networks

- -

The first thing we would like to do is divide the data into two or -three parts. A training set, a validation or dev (development) set, -and a test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: -

- -
    -
  1. Estimate optimal error rate
  2. -
  3. Minimize underfitting (bias) on training data set.
  4. -
  5. Make sure you are not overfitting.
  6. -
-

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs065.html b/doc/src/week42/._week42-bs065.html deleted file mode 100644 index 10f0a6c04..000000000 --- a/doc/src/week42/._week42-bs065.html +++ /dev/null @@ -1,534 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

More top-down perspectives

- -

If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. -

- -

However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs066.html b/doc/src/week42/._week42-bs066.html deleted file mode 100644 index e09ea1f05..000000000 --- a/doc/src/week42/._week42-bs066.html +++ /dev/null @@ -1,522 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Limitations of supervised learning with deep networks

- -

Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs067.html b/doc/src/week42/._week42-bs067.html deleted file mode 100644 index cb9fcad0c..000000000 --- a/doc/src/week42/._week42-bs067.html +++ /dev/null @@ -1,519 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Limitations of NNs

- -

Here we list some of the important limitations of supervised neural network based models.

- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs068.html b/doc/src/week42/._week42-bs068.html deleted file mode 100644 index 14d7860b7..000000000 --- a/doc/src/week42/._week42-bs068.html +++ /dev/null @@ -1,516 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Homogeneous data

- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs069.html b/doc/src/week42/._week42-bs069.html deleted file mode 100644 index 5f26296c1..000000000 --- a/doc/src/week42/._week42-bs069.html +++ /dev/null @@ -1,518 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

More limitations

- - -

Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs070.html b/doc/src/week42/._week42-bs070.html deleted file mode 100644 index 20d771166..000000000 --- a/doc/src/week42/._week42-bs070.html +++ /dev/null @@ -1,547 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Setting up a Multi-layer perceptron model for classification

- -

We are now gong to develop an example based on the MNIST data -base. This is a classification problem and we need to use our -cross-entropy function we discussed in connection with logistic -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. -

- -

In binary classification with two classes \( (0, 1) \) we define the -logistic/sigmoid function as the probability that a particular input -is in class \( 0 \) or \( 1 \). This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. -

- -

For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) -is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) -represents our activation values \( z \). We have -

-$$ -P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , -$$ - -

and

-$$ -P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , -$$ - -

where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases -of our network. -

- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs071.html b/doc/src/week42/._week42-bs071.html deleted file mode 100644 index 2ebf82823..000000000 --- a/doc/src/week42/._week42-bs071.html +++ /dev/null @@ -1,562 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Defining the cost function

- -

Our cost function is given as (see the Logistic regression lectures)

-$$ -\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . -$$ - -

This last equality means that we can interpret our cost function as a sum over the loss function -for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. -

- -

In multiclass classification it is common to treat each integer label as a so called one-hot vector:

- -

\( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

- -\( y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) , \) - -

i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset (numbers from \( 0 \) to \( 9 \))..

- -

If \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th -output vector \( \boldsymbol{y}_i \). -The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: -

- -$$ -P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , -$$ - -

which reduces to the logistic function in the binary case. -The likelihood of this \( C \)-class classifier -is now given as: -

- -$$ -P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -$$ - -

Again we take the negative log-likelihood to define our cost function:

- -$$ -\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. -$$ - -

See the logistic regression lectures for a full definition of the cost function.

- -

The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs072.html b/doc/src/week42/._week42-bs072.html deleted file mode 100644 index 98b9dbe95..000000000 --- a/doc/src/week42/._week42-bs072.html +++ /dev/null @@ -1,556 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Example: binary classification problem

- -

As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as

-$$ -\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), -$$ - -

where we had defined the logistic (sigmoid) function

-$$ -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)}}, -$$ - -

and

-$$ -p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). -$$ - -

The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

- -

Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). -We have then -

-$$ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -$$ - -

with

-$$ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -$$ - -

where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). -Our cost function at the final layer \( l=L \) is now -

-$$ -\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), -$$ - -

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

-$$ -\frac{\partial \mathcal{C}(\boldsymbol{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. -$$ - -

In case we use another activation function than the logistic one, we need to evaluate other derivatives.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs073.html b/doc/src/week42/._week42-bs073.html deleted file mode 100644 index 3880972fc..000000000 --- a/doc/src/week42/._week42-bs073.html +++ /dev/null @@ -1,530 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

The Softmax function

-

In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need

-$$ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -$$ - -

For the Softmax function we have

-$$ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -$$ - -

Its derivative with respect to \( z_j^l \) gives

-$$ -\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), -$$ - -

which in case of the simply binary model reduces to having \( i=j \).

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs074.html b/doc/src/week42/._week42-bs074.html deleted file mode 100644 index 34a6db3e4..000000000 --- a/doc/src/week42/._week42-bs074.html +++ /dev/null @@ -1,523 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Developing a code for doing neural networks with back propagation

- -

One can identify a set of key steps when using neural networks to solve supervised learning problems:

- -
    -
  1. Collect and pre-process data
  2. -
  3. Define model and architecture
  4. -
  5. Choose cost function and optimizer
  6. -
  7. Train the model
  8. -
  9. Evaluate model performance on test data
  10. -
  11. Adjust hyperparameters (if necessary, network architecture)
  12. -
-

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs075.html b/doc/src/week42/._week42-bs075.html deleted file mode 100644 index 18529eb6e..000000000 --- a/doc/src/week42/._week42-bs075.html +++ /dev/null @@ -1,622 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Collect and pre-process data

- -

Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

- -

To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

- -

As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

- -

$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

- -

and the targets would be:

- -

$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

- -

Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

- - - -
-
-
-
-
-
# import necessary packages
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn import datasets
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-
-# display images in notebook
-%matplotlib inline
-plt.rcParams['figure.figsize'] = (12,12)
-
-
-# download MNIST dataset
-digits = datasets.load_digits()
-
-# define inputs and labels
-inputs = digits.images
-labels = digits.target
-
-print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
-print("labels = (n_inputs) = " + str(labels.shape))
-
-
-# flatten the image
-# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
-n_inputs = len(inputs)
-inputs = inputs.reshape(n_inputs, -1)
-print("X = (n_inputs, n_features) = " + str(inputs.shape))
-
-
-# choose some random images to display
-indices = np.arange(n_inputs)
-random_indices = np.random.choice(indices, size=5)
-
-for i, image in enumerate(digits.images[random_indices]):
-    plt.subplot(1, 5, i+1)
-    plt.axis('off')
-    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
-    plt.title("Label: %d" % digits.target[random_indices[i]])
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs076.html b/doc/src/week42/._week42-bs076.html deleted file mode 100644 index a3d1ab913..000000000 --- a/doc/src/week42/._week42-bs076.html +++ /dev/null @@ -1,574 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Train and test datasets

- -

Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

- -

We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

- -

It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

- - - -
-
-
-
-
-
from sklearn.model_selection import train_test_split
-
-# one-liner from scikit-learn library
-train_size = 0.8
-test_size = 1 - train_size
-X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
-                                                    test_size=test_size)
-
-# equivalently in numpy
-def train_test_split_numpy(inputs, labels, train_size, test_size):
-    n_inputs = len(inputs)
-    inputs_shuffled = inputs.copy()
-    labels_shuffled = labels.copy()
-    
-    np.random.shuffle(inputs_shuffled)
-    np.random.shuffle(labels_shuffled)
-    
-    train_end = int(n_inputs*train_size)
-    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
-    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
-    
-    return X_train, X_test, Y_train, Y_test
-
-#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
-
-print("Number of training images: " + str(len(X_train)))
-print("Number of test images: " + str(len(X_test)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs077.html b/doc/src/week42/._week42-bs077.html deleted file mode 100644 index 75bc28881..000000000 --- a/doc/src/week42/._week42-bs077.html +++ /dev/null @@ -1,552 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Define model and architecture

- -

Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

- -

$$ z = \sum_{i=1}^n w_i a_i ,$$

- -

$$ y = f(z) ,$$

- -

where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

- -

The simplest activation function for a neuron is the Heaviside function:

- -

$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

- -

A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

- -

However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

- -

Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

- -

$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$

- -

which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs078.html b/doc/src/week42/._week42-bs078.html deleted file mode 100644 index c5878d261..000000000 --- a/doc/src/week42/._week42-bs078.html +++ /dev/null @@ -1,551 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Layers

- - -

Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

- - -

We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

- - -

If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

- -

For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

- -

Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

- -

$$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

- -

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. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

- -

$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

- -

Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs079.html b/doc/src/week42/._week42-bs079.html deleted file mode 100644 index 1c687c83f..000000000 --- a/doc/src/week42/._week42-bs079.html +++ /dev/null @@ -1,562 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Weights and biases

- -

Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. -

- -

Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

- -

$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

- -

The bias weights \( \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.

- - -
-
-
-
-
-
# building our neural network
-
-n_inputs, n_features = X_train.shape
-n_hidden_neurons = 50
-n_categories = 10
-
-# we make the weights normally distributed using numpy.random.randn
-
-# weights and bias in the hidden layer
-hidden_weights = np.random.randn(n_features, n_hidden_neurons)
-hidden_bias = np.zeros(n_hidden_neurons) + 0.01
-
-# weights and bias in the output layer
-output_weights = np.random.randn(n_hidden_neurons, n_categories)
-output_bias = np.zeros(n_categories) + 0.01
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs080.html b/doc/src/week42/._week42-bs080.html deleted file mode 100644 index db9ca2bc3..000000000 --- a/doc/src/week42/._week42-bs080.html +++ /dev/null @@ -1,533 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Feed-forward pass

- -

Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

- -

$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

- -

this is then passed through our activation function

- -

$$ a_{j}^{l} = f(z_{j}^{l}) .$$

- -

We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

- -

$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

- -

Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

- -

$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs081.html b/doc/src/week42/._week42-bs081.html deleted file mode 100644 index 08053cadb..000000000 --- a/doc/src/week42/._week42-bs081.html +++ /dev/null @@ -1,600 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Matrix multiplications

- -

Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden -layer have the dimensions -\( W_{hidden} = (n_{features}, n_{hidden}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

- -

$$ X W^{h} = (n_{inputs}, n_{hidden}),$$

- -

and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

- -

$$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

- -

meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

- -

$$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

- -

This is fed to the output layer:

- -

$$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

- -

Finally we receive our output values for each image and each category by passing it through the softmax function:

- -

$$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

- - - -
-
-
-
-
-
# setup the feed-forward pass, subscript h = hidden layer
-
-def sigmoid(x):
-    return 1/(1 + np.exp(-x))
-
-def feed_forward(X):
-    # weighted sum of inputs to the hidden layer
-    z_h = np.matmul(X, hidden_weights) + hidden_bias
-    # activation in the hidden layer
-    a_h = sigmoid(z_h)
-    
-    # weighted sum of inputs to the output layer
-    z_o = np.matmul(a_h, output_weights) + output_bias
-    # softmax output
-    # axis 0 holds each input and axis 1 the probabilities of each category
-    exp_term = np.exp(z_o)
-    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-    
-    return probabilities
-
-probabilities = feed_forward(X_train)
-print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
-print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
-print("probabilities sum up to: " + str(probabilities[0].sum()))
-print()
-
-# we obtain a prediction by taking the class with the highest likelihood
-def predict(X):
-    probabilities = feed_forward(X)
-    return np.argmax(probabilities, axis=1)
-
-predictions = predict(X_train)
-print("predictions = (n_inputs) = " + str(predictions.shape))
-print("prediction for image 0: " + str(predictions[0]))
-print("correct label for image 0: " + str(Y_train[0]))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs082.html b/doc/src/week42/._week42-bs082.html deleted file mode 100644 index 89a8662a0..000000000 --- a/doc/src/week42/._week42-bs082.html +++ /dev/null @@ -1,538 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Choose cost function and optimizer

- -

To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

- -

In multiclass classification it is common to treat each integer label as a so called one-hot vector:

- -

$$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

- -

$$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$

- -

i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

- -

Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

- -

In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category \( c' \) -(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. -

- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs083.html b/doc/src/week42/._week42-bs083.html deleted file mode 100644 index cfc98dd0c..000000000 --- a/doc/src/week42/._week42-bs083.html +++ /dev/null @@ -1,545 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Optimizing the cost function

- -

The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

- -

$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

- -

where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

- -

A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

- -

$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

- -

i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

- -

This has two important benefits:

-
    -
  1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
  2. -
  3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
  4. -
-

The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs084.html b/doc/src/week42/._week42-bs084.html deleted file mode 100644 index 2ad20cb2b..000000000 --- a/doc/src/week42/._week42-bs084.html +++ /dev/null @@ -1,540 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Regularization

- -

It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

- -

We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

- -

$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

- -

i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

- -

In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has \( (64 + 1)\times 50=3250 \) weights in -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -layer (\( +1 \) for the bias), and the gradient must be calculated for -every parameter. We use the backpropagation algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs085.html b/doc/src/week42/._week42-bs085.html deleted file mode 100644 index 9a64ac8d6..000000000 --- a/doc/src/week42/._week42-bs085.html +++ /dev/null @@ -1,637 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Matrix multiplication

- -

To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

- -

$$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

- -

The gradient for the output weights is calculated as

- -

$$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

- -

where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

- -

The gradient with respect to the output bias is then

- -

$$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

- -

The error in the hidden layer is

- -

$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

- -

where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

- -

This again gives us the gradients in the hidden layer:

- -

$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

- -

$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

- - - -
-
-
-
-
-
# to categorical turns our integer vector into a onehot representation
-from sklearn.metrics import accuracy_score
-
-# one-hot in numpy
-def to_categorical_numpy(integer_vector):
-    n_inputs = len(integer_vector)
-    n_categories = np.max(integer_vector) + 1
-    onehot_vector = np.zeros((n_inputs, n_categories))
-    onehot_vector[range(n_inputs), integer_vector] = 1
-    
-    return onehot_vector
-
-#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
-Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
-
-def feed_forward_train(X):
-    # weighted sum of inputs to the hidden layer
-    z_h = np.matmul(X, hidden_weights) + hidden_bias
-    # activation in the hidden layer
-    a_h = sigmoid(z_h)
-    
-    # weighted sum of inputs to the output layer
-    z_o = np.matmul(a_h, output_weights) + output_bias
-    # softmax output
-    # axis 0 holds each input and axis 1 the probabilities of each category
-    exp_term = np.exp(z_o)
-    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-    
-    # for backpropagation need activations in hidden and output layers
-    return a_h, probabilities
-
-def backpropagation(X, Y):
-    a_h, probabilities = feed_forward_train(X)
-    
-    # error in the output layer
-    error_output = probabilities - Y
-    # error in the hidden layer
-    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
-    
-    # gradients for the output layer
-    output_weights_gradient = np.matmul(a_h.T, error_output)
-    output_bias_gradient = np.sum(error_output, axis=0)
-    
-    # gradient for the hidden layer
-    hidden_weights_gradient = np.matmul(X.T, error_hidden)
-    hidden_bias_gradient = np.sum(error_hidden, axis=0)
-
-    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
-
-print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
-
-eta = 0.01
-lmbd = 0.01
-for i in range(1000):
-    # calculate gradients
-    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
-    
-    # regularization term gradients
-    dWo += lmbd * output_weights
-    dWh += lmbd * hidden_weights
-    
-    # update weights and biases
-    output_weights -= eta * dWo
-    output_bias -= eta * dBo
-    hidden_weights -= eta * dWh
-    hidden_bias -= eta * dBh
-
-print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs086.html b/doc/src/week42/._week42-bs086.html deleted file mode 100644 index fbaa6169c..000000000 --- a/doc/src/week42/._week42-bs086.html +++ /dev/null @@ -1,527 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Improving performance

- -

As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. -

- -

The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

- -

Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

- -

If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs087.html b/doc/src/week42/._week42-bs087.html deleted file mode 100644 index 52d5da8b3..000000000 --- a/doc/src/week42/._week42-bs087.html +++ /dev/null @@ -1,639 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Full object-oriented implementation

- -

It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. -

- - - -
-
-
-
-
-
class NeuralNetwork:
-    def __init__(
-            self,
-            X_data,
-            Y_data,
-            n_hidden_neurons=50,
-            n_categories=10,
-            epochs=10,
-            batch_size=100,
-            eta=0.1,
-            lmbd=0.0):
-
-        self.X_data_full = X_data
-        self.Y_data_full = Y_data
-
-        self.n_inputs = X_data.shape[0]
-        self.n_features = X_data.shape[1]
-        self.n_hidden_neurons = n_hidden_neurons
-        self.n_categories = n_categories
-
-        self.epochs = epochs
-        self.batch_size = batch_size
-        self.iterations = self.n_inputs // self.batch_size
-        self.eta = eta
-        self.lmbd = lmbd
-
-        self.create_biases_and_weights()
-
-    def create_biases_and_weights(self):
-        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
-        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
-
-        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
-        self.output_bias = np.zeros(self.n_categories) + 0.01
-
-    def feed_forward(self):
-        # feed-forward for training
-        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
-        self.a_h = sigmoid(self.z_h)
-
-        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
-
-        exp_term = np.exp(self.z_o)
-        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-
-    def feed_forward_out(self, X):
-        # feed-forward for output
-        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
-        a_h = sigmoid(z_h)
-
-        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
-        
-        exp_term = np.exp(z_o)
-        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-        return probabilities
-
-    def backpropagation(self):
-        error_output = self.probabilities - self.Y_data
-        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
-
-        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
-        self.output_bias_gradient = np.sum(error_output, axis=0)
-
-        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
-        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
-
-        if self.lmbd > 0.0:
-            self.output_weights_gradient += self.lmbd * self.output_weights
-            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
-
-        self.output_weights -= self.eta * self.output_weights_gradient
-        self.output_bias -= self.eta * self.output_bias_gradient
-        self.hidden_weights -= self.eta * self.hidden_weights_gradient
-        self.hidden_bias -= self.eta * self.hidden_bias_gradient
-
-    def predict(self, X):
-        probabilities = self.feed_forward_out(X)
-        return np.argmax(probabilities, axis=1)
-
-    def predict_probabilities(self, X):
-        probabilities = self.feed_forward_out(X)
-        return probabilities
-
-    def train(self):
-        data_indices = np.arange(self.n_inputs)
-
-        for i in range(self.epochs):
-            for j in range(self.iterations):
-                # pick datapoints with replacement
-                chosen_datapoints = np.random.choice(
-                    data_indices, size=self.batch_size, replace=False
-                )
-
-                # minibatch training data
-                self.X_data = self.X_data_full[chosen_datapoints]
-                self.Y_data = self.Y_data_full[chosen_datapoints]
-
-                self.feed_forward()
-                self.backpropagation()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs088.html b/doc/src/week42/._week42-bs088.html deleted file mode 100644 index ccd1d5147..000000000 --- a/doc/src/week42/._week42-bs088.html +++ /dev/null @@ -1,561 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Evaluate model performance on test data

- -

To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the accuracy score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). -

- -

$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

- -

where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

- - - -
-
-
-
-
-
epochs = 100
-batch_size = 100
-
-dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
-                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
-dnn.train()
-test_predict = dnn.predict(X_test)
-
-# accuracy score from scikit library
-print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
-
-# equivalent in numpy
-def accuracy_score_numpy(Y_test, Y_pred):
-    return np.sum(Y_test == Y_pred) / len(Y_test)
-
-#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs089.html b/doc/src/week42/._week42-bs089.html deleted file mode 100644 index 59d1e1b0a..000000000 --- a/doc/src/week42/._week42-bs089.html +++ /dev/null @@ -1,560 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Adjust hyperparameters

- -

We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

- - - -
-
-
-
-
-
eta_vals = np.logspace(-5, 1, 7)
-lmbd_vals = np.logspace(-5, 1, 7)
-# store the models for later use
-DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-
-# grid search
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
-                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
-        dnn.train()
-        
-        DNN_numpy[i][j] = dnn
-        
-        test_predict = dnn.predict(X_test)
-        
-        print("Learning rate  = ", eta)
-        print("Lambda = ", lmbd)
-        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs090.html b/doc/src/week42/._week42-bs090.html deleted file mode 100644 index 59d6fd6a6..000000000 --- a/doc/src/week42/._week42-bs090.html +++ /dev/null @@ -1,567 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Visualization

- - - -
-
-
-
-
-
# visual representation of grid search
-# uses seaborn heatmap, you can also do this with matplotlib imshow
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        dnn = DNN_numpy[i][j]
-        
-        train_pred = dnn.predict(X_train) 
-        test_pred = dnn.predict(X_test)
-
-        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
-        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs091.html b/doc/src/week42/._week42-bs091.html deleted file mode 100644 index c6bf28f95..000000000 --- a/doc/src/week42/._week42-bs091.html +++ /dev/null @@ -1,563 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

scikit-learn implementation

- -

scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

- -

scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

- - - -
-
-
-
-
-
from sklearn.neural_network import MLPClassifier
-# store models for later use
-DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
-                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
-        dnn.fit(X_train, Y_train)
-        
-        DNN_scikit[i][j] = dnn
-        
-        print("Learning rate  = ", eta)
-        print("Lambda = ", lmbd)
-        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs092.html b/doc/src/week42/._week42-bs092.html deleted file mode 100644 index ab7606ab2..000000000 --- a/doc/src/week42/._week42-bs092.html +++ /dev/null @@ -1,565 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Visualization

- - -
-
-
-
-
-
# optional
-# visual representation of grid search
-# uses seaborn heatmap, could probably do this in matplotlib
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        dnn = DNN_scikit[i][j]
-        
-        train_pred = dnn.predict(X_train) 
-        test_pred = dnn.predict(X_test)
-
-        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
-        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs093.html b/doc/src/week42/._week42-bs093.html deleted file mode 100644 index 0dfa5ef4a..000000000 --- a/doc/src/week42/._week42-bs093.html +++ /dev/null @@ -1,518 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Building neural networks in Tensorflow and Keras

- -

Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. -

- -

In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. -

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs094.html b/doc/src/week42/._week42-bs094.html deleted file mode 100644 index 264b2ce18..000000000 --- a/doc/src/week42/._week42-bs094.html +++ /dev/null @@ -1,610 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Tensorflow

- -

Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. -

- -

Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. -

- -

Tensorflow uses so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow graph -to represent your model, and then create a Tensorflow session to run the graph. -

- -

In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. -

- -

To install tensorflow on Unix/Linux systems, use pip as

- - -
-
-
-
-
-
pip3 install tensorflow
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

and/or if you use anaconda, just write (or install from the graphical user interface) -(current release of CPU-only TensorFlow) -

- - -
-
-
-
-
-
conda create -n tf tensorflow
-conda activate tf
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

To install the current release of GPU TensorFlow

- - -
-
-
-
-
-
conda create -n tf-gpu tensorflow-gpu
-conda activate tf-gpu
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs095.html b/doc/src/week42/._week42-bs095.html deleted file mode 100644 index 5626899cf..000000000 --- a/doc/src/week42/._week42-bs095.html +++ /dev/null @@ -1,537 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Using Keras

- -

Keras is a high level neural network -that supports Tensorflow, CTNK and Theano as backends. -If you have Anaconda installed you may run the following command -

- - -
-
-
-
-
-
conda install keras
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

You can look up the instructions here for more information.

- -

We will to a large extent use keras in this course.

- -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs096.html b/doc/src/week42/._week42-bs096.html deleted file mode 100644 index 49f717d66..000000000 --- a/doc/src/week42/._week42-bs096.html +++ /dev/null @@ -1,729 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - -
-

 

 

 

- - -

Collect and pre-process data

- -

Let us look again at the MINST data set.

- - - -
-
-
-
-
-
# import necessary packages
-import numpy as np
-import matplotlib.pyplot as plt
-import tensorflow as tf
-from sklearn import datasets
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-
-# display images in notebook
-%matplotlib inline
-plt.rcParams['figure.figsize'] = (12,12)
-
-
-# download MNIST dataset
-digits = datasets.load_digits()
-
-# define inputs and labels
-inputs = digits.images
-labels = digits.target
-
-print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
-print("labels = (n_inputs) = " + str(labels.shape))
-
-
-# flatten the image
-# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
-n_inputs = len(inputs)
-inputs = inputs.reshape(n_inputs, -1)
-print("X = (n_inputs, n_features) = " + str(inputs.shape))
-
-
-# choose some random images to display
-indices = np.arange(n_inputs)
-random_indices = np.random.choice(indices, size=5)
-
-for i, image in enumerate(digits.images[random_indices]):
-    plt.subplot(1, 5, i+1)
-    plt.axis('off')
-    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
-    plt.title("Label: %d" % digits.target[random_indices[i]])
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
-from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
-from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
-from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
-from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
-
-from sklearn.model_selection import train_test_split
-
-# one-hot representation of labels
-labels = to_categorical(labels)
-
-# split into train and test data
-train_size = 0.8
-test_size = 1 - train_size
-X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
-                                                    test_size=test_size)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
epochs = 100
-batch_size = 100
-n_neurons_layer1 = 100
-n_neurons_layer2 = 50
-n_categories = 10
-eta_vals = np.logspace(-5, 1, 7)
-lmbd_vals = np.logspace(-5, 1, 7)
-def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
-    model = Sequential()
-    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
-    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
-    model.add(Dense(n_categories, activation='softmax'))
-    
-    sgd = optimizers.SGD(lr=eta)
-    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
-    
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-        
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
-                                         eta=eta, lmbd=lmbd)
-        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
-        scores = DNN.evaluate(X_test, Y_test)
-        
-        DNN_keras[i][j] = DNN
-        
-        print("Learning rate = ", eta)
-        print("Lambda = ", lmbd)
-        print("Test accuracy: %.3f" % scores[1])
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
# optional
-# visual representation of grid search
-# uses seaborn heatmap, could probably do this in matplotlib
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        DNN = DNN_keras[i][j]
-
-        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
-        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs097.html b/doc/src/week42/._week42-bs097.html deleted file mode 100644 index 13332c61b..000000000 --- a/doc/src/week42/._week42-bs097.html +++ /dev/null @@ -1,692 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - -
-
-

 

 

 

- - -

The Breast Cancer Data, now with Keras

- - - -
-
-
-
-
-
import tensorflow as tf
-from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
-from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
-from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
-from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
-from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
-import numpy as np
-import matplotlib.pyplot as plt
-import seaborn as sns
-from sklearn.model_selection import train_test_split as splitter
-from sklearn.datasets import load_breast_cancer
-import pickle
-import os 
-
-
-"""Load breast cancer dataset"""
-
-np.random.seed(0)        #create same seed for random number every time
-
-cancer=load_breast_cancer()      #Download breast cancer dataset
-
-inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
-outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
-labels=cancer.feature_names[0:30]
-
-print('The content of the breast cancer dataset is:')      #Print information about the datasets
-print(labels)
-print('-------------------------')
-print("inputs =  " + str(inputs.shape))
-print("outputs =  " + str(outputs.shape))
-print("labels =  "+ str(labels.shape))
-
-x=inputs      #Reassign the Feature and Label matrices to other variables
-y=outputs
-
-#%% 
-
-# Visualisation of dataset (for correlation analysis)
-
-plt.figure()
-plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean radius',fontweight='bold')
-plt.ylabel('Mean perimeter',fontweight='bold')
-plt.show()
-
-plt.figure()
-plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
-plt.xlabel('Mean compactness',fontweight='bold')
-plt.ylabel('Mean concavity',fontweight='bold')
-plt.show()
-
-
-plt.figure()
-plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean radius',fontweight='bold')
-plt.ylabel('Mean texture',fontweight='bold')
-plt.show()
-
-plt.figure()
-plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean perimeter',fontweight='bold')
-plt.ylabel('Mean compactness',fontweight='bold')
-plt.show()
-
-
-# Generate training and testing datasets
-
-#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
-#and add to input matrix
-
-temp1=np.reshape(x[:,1],(len(x[:,1]),1))
-temp2=np.reshape(x[:,2],(len(x[:,2]),1))
-X=np.hstack((temp1,temp2))      
-temp=np.reshape(x[:,5],(len(x[:,5]),1))
-X=np.hstack((X,temp))       
-temp=np.reshape(x[:,8],(len(x[:,8]),1))
-X=np.hstack((X,temp))       
-
-X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
-
-y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
-y_test=to_categorical(y_test)
-
-del temp1,temp2,temp
-
-# %%
-
-# Define tunable parameters"
-
-eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
-lamda=0.01                                  #Define hyperparameter
-n_layers=2                                  #Define number of hidden layers in the model
-n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
-epochs=100                                   #Number of reiterations over the input data
-batch_size=100                              #Number of samples per gradient update
-
-# %%
-
-"""Define function to return Deep Neural Network model"""
-
-def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
-    model=Sequential()      
-    for i in range(n_layers):       #Run loop to add hidden layers to the model
-        if (i==0):                  #First layer requires input dimensions
-            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
-        else:                       #Subsequent layers are capable of automatic shape inferencing
-            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
-    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
-    sgd=optimizers.SGD(lr=eta)
-    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
-    return model
-
-    
-Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
-Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
-
-for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
-    for j in range(len(eta)):      #accuracy scores 
-        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
-        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
-        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
-        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
-               
-
-def plot_data(x,y,data,title=None):
-
-    # plot results
-    fontsize=16
-
-
-    fig = plt.figure()
-    ax = fig.add_subplot(111)
-    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
-    
-    cbar=fig.colorbar(cax)
-    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
-    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
-    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
-
-    # put text on matrix elements
-    for i, x_val in enumerate(np.arange(len(x))):
-        for j, y_val in enumerate(np.arange(len(y))):
-            c = "${0:.1f}\\%$".format( 100*data[j,i])  
-            ax.text(x_val, y_val, c, va='center', ha='center')
-
-    # convert axis vaues to to string labels
-    x=[str(i) for i in x]
-    y=[str(i) for i in y]
-
-
-    ax.set_xticklabels(['']+x)
-    ax.set_yticklabels(['']+y)
-
-    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
-    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
-    if title is not None:
-        ax.set_title(title)
-
-    plt.tight_layout()
-
-    plt.show()
-    
-plot_data(eta,n_neuron,Train_accuracy, 'training')
-plot_data(eta,n_neuron,Test_accuracy, 'testing')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs098.html b/doc/src/week42/._week42-bs098.html deleted file mode 100644 index c82684f77..000000000 --- a/doc/src/week42/._week42-bs098.html +++ /dev/null @@ -1,1809 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - -
-
-

 

 

 

- - -

Building a neural network code

- -

Here we present a flexible object oriented codebase -for a feed forward neural network, along with a demonstration of how -to use it. Before we get into the details of the neural network, we -will first present some implementations of various schedulers, cost -functions and activation functions that can be used together with the -neural network. -

- -

The codes here were developed by Eric Reber and Gregor Kajda during spring 2023.

-

Learning rate methods

- -

The code below shows object oriented implementations of the Constant, -Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All -of the classes belong to the shared abstract Scheduler class, and -share the update_change() and reset() methods allowing for any of the -schedulers to be seamlessly used during the training stage, as will -later be shown in the fit() method of the neural -network. Update_change() only has one parameter, the gradient -(\( δ^l_ja^{l−1}_k \)), and returns the change which will be subtracted -from the weights. The reset() function takes no parameters, and resets -the desired variables. For Constant and Momentum, reset does nothing. -

- - - -
-
-
-
-
-
import autograd.numpy as np
-
-class Scheduler:
-    """
-    Abstract class for Schedulers
-    """
-
-    def __init__(self, eta):
-        self.eta = eta
-
-    # should be overwritten
-    def update_change(self, gradient):
-        raise NotImplementedError
-
-    # overwritten if needed
-    def reset(self):
-        pass
-
-
-class Constant(Scheduler):
-    def __init__(self, eta):
-        super().__init__(eta)
-
-    def update_change(self, gradient):
-        return self.eta * gradient
-    
-    def reset(self):
-        pass
-
-
-class Momentum(Scheduler):
-    def __init__(self, eta: float, momentum: float):
-        super().__init__(eta)
-        self.momentum = momentum
-        self.change = 0
-
-    def update_change(self, gradient):
-        self.change = self.momentum * self.change + self.eta * gradient
-        return self.change
-
-    def reset(self):
-        pass
-
-
-class Adagrad(Scheduler):
-    def __init__(self, eta):
-        super().__init__(eta)
-        self.G_t = None
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        if self.G_t is None:
-            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
-
-        self.G_t += gradient @ gradient.T
-
-        G_t_inverse = 1 / (
-            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
-        )
-        return self.eta * gradient * G_t_inverse
-
-    def reset(self):
-        self.G_t = None
-
-
-class AdagradMomentum(Scheduler):
-    def __init__(self, eta, momentum):
-        super().__init__(eta)
-        self.G_t = None
-        self.momentum = momentum
-        self.change = 0
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        if self.G_t is None:
-            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
-
-        self.G_t += gradient @ gradient.T
-
-        G_t_inverse = 1 / (
-            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
-        )
-        self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse
-        return self.change
-
-    def reset(self):
-        self.G_t = None
-
-
-class RMS_prop(Scheduler):
-    def __init__(self, eta, rho):
-        super().__init__(eta)
-        self.rho = rho
-        self.second = 0.0
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-        self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient
-        return self.eta * gradient / (np.sqrt(self.second + delta))
-
-    def reset(self):
-        self.second = 0.0
-
-
-class Adam(Scheduler):
-    def __init__(self, eta, rho, rho2):
-        super().__init__(eta)
-        self.rho = rho
-        self.rho2 = rho2
-        self.moment = 0
-        self.second = 0
-        self.n_epochs = 1
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        self.moment = self.rho * self.moment + (1 - self.rho) * gradient
-        self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient
-
-        moment_corrected = self.moment / (1 - self.rho**self.n_epochs)
-        second_corrected = self.second / (1 - self.rho2**self.n_epochs)
-
-        return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))
-
-    def reset(self):
-        self.n_epochs += 1
-        self.moment = 0
-        self.second = 0
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Usage of the above learning rate schedulers

- -

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. -

- - - -
-
-
-
-
-
momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)
-adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Here is a small example for how a segment of code using schedulers -could look. Switching out the schedulers is simple. -

- - - -
-
-
-
-
-
weights = np.ones((3,3))
-print(f"Before scheduler:\n{weights=}")
-
-epochs = 10
-for e in range(epochs):
-    gradient = np.random.rand(3, 3)
-    change = adam_scheduler.update_change(gradient)
-    weights = weights - change
-    adam_scheduler.reset()
-
-print(f"\nAfter scheduler:\n{weights=}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Cost functions

- -

Here we discuss cost functions that can be used when creating the -neural network. Every cost function takes the target vector as its -parameter, and returns a function valued only at \( x \) such that it may -easily be differentiated. -

- - - -
-
-
-
-
-
import autograd.numpy as np
-
-def CostOLS(target):
-    
-    def func(X):
-        return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)
-
-    return func
-
-
-def CostLogReg(target):
-
-    def func(X):
-        
-        return -(1.0 / target.shape[0]) * np.sum(
-            (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))
-        )
-
-    return func
-
-
-def CostCrossEntropy(target):
-    
-    def func(X):
-        return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))
-
-    return func
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Below we give a short example of how these cost function may be used -to obtain results if you wish to test them out on your own using -AutoGrad's automatics differentiation. -

- - - -
-
-
-
-
-
from autograd import grad
-
-target = np.array([[1, 2, 3]]).T
-a = np.array([[4, 5, 6]]).T
-
-cost_func = CostCrossEntropy
-cost_func_derivative = grad(cost_func(target))
-
-valued_at_a = cost_func_derivative(a)
-print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Activation functions

- -

Finally, before we look at the neural network, we will look at the -activation functions which can be specified between the hidden layers -and as the output function. Each function can be valued for any given -vector or matrix X, and can be differentiated via derivate(). -

- - - -
-
-
-
-
-
import autograd.numpy as np
-from autograd import elementwise_grad
-
-def identity(X):
-    return X
-
-
-def sigmoid(X):
-    try:
-        return 1.0 / (1 + np.exp(-X))
-    except FloatingPointError:
-        return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))
-
-
-def softmax(X):
-    X = X - np.max(X, axis=-1, keepdims=True)
-    delta = 10e-10
-    return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)
-
-
-def RELU(X):
-    return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))
-
-
-def LRELU(X):
-    delta = 10e-4
-    return np.where(X > np.zeros(X.shape), X, delta * X)
-
-
-def derivate(func):
-    if func.__name__ == "RELU":
-
-        def func(X):
-            return np.where(X > 0, 1, 0)
-
-        return func
-
-    elif func.__name__ == "LRELU":
-
-        def func(X):
-            delta = 10e-4
-            return np.where(X > 0, 1, delta)
-
-        return func
-
-    else:
-        return elementwise_grad(func)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Below follows a short demonstration of how to use an activation -function. The derivative of the activation function will be important -when calculating the output delta term during backpropagation. Note -that derivate() can also be used for cost functions for a more -generalized approach. -

- - - -
-
-
-
-
-
z = np.array([[4, 5, 6]]).T
-print(f"Input to activation function:\n{z}")
-
-act_func = sigmoid
-a = act_func(z)
-print(f"\nOutput from {act_func.__name__} activation function:\n{a}")
-
-act_func_derivative = derivate(act_func)
-valued_at_z = act_func_derivative(a)
-print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

The Neural Network

- -

Now that we have gotten a good understanding of the implementation of -some important components, we can take a look at an object oriented -implementation of a feed forward neural network. The feed forward -neural network has been implemented as a class named FFNN, which can -be initiated as a regressor or classifier dependant on the choice of -cost function. The FFNN can have any number of input nodes, hidden -layers with any amount of hidden nodes, and any amount of output nodes -meaning it can perform multiclass classification as well as binary -classification and regression problems. Although there is a lot of -code present, it makes for an easy to use and generalizeable interface -for creating many types of neural networks as will be demonstrated -below. -

- - - -
-
-
-
-
-
import math
-import autograd.numpy as np
-import sys
-import warnings
-from autograd import grad, elementwise_grad
-from random import random, seed
-from copy import deepcopy, copy
-from typing import Tuple, Callable
-from sklearn.utils import resample
-
-warnings.simplefilter("error")
-
-
-class FFNN:
-    """
-    Description:
-    ------------
-        Feed Forward Neural Network with interface enabling flexible design of a
-        nerual networks architecture and the specification of activation function
-        in the hidden layers and output layer respectively. This model can be used
-        for both regression and classification problems, depending on the output function.
-
-    Attributes:
-    ------------
-        I   dimensions (tuple[int]): A list of positive integers, which specifies the
-            number of nodes in each of the networks layers. The first integer in the array
-            defines the number of nodes in the input layer, the second integer defines number
-            of nodes in the first hidden layer and so on until the last number, which
-            specifies the number of nodes in the output layer.
-        II  hidden_func (Callable): The activation function for the hidden layers
-        III output_func (Callable): The activation function for the output layer
-        IV  cost_func (Callable): Our cost function
-        V   seed (int): Sets random seed, makes results reproducible
-    """
-
-    def __init__(
-        self,
-        dimensions: tuple[int],
-        hidden_func: Callable = sigmoid,
-        output_func: Callable = lambda x: x,
-        cost_func: Callable = CostOLS,
-        seed: int = None,
-    ):
-        self.dimensions = dimensions
-        self.hidden_func = hidden_func
-        self.output_func = output_func
-        self.cost_func = cost_func
-        self.seed = seed
-        self.weights = list()
-        self.schedulers_weight = list()
-        self.schedulers_bias = list()
-        self.a_matrices = list()
-        self.z_matrices = list()
-        self.classification = None
-
-        self.reset_weights()
-        self._set_classification()
-
-    def fit(
-        self,
-        X: np.ndarray,
-        t: np.ndarray,
-        scheduler: Scheduler,
-        batches: int = 1,
-        epochs: int = 100,
-        lam: float = 0,
-        X_val: np.ndarray = None,
-        t_val: np.ndarray = None,
-    ):
-        """
-        Description:
-        ------------
-            This function performs the training the neural network by performing the feedforward and backpropagation
-            algorithm to update the networks weights.
-
-        Parameters:
-        ------------
-            I    X (np.ndarray) : training data
-            II   t (np.ndarray) : target data
-            III  scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)
-            IV   scheduler_args (list[int]) : list of all arguments necessary for scheduler
-
-        Optional Parameters:
-        ------------
-            V    batches (int) : number of batches the datasets are split into, default equal to 1
-            VI   epochs (int) : number of iterations used to train the network, default equal to 100
-            VII  lam (float) : regularization hyperparameter lambda
-            VIII X_val (np.ndarray) : validation set
-            IX   t_val (np.ndarray) : validation target set
-
-        Returns:
-        ------------
-            I   scores (dict) : A dictionary containing the performance metrics of the model.
-                The number of the metrics depends on the parameters passed to the fit-function.
-
-        """
-
-        # setup 
-        if self.seed is not None:
-            np.random.seed(self.seed)
-
-        val_set = False
-        if X_val is not None and t_val is not None:
-            val_set = True
-
-        # creating arrays for score metrics
-        train_errors = np.empty(epochs)
-        train_errors.fill(np.nan)
-        val_errors = np.empty(epochs)
-        val_errors.fill(np.nan)
-
-        train_accs = np.empty(epochs)
-        train_accs.fill(np.nan)
-        val_accs = np.empty(epochs)
-        val_accs.fill(np.nan)
-
-        self.schedulers_weight = list()
-        self.schedulers_bias = list()
-
-        batch_size = X.shape[0] // batches
-
-        X, t = resample(X, t)
-
-        # this function returns a function valued only at X
-        cost_function_train = self.cost_func(t)
-        if val_set:
-            cost_function_val = self.cost_func(t_val)
-
-        # create schedulers for each weight matrix
-        for i in range(len(self.weights)):
-            self.schedulers_weight.append(copy(scheduler))
-            self.schedulers_bias.append(copy(scheduler))
-
-        print(f"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}")
-
-        try:
-            for e in range(epochs):
-                for i in range(batches):
-                    # allows for minibatch gradient descent
-                    if i == batches - 1:
-                        # If the for loop has reached the last batch, take all thats left
-                        X_batch = X[i * batch_size :, :]
-                        t_batch = t[i * batch_size :, :]
-                    else:
-                        X_batch = X[i * batch_size : (i + 1) * batch_size, :]
-                        t_batch = t[i * batch_size : (i + 1) * batch_size, :]
-
-                    self._feedforward(X_batch)
-                    self._backpropagate(X_batch, t_batch, lam)
-
-                # reset schedulers for each epoch (some schedulers pass in this call)
-                for scheduler in self.schedulers_weight:
-                    scheduler.reset()
-
-                for scheduler in self.schedulers_bias:
-                    scheduler.reset()
-
-                # computing performance metrics
-                pred_train = self.predict(X)
-                train_error = cost_function_train(pred_train)
-
-                train_errors[e] = train_error
-                if val_set:
-                    
-                    pred_val = self.predict(X_val)
-                    val_error = cost_function_val(pred_val)
-                    val_errors[e] = val_error
-
-                if self.classification:
-                    train_acc = self._accuracy(self.predict(X), t)
-                    train_accs[e] = train_acc
-                    if val_set:
-                        val_acc = self._accuracy(pred_val, t_val)
-                        val_accs[e] = val_acc
-
-                # printing progress bar
-                progression = e / epochs
-                print_length = self._progress_bar(
-                    progression,
-                    train_error=train_errors[e],
-                    train_acc=train_accs[e],
-                    val_error=val_errors[e],
-                    val_acc=val_accs[e],
-                )
-        except KeyboardInterrupt:
-            # allows for stopping training at any point and seeing the result
-            pass
-
-        # visualization of training progression (similiar to tensorflow progression bar)
-        sys.stdout.write("\r" + " " * print_length)
-        sys.stdout.flush()
-        self._progress_bar(
-            1,
-            train_error=train_errors[e],
-            train_acc=train_accs[e],
-            val_error=val_errors[e],
-            val_acc=val_accs[e],
-        )
-        sys.stdout.write("")
-
-        # return performance metrics for the entire run
-        scores = dict()
-
-        scores["train_errors"] = train_errors
-
-        if val_set:
-            scores["val_errors"] = val_errors
-
-        if self.classification:
-            scores["train_accs"] = train_accs
-
-            if val_set:
-                scores["val_accs"] = val_accs
-
-        return scores
-
-    def predict(self, X: np.ndarray, *, threshold=0.5):
-        """
-         Description:
-         ------------
-             Performs prediction after training of the network has been finished.
-
-         Parameters:
-        ------------
-             I   X (np.ndarray): The design matrix, with n rows of p features each
-
-         Optional Parameters:
-         ------------
-             II  threshold (float) : sets minimal value for a prediction to be predicted as the positive class
-                 in classification problems
-
-         Returns:
-         ------------
-             I   z (np.ndarray): A prediction vector (row) for each row in our design matrix
-                 This vector is thresholded if regression=False, meaning that classification results
-                 in a vector of 1s and 0s, while regressions in an array of decimal numbers
-
-        """
-
-        predict = self._feedforward(X)
-
-        if self.classification:
-            return np.where(predict > threshold, 1, 0)
-        else:
-            return predict
-
-    def reset_weights(self):
-        """
-        Description:
-        ------------
-            Resets/Reinitializes the weights in order to train the network for a new problem.
-
-        """
-        if self.seed is not None:
-            np.random.seed(self.seed)
-
-        self.weights = list()
-        for i in range(len(self.dimensions) - 1):
-            weight_array = np.random.randn(
-                self.dimensions[i] + 1, self.dimensions[i + 1]
-            )
-            weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01
-
-            self.weights.append(weight_array)
-
-    def _feedforward(self, X: np.ndarray):
-        """
-        Description:
-        ------------
-            Calculates the activation of each layer starting at the input and ending at the output.
-            Each following activation is calculated from a weighted sum of each of the preceeding
-            activations (except in the case of the input layer).
-
-        Parameters:
-        ------------
-            I   X (np.ndarray): The design matrix, with n rows of p features each
-
-        Returns:
-        ------------
-            I   z (np.ndarray): A prediction vector (row) for each row in our design matrix
-        """
-
-        # reset matrices
-        self.a_matrices = list()
-        self.z_matrices = list()
-
-        # if X is just a vector, make it into a matrix
-        if len(X.shape) == 1:
-            X = X.reshape((1, X.shape[0]))
-
-        # Add a coloumn of zeros as the first coloumn of the design matrix, in order
-        # to add bias to our data
-        bias = np.ones((X.shape[0], 1)) * 0.01
-        X = np.hstack([bias, X])
-
-        # a^0, the nodes in the input layer (one a^0 for each row in X - where the
-        # exponent indicates layer number).
-        a = X
-        self.a_matrices.append(a)
-        self.z_matrices.append(a)
-
-        # The feed forward algorithm
-        for i in range(len(self.weights)):
-            if i < len(self.weights) - 1:
-                z = a @ self.weights[i]
-                self.z_matrices.append(z)
-                a = self.hidden_func(z)
-                # bias column again added to the data here
-                bias = np.ones((a.shape[0], 1)) * 0.01
-                a = np.hstack([bias, a])
-                self.a_matrices.append(a)
-            else:
-                try:
-                    # a^L, the nodes in our output layers
-                    z = a @ self.weights[i]
-                    a = self.output_func(z)
-                    self.a_matrices.append(a)
-                    self.z_matrices.append(z)
-                except Exception as OverflowError:
-                    print(
-                        "OverflowError in fit() in FFNN\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling"
-                    )
-
-        # this will be a^L
-        return a
-
-    def _backpropagate(self, X, t, lam):
-        """
-        Description:
-        ------------
-            Performs the backpropagation algorithm. In other words, this method
-            calculates the gradient of all the layers starting at the
-            output layer, and moving from right to left accumulates the gradient until
-            the input layer is reached. Each layers respective weights are updated while
-            the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).
-
-        Parameters:
-        ------------
-            I   X (np.ndarray): The design matrix, with n rows of p features each.
-            II  t (np.ndarray): The target vector, with n rows of p targets.
-            III lam (float32): regularization parameter used to punish the weights in case of overfitting
-
-        Returns:
-        ------------
-            No return value.
-
-        """
-        out_derivative = derivate(self.output_func)
-        hidden_derivative = derivate(self.hidden_func)
-
-        for i in range(len(self.weights) - 1, -1, -1):
-            # delta terms for output
-            if i == len(self.weights) - 1:
-                # for multi-class classification
-                if (
-                    self.output_func.__name__ == "softmax"
-                ):
-                    delta_matrix = self.a_matrices[i + 1] - t
-                # for single class classification
-                else:
-                    cost_func_derivative = grad(self.cost_func(t))
-                    delta_matrix = out_derivative(
-                        self.z_matrices[i + 1]
-                    ) * cost_func_derivative(self.a_matrices[i + 1])
-
-            # delta terms for hidden layer
-            else:
-                delta_matrix = (
-                    self.weights[i + 1][1:, :] @ delta_matrix.T
-                ).T * hidden_derivative(self.z_matrices[i + 1])
-
-            # calculate gradient
-            gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix
-            gradient_bias = np.sum(delta_matrix, axis=0).reshape(
-                1, delta_matrix.shape[1]
-            )
-
-            # regularization term
-            gradient_weights += self.weights[i][1:, :] * lam
-
-            # use scheduler
-            update_matrix = np.vstack(
-                [
-                    self.schedulers_bias[i].update_change(gradient_bias),
-                    self.schedulers_weight[i].update_change(gradient_weights),
-                ]
-            )
-
-            # update weights and bias
-            self.weights[i] -= update_matrix
-
-    def _accuracy(self, prediction: np.ndarray, target: np.ndarray):
-        """
-        Description:
-        ------------
-            Calculates accuracy of given prediction to target
-
-        Parameters:
-        ------------
-            I   prediction (np.ndarray): vector of predicitons output network
-                (1s and 0s in case of classification, and real numbers in case of regression)
-            II  target (np.ndarray): vector of true values (What the network ideally should predict)
-
-        Returns:
-        ------------
-            A floating point number representing the percentage of correctly classified instances.
-        """
-        assert prediction.size == target.size
-        return np.average((target == prediction))
-    def _set_classification(self):
-        """
-        Description:
-        ------------
-            Decides if FFNN acts as classifier (True) og regressor (False),
-            sets self.classification during init()
-        """
-        self.classification = False
-        if (
-            self.cost_func.__name__ == "CostLogReg"
-            or self.cost_func.__name__ == "CostCrossEntropy"
-        ):
-            self.classification = True
-
-    def _progress_bar(self, progression, **kwargs):
-        """
-        Description:
-        ------------
-            Displays progress of training
-        """
-        print_length = 40
-        num_equals = int(progression * print_length)
-        num_not = print_length - num_equals
-        arrow = ">" if num_equals > 0 else ""
-        bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]"
-        perc_print = self._format(progression * 100, decimals=5)
-        line = f"  {bar} {perc_print}% "
-
-        for key in kwargs:
-            if not np.isnan(kwargs[key]):
-                value = self._format(kwargs[key], decimals=4)
-                line += f"| {key}: {value} "
-        sys.stdout.write("\r" + line)
-        sys.stdout.flush()
-        return len(line)
-
-    def _format(self, value, decimals=4):
-        """
-        Description:
-        ------------
-            Formats decimal numbers for progress bar
-        """
-        if value > 0:
-            v = value
-        elif value < 0:
-            v = -10 * value
-        else:
-            v = 1
-        n = 1 + math.floor(math.log10(v))
-        if n >= decimals - 1:
-            return str(round(value))
-        return f"{value:.{decimals-n-1}f}"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Before we make a model, we will quickly generate a dataset we can use -for our linear regression problem as shown below -

- - - -
-
-
-
-
-
import autograd.numpy as np
-from sklearn.model_selection import train_test_split
-
-def SkrankeFunction(x, y):
-    return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)
-
-def create_X(x, y, n):
-    if len(x.shape) > 1:
-        x = np.ravel(x)
-        y = np.ravel(y)
-
-    N = len(x)
-    l = int((n + 1) * (n + 2) / 2)  # Number of elements in beta
-    X = np.ones((N, l))
-
-    for i in range(1, n + 1):
-        q = int((i) * (i + 1) / 2)
-        for k in range(i + 1):
-            X[:, q + k] = (x ** (i - k)) * (y**k)
-
-    return X
-
-step=0.5
-x = np.arange(0, 1, step)
-y = np.arange(0, 1, step)
-x, y = np.meshgrid(x, y)
-target = SkrankeFunction(x, y)
-target = target.reshape(target.shape[0], 1)
-
-poly_degree=3
-X = create_X(x, y, poly_degree)
-
-X_train, X_test, t_train, t_test = train_test_split(X, target)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now that we have our dataset ready for the regression, we can create -our regressor. Note that with the seed parameter, we can make sure our -results stay the same every time we run the neural network. For -inititialization, we simply specify the dimensions (we wish the amount -of input nodes to be equal to the datapoints, and the output to -predict one value). -

- - - -
-
-
-
-
-
input_nodes = X_train.shape[1]
-output_nodes = 1
-
-linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We then fit our model with our training data using the scheduler of our choice.

- - - -
-
-
-
-
-
linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Constant(eta=1e-3)
-scores = linear_regression.fit(X_train, t_train, scheduler)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Due to the progress bar we can see the MSE (train_error) throughout -the FFNN's training. Note that the fit() function has some optional -parameters with defualt arguments. For example, the regularization -hyperparameter can be left ignored if not needed, and equally the FFNN -will by default run for 100 epochs. These can easily be changed, such -as for example: -

- - - -
-
-
-
-
-
linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that given more epochs to train on, the regressor reaches a lower MSE.

- -

Let us then switch to a binary classification. We use a binary -classification dataset, and follow a similar setup to the regression -case. -

- - - -
-
-
-
-
-
from sklearn.datasets import load_breast_cancer
-from sklearn.preprocessing import MinMaxScaler
-
-wisconsin = load_breast_cancer()
-X = wisconsin.data
-target = wisconsin.target
-target = target.reshape(target.shape[0], 1)
-
-X_train, X_val, t_train, t_val = train_test_split(X, target)
-
-scaler = MinMaxScaler()
-scaler.fit(X_train)
-X_train = scaler.transform(X_train)
-X_val = scaler.transform(X_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
input_nodes = X_train.shape[1]
-output_nodes = 1
-
-logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We will now make use of our validation data by passing it into our fit function as a keyword argument

- - - -
-
-
-
-
-
logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
-scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Finally, we will create a neural network with 2 hidden layers with activation functions.

- - -
-
-
-
-
-
input_nodes = X_train.shape[1]
-hidden_nodes1 = 100
-hidden_nodes2 = 30
-output_nodes = 1
-
-dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
-
-neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
-scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Multiclass classification

- -

Finally, we will demonstrate the use case of multiclass classification -using our FFNN with the famous MNIST dataset, which contain images of -digits between the range of 0 to 9. -

- - - -
-
-
-
-
-
from sklearn.datasets import load_digits
-
-def onehot(target: np.ndarray):
-    onehot = np.zeros((target.size, target.max() + 1))
-    onehot[np.arange(target.size), target] = 1
-    return onehot
-
-digits = load_digits()
-
-X = digits.data
-target = digits.target
-target = onehot(target)
-
-input_nodes = 64
-hidden_nodes1 = 100
-hidden_nodes2 = 30
-output_nodes = 10
-
-dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
-
-multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)
-
-multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
-scores = multiclass.fit(X, target, scheduler, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/._week42-bs099.html b/doc/src/week42/._week42-bs099.html deleted file mode 100644 index 8a2bdbe59..000000000 --- a/doc/src/week42/._week42-bs099.html +++ /dev/null @@ -1,538 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - -
-
-

 

 

 

- - -

Testing the XOR gate and other gates

- -

Let us now use our code to test the XOR gate.

- - - -
-
-
-
-
-
X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
-
-# The XOR gate
-yXOR = np.array( [[ 0], [1] ,[1], [0]])
-
-input_nodes = X.shape[1]
-output_nodes = 1
-
-logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999)
-scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Not bad, but the results depend strongly on the learning reate. Try different learning rates.

-

- -

- -
- - - - -
- -
- - - diff --git a/doc/src/week42/ipynb-week42-src.tar.gz b/doc/src/week42/ipynb-week42-src.tar.gz deleted file mode 100644 index 126c04428..000000000 Binary files a/doc/src/week42/ipynb-week42-src.tar.gz and /dev/null differ diff --git a/doc/src/week42/reveal.js/.gitignore b/doc/src/week42/reveal.js/.gitignore deleted file mode 100644 index a5df3133d..000000000 --- a/doc/src/week42/reveal.js/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -.DS_Store -.svn -log/*.log -tmp/** -node_modules/ -.sass-cache -css/reveal.min.css -js/reveal.min.js diff --git a/doc/src/week42/reveal.js/.travis.yml b/doc/src/week42/reveal.js/.travis.yml deleted file mode 100644 index 165d9ae9f..000000000 --- a/doc/src/week42/reveal.js/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.10 -before_script: - - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/src/week42/reveal.js/CONTRIBUTING.md b/doc/src/week42/reveal.js/CONTRIBUTING.md deleted file mode 100644 index c2091e88f..000000000 --- a/doc/src/week42/reveal.js/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -## Contributing - -Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. - - -### Personal Support -If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). - - -### Bug Reports -When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. - - -### Pull Requests -- Should follow the coding style of the file you work in, most importantly: - - Tabs to indent - - Single-quoted strings -- Should be made towards the **dev branch** -- Should be submitted from a feature/topic branch (not your master) - - -### Plugins -Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/src/week42/reveal.js/Gruntfile.js b/doc/src/week42/reveal.js/Gruntfile.js deleted file mode 100644 index b257e8f32..000000000 --- a/doc/src/week42/reveal.js/Gruntfile.js +++ /dev/null @@ -1,140 +0,0 @@ -/* global module:false */ -module.exports = function(grunt) { - var port = grunt.option('port') || 8000; - // Project configuration - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - meta: { - banner: - '/*!\n' + - ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + - ' * http://lab.hakim.se/reveal-js\n' + - ' * MIT licensed\n' + - ' *\n' + - ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + - ' */' - }, - - qunit: { - files: [ 'test/*.html' ] - }, - - uglify: { - options: { - banner: '<%= meta.banner %>\n' - }, - build: { - src: 'js/reveal.js', - dest: 'js/reveal.min.js' - } - }, - - cssmin: { - compress: { - files: { - 'css/reveal.min.css': [ 'css/reveal.css' ] - } - } - }, - - sass: { - main: { - files: { - 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', - 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', - 'css/theme/cbc.css': 'css/theme/source/cbc.scss', - 'css/theme/default.css': 'css/theme/source/default.scss', - 'css/theme/beige.css': 'css/theme/source/beige.scss', - 'css/theme/night.css': 'css/theme/source/night.scss', - 'css/theme/serif.css': 'css/theme/source/serif.scss', - 'css/theme/simple.css': 'css/theme/source/simple.scss', - 'css/theme/sky.css': 'css/theme/source/sky.scss', - 'css/theme/moon.css': 'css/theme/source/moon.scss', - 'css/theme/solarized.css': 'css/theme/source/solarized.scss', - 'css/theme/blood.css': 'css/theme/source/blood.scss' - } - } - }, - - jshint: { - options: { - curly: false, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - eqnull: true, - browser: true, - expr: true, - globals: { - head: false, - module: false, - console: false, - unescape: false - } - }, - files: [ 'Gruntfile.js', 'js/reveal.js' ] - }, - - connect: { - server: { - options: { - port: port, - base: '.' - } - } - }, - - zip: { - 'reveal-js-presentation.zip': [ - 'index.html', - 'css/**', - 'js/**', - 'lib/**', - 'images/**', - 'plugin/**' - ] - }, - - watch: { - main: { - files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], - tasks: 'default' - }, - theme: { - files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], - tasks: 'themes' - } - } - - }); - - // Dependencies - grunt.loadNpmTasks( 'grunt-contrib-qunit' ); - grunt.loadNpmTasks( 'grunt-contrib-jshint' ); - grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); - grunt.loadNpmTasks( 'grunt-contrib-uglify' ); - grunt.loadNpmTasks( 'grunt-contrib-watch' ); - grunt.loadNpmTasks( 'grunt-contrib-sass' ); - grunt.loadNpmTasks( 'grunt-contrib-connect' ); - grunt.loadNpmTasks( 'grunt-zip' ); - - // Default task - grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); - - // Theme task - grunt.registerTask( 'themes', [ 'sass' ] ); - - // Package presentation to archive - grunt.registerTask( 'package', [ 'default', 'zip' ] ); - - // Serve presentation locally - grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); - - // Run tests - grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); - -}; diff --git a/doc/src/week42/reveal.js/LICENSE b/doc/src/week42/reveal.js/LICENSE deleted file mode 100644 index 09623076f..000000000 --- a/doc/src/week42/reveal.js/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2015 Hakim El Hattab, http://hakim.se - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/doc/src/week42/reveal.js/README.md b/doc/src/week42/reveal.js/README.md deleted file mode 100644 index 573b19597..000000000 --- a/doc/src/week42/reveal.js/README.md +++ /dev/null @@ -1,1052 +0,0 @@ -# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) - -A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). - -reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. - - -#### More reading: -- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. -- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. -- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! -- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. -- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. - -## Online Editor - -Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). - - -## Instructions - -### Markup - -Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: - -```html -
-
-
Single Horizontal Slide
-
-
Vertical Slide 1
-
Vertical Slide 2
-
-
-
-``` - -### Markdown - -It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` -
-``` - -#### External Markdown - -You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. - -When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). - -```html -
-
-``` - -#### Element Attributes - -Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. - -```html -
- -
-``` - -#### Slide Attributes - -Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. - -```html -
- -
-``` - - -### Configuration - -At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. - -```javascript -Reveal.initialize({ - - // Display controls in the bottom right corner - controls: true, - - // Display a presentation progress bar - progress: true, - - // Display the page number of the current slide - slideNumber: false, - - // Push each slide change to the browser history - history: false, - - // Enable keyboard shortcuts for navigation - keyboard: true, - - // Enable the slide overview mode - overview: true, - - // Vertical centering of slides - center: true, - - // Enables touch navigation on devices with touch input - touch: true, - - // Loop the presentation - loop: false, - - // Change the presentation direction to be RTL - rtl: false, - - // Turns fragments on and off globally - fragments: true, - - // Flags if the presentation is running in an embedded mode, - // i.e. contained within a limited portion of the screen - embedded: false, - - // Flags if we should show a help overlay when the questionmark - // key is pressed - help: true, - - // Number of milliseconds between automatically proceeding to the - // next slide, disabled when set to 0, this value can be overwritten - // by using a data-autoslide attribute on your slides - autoSlide: 0, - - // Stop auto-sliding after user input - autoSlideStoppable: true, - - // Enable slide navigation via mouse wheel - mouseWheel: false, - - // Hides the address bar on mobile devices - hideAddressBar: true, - - // Opens links in an iframe preview overlay - previewLinks: false, - - // Transition style - transition: 'default', // none/fade/slide/convex/concave/zoom - - // Transition speed - transitionSpeed: 'default', // default/fast/slow - - // Transition style for full page slide backgrounds - backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom - - // Number of slides away from the current that are visible - viewDistance: 3, - - // Parallax background image - parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - - // Amount to move parallax background (horizontal and vertical) on slide change - // Number, e.g. 100 - parallaxBackgroundHorizontal: '', - parallaxBackgroundVertical: '' - -}); -``` - - -The configuration can be updated after initialization using the ```configure``` method: - -```javascript -// Turn autoSlide off -Reveal.configure({ autoSlide: 0 }); - -// Start auto-sliding every 5s -Reveal.configure({ autoSlide: 5000 }); -``` - - -### Dependencies - -Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: - -```javascript -Reveal.initialize({ - dependencies: [ - // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ - { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, - - // Interpret Markdown in
elements - { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - - // Syntax highlight for elements - { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, - - // Zoom in and out with Alt+click - { src: 'plugin/zoom-js/zoom.js', async: true }, - - // Speaker notes - { src: 'plugin/notes/notes.js', async: true }, - - // Remote control your reveal.js presentation using a touch device - { src: 'plugin/remotes/remotes.js', async: true }, - - // MathJax - { src: 'plugin/math/math.js', async: true } - ] -}); -``` - -You can add your own extensions using the same syntax. The following properties are available for each dependency object: -- **src**: Path to the script to load -- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false -- **callback**: [optional] Function to execute when the script has loaded -- **condition**: [optional] Function which must return true for the script to be loaded - - -### Ready Event - -A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. - -```javascript -Reveal.addEventListener( 'ready', function( event ) { - // event.currentSlide, event.indexh, event.indexv -} ); -``` - - -### Presentation Size - -All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. - -See below for a list of configuration options related to sizing, including default values: - -```javascript -Reveal.initialize({ - - ... - - // The "normal" size of the presentation, aspect ratio will be preserved - // when the presentation is scaled to fit different resolutions. Can be - // specified using percentage units. - width: 960, - height: 700, - - // Factor of the display size that should remain empty around the content - margin: 0.1, - - // Bounds for smallest/largest possible scale to apply to content - minScale: 0.2, - maxScale: 1.5 - -}); -``` - - -### Auto-sliding - -Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: - -```javascript -// Slide every five seconds -Reveal.configure({ - autoSlide: 5000 -}); -``` -When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. - -You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: - -```html -
-

After 2 seconds the first fragment will be shown.

-

After 10 seconds the next fragment will be shown.

-

Now, the fragment is displayed for 2 seconds before the next slide is shown.

-
-``` - -Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. - - -### Keyboard Bindings - -If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: - -```javascript -Reveal.configure({ - keyboard: { - 13: 'next', // go to the next slide when the ENTER key is pressed - 27: function() {}, // do something custom when ESC is pressed - 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) - } -}); -``` - -### Lazy Loading - -When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. - -To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. - -```html -
- - - -
-``` - - -### API - -The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: - -```javascript -// Navigation -Reveal.slide( indexh, indexv, indexf ); -Reveal.left(); -Reveal.right(); -Reveal.up(); -Reveal.down(); -Reveal.prev(); -Reveal.next(); -Reveal.prevFragment(); -Reveal.nextFragment(); - -// Toggle presentation states, optionally pass true/false to force on/off -Reveal.toggleOverview(); -Reveal.togglePause(); -Reveal.toggleAutoSlide(); - -// Change a config value at runtime -Reveal.configure({ controls: true }); - -// Returns the present configuration options -Reveal.getConfig(); - -// Fetch the current scale of the presentation -Reveal.getScale(); - -// Retrieves the previous and current slide elements -Reveal.getPreviousSlide(); -Reveal.getCurrentSlide(); - -Reveal.getIndices(); // { h: 0, v: 0 } } -Reveal.getProgress(); // 0-1 -Reveal.getTotalSlides(); - -// State checks -Reveal.isFirstSlide(); -Reveal.isLastSlide(); -Reveal.isOverview(); -Reveal.isPaused(); -Reveal.isAutoSliding(); -``` - -### Slide Changed Event - -A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. - -Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. - -```javascript -Reveal.addEventListener( 'slidechanged', function( event ) { - // event.previousSlide, event.currentSlide, event.indexh, event.indexv -} ); -``` - -### Presentation State - -The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. - -```javascript -Reveal.slide( 1 ); -// we're on slide 1 - -var state = Reveal.getState(); - -Reveal.slide( 3 ); -// we're on slide 3 - -Reveal.setState( state ); -// we're back on slide 1 -``` - -### Slide States - -If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. - -Furthermore you can also listen to these changes in state via JavaScript: - -```javascript -Reveal.addEventListener( 'somestate', function() { - // TODO: Sprinkle magic -}, false ); -``` - -### Slide Backgrounds - -Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. - -```html -
-

All CSS color formats are supported, like rgba() or hsl().

-
-
-

This slide will have a full-size background image.

-
-
-

This background image will be sized to 100px and repeated.

-
-
-

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

-
-
-

Embeds a web page as a background. Note that the page won't be interactive.

-
-``` - -Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. - - -### Parallax Background - -If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). - -```javascript -Reveal.initialize({ - - // Parallax background image - parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) - - // Amount of pixels to move the parallax background per slide step, - // a value of 0 disables movement along the given axis - // These are optional, if they aren't specified they'll be calculated automatically - parallaxBackgroundHorizontal: 200, - parallaxBackgroundVertical: 50 - -}); -``` - -Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). - - - -### Slide Transitions -The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: - -```html -
-

This slide will override the presentation transition and zoom!

-
- -
-

Choose from three transition speeds: default, fast or slow!

-
-``` - -You can also use different in and out transitions for the same slide: - -```html -
- The train goes on … -
-
- and on … -
-
- and stops. -
-
- (Passengers entering and leaving) -
-
- And it starts again. -
-``` - - -Note that this does not work with the page and cube transitions. - - -### Internal links - -It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): - -```html -Link -Link -``` - -You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. - -```html - - - - - - -``` - - -### Fragments -Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments - -The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: - -```html -
-

grow

-

shrink

-

fade-out

-

visible only once

-

blue only once

-

highlight-red

-

highlight-green

-

highlight-blue

-
-``` - -Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. - -```html -
- - I'll fade in, then out - -
-``` - -The display order of fragments can be controlled using the ```data-fragment-index``` attribute. - -```html -
-

Appears last

-

Appears first

-

Appears second

-
-``` - -### Fragment events - -When a slide fragment is either shown or hidden reveal.js will dispatch an event. - -Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. - -```javascript -Reveal.addEventListener( 'fragmentshown', function( event ) { - // event.fragment = the fragment DOM element -} ); -Reveal.addEventListener( 'fragmenthidden', function( event ) { - // event.fragment = the fragment DOM element -} ); -``` - -### Code syntax highlighting - -By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. - -```html -
-

-(def lazy-fib
-  (concat
-   [0 1]
-   ((fn rfib [a b]
-        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
-	
-
-``` - -### Slide number -If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. - -```javascript -// Shows the slide number using default formatting -Reveal.configure({ slideNumber: true }); - -// Slide number formatting can be configured using these variables: -// h: current slide's horizontal index -// v: current slide's vertical index -// c: current slide index (flattened) -// t: total number of slides (flattened) -Reveal.configure({ slideNumber: 'c / t' }); - -``` - - -### Overview mode - -Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, -as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: - -```javascript -Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); -Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); - -// Toggle the overview mode programmatically -Reveal.toggleOverview(); -``` - -### Fullscreen mode -Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. - - -### Embedded media -Embedded HTML5 `
-
-

 

 

 

- - -
-
-

Week 42 Constructing a Neural Network code with examples

-
- - -
-Morten Hjorth-Jensen [1, 2] -
- -
-[1] Department of Physics, University of Oslo -
-
-[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University -
-
-
-

October 14-18, 2024

-
-
- - - -

Read »

- - -
- -

- -

- -
- - - - -
- © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - diff --git a/doc/src/week42/week42-reveal.html b/doc/src/week42/week42-reveal.html deleted file mode 100644 index 88db3fbfa..000000000 --- a/doc/src/week42/week42-reveal.html +++ /dev/null @@ -1,5174 +0,0 @@ - - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - - - - - - - - - -
- -
-

Week 42 Constructing a Neural Network code with examples

-
- - -
-Morten Hjorth-Jensen [1, 2] -
- -
-[1] Department of Physics, University of Oslo -
-
-[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University -
-
-
-

October 14-18, 2024

-
-
- - -
- © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
-
- -
-

Lecture October 14, 2024

-
- -

-

    -

  1. Building our own Feed-forward Neural Network and discussion of project 2
  2. -
-
- -
-Readings and videos -

-

    -

  1. These lecture notes - -
  2. -

  3. For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7.
  4. - -

  5. Neural Networks demystified at https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs
  6. -

  7. Building Neural Networks from scratch at https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex
  8. -

  9. Video on Neural Networks at https://www.youtube.com/watch?v=CqOfi41LfDw
  10. -

  11. Video on the back propagation algorithm at https://www.youtube.com/watch?v=Ilg3gGewQ5U
  12. -
-

-

I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at http://neuralnetworksanddeeplearning.com/chap4.html.

-
-
- -
-

Material for the active learning sessions on Tuesday and Wednesday

-
- -

-

    - -

  • Exercise on starting to write a code for neural networks, feed forward part. We will also continue ur discussions of gradient descent methods from last week. If you have time, start considering the back-propagation part as well (exercises for next week)
  • - -

  • Discussion of project 2
  • -
-
- -

Note: some of the codes will also be discussed next week in connection with the solution of differential equations.

-
- -
-

Writing a code which implements a feed-forward neural network

- -

Last week we discussed the basics of neural networks and deep learning -and the basics of automatic differentiation. We looked also at -examples on how compute the parameters of a simple network with scalar -inputs and ouputs and no or just one hidden layers. -

- -

We ended our discussions with the derivation of the equations for a -neural network with one hidden layers and two input variables and two -hidden nodes but only one output node. -

-
- -
-

Mathematics of deep learning

- - -
- -
-

Reminder on books with hands-on material and codes

- -
- -
-

Reading recommendations

- -
    -

  1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub
  2. -

  3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
  4. -
-
- -
-

First network example, simple percepetron with one input

- -

As yet another example we define now a simple perceptron model with -all quantities given by scalars. We consider only one input variable -\( x \) and one target value \( y \). We define an activation function -\( \sigma_1 \) which takes as input -

- -

 
-$$ -z_1 = w_1x+b_1, -$$ -

 
- -

where \( w_1 \) is the weight and \( b_1 \) is the bias. These are the -parameters we want to optimize. The output is \( a_1=\sigma(z_1) \) (see -graph from whiteboard notes). This output is then fed into the -cost/loss function, which we here for the sake of simplicity just -define as the squared error -

- -

 
-$$ -C(x;w_1,b_1)=\frac{1}{2}(a_1-y)^2. -$$ -

 
-

- -
-

Layout of a simple neural network with no hidden layer

- -

-
-

-
-

-
- -
-

Optimizing the parameters

- -

In setting up the feed forward and back propagation parts of the -algorithm, we need now the derivative of the various variables we want -to train. -

- -

We need

-

 
-$$ -\frac{\partial C}{\partial w_1} \hspace{0.1cm}\mathrm{and}\hspace{0.1cm}\frac{\partial C}{\partial b_1}. -$$ -

 
- -

Using the chain rule we find

-

 
-$$ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_1-y)\sigma_1'x, -$$ -

 
- -

and

-

 
-$$ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_1-y)\sigma_1', -$$ -

 
- -

which we later will just define as

-

 
-$$ -\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}=\delta_1. -$$ -

 
-

- -
-

Adding a hidden layer

- -

We change our simple model to (see graph) -a network with just one hidden layer but with scalar variables only. -

- -

Our output variable changes to \( a_2 \) and \( a_1 \) is now the output from the hidden node and \( a_0=x \). -We have then -

-

 
-$$ -z_1 = w_1a_0+b_1 \hspace{0.1cm} \wedge a_1 = \sigma_1(z_1), -$$ -

 
- -

 
-$$ -z_2 = w_2a_1+b_2 \hspace{0.1cm} \wedge a_2 = \sigma_2(z_2), -$$ -

 
- -

and the cost function

-

 
-$$ -C(x;\boldsymbol{\Theta})=\frac{1}{2}(a_2-y)^2, -$$ -

 
- -

with \( \boldsymbol{\Theta}=[w_1,w_2,b_1,b_2] \).

-
- -
-

Layout of a simple neural network with one hidden layer

- -

-
-

-
-

-
- -
-

The derivatives

- -

The derivatives are now, using the chain rule again

- -

 
-$$ -\frac{\partial C}{\partial w_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial w_2}=(a_2-y)\sigma_2'a_1=\delta_2a_1, -$$ -

 
- -

 
-$$ -\frac{\partial C}{\partial b_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial b_2}=(a_2-y)\sigma_2'=\delta_2, -$$ -

 
- -

 
-$$ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_2-y)\sigma_2'a_1\sigma_1'a_0, -$$ -

 
- -

 
-$$ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_2-y)\sigma_2'\sigma_1'=\delta_1. -$$ -

 
- -

Can you generalize this to more than one hidden layer?

-
- -
-

Important observations

- -
- -

-

From the above equations we see that the derivatives of the activation -functions play a central role. If they vanish, the training may -stop. This is called the vanishing gradient problem, see discussions below. If they become -large, the parameters \( w_i \) and \( b_i \) may simply go to infinity. This -is referenced as the exploding gradient problem. -

-
-
- -
-

The training

- -

The training of the parameters is done through various gradient descent approximations with

- -

 
-$$ -w_{i}\leftarrow w_{i}- \eta \delta_i a_{i-1}, -$$ -

 
- -

and

-

 
-$$ -b_i \leftarrow b_i-\eta \delta_i, -$$ -

 
- -

with \( \eta \) is the learning rate.

- -

One iteration consists of one feed forward step and one back-propagation step. Each back-propagation step does one update of the parameters \( \boldsymbol{\Theta} \).

- -

For the first hidden layer \( a_{i-1}=a_0=x \) for this simple model.

-
- -
-

Code example

- -

The code here implements the above model with one hidden layer and -scalar variables for the same function we studied in the previous -example. The code is however set up so that we can add multiple -inputs \( x \) and target values \( y \). Note also that we have the -possibility of defining a feature matrix \( \boldsymbol{X} \) with more than just -one column for the input values. This will turn useful in our next example. We have also defined matrices and vectors for all of our operations although it is not necessary here. -

- - - -
-
-
-
-
-
import numpy as np
-# We use the Sigmoid function as activation function
-def sigmoid(z):
-    return 1.0/(1.0+np.exp(-z))
-
-def forwardpropagation(x):
-    # weighted sum of inputs to the hidden layer
-    z_1 = np.matmul(x, w_1) + b_1
-    # activation in the hidden layer
-    a_1 = sigmoid(z_1)
-    # weighted sum of inputs to the output layer
-    z_2 = np.matmul(a_1, w_2) + b_2
-    a_2 = z_2
-    return a_1, a_2
-
-def backpropagation(x, y):
-    a_1, a_2 = forwardpropagation(x)
-    # parameter delta for the output layer, note that a_2=z_2 and its derivative wrt z_2 is just 1
-    delta_2 = a_2 - y
-    print(0.5*((a_2-y)**2))
-    # delta for  the hidden layer
-    delta_1 = np.matmul(delta_2, w_2.T) * a_1 * (1 - a_1)
-    # gradients for the output layer
-    output_weights_gradient = np.matmul(a_1.T, delta_2)
-    output_bias_gradient = np.sum(delta_2, axis=0)
-    # gradient for the hidden layer
-    hidden_weights_gradient = np.matmul(x.T, delta_1)
-    hidden_bias_gradient = np.sum(delta_1, axis=0)
-    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-# Input variable
-x = np.array([4.0],dtype=np.float64)
-# Target values
-y = 2*x+1.0 
-
-# Defining the neural network, only scalars here
-n_inputs = x.shape
-n_features = 1
-n_hidden_neurons = 1
-n_outputs = 1
-
-# Initialize the network
-# weights and bias in the hidden layer
-w_1 = np.random.randn(n_features, n_hidden_neurons)
-b_1 = np.zeros(n_hidden_neurons) + 0.01
-
-# weights and bias in the output layer
-w_2 = np.random.randn(n_hidden_neurons, n_outputs)
-b_2 = np.zeros(n_outputs) + 0.01
-
-eta = 0.1
-for i in range(50):
-    # calculate gradients
-    derivW2, derivB2, derivW1, derivB1 = backpropagation(x, y)
-    # update weights and biases
-    w_2 -= eta * derivW2
-    b_2 -= eta * derivB2
-    w_1 -= eta * derivW1
-    b_1 -= eta * derivB1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that after some few iterations (the results do depend on the learning rate however), we get an error which is rather small.

-
- -
-

Simple neural network and the back propagation equations

- -

Let us now try to increase our level of ambition and attempt at setting -up the equations for a neural network with two input nodes, one hidden -layer with two hidden nodes and one output layer with one output node/neuron only (see graph).. -

- -

We need to define the following parameters and variables with the input layer (layer \( (0) \)) -where we label the nodes \( x_0 \) and \( x_1 \) -

-

 
-$$ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. -$$ -

 
- -

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_0^{(1)} \) and \( a_1^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

-

 
-$$ -w_{ij}^{(1)}=\left\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\right\} \wedge b^{(1)}=\left\{b_0^{(1)},b_1^{(1)}\right\}. -$$ -

 
-

- -
-

Layout of a simple neural network with two input nodes, one hidden layer with two hidden noeds and one output node

- -

-
-

-
-

-
- -
-

The ouput layer

- -

We have the ouput layer given by layer label \( (2) \) with output \( a^{(2)} \) and weights and biases to be determined given by the variables

-

 
-$$ -w_{i}^{(2)}=\left\{w_{1}^{(2)},w_{2}^{(2)}\right\} \wedge b^{(2)}. -$$ -

 
- -

Our output is \( \tilde{y}=a^{(2)} \) and we define a generic cost function \( C(a^{(2)},y;\boldsymbol{\Theta}) \) where \( y \) is the target value (a scalar here). -The parameters we need to optimize are given by -

-

 
-$$ -\boldsymbol{\Theta}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)},w_{1}^{(2)},w_{2}^{(2)},b_1^{(1)},b_2^{(1)},b^{(2)}\right\}. -$$ -

 
-

- -
-

Compact expressions

- -

We can define the inputs to the activation functions for the various layers in terms of various matrix-vector multiplications and vector additions. -The inputs to the first hidden layer are -

-

 
-$$ -\begin{bmatrix}z_1^{(1)} \\ z_2^{(1)} \end{bmatrix}=\left(\begin{bmatrix}w_{11}^{(1)} & w_{12}^{(1)}\\ w_{21}^{(1)} &w_{22}^{(1)} \end{bmatrix}\right)^{T}\begin{bmatrix}a_1^{(0)} \\ a_2^{(0)} \end{bmatrix}+\begin{bmatrix}b_1^{(1)} \\ b_2^{(1)} \end{bmatrix}, -$$ -

 
- -

with outputs

-

 
-$$ -\begin{bmatrix}a_1^{(1)} \\ a_2^{(1)} \end{bmatrix}=\begin{bmatrix}\sigma^{(1)}(z_1^{(1)}) \\ \sigma^{(1)}(z_2^{(1)}) \end{bmatrix}. -$$ -

 
-

- -
-

Output layer

- -

For the final output layer we have the inputs to the final activation function

-

 
-$$ -z^{(2)} = w_{1}^{(2)}a_1^{(1)} +w_{2}^{(2)}a_2^{(1)}+b^{(2)}, -$$ -

 
- -

resulting in the output

-

 
-$$ -a^{(2)}=\sigma^{(2)}(z^{(2)}). -$$ -

 
-

- -
-

Explicit derivatives

- -

In total we have nine parameters which we need to train. Using the -chain rule (or just the back-propagation algorithm) we can find all -derivatives. Since we will use automatic differentiation in reverse -mode, we start with the derivatives of the cost function with respect -to the parameters of the output layer, namely -

- -

 
-$$ -\frac{\partial C}{\partial w_{i}^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial w_{i}^{(2)}}=\delta^{(2)}a_i^{(1)}, -$$ -

 
- -

with

-

 
-$$ -\delta^{(2)}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -$$ -

 
- -

and finally

-

 
-$$ -\frac{\partial C}{\partial b^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial b^{(2)}}=\delta^{(2)}. -$$ -

 
-

- -
-

Derivatives of the hidden layer

- -

Using the chain rule we have the following expressions for say one of the weight parameters (it is easy to generalize to the other weight parameters)

-

 
-$$ -\frac{\partial C}{\partial w_{11}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}= \delta^{(2)}\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}, -$$ -

 
- -

which, noting that

-

 
-$$ -z^{(2)} =w_1^{(2)}a_1^{(1)}+w_2^{(2)}a_2^{(1)}+b^{(2)}, -$$ -

 
- -

allows us to rewrite

-

 
-$$ -\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}a_1^{(1)}. -$$ -

 
-

- -
-

Final expression

-

Defining

-

 
-$$ -\delta_1^{(1)}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}\delta^{(2)}, -$$ -

 
- -

we have

-

 
-$$ -\frac{\partial C}{\partial w_{11}^{(1)}}=\delta_1^{(1)}a_1^{(1)}. -$$ -

 
- -

Similarly, we obtain

-

 
-$$ -\frac{\partial C}{\partial w_{12}^{(1)}}=\delta_1^{(1)}a_2^{(1)}. -$$ -

 
-

- -
-

Completing the list

- -

Similarly, we find

-

 
-$$ -\frac{\partial C}{\partial w_{21}^{(1)}}=\delta_2^{(1)}a_1^{(1)}, -$$ -

 
- -

and

-

 
-$$ -\frac{\partial C}{\partial w_{22}^{(1)}}=\delta_2^{(1)}a_2^{(1)}, -$$ -

 
- -

where we have defined

-

 
-$$ -\delta_2^{(1)}=w_2^{(2)}\frac{\partial a_2^{(1)}}{\partial z_2^{(1)}}\delta^{(2)}. -$$ -

 
-

- -
-

Final expressions for the biases of the hidden layer

- -

For the sake of completeness, we list the derivatives of the biases, which are

-

 
-$$ -\frac{\partial C}{\partial b_{1}^{(1)}}=\delta_1^{(1)}, -$$ -

 
- -

and

-

 
-$$ -\frac{\partial C}{\partial b_{2}^{(1)}}=\delta_2^{(1)}. -$$ -

 
- -

As we will see below, these expressions can be generalized in a more compact form.

-
- -
-

Gradient expressions

- -

For this specific model, with just one output node and two hidden -nodes, the gradient descent equations take the following form for output layer -

-

 
-$$ -w_{i}^{(2)}\leftarrow w_{i}^{(2)}- \eta \delta^{(2)} a_{i}^{(1)}, -$$ -

 
- -

and

-

 
-$$ -b^{(2)} \leftarrow b^{(2)}-\eta \delta^{(2)}, -$$ -

 
- -

and

-

 
-$$ -w_{ij}^{(1)}\leftarrow w_{ij}^{(1)}- \eta \delta_{i}^{(1)} a_{j}^{(0)}, -$$ -

 
- -

and

-

 
-$$ -b_{i}^{(1)} \leftarrow b_{i}^{(1)}-\eta \delta_{i}^{(1)}, -$$ -

 
- -

where \( \eta \) is the learning rate.

-
- -
-

Setting up the equations for a neural network

- -

The questions we want to ask are how do changes in the biases and the -weights in our network change the cost function and how can we use the -final output to modify the weights and biases? -

- -

To derive these equations let us start with a plain regression problem -and define our cost function as -

- -

 
-$$ -{\cal C}(\boldsymbol{\Theta}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2, -$$ -

 
- -

where the $y_i$s are our \( n \) targets (the values we want to -reproduce), while the outputs of the network after having propagated -all inputs \( \boldsymbol{x} \) are given by \( \boldsymbol{\tilde{y}}_i \). -

-
- -
-

Layout of a neural network with three hidden layers (last later = \( l=L=4 \), first layer \( l=0 \))

- -

-
-

-
-

-
- -
-

Definitions

- -

With our definition of the targets \( \boldsymbol{y} \), the outputs of the -network \( \boldsymbol{\tilde{y}} \) and the inputs \( \boldsymbol{x} \) we -define now the activation \( z_j^l \) of node/neuron/unit \( j \) of the -\( l \)-th layer as a function of the bias, the weights which add up from -the previous layer \( l-1 \) and the forward passes/outputs -\( \boldsymbol{a}^{l-1} \) from the previous layer as -

- -

 
-$$ -z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, -$$ -

 
- -

where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) -represents the total number of nodes/neurons/units of layer \( l-1 \). The -figure in the whiteboard notes illustrates this equation. We can rewrite this in a more -compact form as the matrix-vector products we discussed earlier, -

- -

 
-$$ -\boldsymbol{z}^l = \left(\boldsymbol{W}^l\right)^T\boldsymbol{a}^{l-1}+\boldsymbol{b}^l. -$$ -

 
-

- -
-

Inputs to the activation function

- -

With the activation values \( \boldsymbol{z}^l \) we can in turn define the -output of layer \( l \) as \( \boldsymbol{a}^l = \sigma(\boldsymbol{z}^l) \) where \( \sigma \) is our -activation function. In the examples here we will use the sigmoid -function discussed in our logistic regression lectures. We will also use the same activation function \( \sigma \) for all layers -and their nodes. It means we have -

- -

 
-$$ -a_j^l = \sigma(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. -$$ -

 
-

- -
-

Layout of input to first hidden layer \( l=1 \) from input layer \( l=0 \)

- -

-
-

-
-

-
- -
-

Derivatives and the chain rule

- -

From the definition of the input variable to the activation function, that is \( z_j^l \) we have

-

 
-$$ -\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, -$$ -

 
- -

and

-

 
-$$ -\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. -$$ -

 
- -

With our definition of the activation function we have that (note that this function depends only on \( z_j^l \))

-

 
-$$ -\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=\sigma(z_j^l)(1-\sigma(z_j^l)). -$$ -

 
-

- -
-

Derivative of the cost function

- -

With these definitions we can now compute the derivative of the cost function in terms of the weights.

- -

Let us specialize to the output layer \( l=L \). Our cost function is

-

 
-$$ -{\cal C}(\boldsymbol{\Theta}^L) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - y_i\right)^2, -$$ -

 
- -

The derivative of this function with respect to the weights is

- -

 
-$$ -\frac{\partial{\cal C}(\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)\frac{\partial a_j^L}{\partial w_{ij}^{L}}, -$$ -

 
- -

The last partial derivative can easily be computed and reads (by applying the chain rule)

-

 
-$$ -\frac{\partial a_j^L}{\partial w_{ij}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{ij}^{L}}=a_j^L(1-a_j^L)a_i^{L-1}. -$$ -

 
-

- -
-

The back propagation equations for a neural network

- -

We have thus

-

 
-$$ -\frac{\partial{\cal C}((\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)a_j^L(1-a_j^L)a_i^{L-1}, -$$ -

 
- -

Defining

-

 
-$$ -\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - y_j\right) = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -$$ -

 
- -

and using the Hadamard product of two vectors we can write this as

-

 
-$$ -\boldsymbol{\delta}^L = \sigma'(\boldsymbol{z}^L)\circ\frac{\partial {\cal C}}{\partial (\boldsymbol{a}^L)}. -$$ -

 
-

- -
-

Analyzing the last results

- -

This is an important expression. The second term on the right handside -measures how fast the cost function is changing as a function of the $j$th -output activation. If, for example, the cost function doesn't depend -much on a particular output node \( j \), then \( \delta_j^L \) will be small, -which is what we would expect. The first term on the right, measures -how fast the activation function \( f \) is changing at a given activation -value \( z_j^L \). -

-
- -
-

More considerations

- -

Notice that everything in the above equations is easily computed. In -particular, we compute \( z_j^L \) while computing the behaviour of the -network, and it is only a small additional overhead to compute -\( \sigma'(z^L_j) \). The exact form of the derivative with respect to the -output depends on the form of the cost function. -However, provided the cost function is known there should be little -trouble in calculating -

- -

 
-$$ -\frac{\partial {\cal C}}{\partial (a_j^L)} -$$ -

 
- -

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

-

 
-$$ -\frac{\partial{\cal C}}{\partial w_{ij}^L} = \delta_j^La_i^{L-1}. -$$ -

 
-

- -
-

Derivatives in terms of \( z_j^L \)

- -

It is also easy to see that our previous equation can be written as

- -

 
-$$ -\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}, -$$ -

 
- -

which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely

-

 
-$$ -\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}, -$$ -

 
- -

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.

-
- -
-

Bringing it together

- -

We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are

- -

 
-$$ -\begin{equation} -\frac{\partial{\cal C}(\boldsymbol{W^L})}{\partial w_{ij}^L} = \delta_j^La_i^{L-1}, -\tag{1} -\end{equation} -$$ -

 
- -

and

-

 
-$$ -\begin{equation} -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\tag{2} -\end{equation} -$$ -

 
- -

and

- -

 
-$$ -\begin{equation} -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}, -\tag{3} -\end{equation} -$$ -

 
-

- -
-

Final back propagating equation

- -

We have that (replacing \( L \) with a general layer \( l \))

-

 
-$$ -\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. -$$ -

 
- -

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 obtain

-

 
-$$ -\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}}, -$$ -

 
- -

and recalling that

-

 
-$$ -z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, -$$ -

 
- -

with \( M_l \) being the number of nodes in layer \( l \), we obtain

-

 
-$$ -\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -$$ -

 
- -

This is our final equation.

- -

We are now ready to set up the algorithm for back propagation and learning the weights and biases.

-
- -
-

Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

- -
-The architecture (our model) -

-

    -

  1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)
  2. -

  3. Define the number of hidden layers and hidden nodes
  4. -

  5. Define activation functions for hidden layers and output layers
  6. -

  7. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates
  8. -

  9. Define cost function and possible regularization terms with hyperparameters
  10. -

  11. Initialize weights and biases
  12. -

  13. Fix number of iterations for the feed forward part and back propagation part
  14. -
-
-
- -
-

Setting up the back propagation algorithm, part 1

- -

The four equations provide us with a way of computing the gradients of the cost function. Let us write this out in the form of an algorithm.

- -

First, we set up the input data \( \boldsymbol{x} \) and the activations -\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and -the pertinent outputs \( \boldsymbol{a}^1 \). -

- -

Secondly, we perform then the feed forward till we reach the output -layer and compute all \( \boldsymbol{z}_l \) of the input layer and compute the -activation function and the pertinent outputs \( \boldsymbol{a}^l \) for -\( l=1,2,3,\dots,L \). -

- -

Notation: The first hidden layer has \( l=1 \) as label and the final output layer has \( l=L \).

-
- -
-

Setting up the back propagation algorithm, part 2

- -

Thereafter we compute the ouput error \( \boldsymbol{\delta}^L \) by computing all

-

 
-$$ -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. -$$ -

 
- -

Then we compute the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

-

 
-$$ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). -$$ -

 
-

- -
-

Setting up the Back propagation algorithm, part 3

- -

Finally, we update the weights and the biases using gradient descent -for each \( l=L-1,L-2,\dots,1 \) (the first hidden layer) and update the weights and biases -according to the rules -

- -

 
-$$ -w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, -$$ -

 
- -

 
-$$ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -$$ -

 
- -

with \( \eta \) being the learning rate.

-
- -
-

Updating the gradients

- -

With the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

-

 
-$$ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -$$ -

 
- -

we update the weights and the biases using gradient descent for each \( l=L-1,L-2,\dots,1 \) and update the weights and biases according to the rules

-

 
-$$ -w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, -$$ -

 
- -

 
-$$ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -$$ -

 
-

- -
-

Activation functions

- -

A property that characterizes a neural network, other than its -connectivity, is the choice of activation function(s). The following -restrictions are imposed on an activation function for an FFNN to -fulfill the universal approximation theorem -

- -
    - -

  • Non-constant
  • - -

  • Bounded
  • - -

  • Monotonically-increasing
  • - -

  • Continuous
  • -
-
- -
-

Activation functions, Logistic and Hyperbolic ones

- -

The second requirement excludes all linear functions. Furthermore, in -a MLP with only linear activation functions, each layer simply -performs a linear transformation of its inputs. -

- -

Regardless of the number of layers, the output of the NN will be -nothing but a linear function of the inputs. Thus we need to introduce -some kind of non-linearity to the NN to be able to fit non-linear -functions Typical examples are the logistic Sigmoid -

- -

 
-$$ - \sigma(x) = \frac{1}{1 + e^{-x}}, -$$ -

 
- -

and the hyperbolic tangent function

-

 
-$$ - \sigma(x) = \tanh(x) -$$ -

 
-

- -
-

Relevance

- -

The sigmoid function are more biologically plausible because the -output of inactive neurons are zero. Such activation function are -called one-sided. However, it has been shown that the hyperbolic -tangent performs better than the sigmoid for training MLPs. has -become the most popular for deep neural networks -

- - - -
-
-
-
-
-
"""The sigmoid function (or the logistic curve) is a 
-function that takes any real number, z, and outputs a number (0,1).
-It is useful in neural networks for assigning weights on a relative scale.
-The value z is the weighted sum of parameters involved in the learning algorithm."""
-
-import numpy
-import matplotlib.pyplot as plt
-import math as mt
-
-z = numpy.arange(-5, 5, .1)
-sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
-sigma = sigma_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, sigma)
-ax.set_ylim([-0.1, 1.1])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sigmoid function')
-
-plt.show()
-
-"""Step Function"""
-z = numpy.arange(-5, 5, .02)
-step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
-step = step_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, step)
-ax.set_ylim([-0.5, 1.5])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('step function')
-
-plt.show()
-
-"""Sine Function"""
-z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
-t = numpy.sin(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, t)
-ax.set_ylim([-1.0, 1.0])
-ax.set_xlim([-2*mt.pi,2*mt.pi])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sine function')
-
-plt.show()
-
-"""Plots a graph of the squashing function used by a rectified linear
-unit"""
-z = numpy.arange(-2, 2, .1)
-zero = numpy.zeros(len(z))
-y = numpy.max([zero, z], axis=0)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, y)
-ax.set_ylim([-2.0, 2.0])
-ax.set_xlim([-2.0, 2.0])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('Rectified linear unit')
-
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Vanishing gradients

- -

The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. -

- -

Unfortunately for us, the gradients often get smaller and smaller as -the algorithm progresses down to the first hidden layers. As a result, -the GD update leaves the lower layer connection weights virtually -unchanged, and training never converges to a good solution. This is -known in the literature as the vanishing gradients problem. -

-
- -
-

Exploding gradients

- -

In other cases, the opposite can happen, namely the the gradients can -grow bigger and bigger. The result is that many of the layers get -large updates of the weights the algorithm diverges. This is the -exploding gradients problem, which is mostly encountered in -recurrent neural networks. More generally, deep neural networks suffer -from unstable gradients, different layers may learn at widely -different speeds -

-
- -
-

Is the Logistic activation function (Sigmoid) our choice?

- -

Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. -

- -

A paper titled Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -

-
- -
-

Logistic function as the root of problems

- -

They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -

-
- -
-

The derivative of the Logistic funtion

- -

Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. -

- -

In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -

-
- -
-

Insights from the paper by Glorot and Bengio

- -

One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -

-
- -
-

The RELU function family

- -

The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. -

- -

In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. -

-
- -
-

ELU function

- -

To solve this problem, nowadays practitioners use a variant of the -ReLU function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function -

- -

 
-$$ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -$$ -

 
-

- -
-

Which activation function should we use?

- -

In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than \( \tanh \) which in turn performs better -than the logistic function. -

- -

If runtime performance is an issue, then you may opt for the leaky -ReLU function over the ELU function If you don’t want to tweak yet -another hyperparameter, you may just use the default \( \alpha \) of -\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and -computing power, you can use cross-validation or bootstrap to evaluate -other activation functions. -

-
- -
-

More on activation functions, output layers

- -

In most cases you can use the ReLU activation function in the hidden -layers (or one of its variants). -

- -

It is a bit faster to compute than other activation functions, and the -gradient descent optimization does in general not get stuck. -

- -For the output layer: - -
    -

  • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
  • -

  • For regression tasks, you can simply use no activation function at all.
  • -
-
- -
-

Fine-tuning neural network hyperparameters

- -

The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are -interconnected), but even in a simple FFNN you can change the number -of layers, the number of neurons per layer, the type of activation -function to use in each layer, the weight initialization logic, the -stochastic gradient optmized and much more. How do you know what -combination of hyperparameters is the best for your task? -

- -
    -

  • You can use grid search with cross-validation to find the right hyperparameters.
  • -
-

-

However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. -

- -
    -

  • You can use randomized search.
  • -

  • Or use tools like Oscar, which implements more complex algorithms to help you find a good set of hyperparameters quickly.
  • -
-
- -
-

Hidden layers

- -

For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set discussed below you can easily get a -high accuracy using just one hidden layer with a few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden -layers with the same total amount of neurons, in roughly the same -amount of training time. -

- -

For more complex problems, you can gradually ramp up the number of -hidden layers, until you start overfitting the training set. Very -complex tasks, such as large image classification or speech -recognition, typically require networks with dozens of layers and they -need a huge amount of training data. However, you will rarely have to -train such networks from scratch: it is much more common to reuse -parts of a pretrained state-of-the-art network that performs a similar -task. -

-
- -
-

Batch Normalization

- -

Batch Normalization aims to address the vanishing/exploding gradients -problems, and more generally the problem that the distribution of each -layer’s inputs changes during training, as the parameters of the -previous layers change. -

- -

The technique consists of adding an operation in the model just before -the activation function of each layer, simply zero-centering and -normalizing the inputs, then scaling and shifting the result using two -new parameters per layer (one for scaling, the other for shifting). In -other words, this operation lets the model learn the optimal scale and -mean of the inputs for each layer. In order to zero-center and -normalize the inputs, the algorithm needs to estimate the inputs’ mean -and standard deviation. It does so by evaluating the mean and standard -deviation of the inputs over the current mini-batch, from this the -name batch normalization. -

-
- -
-

Dropout

- -

It is a fairly simple algorithm: at every training step, every neuron -(including the input neurons but excluding the output neurons) has a -probability \( p \) of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active -during the next step. -

- -

The hyperparameter \( p \) is called the dropout rate, and it is typically -set to 50%. After training, the neurons are not dropped anymore. It -is viewed as one of the most popular regularization techniques. -

-
- -
-

Gradient Clipping

- -

A popular technique to lessen the exploding gradients problem is to -simply clip the gradients during backpropagation so that they never -exceed some threshold (this is mostly useful for recurrent neural -networks). -

- -

This technique is called Gradient Clipping.

- -

In general however, Batch -Normalization is preferred. -

-
- -
-

A top-down perspective on Neural networks

- -

The first thing we would like to do is divide the data into two or -three parts. A training set, a validation or dev (development) set, -and a test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: -

- -
    -

  1. Estimate optimal error rate
  2. -

  3. Minimize underfitting (bias) on training data set.
  4. -

  5. Make sure you are not overfitting.
  6. -
-
- -
-

More top-down perspectives

- -

If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. -

- -

However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -

-
- -
-

Limitations of supervised learning with deep networks

- -

Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). -

-
- -
-

Limitations of NNs

- -

Here we list some of the important limitations of supervised neural network based models.

- -
    -

  • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
  • -

  • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
  • -
-
- -
-

Homogeneous data

- -
    -

  • Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
  • -
-
- -
-

More limitations

- -
    -

  • Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
  • -
-

-

Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.

-
- -
-

Setting up a Multi-layer perceptron model for classification

- -

We are now gong to develop an example based on the MNIST data -base. This is a classification problem and we need to use our -cross-entropy function we discussed in connection with logistic -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. -

- -

In binary classification with two classes \( (0, 1) \) we define the -logistic/sigmoid function as the probability that a particular input -is in class \( 0 \) or \( 1 \). This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. -

- -

For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) -is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) -represents our activation values \( z \). We have -

-

 
-$$ -P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , -$$ -

 
- -

and

-

 
-$$ -P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , -$$ -

 
- -

where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases -of our network. -

-
- -
-

Defining the cost function

- -

Our cost function is given as (see the Logistic regression lectures)

-

 
-$$ -\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . -$$ -

 
- -

This last equality means that we can interpret our cost function as a sum over the loss function -for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. -

- -

In multiclass classification it is common to treat each integer label as a so called one-hot vector:

- -

\( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

- -\( y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) , \) - -

i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset (numbers from \( 0 \) to \( 9 \))..

- -

If \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th -output vector \( \boldsymbol{y}_i \). -The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: -

- -

 
-$$ -P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , -$$ -

 
- -

which reduces to the logistic function in the binary case. -The likelihood of this \( C \)-class classifier -is now given as: -

- -

 
-$$ -P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -$$ -

 
- -

Again we take the negative log-likelihood to define our cost function:

- -

 
-$$ -\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. -$$ -

 
- -

See the logistic regression lectures for a full definition of the cost function.

- -

The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!

-
- -
-

Example: binary classification problem

- -

As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as

-

 
-$$ -\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), -$$ -

 
- -

where we had defined the logistic (sigmoid) function

-

 
-$$ -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)}}, -$$ -

 
- -

and

-

 
-$$ -p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). -$$ -

 
- -

The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

- -

Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). -We have then -

-

 
-$$ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -$$ -

 
- -

with

-

 
-$$ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -$$ -

 
- -

where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). -Our cost function at the final layer \( l=L \) is now -

-

 
-$$ -\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), -$$ -

 
- -

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

-

 
-$$ -\frac{\partial \mathcal{C}(\boldsymbol{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. -$$ -

 
- -

In case we use another activation function than the logistic one, we need to evaluate other derivatives.

-
- -
-

The Softmax function

-

In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need

-

 
-$$ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -$$ -

 
- -

For the Softmax function we have

-

 
-$$ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -$$ -

 
- -

Its derivative with respect to \( z_j^l \) gives

-

 
-$$ -\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), -$$ -

 
- -

which in case of the simply binary model reduces to having \( i=j \).

-
- -
-

Developing a code for doing neural networks with back propagation

- -

One can identify a set of key steps when using neural networks to solve supervised learning problems:

- -
    -

  1. Collect and pre-process data
  2. - -

  3. Define model and architecture
  4. - -

  5. Choose cost function and optimizer
  6. - -

  7. Train the model
  8. - -

  9. Evaluate model performance on test data
  10. - -

  11. Adjust hyperparameters (if necessary, network architecture)
  12. -
-
- -
-

Collect and pre-process data

- -

Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

- -

To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

- -

As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

- -

 
-$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

 
-

- -

and the targets would be:

- -

 
-$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ -

 

- -

Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

- - - -
-
-
-
-
-
# import necessary packages
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn import datasets
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-
-# display images in notebook
-%matplotlib inline
-plt.rcParams['figure.figsize'] = (12,12)
-
-
-# download MNIST dataset
-digits = datasets.load_digits()
-
-# define inputs and labels
-inputs = digits.images
-labels = digits.target
-
-print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
-print("labels = (n_inputs) = " + str(labels.shape))
-
-
-# flatten the image
-# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
-n_inputs = len(inputs)
-inputs = inputs.reshape(n_inputs, -1)
-print("X = (n_inputs, n_features) = " + str(inputs.shape))
-
-
-# choose some random images to display
-indices = np.arange(n_inputs)
-random_indices = np.random.choice(indices, size=5)
-
-for i, image in enumerate(digits.images[random_indices]):
-    plt.subplot(1, 5, i+1)
-    plt.axis('off')
-    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
-    plt.title("Label: %d" % digits.target[random_indices[i]])
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Train and test datasets

- -

Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

- -

We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

- -

It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

- - - -
-
-
-
-
-
from sklearn.model_selection import train_test_split
-
-# one-liner from scikit-learn library
-train_size = 0.8
-test_size = 1 - train_size
-X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
-                                                    test_size=test_size)
-
-# equivalently in numpy
-def train_test_split_numpy(inputs, labels, train_size, test_size):
-    n_inputs = len(inputs)
-    inputs_shuffled = inputs.copy()
-    labels_shuffled = labels.copy()
-    
-    np.random.shuffle(inputs_shuffled)
-    np.random.shuffle(labels_shuffled)
-    
-    train_end = int(n_inputs*train_size)
-    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
-    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
-    
-    return X_train, X_test, Y_train, Y_test
-
-#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
-
-print("Number of training images: " + str(len(X_train)))
-print("Number of test images: " + str(len(X_test)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Define model and architecture

- -

Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

- -

 
-$$ z = \sum_{i=1}^n w_i a_i ,$$ -

 

- -

 
-$$ y = f(z) ,$$ -

 

- -

where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

- -

The simplest activation function for a neuron is the Heaviside function:

- -

 
-$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

 
-

- -

A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

- -

However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

- -

Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

- -

 
-$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$ -

 

- -

which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

-
- -
-

Layers

- -
    -

  • Input
  • -
-

-

Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

- -
    -

  • Hidden layer
  • -
-

-

We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

- -
    -

  • Output
  • -
-

-

If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

- -

For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

- -

Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

- -

 
-$$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

 
-

- -

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. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

- -

 
-$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ -

 

- -

Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. -

-
- -
-

Weights and biases

- -

Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. -

- -

Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

- -

 
-$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ -

 

- -

The bias weights \( \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.

- - -
-
-
-
-
-
# building our neural network
-
-n_inputs, n_features = X_train.shape
-n_hidden_neurons = 50
-n_categories = 10
-
-# we make the weights normally distributed using numpy.random.randn
-
-# weights and bias in the hidden layer
-hidden_weights = np.random.randn(n_features, n_hidden_neurons)
-hidden_bias = np.zeros(n_hidden_neurons) + 0.01
-
-# weights and bias in the output layer
-output_weights = np.random.randn(n_hidden_neurons, n_categories)
-output_bias = np.zeros(n_categories) + 0.01
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Feed-forward pass

- -

Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

- -

 
-$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ -

 

- -

this is then passed through our activation function

- -

 
-$$ a_{j}^{l} = f(z_{j}^{l}) .$$ -

 

- -

We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

- -

 
-$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ -

 

- -

Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

- -

 
-$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

 
-

-
- -
-

Matrix multiplications

- -

Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden -layer have the dimensions -\( W_{hidden} = (n_{features}, n_{hidden}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

- -

 
-$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ -

 

- -

and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

- -

 
-$$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$ -

 

- -

meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

- -

 
-$$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$ -

 

- -

This is fed to the output layer:

- -

 
-$$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$ -

 

- -

Finally we receive our output values for each image and each category by passing it through the softmax function:

- -

 
-$$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$ -

 

- - - -
-
-
-
-
-
# setup the feed-forward pass, subscript h = hidden layer
-
-def sigmoid(x):
-    return 1/(1 + np.exp(-x))
-
-def feed_forward(X):
-    # weighted sum of inputs to the hidden layer
-    z_h = np.matmul(X, hidden_weights) + hidden_bias
-    # activation in the hidden layer
-    a_h = sigmoid(z_h)
-    
-    # weighted sum of inputs to the output layer
-    z_o = np.matmul(a_h, output_weights) + output_bias
-    # softmax output
-    # axis 0 holds each input and axis 1 the probabilities of each category
-    exp_term = np.exp(z_o)
-    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-    
-    return probabilities
-
-probabilities = feed_forward(X_train)
-print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
-print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
-print("probabilities sum up to: " + str(probabilities[0].sum()))
-print()
-
-# we obtain a prediction by taking the class with the highest likelihood
-def predict(X):
-    probabilities = feed_forward(X)
-    return np.argmax(probabilities, axis=1)
-
-predictions = predict(X_train)
-print("predictions = (n_inputs) = " + str(predictions.shape))
-print("prediction for image 0: " + str(predictions[0]))
-print("correct label for image 0: " + str(Y_train[0]))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Choose cost function and optimizer

- -

To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

- -

In multiclass classification it is common to treat each integer label as a so called one-hot vector:

- -

 
-$$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ -

 

- -

 
-$$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ -

 

- -

i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

- -

Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

- -

In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category \( c' \) -(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. -

-
- -
-

Optimizing the cost function

- -

The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

- -

 
-$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ -

 

- -

where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

- -

A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

- -

 
-$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

 
-

- -

i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

- -

This has two important benefits:

-
    -

  1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
  2. - -

  3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
  4. -
-

-

The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

-
- -
-

Regularization

- -

It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

- -

We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

- -

 
-$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

 
-

- -

i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

- -

In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has \( (64 + 1)\times 50=3250 \) weights in -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -layer (\( +1 \) for the bias), and the gradient must be calculated for -every parameter. We use the backpropagation algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. -

-
- -
-

Matrix multiplication

- -

To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

- -

 
-$$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ -

 

- -

The gradient for the output weights is calculated as

- -

 
-$$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ -

 

- -

where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

- -

The gradient with respect to the output bias is then

- -

 
-$$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ -

 

- -

The error in the hidden layer is

- -

 
-$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ -

 

- -

where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

- -

This again gives us the gradients in the hidden layer:

- -

 
-$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ -

 

- -

 
-$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ -

 

- - - -
-
-
-
-
-
# to categorical turns our integer vector into a onehot representation
-from sklearn.metrics import accuracy_score
-
-# one-hot in numpy
-def to_categorical_numpy(integer_vector):
-    n_inputs = len(integer_vector)
-    n_categories = np.max(integer_vector) + 1
-    onehot_vector = np.zeros((n_inputs, n_categories))
-    onehot_vector[range(n_inputs), integer_vector] = 1
-    
-    return onehot_vector
-
-#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
-Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
-
-def feed_forward_train(X):
-    # weighted sum of inputs to the hidden layer
-    z_h = np.matmul(X, hidden_weights) + hidden_bias
-    # activation in the hidden layer
-    a_h = sigmoid(z_h)
-    
-    # weighted sum of inputs to the output layer
-    z_o = np.matmul(a_h, output_weights) + output_bias
-    # softmax output
-    # axis 0 holds each input and axis 1 the probabilities of each category
-    exp_term = np.exp(z_o)
-    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-    
-    # for backpropagation need activations in hidden and output layers
-    return a_h, probabilities
-
-def backpropagation(X, Y):
-    a_h, probabilities = feed_forward_train(X)
-    
-    # error in the output layer
-    error_output = probabilities - Y
-    # error in the hidden layer
-    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
-    
-    # gradients for the output layer
-    output_weights_gradient = np.matmul(a_h.T, error_output)
-    output_bias_gradient = np.sum(error_output, axis=0)
-    
-    # gradient for the hidden layer
-    hidden_weights_gradient = np.matmul(X.T, error_hidden)
-    hidden_bias_gradient = np.sum(error_hidden, axis=0)
-
-    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
-
-print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
-
-eta = 0.01
-lmbd = 0.01
-for i in range(1000):
-    # calculate gradients
-    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
-    
-    # regularization term gradients
-    dWo += lmbd * output_weights
-    dWh += lmbd * hidden_weights
-    
-    # update weights and biases
-    output_weights -= eta * dWo
-    output_bias -= eta * dBo
-    hidden_weights -= eta * dWh
-    hidden_bias -= eta * dBh
-
-print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Improving performance

- -

As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. -

- -

The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

- -

Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

- -

If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. -

-
- -
-

Full object-oriented implementation

- -

It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. -

- - - -
-
-
-
-
-
class NeuralNetwork:
-    def __init__(
-            self,
-            X_data,
-            Y_data,
-            n_hidden_neurons=50,
-            n_categories=10,
-            epochs=10,
-            batch_size=100,
-            eta=0.1,
-            lmbd=0.0):
-
-        self.X_data_full = X_data
-        self.Y_data_full = Y_data
-
-        self.n_inputs = X_data.shape[0]
-        self.n_features = X_data.shape[1]
-        self.n_hidden_neurons = n_hidden_neurons
-        self.n_categories = n_categories
-
-        self.epochs = epochs
-        self.batch_size = batch_size
-        self.iterations = self.n_inputs // self.batch_size
-        self.eta = eta
-        self.lmbd = lmbd
-
-        self.create_biases_and_weights()
-
-    def create_biases_and_weights(self):
-        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
-        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
-
-        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
-        self.output_bias = np.zeros(self.n_categories) + 0.01
-
-    def feed_forward(self):
-        # feed-forward for training
-        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
-        self.a_h = sigmoid(self.z_h)
-
-        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
-
-        exp_term = np.exp(self.z_o)
-        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-
-    def feed_forward_out(self, X):
-        # feed-forward for output
-        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
-        a_h = sigmoid(z_h)
-
-        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
-        
-        exp_term = np.exp(z_o)
-        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-        return probabilities
-
-    def backpropagation(self):
-        error_output = self.probabilities - self.Y_data
-        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
-
-        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
-        self.output_bias_gradient = np.sum(error_output, axis=0)
-
-        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
-        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
-
-        if self.lmbd > 0.0:
-            self.output_weights_gradient += self.lmbd * self.output_weights
-            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
-
-        self.output_weights -= self.eta * self.output_weights_gradient
-        self.output_bias -= self.eta * self.output_bias_gradient
-        self.hidden_weights -= self.eta * self.hidden_weights_gradient
-        self.hidden_bias -= self.eta * self.hidden_bias_gradient
-
-    def predict(self, X):
-        probabilities = self.feed_forward_out(X)
-        return np.argmax(probabilities, axis=1)
-
-    def predict_probabilities(self, X):
-        probabilities = self.feed_forward_out(X)
-        return probabilities
-
-    def train(self):
-        data_indices = np.arange(self.n_inputs)
-
-        for i in range(self.epochs):
-            for j in range(self.iterations):
-                # pick datapoints with replacement
-                chosen_datapoints = np.random.choice(
-                    data_indices, size=self.batch_size, replace=False
-                )
-
-                # minibatch training data
-                self.X_data = self.X_data_full[chosen_datapoints]
-                self.Y_data = self.Y_data_full[chosen_datapoints]
-
-                self.feed_forward()
-                self.backpropagation()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Evaluate model performance on test data

- -

To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the accuracy score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). -

- -

 
-$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ -

 

- -

where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

- - - -
-
-
-
-
-
epochs = 100
-batch_size = 100
-
-dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
-                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
-dnn.train()
-test_predict = dnn.predict(X_test)
-
-# accuracy score from scikit library
-print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
-
-# equivalent in numpy
-def accuracy_score_numpy(Y_test, Y_pred):
-    return np.sum(Y_test == Y_pred) / len(Y_test)
-
-#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Adjust hyperparameters

- -

We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

- - - -
-
-
-
-
-
eta_vals = np.logspace(-5, 1, 7)
-lmbd_vals = np.logspace(-5, 1, 7)
-# store the models for later use
-DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-
-# grid search
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
-                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
-        dnn.train()
-        
-        DNN_numpy[i][j] = dnn
-        
-        test_predict = dnn.predict(X_test)
-        
-        print("Learning rate  = ", eta)
-        print("Lambda = ", lmbd)
-        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Visualization

- - - -
-
-
-
-
-
# visual representation of grid search
-# uses seaborn heatmap, you can also do this with matplotlib imshow
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        dnn = DNN_numpy[i][j]
-        
-        train_pred = dnn.predict(X_train) 
-        test_pred = dnn.predict(X_test)
-
-        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
-        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

scikit-learn implementation

- -

scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

- -

scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

- - - -
-
-
-
-
-
from sklearn.neural_network import MLPClassifier
-# store models for later use
-DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
-                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
-        dnn.fit(X_train, Y_train)
-        
-        DNN_scikit[i][j] = dnn
-        
-        print("Learning rate  = ", eta)
-        print("Lambda = ", lmbd)
-        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Visualization

- - -
-
-
-
-
-
# optional
-# visual representation of grid search
-# uses seaborn heatmap, could probably do this in matplotlib
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        dnn = DNN_scikit[i][j]
-        
-        train_pred = dnn.predict(X_train) 
-        test_pred = dnn.predict(X_test)
-
-        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
-        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Building neural networks in Tensorflow and Keras

- -

Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. -

- -

In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. -

-
- -
-

Tensorflow

- -

Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. -

- -

Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. -

- -

Tensorflow uses so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow graph -to represent your model, and then create a Tensorflow session to run the graph. -

- -

In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. -

- -

To install tensorflow on Unix/Linux systems, use pip as

- - -
-
-
-
-
-
pip3 install tensorflow
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

and/or if you use anaconda, just write (or install from the graphical user interface) -(current release of CPU-only TensorFlow) -

- - -
-
-
-
-
-
conda create -n tf tensorflow
-conda activate tf
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

To install the current release of GPU TensorFlow

- - -
-
-
-
-
-
conda create -n tf-gpu tensorflow-gpu
-conda activate tf-gpu
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Using Keras

- -

Keras is a high level neural network -that supports Tensorflow, CTNK and Theano as backends. -If you have Anaconda installed you may run the following command -

- - -
-
-
-
-
-
conda install keras
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

You can look up the instructions here for more information.

- -

We will to a large extent use keras in this course.

-
- -
-

Collect and pre-process data

- -

Let us look again at the MINST data set.

- - - -
-
-
-
-
-
# import necessary packages
-import numpy as np
-import matplotlib.pyplot as plt
-import tensorflow as tf
-from sklearn import datasets
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-
-# display images in notebook
-%matplotlib inline
-plt.rcParams['figure.figsize'] = (12,12)
-
-
-# download MNIST dataset
-digits = datasets.load_digits()
-
-# define inputs and labels
-inputs = digits.images
-labels = digits.target
-
-print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
-print("labels = (n_inputs) = " + str(labels.shape))
-
-
-# flatten the image
-# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
-n_inputs = len(inputs)
-inputs = inputs.reshape(n_inputs, -1)
-print("X = (n_inputs, n_features) = " + str(inputs.shape))
-
-
-# choose some random images to display
-indices = np.arange(n_inputs)
-random_indices = np.random.choice(indices, size=5)
-
-for i, image in enumerate(digits.images[random_indices]):
-    plt.subplot(1, 5, i+1)
-    plt.axis('off')
-    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
-    plt.title("Label: %d" % digits.target[random_indices[i]])
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
-from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
-from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
-from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
-from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
-
-from sklearn.model_selection import train_test_split
-
-# one-hot representation of labels
-labels = to_categorical(labels)
-
-# split into train and test data
-train_size = 0.8
-test_size = 1 - train_size
-X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
-                                                    test_size=test_size)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
epochs = 100
-batch_size = 100
-n_neurons_layer1 = 100
-n_neurons_layer2 = 50
-n_categories = 10
-eta_vals = np.logspace(-5, 1, 7)
-lmbd_vals = np.logspace(-5, 1, 7)
-def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
-    model = Sequential()
-    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
-    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
-    model.add(Dense(n_categories, activation='softmax'))
-    
-    sgd = optimizers.SGD(lr=eta)
-    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
-    
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-        
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
-                                         eta=eta, lmbd=lmbd)
-        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
-        scores = DNN.evaluate(X_test, Y_test)
-        
-        DNN_keras[i][j] = DNN
-        
-        print("Learning rate = ", eta)
-        print("Lambda = ", lmbd)
-        print("Test accuracy: %.3f" % scores[1])
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
# optional
-# visual representation of grid search
-# uses seaborn heatmap, could probably do this in matplotlib
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        DNN = DNN_keras[i][j]
-
-        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
-        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

The Breast Cancer Data, now with Keras

- - - -
-
-
-
-
-
import tensorflow as tf
-from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
-from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
-from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
-from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
-from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
-import numpy as np
-import matplotlib.pyplot as plt
-import seaborn as sns
-from sklearn.model_selection import train_test_split as splitter
-from sklearn.datasets import load_breast_cancer
-import pickle
-import os 
-
-
-"""Load breast cancer dataset"""
-
-np.random.seed(0)        #create same seed for random number every time
-
-cancer=load_breast_cancer()      #Download breast cancer dataset
-
-inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
-outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
-labels=cancer.feature_names[0:30]
-
-print('The content of the breast cancer dataset is:')      #Print information about the datasets
-print(labels)
-print('-------------------------')
-print("inputs =  " + str(inputs.shape))
-print("outputs =  " + str(outputs.shape))
-print("labels =  "+ str(labels.shape))
-
-x=inputs      #Reassign the Feature and Label matrices to other variables
-y=outputs
-
-#%% 
-
-# Visualisation of dataset (for correlation analysis)
-
-plt.figure()
-plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean radius',fontweight='bold')
-plt.ylabel('Mean perimeter',fontweight='bold')
-plt.show()
-
-plt.figure()
-plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
-plt.xlabel('Mean compactness',fontweight='bold')
-plt.ylabel('Mean concavity',fontweight='bold')
-plt.show()
-
-
-plt.figure()
-plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean radius',fontweight='bold')
-plt.ylabel('Mean texture',fontweight='bold')
-plt.show()
-
-plt.figure()
-plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean perimeter',fontweight='bold')
-plt.ylabel('Mean compactness',fontweight='bold')
-plt.show()
-
-
-# Generate training and testing datasets
-
-#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
-#and add to input matrix
-
-temp1=np.reshape(x[:,1],(len(x[:,1]),1))
-temp2=np.reshape(x[:,2],(len(x[:,2]),1))
-X=np.hstack((temp1,temp2))      
-temp=np.reshape(x[:,5],(len(x[:,5]),1))
-X=np.hstack((X,temp))       
-temp=np.reshape(x[:,8],(len(x[:,8]),1))
-X=np.hstack((X,temp))       
-
-X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
-
-y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
-y_test=to_categorical(y_test)
-
-del temp1,temp2,temp
-
-# %%
-
-# Define tunable parameters"
-
-eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
-lamda=0.01                                  #Define hyperparameter
-n_layers=2                                  #Define number of hidden layers in the model
-n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
-epochs=100                                   #Number of reiterations over the input data
-batch_size=100                              #Number of samples per gradient update
-
-# %%
-
-"""Define function to return Deep Neural Network model"""
-
-def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
-    model=Sequential()      
-    for i in range(n_layers):       #Run loop to add hidden layers to the model
-        if (i==0):                  #First layer requires input dimensions
-            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
-        else:                       #Subsequent layers are capable of automatic shape inferencing
-            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
-    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
-    sgd=optimizers.SGD(lr=eta)
-    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
-    return model
-
-    
-Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
-Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
-
-for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
-    for j in range(len(eta)):      #accuracy scores 
-        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
-        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
-        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
-        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
-               
-
-def plot_data(x,y,data,title=None):
-
-    # plot results
-    fontsize=16
-
-
-    fig = plt.figure()
-    ax = fig.add_subplot(111)
-    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
-    
-    cbar=fig.colorbar(cax)
-    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
-    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
-    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
-
-    # put text on matrix elements
-    for i, x_val in enumerate(np.arange(len(x))):
-        for j, y_val in enumerate(np.arange(len(y))):
-            c = "${0:.1f}\\%$".format( 100*data[j,i])  
-            ax.text(x_val, y_val, c, va='center', ha='center')
-
-    # convert axis vaues to to string labels
-    x=[str(i) for i in x]
-    y=[str(i) for i in y]
-
-
-    ax.set_xticklabels(['']+x)
-    ax.set_yticklabels(['']+y)
-
-    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
-    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
-    if title is not None:
-        ax.set_title(title)
-
-    plt.tight_layout()
-
-    plt.show()
-    
-plot_data(eta,n_neuron,Train_accuracy, 'training')
-plot_data(eta,n_neuron,Test_accuracy, 'testing')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Building a neural network code

- -

Here we present a flexible object oriented codebase -for a feed forward neural network, along with a demonstration of how -to use it. Before we get into the details of the neural network, we -will first present some implementations of various schedulers, cost -functions and activation functions that can be used together with the -neural network. -

- -

The codes here were developed by Eric Reber and Gregor Kajda during spring 2023.

-

Learning rate methods

- -

The code below shows object oriented implementations of the Constant, -Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All -of the classes belong to the shared abstract Scheduler class, and -share the update_change() and reset() methods allowing for any of the -schedulers to be seamlessly used during the training stage, as will -later be shown in the fit() method of the neural -network. Update_change() only has one parameter, the gradient -(\( δ^l_ja^{l−1}_k \)), and returns the change which will be subtracted -from the weights. The reset() function takes no parameters, and resets -the desired variables. For Constant and Momentum, reset does nothing. -

- - - -
-
-
-
-
-
import autograd.numpy as np
-
-class Scheduler:
-    """
-    Abstract class for Schedulers
-    """
-
-    def __init__(self, eta):
-        self.eta = eta
-
-    # should be overwritten
-    def update_change(self, gradient):
-        raise NotImplementedError
-
-    # overwritten if needed
-    def reset(self):
-        pass
-
-
-class Constant(Scheduler):
-    def __init__(self, eta):
-        super().__init__(eta)
-
-    def update_change(self, gradient):
-        return self.eta * gradient
-    
-    def reset(self):
-        pass
-
-
-class Momentum(Scheduler):
-    def __init__(self, eta: float, momentum: float):
-        super().__init__(eta)
-        self.momentum = momentum
-        self.change = 0
-
-    def update_change(self, gradient):
-        self.change = self.momentum * self.change + self.eta * gradient
-        return self.change
-
-    def reset(self):
-        pass
-
-
-class Adagrad(Scheduler):
-    def __init__(self, eta):
-        super().__init__(eta)
-        self.G_t = None
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        if self.G_t is None:
-            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
-
-        self.G_t += gradient @ gradient.T
-
-        G_t_inverse = 1 / (
-            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
-        )
-        return self.eta * gradient * G_t_inverse
-
-    def reset(self):
-        self.G_t = None
-
-
-class AdagradMomentum(Scheduler):
-    def __init__(self, eta, momentum):
-        super().__init__(eta)
-        self.G_t = None
-        self.momentum = momentum
-        self.change = 0
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        if self.G_t is None:
-            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
-
-        self.G_t += gradient @ gradient.T
-
-        G_t_inverse = 1 / (
-            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
-        )
-        self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse
-        return self.change
-
-    def reset(self):
-        self.G_t = None
-
-
-class RMS_prop(Scheduler):
-    def __init__(self, eta, rho):
-        super().__init__(eta)
-        self.rho = rho
-        self.second = 0.0
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-        self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient
-        return self.eta * gradient / (np.sqrt(self.second + delta))
-
-    def reset(self):
-        self.second = 0.0
-
-
-class Adam(Scheduler):
-    def __init__(self, eta, rho, rho2):
-        super().__init__(eta)
-        self.rho = rho
-        self.rho2 = rho2
-        self.moment = 0
-        self.second = 0
-        self.n_epochs = 1
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        self.moment = self.rho * self.moment + (1 - self.rho) * gradient
-        self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient
-
-        moment_corrected = self.moment / (1 - self.rho**self.n_epochs)
-        second_corrected = self.second / (1 - self.rho2**self.n_epochs)
-
-        return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))
-
-    def reset(self):
-        self.n_epochs += 1
-        self.moment = 0
-        self.second = 0
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Usage of the above learning rate schedulers

- -

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. -

- - - -
-
-
-
-
-
momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)
-adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Here is a small example for how a segment of code using schedulers -could look. Switching out the schedulers is simple. -

- - - -
-
-
-
-
-
weights = np.ones((3,3))
-print(f"Before scheduler:\n{weights=}")
-
-epochs = 10
-for e in range(epochs):
-    gradient = np.random.rand(3, 3)
-    change = adam_scheduler.update_change(gradient)
-    weights = weights - change
-    adam_scheduler.reset()
-
-print(f"\nAfter scheduler:\n{weights=}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Cost functions

- -

Here we discuss cost functions that can be used when creating the -neural network. Every cost function takes the target vector as its -parameter, and returns a function valued only at \( x \) such that it may -easily be differentiated. -

- - - -
-
-
-
-
-
import autograd.numpy as np
-
-def CostOLS(target):
-    
-    def func(X):
-        return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)
-
-    return func
-
-
-def CostLogReg(target):
-
-    def func(X):
-        
-        return -(1.0 / target.shape[0]) * np.sum(
-            (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))
-        )
-
-    return func
-
-
-def CostCrossEntropy(target):
-    
-    def func(X):
-        return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))
-
-    return func
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Below we give a short example of how these cost function may be used -to obtain results if you wish to test them out on your own using -AutoGrad's automatics differentiation. -

- - - -
-
-
-
-
-
from autograd import grad
-
-target = np.array([[1, 2, 3]]).T
-a = np.array([[4, 5, 6]]).T
-
-cost_func = CostCrossEntropy
-cost_func_derivative = grad(cost_func(target))
-
-valued_at_a = cost_func_derivative(a)
-print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Activation functions

- -

Finally, before we look at the neural network, we will look at the -activation functions which can be specified between the hidden layers -and as the output function. Each function can be valued for any given -vector or matrix X, and can be differentiated via derivate(). -

- - - -
-
-
-
-
-
import autograd.numpy as np
-from autograd import elementwise_grad
-
-def identity(X):
-    return X
-
-
-def sigmoid(X):
-    try:
-        return 1.0 / (1 + np.exp(-X))
-    except FloatingPointError:
-        return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))
-
-
-def softmax(X):
-    X = X - np.max(X, axis=-1, keepdims=True)
-    delta = 10e-10
-    return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)
-
-
-def RELU(X):
-    return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))
-
-
-def LRELU(X):
-    delta = 10e-4
-    return np.where(X > np.zeros(X.shape), X, delta * X)
-
-
-def derivate(func):
-    if func.__name__ == "RELU":
-
-        def func(X):
-            return np.where(X > 0, 1, 0)
-
-        return func
-
-    elif func.__name__ == "LRELU":
-
-        def func(X):
-            delta = 10e-4
-            return np.where(X > 0, 1, delta)
-
-        return func
-
-    else:
-        return elementwise_grad(func)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Below follows a short demonstration of how to use an activation -function. The derivative of the activation function will be important -when calculating the output delta term during backpropagation. Note -that derivate() can also be used for cost functions for a more -generalized approach. -

- - - -
-
-
-
-
-
z = np.array([[4, 5, 6]]).T
-print(f"Input to activation function:\n{z}")
-
-act_func = sigmoid
-a = act_func(z)
-print(f"\nOutput from {act_func.__name__} activation function:\n{a}")
-
-act_func_derivative = derivate(act_func)
-valued_at_z = act_func_derivative(a)
-print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

The Neural Network

- -

Now that we have gotten a good understanding of the implementation of -some important components, we can take a look at an object oriented -implementation of a feed forward neural network. The feed forward -neural network has been implemented as a class named FFNN, which can -be initiated as a regressor or classifier dependant on the choice of -cost function. The FFNN can have any number of input nodes, hidden -layers with any amount of hidden nodes, and any amount of output nodes -meaning it can perform multiclass classification as well as binary -classification and regression problems. Although there is a lot of -code present, it makes for an easy to use and generalizeable interface -for creating many types of neural networks as will be demonstrated -below. -

- - - -
-
-
-
-
-
import math
-import autograd.numpy as np
-import sys
-import warnings
-from autograd import grad, elementwise_grad
-from random import random, seed
-from copy import deepcopy, copy
-from typing import Tuple, Callable
-from sklearn.utils import resample
-
-warnings.simplefilter("error")
-
-
-class FFNN:
-    """
-    Description:
-    ------------
-        Feed Forward Neural Network with interface enabling flexible design of a
-        nerual networks architecture and the specification of activation function
-        in the hidden layers and output layer respectively. This model can be used
-        for both regression and classification problems, depending on the output function.
-
-    Attributes:
-    ------------
-        I   dimensions (tuple[int]): A list of positive integers, which specifies the
-            number of nodes in each of the networks layers. The first integer in the array
-            defines the number of nodes in the input layer, the second integer defines number
-            of nodes in the first hidden layer and so on until the last number, which
-            specifies the number of nodes in the output layer.
-        II  hidden_func (Callable): The activation function for the hidden layers
-        III output_func (Callable): The activation function for the output layer
-        IV  cost_func (Callable): Our cost function
-        V   seed (int): Sets random seed, makes results reproducible
-    """
-
-    def __init__(
-        self,
-        dimensions: tuple[int],
-        hidden_func: Callable = sigmoid,
-        output_func: Callable = lambda x: x,
-        cost_func: Callable = CostOLS,
-        seed: int = None,
-    ):
-        self.dimensions = dimensions
-        self.hidden_func = hidden_func
-        self.output_func = output_func
-        self.cost_func = cost_func
-        self.seed = seed
-        self.weights = list()
-        self.schedulers_weight = list()
-        self.schedulers_bias = list()
-        self.a_matrices = list()
-        self.z_matrices = list()
-        self.classification = None
-
-        self.reset_weights()
-        self._set_classification()
-
-    def fit(
-        self,
-        X: np.ndarray,
-        t: np.ndarray,
-        scheduler: Scheduler,
-        batches: int = 1,
-        epochs: int = 100,
-        lam: float = 0,
-        X_val: np.ndarray = None,
-        t_val: np.ndarray = None,
-    ):
-        """
-        Description:
-        ------------
-            This function performs the training the neural network by performing the feedforward and backpropagation
-            algorithm to update the networks weights.
-
-        Parameters:
-        ------------
-            I    X (np.ndarray) : training data
-            II   t (np.ndarray) : target data
-            III  scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)
-            IV   scheduler_args (list[int]) : list of all arguments necessary for scheduler
-
-        Optional Parameters:
-        ------------
-            V    batches (int) : number of batches the datasets are split into, default equal to 1
-            VI   epochs (int) : number of iterations used to train the network, default equal to 100
-            VII  lam (float) : regularization hyperparameter lambda
-            VIII X_val (np.ndarray) : validation set
-            IX   t_val (np.ndarray) : validation target set
-
-        Returns:
-        ------------
-            I   scores (dict) : A dictionary containing the performance metrics of the model.
-                The number of the metrics depends on the parameters passed to the fit-function.
-
-        """
-
-        # setup 
-        if self.seed is not None:
-            np.random.seed(self.seed)
-
-        val_set = False
-        if X_val is not None and t_val is not None:
-            val_set = True
-
-        # creating arrays for score metrics
-        train_errors = np.empty(epochs)
-        train_errors.fill(np.nan)
-        val_errors = np.empty(epochs)
-        val_errors.fill(np.nan)
-
-        train_accs = np.empty(epochs)
-        train_accs.fill(np.nan)
-        val_accs = np.empty(epochs)
-        val_accs.fill(np.nan)
-
-        self.schedulers_weight = list()
-        self.schedulers_bias = list()
-
-        batch_size = X.shape[0] // batches
-
-        X, t = resample(X, t)
-
-        # this function returns a function valued only at X
-        cost_function_train = self.cost_func(t)
-        if val_set:
-            cost_function_val = self.cost_func(t_val)
-
-        # create schedulers for each weight matrix
-        for i in range(len(self.weights)):
-            self.schedulers_weight.append(copy(scheduler))
-            self.schedulers_bias.append(copy(scheduler))
-
-        print(f"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}")
-
-        try:
-            for e in range(epochs):
-                for i in range(batches):
-                    # allows for minibatch gradient descent
-                    if i == batches - 1:
-                        # If the for loop has reached the last batch, take all thats left
-                        X_batch = X[i * batch_size :, :]
-                        t_batch = t[i * batch_size :, :]
-                    else:
-                        X_batch = X[i * batch_size : (i + 1) * batch_size, :]
-                        t_batch = t[i * batch_size : (i + 1) * batch_size, :]
-
-                    self._feedforward(X_batch)
-                    self._backpropagate(X_batch, t_batch, lam)
-
-                # reset schedulers for each epoch (some schedulers pass in this call)
-                for scheduler in self.schedulers_weight:
-                    scheduler.reset()
-
-                for scheduler in self.schedulers_bias:
-                    scheduler.reset()
-
-                # computing performance metrics
-                pred_train = self.predict(X)
-                train_error = cost_function_train(pred_train)
-
-                train_errors[e] = train_error
-                if val_set:
-                    
-                    pred_val = self.predict(X_val)
-                    val_error = cost_function_val(pred_val)
-                    val_errors[e] = val_error
-
-                if self.classification:
-                    train_acc = self._accuracy(self.predict(X), t)
-                    train_accs[e] = train_acc
-                    if val_set:
-                        val_acc = self._accuracy(pred_val, t_val)
-                        val_accs[e] = val_acc
-
-                # printing progress bar
-                progression = e / epochs
-                print_length = self._progress_bar(
-                    progression,
-                    train_error=train_errors[e],
-                    train_acc=train_accs[e],
-                    val_error=val_errors[e],
-                    val_acc=val_accs[e],
-                )
-        except KeyboardInterrupt:
-            # allows for stopping training at any point and seeing the result
-            pass
-
-        # visualization of training progression (similiar to tensorflow progression bar)
-        sys.stdout.write("\r" + " " * print_length)
-        sys.stdout.flush()
-        self._progress_bar(
-            1,
-            train_error=train_errors[e],
-            train_acc=train_accs[e],
-            val_error=val_errors[e],
-            val_acc=val_accs[e],
-        )
-        sys.stdout.write("")
-
-        # return performance metrics for the entire run
-        scores = dict()
-
-        scores["train_errors"] = train_errors
-
-        if val_set:
-            scores["val_errors"] = val_errors
-
-        if self.classification:
-            scores["train_accs"] = train_accs
-
-            if val_set:
-                scores["val_accs"] = val_accs
-
-        return scores
-
-    def predict(self, X: np.ndarray, *, threshold=0.5):
-        """
-         Description:
-         ------------
-             Performs prediction after training of the network has been finished.
-
-         Parameters:
-        ------------
-             I   X (np.ndarray): The design matrix, with n rows of p features each
-
-         Optional Parameters:
-         ------------
-             II  threshold (float) : sets minimal value for a prediction to be predicted as the positive class
-                 in classification problems
-
-         Returns:
-         ------------
-             I   z (np.ndarray): A prediction vector (row) for each row in our design matrix
-                 This vector is thresholded if regression=False, meaning that classification results
-                 in a vector of 1s and 0s, while regressions in an array of decimal numbers
-
-        """
-
-        predict = self._feedforward(X)
-
-        if self.classification:
-            return np.where(predict > threshold, 1, 0)
-        else:
-            return predict
-
-    def reset_weights(self):
-        """
-        Description:
-        ------------
-            Resets/Reinitializes the weights in order to train the network for a new problem.
-
-        """
-        if self.seed is not None:
-            np.random.seed(self.seed)
-
-        self.weights = list()
-        for i in range(len(self.dimensions) - 1):
-            weight_array = np.random.randn(
-                self.dimensions[i] + 1, self.dimensions[i + 1]
-            )
-            weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01
-
-            self.weights.append(weight_array)
-
-    def _feedforward(self, X: np.ndarray):
-        """
-        Description:
-        ------------
-            Calculates the activation of each layer starting at the input and ending at the output.
-            Each following activation is calculated from a weighted sum of each of the preceeding
-            activations (except in the case of the input layer).
-
-        Parameters:
-        ------------
-            I   X (np.ndarray): The design matrix, with n rows of p features each
-
-        Returns:
-        ------------
-            I   z (np.ndarray): A prediction vector (row) for each row in our design matrix
-        """
-
-        # reset matrices
-        self.a_matrices = list()
-        self.z_matrices = list()
-
-        # if X is just a vector, make it into a matrix
-        if len(X.shape) == 1:
-            X = X.reshape((1, X.shape[0]))
-
-        # Add a coloumn of zeros as the first coloumn of the design matrix, in order
-        # to add bias to our data
-        bias = np.ones((X.shape[0], 1)) * 0.01
-        X = np.hstack([bias, X])
-
-        # a^0, the nodes in the input layer (one a^0 for each row in X - where the
-        # exponent indicates layer number).
-        a = X
-        self.a_matrices.append(a)
-        self.z_matrices.append(a)
-
-        # The feed forward algorithm
-        for i in range(len(self.weights)):
-            if i < len(self.weights) - 1:
-                z = a @ self.weights[i]
-                self.z_matrices.append(z)
-                a = self.hidden_func(z)
-                # bias column again added to the data here
-                bias = np.ones((a.shape[0], 1)) * 0.01
-                a = np.hstack([bias, a])
-                self.a_matrices.append(a)
-            else:
-                try:
-                    # a^L, the nodes in our output layers
-                    z = a @ self.weights[i]
-                    a = self.output_func(z)
-                    self.a_matrices.append(a)
-                    self.z_matrices.append(z)
-                except Exception as OverflowError:
-                    print(
-                        "OverflowError in fit() in FFNN\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling"
-                    )
-
-        # this will be a^L
-        return a
-
-    def _backpropagate(self, X, t, lam):
-        """
-        Description:
-        ------------
-            Performs the backpropagation algorithm. In other words, this method
-            calculates the gradient of all the layers starting at the
-            output layer, and moving from right to left accumulates the gradient until
-            the input layer is reached. Each layers respective weights are updated while
-            the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).
-
-        Parameters:
-        ------------
-            I   X (np.ndarray): The design matrix, with n rows of p features each.
-            II  t (np.ndarray): The target vector, with n rows of p targets.
-            III lam (float32): regularization parameter used to punish the weights in case of overfitting
-
-        Returns:
-        ------------
-            No return value.
-
-        """
-        out_derivative = derivate(self.output_func)
-        hidden_derivative = derivate(self.hidden_func)
-
-        for i in range(len(self.weights) - 1, -1, -1):
-            # delta terms for output
-            if i == len(self.weights) - 1:
-                # for multi-class classification
-                if (
-                    self.output_func.__name__ == "softmax"
-                ):
-                    delta_matrix = self.a_matrices[i + 1] - t
-                # for single class classification
-                else:
-                    cost_func_derivative = grad(self.cost_func(t))
-                    delta_matrix = out_derivative(
-                        self.z_matrices[i + 1]
-                    ) * cost_func_derivative(self.a_matrices[i + 1])
-
-            # delta terms for hidden layer
-            else:
-                delta_matrix = (
-                    self.weights[i + 1][1:, :] @ delta_matrix.T
-                ).T * hidden_derivative(self.z_matrices[i + 1])
-
-            # calculate gradient
-            gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix
-            gradient_bias = np.sum(delta_matrix, axis=0).reshape(
-                1, delta_matrix.shape[1]
-            )
-
-            # regularization term
-            gradient_weights += self.weights[i][1:, :] * lam
-
-            # use scheduler
-            update_matrix = np.vstack(
-                [
-                    self.schedulers_bias[i].update_change(gradient_bias),
-                    self.schedulers_weight[i].update_change(gradient_weights),
-                ]
-            )
-
-            # update weights and bias
-            self.weights[i] -= update_matrix
-
-    def _accuracy(self, prediction: np.ndarray, target: np.ndarray):
-        """
-        Description:
-        ------------
-            Calculates accuracy of given prediction to target
-
-        Parameters:
-        ------------
-            I   prediction (np.ndarray): vector of predicitons output network
-                (1s and 0s in case of classification, and real numbers in case of regression)
-            II  target (np.ndarray): vector of true values (What the network ideally should predict)
-
-        Returns:
-        ------------
-            A floating point number representing the percentage of correctly classified instances.
-        """
-        assert prediction.size == target.size
-        return np.average((target == prediction))
-    def _set_classification(self):
-        """
-        Description:
-        ------------
-            Decides if FFNN acts as classifier (True) og regressor (False),
-            sets self.classification during init()
-        """
-        self.classification = False
-        if (
-            self.cost_func.__name__ == "CostLogReg"
-            or self.cost_func.__name__ == "CostCrossEntropy"
-        ):
-            self.classification = True
-
-    def _progress_bar(self, progression, **kwargs):
-        """
-        Description:
-        ------------
-            Displays progress of training
-        """
-        print_length = 40
-        num_equals = int(progression * print_length)
-        num_not = print_length - num_equals
-        arrow = ">" if num_equals > 0 else ""
-        bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]"
-        perc_print = self._format(progression * 100, decimals=5)
-        line = f"  {bar} {perc_print}% "
-
-        for key in kwargs:
-            if not np.isnan(kwargs[key]):
-                value = self._format(kwargs[key], decimals=4)
-                line += f"| {key}: {value} "
-        sys.stdout.write("\r" + line)
-        sys.stdout.flush()
-        return len(line)
-
-    def _format(self, value, decimals=4):
-        """
-        Description:
-        ------------
-            Formats decimal numbers for progress bar
-        """
-        if value > 0:
-            v = value
-        elif value < 0:
-            v = -10 * value
-        else:
-            v = 1
-        n = 1 + math.floor(math.log10(v))
-        if n >= decimals - 1:
-            return str(round(value))
-        return f"{value:.{decimals-n-1}f}"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Before we make a model, we will quickly generate a dataset we can use -for our linear regression problem as shown below -

- - - -
-
-
-
-
-
import autograd.numpy as np
-from sklearn.model_selection import train_test_split
-
-def SkrankeFunction(x, y):
-    return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)
-
-def create_X(x, y, n):
-    if len(x.shape) > 1:
-        x = np.ravel(x)
-        y = np.ravel(y)
-
-    N = len(x)
-    l = int((n + 1) * (n + 2) / 2)  # Number of elements in beta
-    X = np.ones((N, l))
-
-    for i in range(1, n + 1):
-        q = int((i) * (i + 1) / 2)
-        for k in range(i + 1):
-            X[:, q + k] = (x ** (i - k)) * (y**k)
-
-    return X
-
-step=0.5
-x = np.arange(0, 1, step)
-y = np.arange(0, 1, step)
-x, y = np.meshgrid(x, y)
-target = SkrankeFunction(x, y)
-target = target.reshape(target.shape[0], 1)
-
-poly_degree=3
-X = create_X(x, y, poly_degree)
-
-X_train, X_test, t_train, t_test = train_test_split(X, target)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now that we have our dataset ready for the regression, we can create -our regressor. Note that with the seed parameter, we can make sure our -results stay the same every time we run the neural network. For -inititialization, we simply specify the dimensions (we wish the amount -of input nodes to be equal to the datapoints, and the output to -predict one value). -

- - - -
-
-
-
-
-
input_nodes = X_train.shape[1]
-output_nodes = 1
-
-linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We then fit our model with our training data using the scheduler of our choice.

- - - -
-
-
-
-
-
linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Constant(eta=1e-3)
-scores = linear_regression.fit(X_train, t_train, scheduler)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Due to the progress bar we can see the MSE (train_error) throughout -the FFNN's training. Note that the fit() function has some optional -parameters with defualt arguments. For example, the regularization -hyperparameter can be left ignored if not needed, and equally the FFNN -will by default run for 100 epochs. These can easily be changed, such -as for example: -

- - - -
-
-
-
-
-
linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that given more epochs to train on, the regressor reaches a lower MSE.

- -

Let us then switch to a binary classification. We use a binary -classification dataset, and follow a similar setup to the regression -case. -

- - - -
-
-
-
-
-
from sklearn.datasets import load_breast_cancer
-from sklearn.preprocessing import MinMaxScaler
-
-wisconsin = load_breast_cancer()
-X = wisconsin.data
-target = wisconsin.target
-target = target.reshape(target.shape[0], 1)
-
-X_train, X_val, t_train, t_val = train_test_split(X, target)
-
-scaler = MinMaxScaler()
-scaler.fit(X_train)
-X_train = scaler.transform(X_train)
-X_val = scaler.transform(X_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
input_nodes = X_train.shape[1]
-output_nodes = 1
-
-logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We will now make use of our validation data by passing it into our fit function as a keyword argument

- - - -
-
-
-
-
-
logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
-scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Finally, we will create a neural network with 2 hidden layers with activation functions.

- - -
-
-
-
-
-
input_nodes = X_train.shape[1]
-hidden_nodes1 = 100
-hidden_nodes2 = 30
-output_nodes = 1
-
-dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
-
-neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
-scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Multiclass classification

- -

Finally, we will demonstrate the use case of multiclass classification -using our FFNN with the famous MNIST dataset, which contain images of -digits between the range of 0 to 9. -

- - - -
-
-
-
-
-
from sklearn.datasets import load_digits
-
-def onehot(target: np.ndarray):
-    onehot = np.zeros((target.size, target.max() + 1))
-    onehot[np.arange(target.size), target] = 1
-    return onehot
-
-digits = load_digits()
-
-X = digits.data
-target = digits.target
-target = onehot(target)
-
-input_nodes = 64
-hidden_nodes1 = 100
-hidden_nodes2 = 30
-output_nodes = 10
-
-dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
-
-multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)
-
-multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
-scores = multiclass.fit(X, target, scheduler, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Testing the XOR gate and other gates

- -

Let us now use our code to test the XOR gate.

- - - -
-
-
-
-
-
X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
-
-# The XOR gate
-yXOR = np.array( [[ 0], [1] ,[1], [0]])
-
-input_nodes = X.shape[1]
-output_nodes = 1
-
-logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999)
-scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Not bad, but the results depend strongly on the learning reate. Try different learning rates.

-
- - - -
-
- - - - - - - - - - - - - diff --git a/doc/src/week42/week42-solarized.html b/doc/src/week42/week42-solarized.html deleted file mode 100644 index 09a6aa095..000000000 --- a/doc/src/week42/week42-solarized.html +++ /dev/null @@ -1,4901 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - - - - - -
-

Week 42 Constructing a Neural Network code with examples

-
- - -
-Morten Hjorth-Jensen [1, 2] -
- -
-[1] Department of Physics, University of Oslo -
-
-[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University -
-
-
-

October 14-18, 2024

-
-
- -









-

Lecture October 14, 2024

-
- -

-

    -
  1. Building our own Feed-forward Neural Network and discussion of project 2
  2. -
-
- -
-Readings and videos -

-

    -
  1. These lecture notes - -
  2. -
  3. For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7.
  4. -
  5. Neural Networks demystified at https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs
  6. -
  7. Building Neural Networks from scratch at https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex
  8. -
  9. Video on Neural Networks at https://www.youtube.com/watch?v=CqOfi41LfDw
  10. -
  11. Video on the back propagation algorithm at https://www.youtube.com/watch?v=Ilg3gGewQ5U
  12. -
-

I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at http://neuralnetworksanddeeplearning.com/chap4.html.

-
- - -









-

Material for the active learning sessions on Tuesday and Wednesday

-
- -

-

    -
  • Exercise on starting to write a code for neural networks, feed forward part. We will also continue ur discussions of gradient descent methods from last week. If you have time, start considering the back-propagation part as well (exercises for next week)
  • -
  • Discussion of project 2
  • -
-
- - -

Note: some of the codes will also be discussed next week in connection with the solution of differential equations.

- -









-

Writing a code which implements a feed-forward neural network

- -

Last week we discussed the basics of neural networks and deep learning -and the basics of automatic differentiation. We looked also at -examples on how compute the parameters of a simple network with scalar -inputs and ouputs and no or just one hidden layers. -

- -

We ended our discussions with the derivation of the equations for a -neural network with one hidden layers and two input variables and two -hidden nodes but only one output node. -

- -









-

Mathematics of deep learning

- - - - -









-

Reminder on books with hands-on material and codes

- - - -









-

Reading recommendations

- -
    -
  1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub
  2. -
  3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
  4. -
-









-

First network example, simple percepetron with one input

- -

As yet another example we define now a simple perceptron model with -all quantities given by scalars. We consider only one input variable -\( x \) and one target value \( y \). We define an activation function -\( \sigma_1 \) which takes as input -

- -$$ -z_1 = w_1x+b_1, -$$ - -

where \( w_1 \) is the weight and \( b_1 \) is the bias. These are the -parameters we want to optimize. The output is \( a_1=\sigma(z_1) \) (see -graph from whiteboard notes). This output is then fed into the -cost/loss function, which we here for the sake of simplicity just -define as the squared error -

- -$$ -C(x;w_1,b_1)=\frac{1}{2}(a_1-y)^2. -$$ - - -









-

Layout of a simple neural network with no hidden layer

- -

-
-

-
-

- -









-

Optimizing the parameters

- -

In setting up the feed forward and back propagation parts of the -algorithm, we need now the derivative of the various variables we want -to train. -

- -

We need

-$$ -\frac{\partial C}{\partial w_1} \hspace{0.1cm}\mathrm{and}\hspace{0.1cm}\frac{\partial C}{\partial b_1}. -$$ - -

Using the chain rule we find

-$$ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_1-y)\sigma_1'x, -$$ - -

and

-$$ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_1-y)\sigma_1', -$$ - -

which we later will just define as

-$$ -\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}=\delta_1. -$$ - - -









-

Adding a hidden layer

- -

We change our simple model to (see graph) -a network with just one hidden layer but with scalar variables only. -

- -

Our output variable changes to \( a_2 \) and \( a_1 \) is now the output from the hidden node and \( a_0=x \). -We have then -

-$$ -z_1 = w_1a_0+b_1 \hspace{0.1cm} \wedge a_1 = \sigma_1(z_1), -$$ - -$$ -z_2 = w_2a_1+b_2 \hspace{0.1cm} \wedge a_2 = \sigma_2(z_2), -$$ - -

and the cost function

-$$ -C(x;\boldsymbol{\Theta})=\frac{1}{2}(a_2-y)^2, -$$ - -

with \( \boldsymbol{\Theta}=[w_1,w_2,b_1,b_2] \).

- -









-

Layout of a simple neural network with one hidden layer

- -

-
-

-
-

- -









-

The derivatives

- -

The derivatives are now, using the chain rule again

- -$$ -\frac{\partial C}{\partial w_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial w_2}=(a_2-y)\sigma_2'a_1=\delta_2a_1, -$$ - -$$ -\frac{\partial C}{\partial b_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial b_2}=(a_2-y)\sigma_2'=\delta_2, -$$ - -$$ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_2-y)\sigma_2'a_1\sigma_1'a_0, -$$ - -$$ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_2-y)\sigma_2'\sigma_1'=\delta_1. -$$ - -

Can you generalize this to more than one hidden layer?

- -









-

Important observations

- -
- -

-

From the above equations we see that the derivatives of the activation -functions play a central role. If they vanish, the training may -stop. This is called the vanishing gradient problem, see discussions below. If they become -large, the parameters \( w_i \) and \( b_i \) may simply go to infinity. This -is referenced as the exploding gradient problem. -

-
- - -









-

The training

- -

The training of the parameters is done through various gradient descent approximations with

- -$$ -w_{i}\leftarrow w_{i}- \eta \delta_i a_{i-1}, -$$ - -

and

-$$ -b_i \leftarrow b_i-\eta \delta_i, -$$ - -

with \( \eta \) is the learning rate.

- -

One iteration consists of one feed forward step and one back-propagation step. Each back-propagation step does one update of the parameters \( \boldsymbol{\Theta} \).

- -

For the first hidden layer \( a_{i-1}=a_0=x \) for this simple model.

- -









-

Code example

- -

The code here implements the above model with one hidden layer and -scalar variables for the same function we studied in the previous -example. The code is however set up so that we can add multiple -inputs \( x \) and target values \( y \). Note also that we have the -possibility of defining a feature matrix \( \boldsymbol{X} \) with more than just -one column for the input values. This will turn useful in our next example. We have also defined matrices and vectors for all of our operations although it is not necessary here. -

- - - -
-
-
-
-
-
import numpy as np
-# We use the Sigmoid function as activation function
-def sigmoid(z):
-    return 1.0/(1.0+np.exp(-z))
-
-def forwardpropagation(x):
-    # weighted sum of inputs to the hidden layer
-    z_1 = np.matmul(x, w_1) + b_1
-    # activation in the hidden layer
-    a_1 = sigmoid(z_1)
-    # weighted sum of inputs to the output layer
-    z_2 = np.matmul(a_1, w_2) + b_2
-    a_2 = z_2
-    return a_1, a_2
-
-def backpropagation(x, y):
-    a_1, a_2 = forwardpropagation(x)
-    # parameter delta for the output layer, note that a_2=z_2 and its derivative wrt z_2 is just 1
-    delta_2 = a_2 - y
-    print(0.5*((a_2-y)**2))
-    # delta for  the hidden layer
-    delta_1 = np.matmul(delta_2, w_2.T) * a_1 * (1 - a_1)
-    # gradients for the output layer
-    output_weights_gradient = np.matmul(a_1.T, delta_2)
-    output_bias_gradient = np.sum(delta_2, axis=0)
-    # gradient for the hidden layer
-    hidden_weights_gradient = np.matmul(x.T, delta_1)
-    hidden_bias_gradient = np.sum(delta_1, axis=0)
-    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-# Input variable
-x = np.array([4.0],dtype=np.float64)
-# Target values
-y = 2*x+1.0 
-
-# Defining the neural network, only scalars here
-n_inputs = x.shape
-n_features = 1
-n_hidden_neurons = 1
-n_outputs = 1
-
-# Initialize the network
-# weights and bias in the hidden layer
-w_1 = np.random.randn(n_features, n_hidden_neurons)
-b_1 = np.zeros(n_hidden_neurons) + 0.01
-
-# weights and bias in the output layer
-w_2 = np.random.randn(n_hidden_neurons, n_outputs)
-b_2 = np.zeros(n_outputs) + 0.01
-
-eta = 0.1
-for i in range(50):
-    # calculate gradients
-    derivW2, derivB2, derivW1, derivB1 = backpropagation(x, y)
-    # update weights and biases
-    w_2 -= eta * derivW2
-    b_2 -= eta * derivB2
-    w_1 -= eta * derivW1
-    b_1 -= eta * derivB1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that after some few iterations (the results do depend on the learning rate however), we get an error which is rather small.

- -









-

Simple neural network and the back propagation equations

- -

Let us now try to increase our level of ambition and attempt at setting -up the equations for a neural network with two input nodes, one hidden -layer with two hidden nodes and one output layer with one output node/neuron only (see graph).. -

- -

We need to define the following parameters and variables with the input layer (layer \( (0) \)) -where we label the nodes \( x_0 \) and \( x_1 \) -

-$$ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. -$$ - -

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_0^{(1)} \) and \( a_1^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

-$$ -w_{ij}^{(1)}=\left\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\right\} \wedge b^{(1)}=\left\{b_0^{(1)},b_1^{(1)}\right\}. -$$ - - -









-

Layout of a simple neural network with two input nodes, one hidden layer with two hidden noeds and one output node

- -

-
-

-
-

- -









-

The ouput layer

- -

We have the ouput layer given by layer label \( (2) \) with output \( a^{(2)} \) and weights and biases to be determined given by the variables

-$$ -w_{i}^{(2)}=\left\{w_{1}^{(2)},w_{2}^{(2)}\right\} \wedge b^{(2)}. -$$ - -

Our output is \( \tilde{y}=a^{(2)} \) and we define a generic cost function \( C(a^{(2)},y;\boldsymbol{\Theta}) \) where \( y \) is the target value (a scalar here). -The parameters we need to optimize are given by -

-$$ -\boldsymbol{\Theta}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)},w_{1}^{(2)},w_{2}^{(2)},b_1^{(1)},b_2^{(1)},b^{(2)}\right\}. -$$ - - -









-

Compact expressions

- -

We can define the inputs to the activation functions for the various layers in terms of various matrix-vector multiplications and vector additions. -The inputs to the first hidden layer are -

-$$ -\begin{bmatrix}z_1^{(1)} \\ z_2^{(1)} \end{bmatrix}=\left(\begin{bmatrix}w_{11}^{(1)} & w_{12}^{(1)}\\ w_{21}^{(1)} &w_{22}^{(1)} \end{bmatrix}\right)^{T}\begin{bmatrix}a_1^{(0)} \\ a_2^{(0)} \end{bmatrix}+\begin{bmatrix}b_1^{(1)} \\ b_2^{(1)} \end{bmatrix}, -$$ - -

with outputs

-$$ -\begin{bmatrix}a_1^{(1)} \\ a_2^{(1)} \end{bmatrix}=\begin{bmatrix}\sigma^{(1)}(z_1^{(1)}) \\ \sigma^{(1)}(z_2^{(1)}) \end{bmatrix}. -$$ - - -









-

Output layer

- -

For the final output layer we have the inputs to the final activation function

-$$ -z^{(2)} = w_{1}^{(2)}a_1^{(1)} +w_{2}^{(2)}a_2^{(1)}+b^{(2)}, -$$ - -

resulting in the output

-$$ -a^{(2)}=\sigma^{(2)}(z^{(2)}). -$$ - - -









-

Explicit derivatives

- -

In total we have nine parameters which we need to train. Using the -chain rule (or just the back-propagation algorithm) we can find all -derivatives. Since we will use automatic differentiation in reverse -mode, we start with the derivatives of the cost function with respect -to the parameters of the output layer, namely -

- -$$ -\frac{\partial C}{\partial w_{i}^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial w_{i}^{(2)}}=\delta^{(2)}a_i^{(1)}, -$$ - -

with

-$$ -\delta^{(2)}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -$$ - -

and finally

-$$ -\frac{\partial C}{\partial b^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial b^{(2)}}=\delta^{(2)}. -$$ - - -









-

Derivatives of the hidden layer

- -

Using the chain rule we have the following expressions for say one of the weight parameters (it is easy to generalize to the other weight parameters)

-$$ -\frac{\partial C}{\partial w_{11}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}= \delta^{(2)}\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}, -$$ - -

which, noting that

-$$ -z^{(2)} =w_1^{(2)}a_1^{(1)}+w_2^{(2)}a_2^{(1)}+b^{(2)}, -$$ - -

allows us to rewrite

-$$ -\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}a_1^{(1)}. -$$ - - -









-

Final expression

-

Defining

-$$ -\delta_1^{(1)}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}\delta^{(2)}, -$$ - -

we have

-$$ -\frac{\partial C}{\partial w_{11}^{(1)}}=\delta_1^{(1)}a_1^{(1)}. -$$ - -

Similarly, we obtain

-$$ -\frac{\partial C}{\partial w_{12}^{(1)}}=\delta_1^{(1)}a_2^{(1)}. -$$ - - -









-

Completing the list

- -

Similarly, we find

-$$ -\frac{\partial C}{\partial w_{21}^{(1)}}=\delta_2^{(1)}a_1^{(1)}, -$$ - -

and

-$$ -\frac{\partial C}{\partial w_{22}^{(1)}}=\delta_2^{(1)}a_2^{(1)}, -$$ - -

where we have defined

-$$ -\delta_2^{(1)}=w_2^{(2)}\frac{\partial a_2^{(1)}}{\partial z_2^{(1)}}\delta^{(2)}. -$$ - - -









-

Final expressions for the biases of the hidden layer

- -

For the sake of completeness, we list the derivatives of the biases, which are

-$$ -\frac{\partial C}{\partial b_{1}^{(1)}}=\delta_1^{(1)}, -$$ - -

and

-$$ -\frac{\partial C}{\partial b_{2}^{(1)}}=\delta_2^{(1)}. -$$ - -

As we will see below, these expressions can be generalized in a more compact form.

- -









-

Gradient expressions

- -

For this specific model, with just one output node and two hidden -nodes, the gradient descent equations take the following form for output layer -

-$$ -w_{i}^{(2)}\leftarrow w_{i}^{(2)}- \eta \delta^{(2)} a_{i}^{(1)}, -$$ - -

and

-$$ -b^{(2)} \leftarrow b^{(2)}-\eta \delta^{(2)}, -$$ - -

and

-$$ -w_{ij}^{(1)}\leftarrow w_{ij}^{(1)}- \eta \delta_{i}^{(1)} a_{j}^{(0)}, -$$ - -

and

-$$ -b_{i}^{(1)} \leftarrow b_{i}^{(1)}-\eta \delta_{i}^{(1)}, -$$ - -

where \( \eta \) is the learning rate.

- -









-

Setting up the equations for a neural network

- -

The questions we want to ask are how do changes in the biases and the -weights in our network change the cost function and how can we use the -final output to modify the weights and biases? -

- -

To derive these equations let us start with a plain regression problem -and define our cost function as -

- -$$ -{\cal C}(\boldsymbol{\Theta}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2, -$$ - -

where the $y_i$s are our \( n \) targets (the values we want to -reproduce), while the outputs of the network after having propagated -all inputs \( \boldsymbol{x} \) are given by \( \boldsymbol{\tilde{y}}_i \). -

- -









-

Layout of a neural network with three hidden layers (last later = \( l=L=4 \), first layer \( l=0 \))

- -

-
-

-
-

- -









-

Definitions

- -

With our definition of the targets \( \boldsymbol{y} \), the outputs of the -network \( \boldsymbol{\tilde{y}} \) and the inputs \( \boldsymbol{x} \) we -define now the activation \( z_j^l \) of node/neuron/unit \( j \) of the -\( l \)-th layer as a function of the bias, the weights which add up from -the previous layer \( l-1 \) and the forward passes/outputs -\( \boldsymbol{a}^{l-1} \) from the previous layer as -

- -$$ -z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, -$$ - -

where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) -represents the total number of nodes/neurons/units of layer \( l-1 \). The -figure in the whiteboard notes illustrates this equation. We can rewrite this in a more -compact form as the matrix-vector products we discussed earlier, -

- -$$ -\boldsymbol{z}^l = \left(\boldsymbol{W}^l\right)^T\boldsymbol{a}^{l-1}+\boldsymbol{b}^l. -$$ - - -









-

Inputs to the activation function

- -

With the activation values \( \boldsymbol{z}^l \) we can in turn define the -output of layer \( l \) as \( \boldsymbol{a}^l = \sigma(\boldsymbol{z}^l) \) where \( \sigma \) is our -activation function. In the examples here we will use the sigmoid -function discussed in our logistic regression lectures. We will also use the same activation function \( \sigma \) for all layers -and their nodes. It means we have -

- -$$ -a_j^l = \sigma(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. -$$ - - -









-

Layout of input to first hidden layer \( l=1 \) from input layer \( l=0 \)

- -

-
-

-
-

- -









-

Derivatives and the chain rule

- -

From the definition of the input variable to the activation function, that is \( z_j^l \) we have

-$$ -\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, -$$ - -

and

-$$ -\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. -$$ - -

With our definition of the activation function we have that (note that this function depends only on \( z_j^l \))

-$$ -\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=\sigma(z_j^l)(1-\sigma(z_j^l)). -$$ - - -









-

Derivative of the cost function

- -

With these definitions we can now compute the derivative of the cost function in terms of the weights.

- -

Let us specialize to the output layer \( l=L \). Our cost function is

-$$ -{\cal C}(\boldsymbol{\Theta}^L) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - y_i\right)^2, -$$ - -

The derivative of this function with respect to the weights is

- -$$ -\frac{\partial{\cal C}(\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)\frac{\partial a_j^L}{\partial w_{ij}^{L}}, -$$ - -

The last partial derivative can easily be computed and reads (by applying the chain rule)

-$$ -\frac{\partial a_j^L}{\partial w_{ij}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{ij}^{L}}=a_j^L(1-a_j^L)a_i^{L-1}. -$$ - - -









-

The back propagation equations for a neural network

- -

We have thus

-$$ -\frac{\partial{\cal C}((\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)a_j^L(1-a_j^L)a_i^{L-1}, -$$ - -

Defining

-$$ -\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - y_j\right) = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -$$ - -

and using the Hadamard product of two vectors we can write this as

-$$ -\boldsymbol{\delta}^L = \sigma'(\boldsymbol{z}^L)\circ\frac{\partial {\cal C}}{\partial (\boldsymbol{a}^L)}. -$$ - - -









-

Analyzing the last results

- -

This is an important expression. The second term on the right handside -measures how fast the cost function is changing as a function of the $j$th -output activation. If, for example, the cost function doesn't depend -much on a particular output node \( j \), then \( \delta_j^L \) will be small, -which is what we would expect. The first term on the right, measures -how fast the activation function \( f \) is changing at a given activation -value \( z_j^L \). -

- -









-

More considerations

- -

Notice that everything in the above equations is easily computed. In -particular, we compute \( z_j^L \) while computing the behaviour of the -network, and it is only a small additional overhead to compute -\( \sigma'(z^L_j) \). The exact form of the derivative with respect to the -output depends on the form of the cost function. -However, provided the cost function is known there should be little -trouble in calculating -

- -$$ -\frac{\partial {\cal C}}{\partial (a_j^L)} -$$ - -

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

-$$ -\frac{\partial{\cal C}}{\partial w_{ij}^L} = \delta_j^La_i^{L-1}. -$$ - - -









-

Derivatives in terms of \( z_j^L \)

- -

It is also easy to see that our previous equation can be written as

- -$$ -\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}, -$$ - -

which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely

-$$ -\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}, -$$ - -

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.

- -









-

Bringing it together

- -

We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are

- -$$ -\begin{equation} -\frac{\partial{\cal C}(\boldsymbol{W^L})}{\partial w_{ij}^L} = \delta_j^La_i^{L-1}, -\label{_auto1} -\end{equation} -$$ - -

and

-$$ -\begin{equation} -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\label{_auto2} -\end{equation} -$$ - -

and

- -$$ -\begin{equation} -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}, -\label{_auto3} -\end{equation} -$$ - - -









-

Final back propagating equation

- -

We have that (replacing \( L \) with a general layer \( l \))

-$$ -\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. -$$ - -

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 obtain

-$$ -\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}}, -$$ - -

and recalling that

-$$ -z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, -$$ - -

with \( M_l \) being the number of nodes in layer \( l \), we obtain

-$$ -\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -$$ - -

This is our final equation.

- -

We are now ready to set up the algorithm for back propagation and learning the weights and biases.

- -









-

Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

- -
-The architecture (our model) -

-

    -
  1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)
  2. -
  3. Define the number of hidden layers and hidden nodes
  4. -
  5. Define activation functions for hidden layers and output layers
  6. -
  7. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates
  8. -
  9. Define cost function and possible regularization terms with hyperparameters
  10. -
  11. Initialize weights and biases
  12. -
  13. Fix number of iterations for the feed forward part and back propagation part
  14. -
-
- - -









-

Setting up the back propagation algorithm, part 1

- -

The four equations provide us with a way of computing the gradients of the cost function. Let us write this out in the form of an algorithm.

- -

First, we set up the input data \( \boldsymbol{x} \) and the activations -\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and -the pertinent outputs \( \boldsymbol{a}^1 \). -

- -

Secondly, we perform then the feed forward till we reach the output -layer and compute all \( \boldsymbol{z}_l \) of the input layer and compute the -activation function and the pertinent outputs \( \boldsymbol{a}^l \) for -\( l=1,2,3,\dots,L \). -

- -

Notation: The first hidden layer has \( l=1 \) as label and the final output layer has \( l=L \).

- -









-

Setting up the back propagation algorithm, part 2

- -

Thereafter we compute the ouput error \( \boldsymbol{\delta}^L \) by computing all

-$$ -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. -$$ - -

Then we compute the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

-$$ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). -$$ - - -









-

Setting up the Back propagation algorithm, part 3

- -

Finally, we update the weights and the biases using gradient descent -for each \( l=L-1,L-2,\dots,1 \) (the first hidden layer) and update the weights and biases -according to the rules -

- -$$ -w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, -$$ - - -$$ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -$$ - -

with \( \eta \) being the learning rate.

- -









-

Updating the gradients

- -

With the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

-$$ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -$$ - -

we update the weights and the biases using gradient descent for each \( l=L-1,L-2,\dots,1 \) and update the weights and biases according to the rules

-$$ -w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, -$$ - - -$$ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -$$ - - -









-

Activation functions

- -

A property that characterizes a neural network, other than its -connectivity, is the choice of activation function(s). The following -restrictions are imposed on an activation function for an FFNN to -fulfill the universal approximation theorem -

- -
    -
  • Non-constant
  • -
  • Bounded
  • -
  • Monotonically-increasing
  • -
  • Continuous
  • -
-









-

Activation functions, Logistic and Hyperbolic ones

- -

The second requirement excludes all linear functions. Furthermore, in -a MLP with only linear activation functions, each layer simply -performs a linear transformation of its inputs. -

- -

Regardless of the number of layers, the output of the NN will be -nothing but a linear function of the inputs. Thus we need to introduce -some kind of non-linearity to the NN to be able to fit non-linear -functions Typical examples are the logistic Sigmoid -

- -$$ - \sigma(x) = \frac{1}{1 + e^{-x}}, -$$ - -

and the hyperbolic tangent function

-$$ - \sigma(x) = \tanh(x) -$$ - - -









-

Relevance

- -

The sigmoid function are more biologically plausible because the -output of inactive neurons are zero. Such activation function are -called one-sided. However, it has been shown that the hyperbolic -tangent performs better than the sigmoid for training MLPs. has -become the most popular for deep neural networks -

- - - -
-
-
-
-
-
"""The sigmoid function (or the logistic curve) is a 
-function that takes any real number, z, and outputs a number (0,1).
-It is useful in neural networks for assigning weights on a relative scale.
-The value z is the weighted sum of parameters involved in the learning algorithm."""
-
-import numpy
-import matplotlib.pyplot as plt
-import math as mt
-
-z = numpy.arange(-5, 5, .1)
-sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
-sigma = sigma_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, sigma)
-ax.set_ylim([-0.1, 1.1])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sigmoid function')
-
-plt.show()
-
-"""Step Function"""
-z = numpy.arange(-5, 5, .02)
-step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
-step = step_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, step)
-ax.set_ylim([-0.5, 1.5])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('step function')
-
-plt.show()
-
-"""Sine Function"""
-z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
-t = numpy.sin(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, t)
-ax.set_ylim([-1.0, 1.0])
-ax.set_xlim([-2*mt.pi,2*mt.pi])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sine function')
-
-plt.show()
-
-"""Plots a graph of the squashing function used by a rectified linear
-unit"""
-z = numpy.arange(-2, 2, .1)
-zero = numpy.zeros(len(z))
-y = numpy.max([zero, z], axis=0)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, y)
-ax.set_ylim([-2.0, 2.0])
-ax.set_xlim([-2.0, 2.0])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('Rectified linear unit')
-
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Vanishing gradients

- -

The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. -

- -

Unfortunately for us, the gradients often get smaller and smaller as -the algorithm progresses down to the first hidden layers. As a result, -the GD update leaves the lower layer connection weights virtually -unchanged, and training never converges to a good solution. This is -known in the literature as the vanishing gradients problem. -

- -









-

Exploding gradients

- -

In other cases, the opposite can happen, namely the the gradients can -grow bigger and bigger. The result is that many of the layers get -large updates of the weights the algorithm diverges. This is the -exploding gradients problem, which is mostly encountered in -recurrent neural networks. More generally, deep neural networks suffer -from unstable gradients, different layers may learn at widely -different speeds -

- - -

Is the Logistic activation function (Sigmoid) our choice?

- -

Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. -

- -

A paper titled Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -

- -









-

Logistic function as the root of problems

- -

They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -

- -









-

The derivative of the Logistic funtion

- -

Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. -

- -

In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -

- -









-

Insights from the paper by Glorot and Bengio

- -

One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -

- -









-

The RELU function family

- -

The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. -

- -

In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. -

- -









-

ELU function

- -

To solve this problem, nowadays practitioners use a variant of the -ReLU function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function -

- -$$ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -$$ - - -









-

Which activation function should we use?

- -

In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than \( \tanh \) which in turn performs better -than the logistic function. -

- -

If runtime performance is an issue, then you may opt for the leaky -ReLU function over the ELU function If you don’t want to tweak yet -another hyperparameter, you may just use the default \( \alpha \) of -\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and -computing power, you can use cross-validation or bootstrap to evaluate -other activation functions. -

- -









-

More on activation functions, output layers

- -

In most cases you can use the ReLU activation function in the hidden -layers (or one of its variants). -

- -

It is a bit faster to compute than other activation functions, and the -gradient descent optimization does in general not get stuck. -

- -For the output layer: - -
    -
  • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
  • -
  • For regression tasks, you can simply use no activation function at all.
  • -
-









-

Fine-tuning neural network hyperparameters

- -

The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are -interconnected), but even in a simple FFNN you can change the number -of layers, the number of neurons per layer, the type of activation -function to use in each layer, the weight initialization logic, the -stochastic gradient optmized and much more. How do you know what -combination of hyperparameters is the best for your task? -

- -
    -
  • You can use grid search with cross-validation to find the right hyperparameters.
  • -
-

However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. -

- -
    -
  • You can use randomized search.
  • -
  • Or use tools like Oscar, which implements more complex algorithms to help you find a good set of hyperparameters quickly.
  • -
-









-

Hidden layers

- -

For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set discussed below you can easily get a -high accuracy using just one hidden layer with a few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden -layers with the same total amount of neurons, in roughly the same -amount of training time. -

- -

For more complex problems, you can gradually ramp up the number of -hidden layers, until you start overfitting the training set. Very -complex tasks, such as large image classification or speech -recognition, typically require networks with dozens of layers and they -need a huge amount of training data. However, you will rarely have to -train such networks from scratch: it is much more common to reuse -parts of a pretrained state-of-the-art network that performs a similar -task. -

- -









-

Batch Normalization

- -

Batch Normalization aims to address the vanishing/exploding gradients -problems, and more generally the problem that the distribution of each -layer’s inputs changes during training, as the parameters of the -previous layers change. -

- -

The technique consists of adding an operation in the model just before -the activation function of each layer, simply zero-centering and -normalizing the inputs, then scaling and shifting the result using two -new parameters per layer (one for scaling, the other for shifting). In -other words, this operation lets the model learn the optimal scale and -mean of the inputs for each layer. In order to zero-center and -normalize the inputs, the algorithm needs to estimate the inputs’ mean -and standard deviation. It does so by evaluating the mean and standard -deviation of the inputs over the current mini-batch, from this the -name batch normalization. -

- -









-

Dropout

- -

It is a fairly simple algorithm: at every training step, every neuron -(including the input neurons but excluding the output neurons) has a -probability \( p \) of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active -during the next step. -

- -

The hyperparameter \( p \) is called the dropout rate, and it is typically -set to 50%. After training, the neurons are not dropped anymore. It -is viewed as one of the most popular regularization techniques. -

- -









-

Gradient Clipping

- -

A popular technique to lessen the exploding gradients problem is to -simply clip the gradients during backpropagation so that they never -exceed some threshold (this is mostly useful for recurrent neural -networks). -

- -

This technique is called Gradient Clipping.

- -

In general however, Batch -Normalization is preferred. -

- - -

A top-down perspective on Neural networks

- -

The first thing we would like to do is divide the data into two or -three parts. A training set, a validation or dev (development) set, -and a test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: -

- -
    -
  1. Estimate optimal error rate
  2. -
  3. Minimize underfitting (bias) on training data set.
  4. -
  5. Make sure you are not overfitting.
  6. -
-









-

More top-down perspectives

- -

If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. -

- -

However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -

- -









-

Limitations of supervised learning with deep networks

- -

Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). -

- -









-

Limitations of NNs

- -

Here we list some of the important limitations of supervised neural network based models.

- -
    -
  • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
  • -
  • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
  • -
-









-

Homogeneous data

- -
    -
  • Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
  • -
-









-

More limitations

- -
    -
  • Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
  • -
-

Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.

- - -

Setting up a Multi-layer perceptron model for classification

- -

We are now gong to develop an example based on the MNIST data -base. This is a classification problem and we need to use our -cross-entropy function we discussed in connection with logistic -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. -

- -

In binary classification with two classes \( (0, 1) \) we define the -logistic/sigmoid function as the probability that a particular input -is in class \( 0 \) or \( 1 \). This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. -

- -

For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) -is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) -represents our activation values \( z \). We have -

-$$ -P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , -$$ - -

and

-$$ -P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , -$$ - -

where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases -of our network. -

- - -









-

Defining the cost function

- -

Our cost function is given as (see the Logistic regression lectures)

-$$ -\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . -$$ - -

This last equality means that we can interpret our cost function as a sum over the loss function -for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. -

- -

In multiclass classification it is common to treat each integer label as a so called one-hot vector:

- -

\( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

- -\( y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) , \) - -

i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset (numbers from \( 0 \) to \( 9 \))..

- -

If \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th -output vector \( \boldsymbol{y}_i \). -The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: -

- -$$ -P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , -$$ - -

which reduces to the logistic function in the binary case. -The likelihood of this \( C \)-class classifier -is now given as: -

- -$$ -P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -$$ - -

Again we take the negative log-likelihood to define our cost function:

- -$$ -\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. -$$ - -

See the logistic regression lectures for a full definition of the cost function.

- -

The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!

- -









-

Example: binary classification problem

- -

As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as

-$$ -\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), -$$ - -

where we had defined the logistic (sigmoid) function

-$$ -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)}}, -$$ - -

and

-$$ -p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). -$$ - -

The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

- -

Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). -We have then -

-$$ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -$$ - -

with

-$$ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -$$ - -

where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). -Our cost function at the final layer \( l=L \) is now -

-$$ -\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), -$$ - -

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

-$$ -\frac{\partial \mathcal{C}(\boldsymbol{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. -$$ - -

In case we use another activation function than the logistic one, we need to evaluate other derivatives.

- -









-

The Softmax function

-

In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need

-$$ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -$$ - -

For the Softmax function we have

-$$ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -$$ - -

Its derivative with respect to \( z_j^l \) gives

-$$ -\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), -$$ - -

which in case of the simply binary model reduces to having \( i=j \).

- - -

Developing a code for doing neural networks with back propagation

- -

One can identify a set of key steps when using neural networks to solve supervised learning problems:

- -
    -
  1. Collect and pre-process data
  2. -
  3. Define model and architecture
  4. -
  5. Choose cost function and optimizer
  6. -
  7. Train the model
  8. -
  9. Evaluate model performance on test data
  10. -
  11. Adjust hyperparameters (if necessary, network architecture)
  12. -
-









-

Collect and pre-process data

- -

Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

- -

To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

- -

As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

- -

$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

- -

and the targets would be:

- -

$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

- -

Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

- - - -
-
-
-
-
-
# import necessary packages
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn import datasets
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-
-# display images in notebook
-%matplotlib inline
-plt.rcParams['figure.figsize'] = (12,12)
-
-
-# download MNIST dataset
-digits = datasets.load_digits()
-
-# define inputs and labels
-inputs = digits.images
-labels = digits.target
-
-print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
-print("labels = (n_inputs) = " + str(labels.shape))
-
-
-# flatten the image
-# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
-n_inputs = len(inputs)
-inputs = inputs.reshape(n_inputs, -1)
-print("X = (n_inputs, n_features) = " + str(inputs.shape))
-
-
-# choose some random images to display
-indices = np.arange(n_inputs)
-random_indices = np.random.choice(indices, size=5)
-
-for i, image in enumerate(digits.images[random_indices]):
-    plt.subplot(1, 5, i+1)
-    plt.axis('off')
-    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
-    plt.title("Label: %d" % digits.target[random_indices[i]])
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Train and test datasets

- -

Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

- -

We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

- -

It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

- - - -
-
-
-
-
-
from sklearn.model_selection import train_test_split
-
-# one-liner from scikit-learn library
-train_size = 0.8
-test_size = 1 - train_size
-X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
-                                                    test_size=test_size)
-
-# equivalently in numpy
-def train_test_split_numpy(inputs, labels, train_size, test_size):
-    n_inputs = len(inputs)
-    inputs_shuffled = inputs.copy()
-    labels_shuffled = labels.copy()
-    
-    np.random.shuffle(inputs_shuffled)
-    np.random.shuffle(labels_shuffled)
-    
-    train_end = int(n_inputs*train_size)
-    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
-    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
-    
-    return X_train, X_test, Y_train, Y_test
-
-#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
-
-print("Number of training images: " + str(len(X_train)))
-print("Number of test images: " + str(len(X_test)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Define model and architecture

- -

Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

- -

$$ z = \sum_{i=1}^n w_i a_i ,$$

- -

$$ y = f(z) ,$$

- -

where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

- -

The simplest activation function for a neuron is the Heaviside function:

- -

$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

- -

A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

- -

However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

- -

Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

- -

$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$

- -

which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

- - -

Layers

- -
    -
  • Input
  • -
-

Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

- -
    -
  • Hidden layer
  • -
-

We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

- -
    -
  • Output
  • -
-

If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

- -

For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

- -

Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

- -

$$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

- -

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. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

- -

$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

- -

Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. -

- - -

Weights and biases

- -

Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. -

- -

Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

- -

$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

- -

The bias weights \( \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.

- - -
-
-
-
-
-
# building our neural network
-
-n_inputs, n_features = X_train.shape
-n_hidden_neurons = 50
-n_categories = 10
-
-# we make the weights normally distributed using numpy.random.randn
-
-# weights and bias in the hidden layer
-hidden_weights = np.random.randn(n_features, n_hidden_neurons)
-hidden_bias = np.zeros(n_hidden_neurons) + 0.01
-
-# weights and bias in the output layer
-output_weights = np.random.randn(n_hidden_neurons, n_categories)
-output_bias = np.zeros(n_categories) + 0.01
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Feed-forward pass

- -

Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

- -

$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

- -

this is then passed through our activation function

- -

$$ a_{j}^{l} = f(z_{j}^{l}) .$$

- -

We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

- -

$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

- -

Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

- -

$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

- - -

Matrix multiplications

- -

Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden -layer have the dimensions -\( W_{hidden} = (n_{features}, n_{hidden}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

- -

$$ X W^{h} = (n_{inputs}, n_{hidden}),$$

- -

and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

- -

$$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

- -

meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

- -

$$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

- -

This is fed to the output layer:

- -

$$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

- -

Finally we receive our output values for each image and each category by passing it through the softmax function:

- -

$$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

- - - -
-
-
-
-
-
# setup the feed-forward pass, subscript h = hidden layer
-
-def sigmoid(x):
-    return 1/(1 + np.exp(-x))
-
-def feed_forward(X):
-    # weighted sum of inputs to the hidden layer
-    z_h = np.matmul(X, hidden_weights) + hidden_bias
-    # activation in the hidden layer
-    a_h = sigmoid(z_h)
-    
-    # weighted sum of inputs to the output layer
-    z_o = np.matmul(a_h, output_weights) + output_bias
-    # softmax output
-    # axis 0 holds each input and axis 1 the probabilities of each category
-    exp_term = np.exp(z_o)
-    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-    
-    return probabilities
-
-probabilities = feed_forward(X_train)
-print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
-print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
-print("probabilities sum up to: " + str(probabilities[0].sum()))
-print()
-
-# we obtain a prediction by taking the class with the highest likelihood
-def predict(X):
-    probabilities = feed_forward(X)
-    return np.argmax(probabilities, axis=1)
-
-predictions = predict(X_train)
-print("predictions = (n_inputs) = " + str(predictions.shape))
-print("prediction for image 0: " + str(predictions[0]))
-print("correct label for image 0: " + str(Y_train[0]))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Choose cost function and optimizer

- -

To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

- -

In multiclass classification it is common to treat each integer label as a so called one-hot vector:

- -

$$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

- -

$$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$

- -

i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

- -

Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

- -

In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category \( c' \) -(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. -

- - -









-

Optimizing the cost function

- -

The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

- -

$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

- -

where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

- -

A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

- -

$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

- -

i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

- -

This has two important benefits:

-
    -
  1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
  2. -
  3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
  4. -
-

The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

- - -

Regularization

- -

It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

- -

We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

- -

$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

- -

i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

- -

In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has \( (64 + 1)\times 50=3250 \) weights in -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -layer (\( +1 \) for the bias), and the gradient must be calculated for -every parameter. We use the backpropagation algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. -

- -









-

Matrix multiplication

- -

To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

- -

$$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

- -

The gradient for the output weights is calculated as

- -

$$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

- -

where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

- -

The gradient with respect to the output bias is then

- -

$$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

- -

The error in the hidden layer is

- -

$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

- -

where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

- -

This again gives us the gradients in the hidden layer:

- -

$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

- -

$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

- - - -
-
-
-
-
-
# to categorical turns our integer vector into a onehot representation
-from sklearn.metrics import accuracy_score
-
-# one-hot in numpy
-def to_categorical_numpy(integer_vector):
-    n_inputs = len(integer_vector)
-    n_categories = np.max(integer_vector) + 1
-    onehot_vector = np.zeros((n_inputs, n_categories))
-    onehot_vector[range(n_inputs), integer_vector] = 1
-    
-    return onehot_vector
-
-#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
-Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
-
-def feed_forward_train(X):
-    # weighted sum of inputs to the hidden layer
-    z_h = np.matmul(X, hidden_weights) + hidden_bias
-    # activation in the hidden layer
-    a_h = sigmoid(z_h)
-    
-    # weighted sum of inputs to the output layer
-    z_o = np.matmul(a_h, output_weights) + output_bias
-    # softmax output
-    # axis 0 holds each input and axis 1 the probabilities of each category
-    exp_term = np.exp(z_o)
-    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-    
-    # for backpropagation need activations in hidden and output layers
-    return a_h, probabilities
-
-def backpropagation(X, Y):
-    a_h, probabilities = feed_forward_train(X)
-    
-    # error in the output layer
-    error_output = probabilities - Y
-    # error in the hidden layer
-    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
-    
-    # gradients for the output layer
-    output_weights_gradient = np.matmul(a_h.T, error_output)
-    output_bias_gradient = np.sum(error_output, axis=0)
-    
-    # gradient for the hidden layer
-    hidden_weights_gradient = np.matmul(X.T, error_hidden)
-    hidden_bias_gradient = np.sum(error_hidden, axis=0)
-
-    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
-
-print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
-
-eta = 0.01
-lmbd = 0.01
-for i in range(1000):
-    # calculate gradients
-    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
-    
-    # regularization term gradients
-    dWo += lmbd * output_weights
-    dWh += lmbd * hidden_weights
-    
-    # update weights and biases
-    output_weights -= eta * dWo
-    output_bias -= eta * dBo
-    hidden_weights -= eta * dWh
-    hidden_bias -= eta * dBh
-
-print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Improving performance

- -

As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. -

- -

The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

- -

Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

- -

If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. -

- -









-

Full object-oriented implementation

- -

It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. -

- - - -
-
-
-
-
-
class NeuralNetwork:
-    def __init__(
-            self,
-            X_data,
-            Y_data,
-            n_hidden_neurons=50,
-            n_categories=10,
-            epochs=10,
-            batch_size=100,
-            eta=0.1,
-            lmbd=0.0):
-
-        self.X_data_full = X_data
-        self.Y_data_full = Y_data
-
-        self.n_inputs = X_data.shape[0]
-        self.n_features = X_data.shape[1]
-        self.n_hidden_neurons = n_hidden_neurons
-        self.n_categories = n_categories
-
-        self.epochs = epochs
-        self.batch_size = batch_size
-        self.iterations = self.n_inputs // self.batch_size
-        self.eta = eta
-        self.lmbd = lmbd
-
-        self.create_biases_and_weights()
-
-    def create_biases_and_weights(self):
-        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
-        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
-
-        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
-        self.output_bias = np.zeros(self.n_categories) + 0.01
-
-    def feed_forward(self):
-        # feed-forward for training
-        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
-        self.a_h = sigmoid(self.z_h)
-
-        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
-
-        exp_term = np.exp(self.z_o)
-        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-
-    def feed_forward_out(self, X):
-        # feed-forward for output
-        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
-        a_h = sigmoid(z_h)
-
-        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
-        
-        exp_term = np.exp(z_o)
-        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-        return probabilities
-
-    def backpropagation(self):
-        error_output = self.probabilities - self.Y_data
-        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
-
-        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
-        self.output_bias_gradient = np.sum(error_output, axis=0)
-
-        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
-        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
-
-        if self.lmbd > 0.0:
-            self.output_weights_gradient += self.lmbd * self.output_weights
-            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
-
-        self.output_weights -= self.eta * self.output_weights_gradient
-        self.output_bias -= self.eta * self.output_bias_gradient
-        self.hidden_weights -= self.eta * self.hidden_weights_gradient
-        self.hidden_bias -= self.eta * self.hidden_bias_gradient
-
-    def predict(self, X):
-        probabilities = self.feed_forward_out(X)
-        return np.argmax(probabilities, axis=1)
-
-    def predict_probabilities(self, X):
-        probabilities = self.feed_forward_out(X)
-        return probabilities
-
-    def train(self):
-        data_indices = np.arange(self.n_inputs)
-
-        for i in range(self.epochs):
-            for j in range(self.iterations):
-                # pick datapoints with replacement
-                chosen_datapoints = np.random.choice(
-                    data_indices, size=self.batch_size, replace=False
-                )
-
-                # minibatch training data
-                self.X_data = self.X_data_full[chosen_datapoints]
-                self.Y_data = self.Y_data_full[chosen_datapoints]
-
-                self.feed_forward()
-                self.backpropagation()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Evaluate model performance on test data

- -

To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the accuracy score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). -

- -

$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

- -

where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

- - - -
-
-
-
-
-
epochs = 100
-batch_size = 100
-
-dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
-                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
-dnn.train()
-test_predict = dnn.predict(X_test)
-
-# accuracy score from scikit library
-print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
-
-# equivalent in numpy
-def accuracy_score_numpy(Y_test, Y_pred):
-    return np.sum(Y_test == Y_pred) / len(Y_test)
-
-#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Adjust hyperparameters

- -

We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

- - - -
-
-
-
-
-
eta_vals = np.logspace(-5, 1, 7)
-lmbd_vals = np.logspace(-5, 1, 7)
-# store the models for later use
-DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-
-# grid search
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
-                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
-        dnn.train()
-        
-        DNN_numpy[i][j] = dnn
-        
-        test_predict = dnn.predict(X_test)
-        
-        print("Learning rate  = ", eta)
-        print("Lambda = ", lmbd)
-        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Visualization

- - - -
-
-
-
-
-
# visual representation of grid search
-# uses seaborn heatmap, you can also do this with matplotlib imshow
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        dnn = DNN_numpy[i][j]
-        
-        train_pred = dnn.predict(X_train) 
-        test_pred = dnn.predict(X_test)
-
-        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
-        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

scikit-learn implementation

- -

scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

- -

scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

- - - -
-
-
-
-
-
from sklearn.neural_network import MLPClassifier
-# store models for later use
-DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
-                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
-        dnn.fit(X_train, Y_train)
-        
-        DNN_scikit[i][j] = dnn
-        
-        print("Learning rate  = ", eta)
-        print("Lambda = ", lmbd)
-        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Visualization

- - -
-
-
-
-
-
# optional
-# visual representation of grid search
-# uses seaborn heatmap, could probably do this in matplotlib
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        dnn = DNN_scikit[i][j]
-        
-        train_pred = dnn.predict(X_train) 
-        test_pred = dnn.predict(X_test)
-
-        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
-        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Building neural networks in Tensorflow and Keras

- -

Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. -

- -

In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. -

- -









-

Tensorflow

- -

Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. -

- -

Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. -

- -

Tensorflow uses so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow graph -to represent your model, and then create a Tensorflow session to run the graph. -

- -

In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. -

- -

To install tensorflow on Unix/Linux systems, use pip as

- - -
-
-
-
-
-
pip3 install tensorflow
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

and/or if you use anaconda, just write (or install from the graphical user interface) -(current release of CPU-only TensorFlow) -

- - -
-
-
-
-
-
conda create -n tf tensorflow
-conda activate tf
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

To install the current release of GPU TensorFlow

- - -
-
-
-
-
-
conda create -n tf-gpu tensorflow-gpu
-conda activate tf-gpu
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Using Keras

- -

Keras is a high level neural network -that supports Tensorflow, CTNK and Theano as backends. -If you have Anaconda installed you may run the following command -

- - -
-
-
-
-
-
conda install keras
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

You can look up the instructions here for more information.

- -

We will to a large extent use keras in this course.

- -









-

Collect and pre-process data

- -

Let us look again at the MINST data set.

- - - -
-
-
-
-
-
# import necessary packages
-import numpy as np
-import matplotlib.pyplot as plt
-import tensorflow as tf
-from sklearn import datasets
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-
-# display images in notebook
-%matplotlib inline
-plt.rcParams['figure.figsize'] = (12,12)
-
-
-# download MNIST dataset
-digits = datasets.load_digits()
-
-# define inputs and labels
-inputs = digits.images
-labels = digits.target
-
-print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
-print("labels = (n_inputs) = " + str(labels.shape))
-
-
-# flatten the image
-# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
-n_inputs = len(inputs)
-inputs = inputs.reshape(n_inputs, -1)
-print("X = (n_inputs, n_features) = " + str(inputs.shape))
-
-
-# choose some random images to display
-indices = np.arange(n_inputs)
-random_indices = np.random.choice(indices, size=5)
-
-for i, image in enumerate(digits.images[random_indices]):
-    plt.subplot(1, 5, i+1)
-    plt.axis('off')
-    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
-    plt.title("Label: %d" % digits.target[random_indices[i]])
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
-from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
-from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
-from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
-from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
-
-from sklearn.model_selection import train_test_split
-
-# one-hot representation of labels
-labels = to_categorical(labels)
-
-# split into train and test data
-train_size = 0.8
-test_size = 1 - train_size
-X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
-                                                    test_size=test_size)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
epochs = 100
-batch_size = 100
-n_neurons_layer1 = 100
-n_neurons_layer2 = 50
-n_categories = 10
-eta_vals = np.logspace(-5, 1, 7)
-lmbd_vals = np.logspace(-5, 1, 7)
-def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
-    model = Sequential()
-    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
-    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
-    model.add(Dense(n_categories, activation='softmax'))
-    
-    sgd = optimizers.SGD(lr=eta)
-    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
-    
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-        
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
-                                         eta=eta, lmbd=lmbd)
-        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
-        scores = DNN.evaluate(X_test, Y_test)
-        
-        DNN_keras[i][j] = DNN
-        
-        print("Learning rate = ", eta)
-        print("Lambda = ", lmbd)
-        print("Test accuracy: %.3f" % scores[1])
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
# optional
-# visual representation of grid search
-# uses seaborn heatmap, could probably do this in matplotlib
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        DNN = DNN_keras[i][j]
-
-        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
-        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

The Breast Cancer Data, now with Keras

- - - -
-
-
-
-
-
import tensorflow as tf
-from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
-from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
-from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
-from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
-from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
-import numpy as np
-import matplotlib.pyplot as plt
-import seaborn as sns
-from sklearn.model_selection import train_test_split as splitter
-from sklearn.datasets import load_breast_cancer
-import pickle
-import os 
-
-
-"""Load breast cancer dataset"""
-
-np.random.seed(0)        #create same seed for random number every time
-
-cancer=load_breast_cancer()      #Download breast cancer dataset
-
-inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
-outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
-labels=cancer.feature_names[0:30]
-
-print('The content of the breast cancer dataset is:')      #Print information about the datasets
-print(labels)
-print('-------------------------')
-print("inputs =  " + str(inputs.shape))
-print("outputs =  " + str(outputs.shape))
-print("labels =  "+ str(labels.shape))
-
-x=inputs      #Reassign the Feature and Label matrices to other variables
-y=outputs
-
-#%% 
-
-# Visualisation of dataset (for correlation analysis)
-
-plt.figure()
-plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean radius',fontweight='bold')
-plt.ylabel('Mean perimeter',fontweight='bold')
-plt.show()
-
-plt.figure()
-plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
-plt.xlabel('Mean compactness',fontweight='bold')
-plt.ylabel('Mean concavity',fontweight='bold')
-plt.show()
-
-
-plt.figure()
-plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean radius',fontweight='bold')
-plt.ylabel('Mean texture',fontweight='bold')
-plt.show()
-
-plt.figure()
-plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean perimeter',fontweight='bold')
-plt.ylabel('Mean compactness',fontweight='bold')
-plt.show()
-
-
-# Generate training and testing datasets
-
-#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
-#and add to input matrix
-
-temp1=np.reshape(x[:,1],(len(x[:,1]),1))
-temp2=np.reshape(x[:,2],(len(x[:,2]),1))
-X=np.hstack((temp1,temp2))      
-temp=np.reshape(x[:,5],(len(x[:,5]),1))
-X=np.hstack((X,temp))       
-temp=np.reshape(x[:,8],(len(x[:,8]),1))
-X=np.hstack((X,temp))       
-
-X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
-
-y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
-y_test=to_categorical(y_test)
-
-del temp1,temp2,temp
-
-# %%
-
-# Define tunable parameters"
-
-eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
-lamda=0.01                                  #Define hyperparameter
-n_layers=2                                  #Define number of hidden layers in the model
-n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
-epochs=100                                   #Number of reiterations over the input data
-batch_size=100                              #Number of samples per gradient update
-
-# %%
-
-"""Define function to return Deep Neural Network model"""
-
-def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
-    model=Sequential()      
-    for i in range(n_layers):       #Run loop to add hidden layers to the model
-        if (i==0):                  #First layer requires input dimensions
-            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
-        else:                       #Subsequent layers are capable of automatic shape inferencing
-            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
-    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
-    sgd=optimizers.SGD(lr=eta)
-    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
-    return model
-
-    
-Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
-Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
-
-for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
-    for j in range(len(eta)):      #accuracy scores 
-        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
-        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
-        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
-        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
-               
-
-def plot_data(x,y,data,title=None):
-
-    # plot results
-    fontsize=16
-
-
-    fig = plt.figure()
-    ax = fig.add_subplot(111)
-    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
-    
-    cbar=fig.colorbar(cax)
-    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
-    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
-    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
-
-    # put text on matrix elements
-    for i, x_val in enumerate(np.arange(len(x))):
-        for j, y_val in enumerate(np.arange(len(y))):
-            c = "${0:.1f}\\%$".format( 100*data[j,i])  
-            ax.text(x_val, y_val, c, va='center', ha='center')
-
-    # convert axis vaues to to string labels
-    x=[str(i) for i in x]
-    y=[str(i) for i in y]
-
-
-    ax.set_xticklabels(['']+x)
-    ax.set_yticklabels(['']+y)
-
-    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
-    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
-    if title is not None:
-        ax.set_title(title)
-
-    plt.tight_layout()
-
-    plt.show()
-    
-plot_data(eta,n_neuron,Train_accuracy, 'training')
-plot_data(eta,n_neuron,Test_accuracy, 'testing')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Building a neural network code

- -

Here we present a flexible object oriented codebase -for a feed forward neural network, along with a demonstration of how -to use it. Before we get into the details of the neural network, we -will first present some implementations of various schedulers, cost -functions and activation functions that can be used together with the -neural network. -

- -

The codes here were developed by Eric Reber and Gregor Kajda during spring 2023.

-

Learning rate methods

- -

The code below shows object oriented implementations of the Constant, -Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All -of the classes belong to the shared abstract Scheduler class, and -share the update_change() and reset() methods allowing for any of the -schedulers to be seamlessly used during the training stage, as will -later be shown in the fit() method of the neural -network. Update_change() only has one parameter, the gradient -(\( δ^l_ja^{l−1}_k \)), and returns the change which will be subtracted -from the weights. The reset() function takes no parameters, and resets -the desired variables. For Constant and Momentum, reset does nothing. -

- - - -
-
-
-
-
-
import autograd.numpy as np
-
-class Scheduler:
-    """
-    Abstract class for Schedulers
-    """
-
-    def __init__(self, eta):
-        self.eta = eta
-
-    # should be overwritten
-    def update_change(self, gradient):
-        raise NotImplementedError
-
-    # overwritten if needed
-    def reset(self):
-        pass
-
-
-class Constant(Scheduler):
-    def __init__(self, eta):
-        super().__init__(eta)
-
-    def update_change(self, gradient):
-        return self.eta * gradient
-    
-    def reset(self):
-        pass
-
-
-class Momentum(Scheduler):
-    def __init__(self, eta: float, momentum: float):
-        super().__init__(eta)
-        self.momentum = momentum
-        self.change = 0
-
-    def update_change(self, gradient):
-        self.change = self.momentum * self.change + self.eta * gradient
-        return self.change
-
-    def reset(self):
-        pass
-
-
-class Adagrad(Scheduler):
-    def __init__(self, eta):
-        super().__init__(eta)
-        self.G_t = None
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        if self.G_t is None:
-            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
-
-        self.G_t += gradient @ gradient.T
-
-        G_t_inverse = 1 / (
-            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
-        )
-        return self.eta * gradient * G_t_inverse
-
-    def reset(self):
-        self.G_t = None
-
-
-class AdagradMomentum(Scheduler):
-    def __init__(self, eta, momentum):
-        super().__init__(eta)
-        self.G_t = None
-        self.momentum = momentum
-        self.change = 0
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        if self.G_t is None:
-            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
-
-        self.G_t += gradient @ gradient.T
-
-        G_t_inverse = 1 / (
-            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
-        )
-        self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse
-        return self.change
-
-    def reset(self):
-        self.G_t = None
-
-
-class RMS_prop(Scheduler):
-    def __init__(self, eta, rho):
-        super().__init__(eta)
-        self.rho = rho
-        self.second = 0.0
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-        self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient
-        return self.eta * gradient / (np.sqrt(self.second + delta))
-
-    def reset(self):
-        self.second = 0.0
-
-
-class Adam(Scheduler):
-    def __init__(self, eta, rho, rho2):
-        super().__init__(eta)
-        self.rho = rho
-        self.rho2 = rho2
-        self.moment = 0
-        self.second = 0
-        self.n_epochs = 1
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        self.moment = self.rho * self.moment + (1 - self.rho) * gradient
-        self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient
-
-        moment_corrected = self.moment / (1 - self.rho**self.n_epochs)
-        second_corrected = self.second / (1 - self.rho2**self.n_epochs)
-
-        return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))
-
-    def reset(self):
-        self.n_epochs += 1
-        self.moment = 0
-        self.second = 0
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Usage of the above learning rate schedulers

- -

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. -

- - - -
-
-
-
-
-
momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)
-adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Here is a small example for how a segment of code using schedulers -could look. Switching out the schedulers is simple. -

- - - -
-
-
-
-
-
weights = np.ones((3,3))
-print(f"Before scheduler:\n{weights=}")
-
-epochs = 10
-for e in range(epochs):
-    gradient = np.random.rand(3, 3)
-    change = adam_scheduler.update_change(gradient)
-    weights = weights - change
-    adam_scheduler.reset()
-
-print(f"\nAfter scheduler:\n{weights=}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Cost functions

- -

Here we discuss cost functions that can be used when creating the -neural network. Every cost function takes the target vector as its -parameter, and returns a function valued only at \( x \) such that it may -easily be differentiated. -

- - - -
-
-
-
-
-
import autograd.numpy as np
-
-def CostOLS(target):
-    
-    def func(X):
-        return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)
-
-    return func
-
-
-def CostLogReg(target):
-
-    def func(X):
-        
-        return -(1.0 / target.shape[0]) * np.sum(
-            (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))
-        )
-
-    return func
-
-
-def CostCrossEntropy(target):
-    
-    def func(X):
-        return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))
-
-    return func
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Below we give a short example of how these cost function may be used -to obtain results if you wish to test them out on your own using -AutoGrad's automatics differentiation. -

- - - -
-
-
-
-
-
from autograd import grad
-
-target = np.array([[1, 2, 3]]).T
-a = np.array([[4, 5, 6]]).T
-
-cost_func = CostCrossEntropy
-cost_func_derivative = grad(cost_func(target))
-
-valued_at_a = cost_func_derivative(a)
-print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Activation functions

- -

Finally, before we look at the neural network, we will look at the -activation functions which can be specified between the hidden layers -and as the output function. Each function can be valued for any given -vector or matrix X, and can be differentiated via derivate(). -

- - - -
-
-
-
-
-
import autograd.numpy as np
-from autograd import elementwise_grad
-
-def identity(X):
-    return X
-
-
-def sigmoid(X):
-    try:
-        return 1.0 / (1 + np.exp(-X))
-    except FloatingPointError:
-        return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))
-
-
-def softmax(X):
-    X = X - np.max(X, axis=-1, keepdims=True)
-    delta = 10e-10
-    return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)
-
-
-def RELU(X):
-    return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))
-
-
-def LRELU(X):
-    delta = 10e-4
-    return np.where(X > np.zeros(X.shape), X, delta * X)
-
-
-def derivate(func):
-    if func.__name__ == "RELU":
-
-        def func(X):
-            return np.where(X > 0, 1, 0)
-
-        return func
-
-    elif func.__name__ == "LRELU":
-
-        def func(X):
-            delta = 10e-4
-            return np.where(X > 0, 1, delta)
-
-        return func
-
-    else:
-        return elementwise_grad(func)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Below follows a short demonstration of how to use an activation -function. The derivative of the activation function will be important -when calculating the output delta term during backpropagation. Note -that derivate() can also be used for cost functions for a more -generalized approach. -

- - - -
-
-
-
-
-
z = np.array([[4, 5, 6]]).T
-print(f"Input to activation function:\n{z}")
-
-act_func = sigmoid
-a = act_func(z)
-print(f"\nOutput from {act_func.__name__} activation function:\n{a}")
-
-act_func_derivative = derivate(act_func)
-valued_at_z = act_func_derivative(a)
-print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

The Neural Network

- -

Now that we have gotten a good understanding of the implementation of -some important components, we can take a look at an object oriented -implementation of a feed forward neural network. The feed forward -neural network has been implemented as a class named FFNN, which can -be initiated as a regressor or classifier dependant on the choice of -cost function. The FFNN can have any number of input nodes, hidden -layers with any amount of hidden nodes, and any amount of output nodes -meaning it can perform multiclass classification as well as binary -classification and regression problems. Although there is a lot of -code present, it makes for an easy to use and generalizeable interface -for creating many types of neural networks as will be demonstrated -below. -

- - - -
-
-
-
-
-
import math
-import autograd.numpy as np
-import sys
-import warnings
-from autograd import grad, elementwise_grad
-from random import random, seed
-from copy import deepcopy, copy
-from typing import Tuple, Callable
-from sklearn.utils import resample
-
-warnings.simplefilter("error")
-
-
-class FFNN:
-    """
-    Description:
-    ------------
-        Feed Forward Neural Network with interface enabling flexible design of a
-        nerual networks architecture and the specification of activation function
-        in the hidden layers and output layer respectively. This model can be used
-        for both regression and classification problems, depending on the output function.
-
-    Attributes:
-    ------------
-        I   dimensions (tuple[int]): A list of positive integers, which specifies the
-            number of nodes in each of the networks layers. The first integer in the array
-            defines the number of nodes in the input layer, the second integer defines number
-            of nodes in the first hidden layer and so on until the last number, which
-            specifies the number of nodes in the output layer.
-        II  hidden_func (Callable): The activation function for the hidden layers
-        III output_func (Callable): The activation function for the output layer
-        IV  cost_func (Callable): Our cost function
-        V   seed (int): Sets random seed, makes results reproducible
-    """
-
-    def __init__(
-        self,
-        dimensions: tuple[int],
-        hidden_func: Callable = sigmoid,
-        output_func: Callable = lambda x: x,
-        cost_func: Callable = CostOLS,
-        seed: int = None,
-    ):
-        self.dimensions = dimensions
-        self.hidden_func = hidden_func
-        self.output_func = output_func
-        self.cost_func = cost_func
-        self.seed = seed
-        self.weights = list()
-        self.schedulers_weight = list()
-        self.schedulers_bias = list()
-        self.a_matrices = list()
-        self.z_matrices = list()
-        self.classification = None
-
-        self.reset_weights()
-        self._set_classification()
-
-    def fit(
-        self,
-        X: np.ndarray,
-        t: np.ndarray,
-        scheduler: Scheduler,
-        batches: int = 1,
-        epochs: int = 100,
-        lam: float = 0,
-        X_val: np.ndarray = None,
-        t_val: np.ndarray = None,
-    ):
-        """
-        Description:
-        ------------
-            This function performs the training the neural network by performing the feedforward and backpropagation
-            algorithm to update the networks weights.
-
-        Parameters:
-        ------------
-            I    X (np.ndarray) : training data
-            II   t (np.ndarray) : target data
-            III  scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)
-            IV   scheduler_args (list[int]) : list of all arguments necessary for scheduler
-
-        Optional Parameters:
-        ------------
-            V    batches (int) : number of batches the datasets are split into, default equal to 1
-            VI   epochs (int) : number of iterations used to train the network, default equal to 100
-            VII  lam (float) : regularization hyperparameter lambda
-            VIII X_val (np.ndarray) : validation set
-            IX   t_val (np.ndarray) : validation target set
-
-        Returns:
-        ------------
-            I   scores (dict) : A dictionary containing the performance metrics of the model.
-                The number of the metrics depends on the parameters passed to the fit-function.
-
-        """
-
-        # setup 
-        if self.seed is not None:
-            np.random.seed(self.seed)
-
-        val_set = False
-        if X_val is not None and t_val is not None:
-            val_set = True
-
-        # creating arrays for score metrics
-        train_errors = np.empty(epochs)
-        train_errors.fill(np.nan)
-        val_errors = np.empty(epochs)
-        val_errors.fill(np.nan)
-
-        train_accs = np.empty(epochs)
-        train_accs.fill(np.nan)
-        val_accs = np.empty(epochs)
-        val_accs.fill(np.nan)
-
-        self.schedulers_weight = list()
-        self.schedulers_bias = list()
-
-        batch_size = X.shape[0] // batches
-
-        X, t = resample(X, t)
-
-        # this function returns a function valued only at X
-        cost_function_train = self.cost_func(t)
-        if val_set:
-            cost_function_val = self.cost_func(t_val)
-
-        # create schedulers for each weight matrix
-        for i in range(len(self.weights)):
-            self.schedulers_weight.append(copy(scheduler))
-            self.schedulers_bias.append(copy(scheduler))
-
-        print(f"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}")
-
-        try:
-            for e in range(epochs):
-                for i in range(batches):
-                    # allows for minibatch gradient descent
-                    if i == batches - 1:
-                        # If the for loop has reached the last batch, take all thats left
-                        X_batch = X[i * batch_size :, :]
-                        t_batch = t[i * batch_size :, :]
-                    else:
-                        X_batch = X[i * batch_size : (i + 1) * batch_size, :]
-                        t_batch = t[i * batch_size : (i + 1) * batch_size, :]
-
-                    self._feedforward(X_batch)
-                    self._backpropagate(X_batch, t_batch, lam)
-
-                # reset schedulers for each epoch (some schedulers pass in this call)
-                for scheduler in self.schedulers_weight:
-                    scheduler.reset()
-
-                for scheduler in self.schedulers_bias:
-                    scheduler.reset()
-
-                # computing performance metrics
-                pred_train = self.predict(X)
-                train_error = cost_function_train(pred_train)
-
-                train_errors[e] = train_error
-                if val_set:
-                    
-                    pred_val = self.predict(X_val)
-                    val_error = cost_function_val(pred_val)
-                    val_errors[e] = val_error
-
-                if self.classification:
-                    train_acc = self._accuracy(self.predict(X), t)
-                    train_accs[e] = train_acc
-                    if val_set:
-                        val_acc = self._accuracy(pred_val, t_val)
-                        val_accs[e] = val_acc
-
-                # printing progress bar
-                progression = e / epochs
-                print_length = self._progress_bar(
-                    progression,
-                    train_error=train_errors[e],
-                    train_acc=train_accs[e],
-                    val_error=val_errors[e],
-                    val_acc=val_accs[e],
-                )
-        except KeyboardInterrupt:
-            # allows for stopping training at any point and seeing the result
-            pass
-
-        # visualization of training progression (similiar to tensorflow progression bar)
-        sys.stdout.write("\r" + " " * print_length)
-        sys.stdout.flush()
-        self._progress_bar(
-            1,
-            train_error=train_errors[e],
-            train_acc=train_accs[e],
-            val_error=val_errors[e],
-            val_acc=val_accs[e],
-        )
-        sys.stdout.write("")
-
-        # return performance metrics for the entire run
-        scores = dict()
-
-        scores["train_errors"] = train_errors
-
-        if val_set:
-            scores["val_errors"] = val_errors
-
-        if self.classification:
-            scores["train_accs"] = train_accs
-
-            if val_set:
-                scores["val_accs"] = val_accs
-
-        return scores
-
-    def predict(self, X: np.ndarray, *, threshold=0.5):
-        """
-         Description:
-         ------------
-             Performs prediction after training of the network has been finished.
-
-         Parameters:
-        ------------
-             I   X (np.ndarray): The design matrix, with n rows of p features each
-
-         Optional Parameters:
-         ------------
-             II  threshold (float) : sets minimal value for a prediction to be predicted as the positive class
-                 in classification problems
-
-         Returns:
-         ------------
-             I   z (np.ndarray): A prediction vector (row) for each row in our design matrix
-                 This vector is thresholded if regression=False, meaning that classification results
-                 in a vector of 1s and 0s, while regressions in an array of decimal numbers
-
-        """
-
-        predict = self._feedforward(X)
-
-        if self.classification:
-            return np.where(predict > threshold, 1, 0)
-        else:
-            return predict
-
-    def reset_weights(self):
-        """
-        Description:
-        ------------
-            Resets/Reinitializes the weights in order to train the network for a new problem.
-
-        """
-        if self.seed is not None:
-            np.random.seed(self.seed)
-
-        self.weights = list()
-        for i in range(len(self.dimensions) - 1):
-            weight_array = np.random.randn(
-                self.dimensions[i] + 1, self.dimensions[i + 1]
-            )
-            weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01
-
-            self.weights.append(weight_array)
-
-    def _feedforward(self, X: np.ndarray):
-        """
-        Description:
-        ------------
-            Calculates the activation of each layer starting at the input and ending at the output.
-            Each following activation is calculated from a weighted sum of each of the preceeding
-            activations (except in the case of the input layer).
-
-        Parameters:
-        ------------
-            I   X (np.ndarray): The design matrix, with n rows of p features each
-
-        Returns:
-        ------------
-            I   z (np.ndarray): A prediction vector (row) for each row in our design matrix
-        """
-
-        # reset matrices
-        self.a_matrices = list()
-        self.z_matrices = list()
-
-        # if X is just a vector, make it into a matrix
-        if len(X.shape) == 1:
-            X = X.reshape((1, X.shape[0]))
-
-        # Add a coloumn of zeros as the first coloumn of the design matrix, in order
-        # to add bias to our data
-        bias = np.ones((X.shape[0], 1)) * 0.01
-        X = np.hstack([bias, X])
-
-        # a^0, the nodes in the input layer (one a^0 for each row in X - where the
-        # exponent indicates layer number).
-        a = X
-        self.a_matrices.append(a)
-        self.z_matrices.append(a)
-
-        # The feed forward algorithm
-        for i in range(len(self.weights)):
-            if i < len(self.weights) - 1:
-                z = a @ self.weights[i]
-                self.z_matrices.append(z)
-                a = self.hidden_func(z)
-                # bias column again added to the data here
-                bias = np.ones((a.shape[0], 1)) * 0.01
-                a = np.hstack([bias, a])
-                self.a_matrices.append(a)
-            else:
-                try:
-                    # a^L, the nodes in our output layers
-                    z = a @ self.weights[i]
-                    a = self.output_func(z)
-                    self.a_matrices.append(a)
-                    self.z_matrices.append(z)
-                except Exception as OverflowError:
-                    print(
-                        "OverflowError in fit() in FFNN\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling"
-                    )
-
-        # this will be a^L
-        return a
-
-    def _backpropagate(self, X, t, lam):
-        """
-        Description:
-        ------------
-            Performs the backpropagation algorithm. In other words, this method
-            calculates the gradient of all the layers starting at the
-            output layer, and moving from right to left accumulates the gradient until
-            the input layer is reached. Each layers respective weights are updated while
-            the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).
-
-        Parameters:
-        ------------
-            I   X (np.ndarray): The design matrix, with n rows of p features each.
-            II  t (np.ndarray): The target vector, with n rows of p targets.
-            III lam (float32): regularization parameter used to punish the weights in case of overfitting
-
-        Returns:
-        ------------
-            No return value.
-
-        """
-        out_derivative = derivate(self.output_func)
-        hidden_derivative = derivate(self.hidden_func)
-
-        for i in range(len(self.weights) - 1, -1, -1):
-            # delta terms for output
-            if i == len(self.weights) - 1:
-                # for multi-class classification
-                if (
-                    self.output_func.__name__ == "softmax"
-                ):
-                    delta_matrix = self.a_matrices[i + 1] - t
-                # for single class classification
-                else:
-                    cost_func_derivative = grad(self.cost_func(t))
-                    delta_matrix = out_derivative(
-                        self.z_matrices[i + 1]
-                    ) * cost_func_derivative(self.a_matrices[i + 1])
-
-            # delta terms for hidden layer
-            else:
-                delta_matrix = (
-                    self.weights[i + 1][1:, :] @ delta_matrix.T
-                ).T * hidden_derivative(self.z_matrices[i + 1])
-
-            # calculate gradient
-            gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix
-            gradient_bias = np.sum(delta_matrix, axis=0).reshape(
-                1, delta_matrix.shape[1]
-            )
-
-            # regularization term
-            gradient_weights += self.weights[i][1:, :] * lam
-
-            # use scheduler
-            update_matrix = np.vstack(
-                [
-                    self.schedulers_bias[i].update_change(gradient_bias),
-                    self.schedulers_weight[i].update_change(gradient_weights),
-                ]
-            )
-
-            # update weights and bias
-            self.weights[i] -= update_matrix
-
-    def _accuracy(self, prediction: np.ndarray, target: np.ndarray):
-        """
-        Description:
-        ------------
-            Calculates accuracy of given prediction to target
-
-        Parameters:
-        ------------
-            I   prediction (np.ndarray): vector of predicitons output network
-                (1s and 0s in case of classification, and real numbers in case of regression)
-            II  target (np.ndarray): vector of true values (What the network ideally should predict)
-
-        Returns:
-        ------------
-            A floating point number representing the percentage of correctly classified instances.
-        """
-        assert prediction.size == target.size
-        return np.average((target == prediction))
-    def _set_classification(self):
-        """
-        Description:
-        ------------
-            Decides if FFNN acts as classifier (True) og regressor (False),
-            sets self.classification during init()
-        """
-        self.classification = False
-        if (
-            self.cost_func.__name__ == "CostLogReg"
-            or self.cost_func.__name__ == "CostCrossEntropy"
-        ):
-            self.classification = True
-
-    def _progress_bar(self, progression, **kwargs):
-        """
-        Description:
-        ------------
-            Displays progress of training
-        """
-        print_length = 40
-        num_equals = int(progression * print_length)
-        num_not = print_length - num_equals
-        arrow = ">" if num_equals > 0 else ""
-        bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]"
-        perc_print = self._format(progression * 100, decimals=5)
-        line = f"  {bar} {perc_print}% "
-
-        for key in kwargs:
-            if not np.isnan(kwargs[key]):
-                value = self._format(kwargs[key], decimals=4)
-                line += f"| {key}: {value} "
-        sys.stdout.write("\r" + line)
-        sys.stdout.flush()
-        return len(line)
-
-    def _format(self, value, decimals=4):
-        """
-        Description:
-        ------------
-            Formats decimal numbers for progress bar
-        """
-        if value > 0:
-            v = value
-        elif value < 0:
-            v = -10 * value
-        else:
-            v = 1
-        n = 1 + math.floor(math.log10(v))
-        if n >= decimals - 1:
-            return str(round(value))
-        return f"{value:.{decimals-n-1}f}"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Before we make a model, we will quickly generate a dataset we can use -for our linear regression problem as shown below -

- - - -
-
-
-
-
-
import autograd.numpy as np
-from sklearn.model_selection import train_test_split
-
-def SkrankeFunction(x, y):
-    return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)
-
-def create_X(x, y, n):
-    if len(x.shape) > 1:
-        x = np.ravel(x)
-        y = np.ravel(y)
-
-    N = len(x)
-    l = int((n + 1) * (n + 2) / 2)  # Number of elements in beta
-    X = np.ones((N, l))
-
-    for i in range(1, n + 1):
-        q = int((i) * (i + 1) / 2)
-        for k in range(i + 1):
-            X[:, q + k] = (x ** (i - k)) * (y**k)
-
-    return X
-
-step=0.5
-x = np.arange(0, 1, step)
-y = np.arange(0, 1, step)
-x, y = np.meshgrid(x, y)
-target = SkrankeFunction(x, y)
-target = target.reshape(target.shape[0], 1)
-
-poly_degree=3
-X = create_X(x, y, poly_degree)
-
-X_train, X_test, t_train, t_test = train_test_split(X, target)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now that we have our dataset ready for the regression, we can create -our regressor. Note that with the seed parameter, we can make sure our -results stay the same every time we run the neural network. For -inititialization, we simply specify the dimensions (we wish the amount -of input nodes to be equal to the datapoints, and the output to -predict one value). -

- - - -
-
-
-
-
-
input_nodes = X_train.shape[1]
-output_nodes = 1
-
-linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We then fit our model with our training data using the scheduler of our choice.

- - - -
-
-
-
-
-
linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Constant(eta=1e-3)
-scores = linear_regression.fit(X_train, t_train, scheduler)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Due to the progress bar we can see the MSE (train_error) throughout -the FFNN's training. Note that the fit() function has some optional -parameters with defualt arguments. For example, the regularization -hyperparameter can be left ignored if not needed, and equally the FFNN -will by default run for 100 epochs. These can easily be changed, such -as for example: -

- - - -
-
-
-
-
-
linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that given more epochs to train on, the regressor reaches a lower MSE.

- -

Let us then switch to a binary classification. We use a binary -classification dataset, and follow a similar setup to the regression -case. -

- - - -
-
-
-
-
-
from sklearn.datasets import load_breast_cancer
-from sklearn.preprocessing import MinMaxScaler
-
-wisconsin = load_breast_cancer()
-X = wisconsin.data
-target = wisconsin.target
-target = target.reshape(target.shape[0], 1)
-
-X_train, X_val, t_train, t_val = train_test_split(X, target)
-
-scaler = MinMaxScaler()
-scaler.fit(X_train)
-X_train = scaler.transform(X_train)
-X_val = scaler.transform(X_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
input_nodes = X_train.shape[1]
-output_nodes = 1
-
-logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We will now make use of our validation data by passing it into our fit function as a keyword argument

- - - -
-
-
-
-
-
logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
-scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Finally, we will create a neural network with 2 hidden layers with activation functions.

- - -
-
-
-
-
-
input_nodes = X_train.shape[1]
-hidden_nodes1 = 100
-hidden_nodes2 = 30
-output_nodes = 1
-
-dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
-
-neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
-scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Multiclass classification

- -

Finally, we will demonstrate the use case of multiclass classification -using our FFNN with the famous MNIST dataset, which contain images of -digits between the range of 0 to 9. -

- - - -
-
-
-
-
-
from sklearn.datasets import load_digits
-
-def onehot(target: np.ndarray):
-    onehot = np.zeros((target.size, target.max() + 1))
-    onehot[np.arange(target.size), target] = 1
-    return onehot
-
-digits = load_digits()
-
-X = digits.data
-target = digits.target
-target = onehot(target)
-
-input_nodes = 64
-hidden_nodes1 = 100
-hidden_nodes2 = 30
-output_nodes = 10
-
-dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
-
-multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)
-
-multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
-scores = multiclass.fit(X, target, scheduler, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Testing the XOR gate and other gates

- -

Let us now use our code to test the XOR gate.

- - - -
-
-
-
-
-
X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
-
-# The XOR gate
-yXOR = np.array( [[ 0], [1] ,[1], [0]])
-
-input_nodes = X.shape[1]
-output_nodes = 1
-
-logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999)
-scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Not bad, but the results depend strongly on the learning reate. Try different learning rates.

- -
- © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - diff --git a/doc/src/week42/week42.do.txt b/doc/src/week42/week42.do.txt index 786b65b30..146f0cdb0 100644 --- a/doc/src/week42/week42.do.txt +++ b/doc/src/week42/week42.do.txt @@ -322,17 +322,17 @@ up the equations for a neural network with two input nodes, one hidden layer with two hidden nodes and one output layer with one output node/neuron only (see graph).. We need to define the following parameters and variables with the input layer (layer $(0)$) -where we label the nodes $x_0$ and $x_1$ +where we label the nodes $x_1$ and $x_2$ !bt \[ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. +x_1 = a_1^{(0)} \wedge x_2 = a_2^{(0)}. \] !et -The hidden layer (layer $(1)$) has nodes which yield the outputs $a_0^{(1)}$ and $a_1^{(1)}$) with weight $\bm{w}$ and bias $\bm{b}$ parameters +The hidden layer (layer $(1)$) has nodes which yield the outputs $a_1^{(1)}$ and $a_2^{(1)}$) with weight $\bm{w}$ and bias $\bm{b}$ parameters !bt \[ -w_{ij}^{(1)}=\left\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\right\} \wedge b^{(1)}=\left\{b_0^{(1)},b_1^{(1)}\right\}. +w_{ij}^{(1)}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)}\right\} \wedge b^{(1)}=\left\{b_1^{(1)},b_2^{(1)}\right\}. \] !et diff --git a/doc/src/week42/week42.html b/doc/src/week42/week42.html deleted file mode 100644 index 10fd5c21b..000000000 --- a/doc/src/week42/week42.html +++ /dev/null @@ -1,4978 +0,0 @@ - - - - - - - -Week 42 Constructing a Neural Network code with examples - - - - - - - - - - - - - - -
-

Week 42 Constructing a Neural Network code with examples

-
- - -
-Morten Hjorth-Jensen [1, 2] -
- -
-[1] Department of Physics, University of Oslo -
-
-[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University -
-
-
-

October 14-18, 2024

-
-
- -









-

Lecture October 14, 2024

-
- -

-

    -
  1. Building our own Feed-forward Neural Network and discussion of project 2
  2. -
-
- -
-Readings and videos -

-

    -
  1. These lecture notes - -
  2. -
  3. For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7.
  4. -
  5. Neural Networks demystified at https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs
  6. -
  7. Building Neural Networks from scratch at https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex
  8. -
  9. Video on Neural Networks at https://www.youtube.com/watch?v=CqOfi41LfDw
  10. -
  11. Video on the back propagation algorithm at https://www.youtube.com/watch?v=Ilg3gGewQ5U
  12. -
-

I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at http://neuralnetworksanddeeplearning.com/chap4.html.

-
- - -









-

Material for the active learning sessions on Tuesday and Wednesday

-
- -

-

    -
  • Exercise on starting to write a code for neural networks, feed forward part. We will also continue ur discussions of gradient descent methods from last week. If you have time, start considering the back-propagation part as well (exercises for next week)
  • -
  • Discussion of project 2
  • -
-
- - -

Note: some of the codes will also be discussed next week in connection with the solution of differential equations.

- -









-

Writing a code which implements a feed-forward neural network

- -

Last week we discussed the basics of neural networks and deep learning -and the basics of automatic differentiation. We looked also at -examples on how compute the parameters of a simple network with scalar -inputs and ouputs and no or just one hidden layers. -

- -

We ended our discussions with the derivation of the equations for a -neural network with one hidden layers and two input variables and two -hidden nodes but only one output node. -

- -









-

Mathematics of deep learning

- - - - -









-

Reminder on books with hands-on material and codes

- - - -









-

Reading recommendations

- -
    -
  1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub
  2. -
  3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
  4. -
-









-

First network example, simple percepetron with one input

- -

As yet another example we define now a simple perceptron model with -all quantities given by scalars. We consider only one input variable -\( x \) and one target value \( y \). We define an activation function -\( \sigma_1 \) which takes as input -

- -$$ -z_1 = w_1x+b_1, -$$ - -

where \( w_1 \) is the weight and \( b_1 \) is the bias. These are the -parameters we want to optimize. The output is \( a_1=\sigma(z_1) \) (see -graph from whiteboard notes). This output is then fed into the -cost/loss function, which we here for the sake of simplicity just -define as the squared error -

- -$$ -C(x;w_1,b_1)=\frac{1}{2}(a_1-y)^2. -$$ - - -









-

Layout of a simple neural network with no hidden layer

- -

-
-

-
-

- -









-

Optimizing the parameters

- -

In setting up the feed forward and back propagation parts of the -algorithm, we need now the derivative of the various variables we want -to train. -

- -

We need

-$$ -\frac{\partial C}{\partial w_1} \hspace{0.1cm}\mathrm{and}\hspace{0.1cm}\frac{\partial C}{\partial b_1}. -$$ - -

Using the chain rule we find

-$$ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_1-y)\sigma_1'x, -$$ - -

and

-$$ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_1-y)\sigma_1', -$$ - -

which we later will just define as

-$$ -\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}=\delta_1. -$$ - - -









-

Adding a hidden layer

- -

We change our simple model to (see graph) -a network with just one hidden layer but with scalar variables only. -

- -

Our output variable changes to \( a_2 \) and \( a_1 \) is now the output from the hidden node and \( a_0=x \). -We have then -

-$$ -z_1 = w_1a_0+b_1 \hspace{0.1cm} \wedge a_1 = \sigma_1(z_1), -$$ - -$$ -z_2 = w_2a_1+b_2 \hspace{0.1cm} \wedge a_2 = \sigma_2(z_2), -$$ - -

and the cost function

-$$ -C(x;\boldsymbol{\Theta})=\frac{1}{2}(a_2-y)^2, -$$ - -

with \( \boldsymbol{\Theta}=[w_1,w_2,b_1,b_2] \).

- -









-

Layout of a simple neural network with one hidden layer

- -

-
-

-
-

- -









-

The derivatives

- -

The derivatives are now, using the chain rule again

- -$$ -\frac{\partial C}{\partial w_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial w_2}=(a_2-y)\sigma_2'a_1=\delta_2a_1, -$$ - -$$ -\frac{\partial C}{\partial b_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial b_2}=(a_2-y)\sigma_2'=\delta_2, -$$ - -$$ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_2-y)\sigma_2'a_1\sigma_1'a_0, -$$ - -$$ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_2-y)\sigma_2'\sigma_1'=\delta_1. -$$ - -

Can you generalize this to more than one hidden layer?

- -









-

Important observations

- -
- -

-

From the above equations we see that the derivatives of the activation -functions play a central role. If they vanish, the training may -stop. This is called the vanishing gradient problem, see discussions below. If they become -large, the parameters \( w_i \) and \( b_i \) may simply go to infinity. This -is referenced as the exploding gradient problem. -

-
- - -









-

The training

- -

The training of the parameters is done through various gradient descent approximations with

- -$$ -w_{i}\leftarrow w_{i}- \eta \delta_i a_{i-1}, -$$ - -

and

-$$ -b_i \leftarrow b_i-\eta \delta_i, -$$ - -

with \( \eta \) is the learning rate.

- -

One iteration consists of one feed forward step and one back-propagation step. Each back-propagation step does one update of the parameters \( \boldsymbol{\Theta} \).

- -

For the first hidden layer \( a_{i-1}=a_0=x \) for this simple model.

- -









-

Code example

- -

The code here implements the above model with one hidden layer and -scalar variables for the same function we studied in the previous -example. The code is however set up so that we can add multiple -inputs \( x \) and target values \( y \). Note also that we have the -possibility of defining a feature matrix \( \boldsymbol{X} \) with more than just -one column for the input values. This will turn useful in our next example. We have also defined matrices and vectors for all of our operations although it is not necessary here. -

- - - -
-
-
-
-
-
import numpy as np
-# We use the Sigmoid function as activation function
-def sigmoid(z):
-    return 1.0/(1.0+np.exp(-z))
-
-def forwardpropagation(x):
-    # weighted sum of inputs to the hidden layer
-    z_1 = np.matmul(x, w_1) + b_1
-    # activation in the hidden layer
-    a_1 = sigmoid(z_1)
-    # weighted sum of inputs to the output layer
-    z_2 = np.matmul(a_1, w_2) + b_2
-    a_2 = z_2
-    return a_1, a_2
-
-def backpropagation(x, y):
-    a_1, a_2 = forwardpropagation(x)
-    # parameter delta for the output layer, note that a_2=z_2 and its derivative wrt z_2 is just 1
-    delta_2 = a_2 - y
-    print(0.5*((a_2-y)**2))
-    # delta for  the hidden layer
-    delta_1 = np.matmul(delta_2, w_2.T) * a_1 * (1 - a_1)
-    # gradients for the output layer
-    output_weights_gradient = np.matmul(a_1.T, delta_2)
-    output_bias_gradient = np.sum(delta_2, axis=0)
-    # gradient for the hidden layer
-    hidden_weights_gradient = np.matmul(x.T, delta_1)
-    hidden_bias_gradient = np.sum(delta_1, axis=0)
-    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-# Input variable
-x = np.array([4.0],dtype=np.float64)
-# Target values
-y = 2*x+1.0 
-
-# Defining the neural network, only scalars here
-n_inputs = x.shape
-n_features = 1
-n_hidden_neurons = 1
-n_outputs = 1
-
-# Initialize the network
-# weights and bias in the hidden layer
-w_1 = np.random.randn(n_features, n_hidden_neurons)
-b_1 = np.zeros(n_hidden_neurons) + 0.01
-
-# weights and bias in the output layer
-w_2 = np.random.randn(n_hidden_neurons, n_outputs)
-b_2 = np.zeros(n_outputs) + 0.01
-
-eta = 0.1
-for i in range(50):
-    # calculate gradients
-    derivW2, derivB2, derivW1, derivB1 = backpropagation(x, y)
-    # update weights and biases
-    w_2 -= eta * derivW2
-    b_2 -= eta * derivB2
-    w_1 -= eta * derivW1
-    b_1 -= eta * derivB1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that after some few iterations (the results do depend on the learning rate however), we get an error which is rather small.

- -









-

Simple neural network and the back propagation equations

- -

Let us now try to increase our level of ambition and attempt at setting -up the equations for a neural network with two input nodes, one hidden -layer with two hidden nodes and one output layer with one output node/neuron only (see graph).. -

- -

We need to define the following parameters and variables with the input layer (layer \( (0) \)) -where we label the nodes \( x_0 \) and \( x_1 \) -

-$$ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. -$$ - -

The hidden layer (layer \( (1) \)) has nodes which yield the outputs \( a_0^{(1)} \) and \( a_1^{(1)} \)) with weight \( \boldsymbol{w} \) and bias \( \boldsymbol{b} \) parameters

-$$ -w_{ij}^{(1)}=\left\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\right\} \wedge b^{(1)}=\left\{b_0^{(1)},b_1^{(1)}\right\}. -$$ - - -









-

Layout of a simple neural network with two input nodes, one hidden layer with two hidden noeds and one output node

- -

-
-

-
-

- -









-

The ouput layer

- -

We have the ouput layer given by layer label \( (2) \) with output \( a^{(2)} \) and weights and biases to be determined given by the variables

-$$ -w_{i}^{(2)}=\left\{w_{1}^{(2)},w_{2}^{(2)}\right\} \wedge b^{(2)}. -$$ - -

Our output is \( \tilde{y}=a^{(2)} \) and we define a generic cost function \( C(a^{(2)},y;\boldsymbol{\Theta}) \) where \( y \) is the target value (a scalar here). -The parameters we need to optimize are given by -

-$$ -\boldsymbol{\Theta}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)},w_{1}^{(2)},w_{2}^{(2)},b_1^{(1)},b_2^{(1)},b^{(2)}\right\}. -$$ - - -









-

Compact expressions

- -

We can define the inputs to the activation functions for the various layers in terms of various matrix-vector multiplications and vector additions. -The inputs to the first hidden layer are -

-$$ -\begin{bmatrix}z_1^{(1)} \\ z_2^{(1)} \end{bmatrix}=\left(\begin{bmatrix}w_{11}^{(1)} & w_{12}^{(1)}\\ w_{21}^{(1)} &w_{22}^{(1)} \end{bmatrix}\right)^{T}\begin{bmatrix}a_1^{(0)} \\ a_2^{(0)} \end{bmatrix}+\begin{bmatrix}b_1^{(1)} \\ b_2^{(1)} \end{bmatrix}, -$$ - -

with outputs

-$$ -\begin{bmatrix}a_1^{(1)} \\ a_2^{(1)} \end{bmatrix}=\begin{bmatrix}\sigma^{(1)}(z_1^{(1)}) \\ \sigma^{(1)}(z_2^{(1)}) \end{bmatrix}. -$$ - - -









-

Output layer

- -

For the final output layer we have the inputs to the final activation function

-$$ -z^{(2)} = w_{1}^{(2)}a_1^{(1)} +w_{2}^{(2)}a_2^{(1)}+b^{(2)}, -$$ - -

resulting in the output

-$$ -a^{(2)}=\sigma^{(2)}(z^{(2)}). -$$ - - -









-

Explicit derivatives

- -

In total we have nine parameters which we need to train. Using the -chain rule (or just the back-propagation algorithm) we can find all -derivatives. Since we will use automatic differentiation in reverse -mode, we start with the derivatives of the cost function with respect -to the parameters of the output layer, namely -

- -$$ -\frac{\partial C}{\partial w_{i}^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial w_{i}^{(2)}}=\delta^{(2)}a_i^{(1)}, -$$ - -

with

-$$ -\delta^{(2)}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -$$ - -

and finally

-$$ -\frac{\partial C}{\partial b^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial b^{(2)}}=\delta^{(2)}. -$$ - - -









-

Derivatives of the hidden layer

- -

Using the chain rule we have the following expressions for say one of the weight parameters (it is easy to generalize to the other weight parameters)

-$$ -\frac{\partial C}{\partial w_{11}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}= \delta^{(2)}\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}, -$$ - -

which, noting that

-$$ -z^{(2)} =w_1^{(2)}a_1^{(1)}+w_2^{(2)}a_2^{(1)}+b^{(2)}, -$$ - -

allows us to rewrite

-$$ -\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}a_1^{(1)}. -$$ - - -









-

Final expression

-

Defining

-$$ -\delta_1^{(1)}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}\delta^{(2)}, -$$ - -

we have

-$$ -\frac{\partial C}{\partial w_{11}^{(1)}}=\delta_1^{(1)}a_1^{(1)}. -$$ - -

Similarly, we obtain

-$$ -\frac{\partial C}{\partial w_{12}^{(1)}}=\delta_1^{(1)}a_2^{(1)}. -$$ - - -









-

Completing the list

- -

Similarly, we find

-$$ -\frac{\partial C}{\partial w_{21}^{(1)}}=\delta_2^{(1)}a_1^{(1)}, -$$ - -

and

-$$ -\frac{\partial C}{\partial w_{22}^{(1)}}=\delta_2^{(1)}a_2^{(1)}, -$$ - -

where we have defined

-$$ -\delta_2^{(1)}=w_2^{(2)}\frac{\partial a_2^{(1)}}{\partial z_2^{(1)}}\delta^{(2)}. -$$ - - -









-

Final expressions for the biases of the hidden layer

- -

For the sake of completeness, we list the derivatives of the biases, which are

-$$ -\frac{\partial C}{\partial b_{1}^{(1)}}=\delta_1^{(1)}, -$$ - -

and

-$$ -\frac{\partial C}{\partial b_{2}^{(1)}}=\delta_2^{(1)}. -$$ - -

As we will see below, these expressions can be generalized in a more compact form.

- -









-

Gradient expressions

- -

For this specific model, with just one output node and two hidden -nodes, the gradient descent equations take the following form for output layer -

-$$ -w_{i}^{(2)}\leftarrow w_{i}^{(2)}- \eta \delta^{(2)} a_{i}^{(1)}, -$$ - -

and

-$$ -b^{(2)} \leftarrow b^{(2)}-\eta \delta^{(2)}, -$$ - -

and

-$$ -w_{ij}^{(1)}\leftarrow w_{ij}^{(1)}- \eta \delta_{i}^{(1)} a_{j}^{(0)}, -$$ - -

and

-$$ -b_{i}^{(1)} \leftarrow b_{i}^{(1)}-\eta \delta_{i}^{(1)}, -$$ - -

where \( \eta \) is the learning rate.

- -









-

Setting up the equations for a neural network

- -

The questions we want to ask are how do changes in the biases and the -weights in our network change the cost function and how can we use the -final output to modify the weights and biases? -

- -

To derive these equations let us start with a plain regression problem -and define our cost function as -

- -$$ -{\cal C}(\boldsymbol{\Theta}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2, -$$ - -

where the $y_i$s are our \( n \) targets (the values we want to -reproduce), while the outputs of the network after having propagated -all inputs \( \boldsymbol{x} \) are given by \( \boldsymbol{\tilde{y}}_i \). -

- -









-

Layout of a neural network with three hidden layers (last later = \( l=L=4 \), first layer \( l=0 \))

- -

-
-

-
-

- -









-

Definitions

- -

With our definition of the targets \( \boldsymbol{y} \), the outputs of the -network \( \boldsymbol{\tilde{y}} \) and the inputs \( \boldsymbol{x} \) we -define now the activation \( z_j^l \) of node/neuron/unit \( j \) of the -\( l \)-th layer as a function of the bias, the weights which add up from -the previous layer \( l-1 \) and the forward passes/outputs -\( \boldsymbol{a}^{l-1} \) from the previous layer as -

- -$$ -z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, -$$ - -

where \( b_k^l \) are the biases from layer \( l \). Here \( M_{l-1} \) -represents the total number of nodes/neurons/units of layer \( l-1 \). The -figure in the whiteboard notes illustrates this equation. We can rewrite this in a more -compact form as the matrix-vector products we discussed earlier, -

- -$$ -\boldsymbol{z}^l = \left(\boldsymbol{W}^l\right)^T\boldsymbol{a}^{l-1}+\boldsymbol{b}^l. -$$ - - -









-

Inputs to the activation function

- -

With the activation values \( \boldsymbol{z}^l \) we can in turn define the -output of layer \( l \) as \( \boldsymbol{a}^l = \sigma(\boldsymbol{z}^l) \) where \( \sigma \) is our -activation function. In the examples here we will use the sigmoid -function discussed in our logistic regression lectures. We will also use the same activation function \( \sigma \) for all layers -and their nodes. It means we have -

- -$$ -a_j^l = \sigma(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. -$$ - - -









-

Layout of input to first hidden layer \( l=1 \) from input layer \( l=0 \)

- -

-
-

-
-

- -









-

Derivatives and the chain rule

- -

From the definition of the input variable to the activation function, that is \( z_j^l \) we have

-$$ -\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, -$$ - -

and

-$$ -\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. -$$ - -

With our definition of the activation function we have that (note that this function depends only on \( z_j^l \))

-$$ -\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=\sigma(z_j^l)(1-\sigma(z_j^l)). -$$ - - -









-

Derivative of the cost function

- -

With these definitions we can now compute the derivative of the cost function in terms of the weights.

- -

Let us specialize to the output layer \( l=L \). Our cost function is

-$$ -{\cal C}(\boldsymbol{\Theta}^L) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - y_i\right)^2, -$$ - -

The derivative of this function with respect to the weights is

- -$$ -\frac{\partial{\cal C}(\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)\frac{\partial a_j^L}{\partial w_{ij}^{L}}, -$$ - -

The last partial derivative can easily be computed and reads (by applying the chain rule)

-$$ -\frac{\partial a_j^L}{\partial w_{ij}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{ij}^{L}}=a_j^L(1-a_j^L)a_i^{L-1}. -$$ - - -









-

The back propagation equations for a neural network

- -

We have thus

-$$ -\frac{\partial{\cal C}((\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)a_j^L(1-a_j^L)a_i^{L-1}, -$$ - -

Defining

-$$ -\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - y_j\right) = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -$$ - -

and using the Hadamard product of two vectors we can write this as

-$$ -\boldsymbol{\delta}^L = \sigma'(\boldsymbol{z}^L)\circ\frac{\partial {\cal C}}{\partial (\boldsymbol{a}^L)}. -$$ - - -









-

Analyzing the last results

- -

This is an important expression. The second term on the right handside -measures how fast the cost function is changing as a function of the $j$th -output activation. If, for example, the cost function doesn't depend -much on a particular output node \( j \), then \( \delta_j^L \) will be small, -which is what we would expect. The first term on the right, measures -how fast the activation function \( f \) is changing at a given activation -value \( z_j^L \). -

- -









-

More considerations

- -

Notice that everything in the above equations is easily computed. In -particular, we compute \( z_j^L \) while computing the behaviour of the -network, and it is only a small additional overhead to compute -\( \sigma'(z^L_j) \). The exact form of the derivative with respect to the -output depends on the form of the cost function. -However, provided the cost function is known there should be little -trouble in calculating -

- -$$ -\frac{\partial {\cal C}}{\partial (a_j^L)} -$$ - -

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

-$$ -\frac{\partial{\cal C}}{\partial w_{ij}^L} = \delta_j^La_i^{L-1}. -$$ - - -









-

Derivatives in terms of \( z_j^L \)

- -

It is also easy to see that our previous equation can be written as

- -$$ -\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}, -$$ - -

which can also be interpreted as the partial derivative of the cost function with respect to the biases \( b_j^L \), namely

-$$ -\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}, -$$ - -

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.

- -









-

Bringing it together

- -

We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are

- -$$ -\begin{equation} -\frac{\partial{\cal C}(\boldsymbol{W^L})}{\partial w_{ij}^L} = \delta_j^La_i^{L-1}, -\label{_auto1} -\end{equation} -$$ - -

and

-$$ -\begin{equation} -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\label{_auto2} -\end{equation} -$$ - -

and

- -$$ -\begin{equation} -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}, -\label{_auto3} -\end{equation} -$$ - - -









-

Final back propagating equation

- -

We have that (replacing \( L \) with a general layer \( l \))

-$$ -\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. -$$ - -

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 obtain

-$$ -\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}}, -$$ - -

and recalling that

-$$ -z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, -$$ - -

with \( M_l \) being the number of nodes in layer \( l \), we obtain

-$$ -\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -$$ - -

This is our final equation.

- -

We are now ready to set up the algorithm for back propagation and learning the weights and biases.

- -









-

Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

- -
-The architecture (our model) -

-

    -
  1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)
  2. -
  3. Define the number of hidden layers and hidden nodes
  4. -
  5. Define activation functions for hidden layers and output layers
  6. -
  7. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates
  8. -
  9. Define cost function and possible regularization terms with hyperparameters
  10. -
  11. Initialize weights and biases
  12. -
  13. Fix number of iterations for the feed forward part and back propagation part
  14. -
-
- - -









-

Setting up the back propagation algorithm, part 1

- -

The four equations provide us with a way of computing the gradients of the cost function. Let us write this out in the form of an algorithm.

- -

First, we set up the input data \( \boldsymbol{x} \) and the activations -\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and -the pertinent outputs \( \boldsymbol{a}^1 \). -

- -

Secondly, we perform then the feed forward till we reach the output -layer and compute all \( \boldsymbol{z}_l \) of the input layer and compute the -activation function and the pertinent outputs \( \boldsymbol{a}^l \) for -\( l=1,2,3,\dots,L \). -

- -

Notation: The first hidden layer has \( l=1 \) as label and the final output layer has \( l=L \).

- -









-

Setting up the back propagation algorithm, part 2

- -

Thereafter we compute the ouput error \( \boldsymbol{\delta}^L \) by computing all

-$$ -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. -$$ - -

Then we compute the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

-$$ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). -$$ - - -









-

Setting up the Back propagation algorithm, part 3

- -

Finally, we update the weights and the biases using gradient descent -for each \( l=L-1,L-2,\dots,1 \) (the first hidden layer) and update the weights and biases -according to the rules -

- -$$ -w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, -$$ - - -$$ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -$$ - -

with \( \eta \) being the learning rate.

- -









-

Updating the gradients

- -

With the back propagate error for each \( l=L-1,L-2,\dots,1 \) as

-$$ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -$$ - -

we update the weights and the biases using gradient descent for each \( l=L-1,L-2,\dots,1 \) and update the weights and biases according to the rules

-$$ -w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, -$$ - - -$$ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -$$ - - -









-

Activation functions

- -

A property that characterizes a neural network, other than its -connectivity, is the choice of activation function(s). The following -restrictions are imposed on an activation function for an FFNN to -fulfill the universal approximation theorem -

- -
    -
  • Non-constant
  • -
  • Bounded
  • -
  • Monotonically-increasing
  • -
  • Continuous
  • -
-









-

Activation functions, Logistic and Hyperbolic ones

- -

The second requirement excludes all linear functions. Furthermore, in -a MLP with only linear activation functions, each layer simply -performs a linear transformation of its inputs. -

- -

Regardless of the number of layers, the output of the NN will be -nothing but a linear function of the inputs. Thus we need to introduce -some kind of non-linearity to the NN to be able to fit non-linear -functions Typical examples are the logistic Sigmoid -

- -$$ - \sigma(x) = \frac{1}{1 + e^{-x}}, -$$ - -

and the hyperbolic tangent function

-$$ - \sigma(x) = \tanh(x) -$$ - - -









-

Relevance

- -

The sigmoid function are more biologically plausible because the -output of inactive neurons are zero. Such activation function are -called one-sided. However, it has been shown that the hyperbolic -tangent performs better than the sigmoid for training MLPs. has -become the most popular for deep neural networks -

- - - -
-
-
-
-
-
"""The sigmoid function (or the logistic curve) is a 
-function that takes any real number, z, and outputs a number (0,1).
-It is useful in neural networks for assigning weights on a relative scale.
-The value z is the weighted sum of parameters involved in the learning algorithm."""
-
-import numpy
-import matplotlib.pyplot as plt
-import math as mt
-
-z = numpy.arange(-5, 5, .1)
-sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
-sigma = sigma_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, sigma)
-ax.set_ylim([-0.1, 1.1])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sigmoid function')
-
-plt.show()
-
-"""Step Function"""
-z = numpy.arange(-5, 5, .02)
-step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
-step = step_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, step)
-ax.set_ylim([-0.5, 1.5])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('step function')
-
-plt.show()
-
-"""Sine Function"""
-z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
-t = numpy.sin(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, t)
-ax.set_ylim([-1.0, 1.0])
-ax.set_xlim([-2*mt.pi,2*mt.pi])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sine function')
-
-plt.show()
-
-"""Plots a graph of the squashing function used by a rectified linear
-unit"""
-z = numpy.arange(-2, 2, .1)
-zero = numpy.zeros(len(z))
-y = numpy.max([zero, z], axis=0)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, y)
-ax.set_ylim([-2.0, 2.0])
-ax.set_xlim([-2.0, 2.0])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('Rectified linear unit')
-
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Vanishing gradients

- -

The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. -

- -

Unfortunately for us, the gradients often get smaller and smaller as -the algorithm progresses down to the first hidden layers. As a result, -the GD update leaves the lower layer connection weights virtually -unchanged, and training never converges to a good solution. This is -known in the literature as the vanishing gradients problem. -

- -









-

Exploding gradients

- -

In other cases, the opposite can happen, namely the the gradients can -grow bigger and bigger. The result is that many of the layers get -large updates of the weights the algorithm diverges. This is the -exploding gradients problem, which is mostly encountered in -recurrent neural networks. More generally, deep neural networks suffer -from unstable gradients, different layers may learn at widely -different speeds -

- - -

Is the Logistic activation function (Sigmoid) our choice?

- -

Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. -

- -

A paper titled Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -

- -









-

Logistic function as the root of problems

- -

They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -

- -









-

The derivative of the Logistic funtion

- -

Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. -

- -

In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -

- -









-

Insights from the paper by Glorot and Bengio

- -

One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -

- -









-

The RELU function family

- -

The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. -

- -

In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. -

- -









-

ELU function

- -

To solve this problem, nowadays practitioners use a variant of the -ReLU function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function -

- -$$ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -$$ - - -









-

Which activation function should we use?

- -

In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than \( \tanh \) which in turn performs better -than the logistic function. -

- -

If runtime performance is an issue, then you may opt for the leaky -ReLU function over the ELU function If you don’t want to tweak yet -another hyperparameter, you may just use the default \( \alpha \) of -\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and -computing power, you can use cross-validation or bootstrap to evaluate -other activation functions. -

- -









-

More on activation functions, output layers

- -

In most cases you can use the ReLU activation function in the hidden -layers (or one of its variants). -

- -

It is a bit faster to compute than other activation functions, and the -gradient descent optimization does in general not get stuck. -

- -For the output layer: - -
    -
  • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
  • -
  • For regression tasks, you can simply use no activation function at all.
  • -
-









-

Fine-tuning neural network hyperparameters

- -

The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are -interconnected), but even in a simple FFNN you can change the number -of layers, the number of neurons per layer, the type of activation -function to use in each layer, the weight initialization logic, the -stochastic gradient optmized and much more. How do you know what -combination of hyperparameters is the best for your task? -

- -
    -
  • You can use grid search with cross-validation to find the right hyperparameters.
  • -
-

However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. -

- -
    -
  • You can use randomized search.
  • -
  • Or use tools like Oscar, which implements more complex algorithms to help you find a good set of hyperparameters quickly.
  • -
-









-

Hidden layers

- -

For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set discussed below you can easily get a -high accuracy using just one hidden layer with a few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden -layers with the same total amount of neurons, in roughly the same -amount of training time. -

- -

For more complex problems, you can gradually ramp up the number of -hidden layers, until you start overfitting the training set. Very -complex tasks, such as large image classification or speech -recognition, typically require networks with dozens of layers and they -need a huge amount of training data. However, you will rarely have to -train such networks from scratch: it is much more common to reuse -parts of a pretrained state-of-the-art network that performs a similar -task. -

- -









-

Batch Normalization

- -

Batch Normalization aims to address the vanishing/exploding gradients -problems, and more generally the problem that the distribution of each -layer’s inputs changes during training, as the parameters of the -previous layers change. -

- -

The technique consists of adding an operation in the model just before -the activation function of each layer, simply zero-centering and -normalizing the inputs, then scaling and shifting the result using two -new parameters per layer (one for scaling, the other for shifting). In -other words, this operation lets the model learn the optimal scale and -mean of the inputs for each layer. In order to zero-center and -normalize the inputs, the algorithm needs to estimate the inputs’ mean -and standard deviation. It does so by evaluating the mean and standard -deviation of the inputs over the current mini-batch, from this the -name batch normalization. -

- -









-

Dropout

- -

It is a fairly simple algorithm: at every training step, every neuron -(including the input neurons but excluding the output neurons) has a -probability \( p \) of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active -during the next step. -

- -

The hyperparameter \( p \) is called the dropout rate, and it is typically -set to 50%. After training, the neurons are not dropped anymore. It -is viewed as one of the most popular regularization techniques. -

- -









-

Gradient Clipping

- -

A popular technique to lessen the exploding gradients problem is to -simply clip the gradients during backpropagation so that they never -exceed some threshold (this is mostly useful for recurrent neural -networks). -

- -

This technique is called Gradient Clipping.

- -

In general however, Batch -Normalization is preferred. -

- - -

A top-down perspective on Neural networks

- -

The first thing we would like to do is divide the data into two or -three parts. A training set, a validation or dev (development) set, -and a test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: -

- -
    -
  1. Estimate optimal error rate
  2. -
  3. Minimize underfitting (bias) on training data set.
  4. -
  5. Make sure you are not overfitting.
  6. -
-









-

More top-down perspectives

- -

If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. -

- -

However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -

- -









-

Limitations of supervised learning with deep networks

- -

Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). -

- -









-

Limitations of NNs

- -

Here we list some of the important limitations of supervised neural network based models.

- -
    -
  • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
  • -
  • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
  • -
-









-

Homogeneous data

- -
    -
  • Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
  • -
-









-

More limitations

- -
    -
  • Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
  • -
-

Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.

- - -

Setting up a Multi-layer perceptron model for classification

- -

We are now gong to develop an example based on the MNIST data -base. This is a classification problem and we need to use our -cross-entropy function we discussed in connection with logistic -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. -

- -

In binary classification with two classes \( (0, 1) \) we define the -logistic/sigmoid function as the probability that a particular input -is in class \( 0 \) or \( 1 \). This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. -

- -

For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) -is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) -represents our activation values \( z \). We have -

-$$ -P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , -$$ - -

and

-$$ -P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , -$$ - -

where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases -of our network. -

- - -









-

Defining the cost function

- -

Our cost function is given as (see the Logistic regression lectures)

-$$ -\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . -$$ - -

This last equality means that we can interpret our cost function as a sum over the loss function -for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. -

- -

In multiclass classification it is common to treat each integer label as a so called one-hot vector:

- -

\( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

- -\( y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) , \) - -

i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset (numbers from \( 0 \) to \( 9 \))..

- -

If \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th -output vector \( \boldsymbol{y}_i \). -The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: -

- -$$ -P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , -$$ - -

which reduces to the logistic function in the binary case. -The likelihood of this \( C \)-class classifier -is now given as: -

- -$$ -P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -$$ - -

Again we take the negative log-likelihood to define our cost function:

- -$$ -\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. -$$ - -

See the logistic regression lectures for a full definition of the cost function.

- -

The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!

- -









-

Example: binary classification problem

- -

As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as

-$$ -\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), -$$ - -

where we had defined the logistic (sigmoid) function

-$$ -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)}}, -$$ - -

and

-$$ -p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). -$$ - -

The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

- -

Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). -We have then -

-$$ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -$$ - -

with

-$$ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -$$ - -

where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). -Our cost function at the final layer \( l=L \) is now -

-$$ -\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), -$$ - -

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

-$$ -\frac{\partial \mathcal{C}(\boldsymbol{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. -$$ - -

In case we use another activation function than the logistic one, we need to evaluate other derivatives.

- -









-

The Softmax function

-

In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need

-$$ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -$$ - -

For the Softmax function we have

-$$ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -$$ - -

Its derivative with respect to \( z_j^l \) gives

-$$ -\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), -$$ - -

which in case of the simply binary model reduces to having \( i=j \).

- - -

Developing a code for doing neural networks with back propagation

- -

One can identify a set of key steps when using neural networks to solve supervised learning problems:

- -
    -
  1. Collect and pre-process data
  2. -
  3. Define model and architecture
  4. -
  5. Choose cost function and optimizer
  6. -
  7. Train the model
  8. -
  9. Evaluate model performance on test data
  10. -
  11. Adjust hyperparameters (if necessary, network architecture)
  12. -
-









-

Collect and pre-process data

- -

Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

- -

To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

- -

As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

- -

$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

- -

and the targets would be:

- -

$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

- -

Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

- - - -
-
-
-
-
-
# import necessary packages
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn import datasets
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-
-# display images in notebook
-%matplotlib inline
-plt.rcParams['figure.figsize'] = (12,12)
-
-
-# download MNIST dataset
-digits = datasets.load_digits()
-
-# define inputs and labels
-inputs = digits.images
-labels = digits.target
-
-print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
-print("labels = (n_inputs) = " + str(labels.shape))
-
-
-# flatten the image
-# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
-n_inputs = len(inputs)
-inputs = inputs.reshape(n_inputs, -1)
-print("X = (n_inputs, n_features) = " + str(inputs.shape))
-
-
-# choose some random images to display
-indices = np.arange(n_inputs)
-random_indices = np.random.choice(indices, size=5)
-
-for i, image in enumerate(digits.images[random_indices]):
-    plt.subplot(1, 5, i+1)
-    plt.axis('off')
-    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
-    plt.title("Label: %d" % digits.target[random_indices[i]])
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Train and test datasets

- -

Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

- -

We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

- -

It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

- - - -
-
-
-
-
-
from sklearn.model_selection import train_test_split
-
-# one-liner from scikit-learn library
-train_size = 0.8
-test_size = 1 - train_size
-X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
-                                                    test_size=test_size)
-
-# equivalently in numpy
-def train_test_split_numpy(inputs, labels, train_size, test_size):
-    n_inputs = len(inputs)
-    inputs_shuffled = inputs.copy()
-    labels_shuffled = labels.copy()
-    
-    np.random.shuffle(inputs_shuffled)
-    np.random.shuffle(labels_shuffled)
-    
-    train_end = int(n_inputs*train_size)
-    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
-    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
-    
-    return X_train, X_test, Y_train, Y_test
-
-#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
-
-print("Number of training images: " + str(len(X_train)))
-print("Number of test images: " + str(len(X_test)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Define model and architecture

- -

Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

- -

$$ z = \sum_{i=1}^n w_i a_i ,$$

- -

$$ y = f(z) ,$$

- -

where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

- -

The simplest activation function for a neuron is the Heaviside function:

- -

$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

- -

A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

- -

However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

- -

Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

- -

$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$

- -

which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.

- - -

Layers

- -
    -
  • Input
  • -
-

Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

- -
    -
  • Hidden layer
  • -
-

We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

- -
    -
  • Output
  • -
-

If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

- -

For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

- -

Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

- -

$$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

- -

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. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

- -

$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

- -

Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. -

- - -

Weights and biases

- -

Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. -

- -

Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

- -

$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

- -

The bias weights \( \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.

- - -
-
-
-
-
-
# building our neural network
-
-n_inputs, n_features = X_train.shape
-n_hidden_neurons = 50
-n_categories = 10
-
-# we make the weights normally distributed using numpy.random.randn
-
-# weights and bias in the hidden layer
-hidden_weights = np.random.randn(n_features, n_hidden_neurons)
-hidden_bias = np.zeros(n_hidden_neurons) + 0.01
-
-# weights and bias in the output layer
-output_weights = np.random.randn(n_hidden_neurons, n_categories)
-output_bias = np.zeros(n_categories) + 0.01
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Feed-forward pass

- -

Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

- -

$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

- -

this is then passed through our activation function

- -

$$ a_{j}^{l} = f(z_{j}^{l}) .$$

- -

We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

- -

$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

- -

Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

- -

$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

- - -

Matrix multiplications

- -

Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden -layer have the dimensions -\( W_{hidden} = (n_{features}, n_{hidden}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

- -

$$ X W^{h} = (n_{inputs}, n_{hidden}),$$

- -

and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

- -

$$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

- -

meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

- -

$$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

- -

This is fed to the output layer:

- -

$$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

- -

Finally we receive our output values for each image and each category by passing it through the softmax function:

- -

$$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

- - - -
-
-
-
-
-
# setup the feed-forward pass, subscript h = hidden layer
-
-def sigmoid(x):
-    return 1/(1 + np.exp(-x))
-
-def feed_forward(X):
-    # weighted sum of inputs to the hidden layer
-    z_h = np.matmul(X, hidden_weights) + hidden_bias
-    # activation in the hidden layer
-    a_h = sigmoid(z_h)
-    
-    # weighted sum of inputs to the output layer
-    z_o = np.matmul(a_h, output_weights) + output_bias
-    # softmax output
-    # axis 0 holds each input and axis 1 the probabilities of each category
-    exp_term = np.exp(z_o)
-    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-    
-    return probabilities
-
-probabilities = feed_forward(X_train)
-print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
-print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
-print("probabilities sum up to: " + str(probabilities[0].sum()))
-print()
-
-# we obtain a prediction by taking the class with the highest likelihood
-def predict(X):
-    probabilities = feed_forward(X)
-    return np.argmax(probabilities, axis=1)
-
-predictions = predict(X_train)
-print("predictions = (n_inputs) = " + str(predictions.shape))
-print("prediction for image 0: " + str(predictions[0]))
-print("correct label for image 0: " + str(Y_train[0]))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Choose cost function and optimizer

- -

To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

- -

In multiclass classification it is common to treat each integer label as a so called one-hot vector:

- -

$$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

- -

$$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$

- -

i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset.

- -

Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

- -

In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category \( c' \) -(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases. -

- - -









-

Optimizing the cost function

- -

The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

- -

$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

- -

where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

- -

A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

- -

$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

- -

i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

- -

This has two important benefits:

-
    -
  1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
  2. -
  3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
  4. -
-

The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

- - -

Regularization

- -

It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

- -

We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

- -

$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

- -

i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.

- -

In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has \( (64 + 1)\times 50=3250 \) weights in -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -layer (\( +1 \) for the bias), and the gradient must be calculated for -every parameter. We use the backpropagation algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. -

- -









-

Matrix multiplication

- -

To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

- -

$$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

- -

The gradient for the output weights is calculated as

- -

$$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

- -

where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

- -

The gradient with respect to the output bias is then

- -

$$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

- -

The error in the hidden layer is

- -

$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

- -

where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

- -

This again gives us the gradients in the hidden layer:

- -

$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

- -

$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

- - - -
-
-
-
-
-
# to categorical turns our integer vector into a onehot representation
-from sklearn.metrics import accuracy_score
-
-# one-hot in numpy
-def to_categorical_numpy(integer_vector):
-    n_inputs = len(integer_vector)
-    n_categories = np.max(integer_vector) + 1
-    onehot_vector = np.zeros((n_inputs, n_categories))
-    onehot_vector[range(n_inputs), integer_vector] = 1
-    
-    return onehot_vector
-
-#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
-Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
-
-def feed_forward_train(X):
-    # weighted sum of inputs to the hidden layer
-    z_h = np.matmul(X, hidden_weights) + hidden_bias
-    # activation in the hidden layer
-    a_h = sigmoid(z_h)
-    
-    # weighted sum of inputs to the output layer
-    z_o = np.matmul(a_h, output_weights) + output_bias
-    # softmax output
-    # axis 0 holds each input and axis 1 the probabilities of each category
-    exp_term = np.exp(z_o)
-    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-    
-    # for backpropagation need activations in hidden and output layers
-    return a_h, probabilities
-
-def backpropagation(X, Y):
-    a_h, probabilities = feed_forward_train(X)
-    
-    # error in the output layer
-    error_output = probabilities - Y
-    # error in the hidden layer
-    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
-    
-    # gradients for the output layer
-    output_weights_gradient = np.matmul(a_h.T, error_output)
-    output_bias_gradient = np.sum(error_output, axis=0)
-    
-    # gradient for the hidden layer
-    hidden_weights_gradient = np.matmul(X.T, error_hidden)
-    hidden_bias_gradient = np.sum(error_hidden, axis=0)
-
-    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
-
-print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
-
-eta = 0.01
-lmbd = 0.01
-for i in range(1000):
-    # calculate gradients
-    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
-    
-    # regularization term gradients
-    dWo += lmbd * output_weights
-    dWh += lmbd * hidden_weights
-    
-    # update weights and biases
-    output_weights -= eta * dWo
-    output_bias -= eta * dBo
-    hidden_weights -= eta * dWh
-    hidden_bias -= eta * dBh
-
-print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Improving performance

- -

As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. -

- -

The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

- -

Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

- -

If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this video. You can find a summary of the video here. -

- -









-

Full object-oriented implementation

- -

It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. -

- - - -
-
-
-
-
-
class NeuralNetwork:
-    def __init__(
-            self,
-            X_data,
-            Y_data,
-            n_hidden_neurons=50,
-            n_categories=10,
-            epochs=10,
-            batch_size=100,
-            eta=0.1,
-            lmbd=0.0):
-
-        self.X_data_full = X_data
-        self.Y_data_full = Y_data
-
-        self.n_inputs = X_data.shape[0]
-        self.n_features = X_data.shape[1]
-        self.n_hidden_neurons = n_hidden_neurons
-        self.n_categories = n_categories
-
-        self.epochs = epochs
-        self.batch_size = batch_size
-        self.iterations = self.n_inputs // self.batch_size
-        self.eta = eta
-        self.lmbd = lmbd
-
-        self.create_biases_and_weights()
-
-    def create_biases_and_weights(self):
-        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
-        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
-
-        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
-        self.output_bias = np.zeros(self.n_categories) + 0.01
-
-    def feed_forward(self):
-        # feed-forward for training
-        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
-        self.a_h = sigmoid(self.z_h)
-
-        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
-
-        exp_term = np.exp(self.z_o)
-        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-
-    def feed_forward_out(self, X):
-        # feed-forward for output
-        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
-        a_h = sigmoid(z_h)
-
-        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
-        
-        exp_term = np.exp(z_o)
-        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
-        return probabilities
-
-    def backpropagation(self):
-        error_output = self.probabilities - self.Y_data
-        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
-
-        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
-        self.output_bias_gradient = np.sum(error_output, axis=0)
-
-        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
-        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
-
-        if self.lmbd > 0.0:
-            self.output_weights_gradient += self.lmbd * self.output_weights
-            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
-
-        self.output_weights -= self.eta * self.output_weights_gradient
-        self.output_bias -= self.eta * self.output_bias_gradient
-        self.hidden_weights -= self.eta * self.hidden_weights_gradient
-        self.hidden_bias -= self.eta * self.hidden_bias_gradient
-
-    def predict(self, X):
-        probabilities = self.feed_forward_out(X)
-        return np.argmax(probabilities, axis=1)
-
-    def predict_probabilities(self, X):
-        probabilities = self.feed_forward_out(X)
-        return probabilities
-
-    def train(self):
-        data_indices = np.arange(self.n_inputs)
-
-        for i in range(self.epochs):
-            for j in range(self.iterations):
-                # pick datapoints with replacement
-                chosen_datapoints = np.random.choice(
-                    data_indices, size=self.batch_size, replace=False
-                )
-
-                # minibatch training data
-                self.X_data = self.X_data_full[chosen_datapoints]
-                self.Y_data = self.Y_data_full[chosen_datapoints]
-
-                self.feed_forward()
-                self.backpropagation()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Evaluate model performance on test data

- -

To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the accuracy score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \). -

- -

$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

- -

where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

- - - -
-
-
-
-
-
epochs = 100
-batch_size = 100
-
-dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
-                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
-dnn.train()
-test_predict = dnn.predict(X_test)
-
-# accuracy score from scikit library
-print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
-
-# equivalent in numpy
-def accuracy_score_numpy(Y_test, Y_pred):
-    return np.sum(Y_test == Y_pred) / len(Y_test)
-
-#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Adjust hyperparameters

- -

We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

- - - -
-
-
-
-
-
eta_vals = np.logspace(-5, 1, 7)
-lmbd_vals = np.logspace(-5, 1, 7)
-# store the models for later use
-DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-
-# grid search
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
-                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
-        dnn.train()
-        
-        DNN_numpy[i][j] = dnn
-        
-        test_predict = dnn.predict(X_test)
-        
-        print("Learning rate  = ", eta)
-        print("Lambda = ", lmbd)
-        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Visualization

- - - -
-
-
-
-
-
# visual representation of grid search
-# uses seaborn heatmap, you can also do this with matplotlib imshow
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        dnn = DNN_numpy[i][j]
-        
-        train_pred = dnn.predict(X_train) 
-        test_pred = dnn.predict(X_test)
-
-        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
-        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

scikit-learn implementation

- -

scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

- -

scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

- - - -
-
-
-
-
-
from sklearn.neural_network import MLPClassifier
-# store models for later use
-DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
-                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
-        dnn.fit(X_train, Y_train)
-        
-        DNN_scikit[i][j] = dnn
-        
-        print("Learning rate  = ", eta)
-        print("Lambda = ", lmbd)
-        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Visualization

- - -
-
-
-
-
-
# optional
-# visual representation of grid search
-# uses seaborn heatmap, could probably do this in matplotlib
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        dnn = DNN_scikit[i][j]
-        
-        train_pred = dnn.predict(X_train) 
-        test_pred = dnn.predict(X_test)
-
-        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
-        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Building neural networks in Tensorflow and Keras

- -

Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. -

- -

In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. -

- -









-

Tensorflow

- -

Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. -

- -

Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. -

- -

Tensorflow uses so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow graph -to represent your model, and then create a Tensorflow session to run the graph. -

- -

In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. -

- -

To install tensorflow on Unix/Linux systems, use pip as

- - -
-
-
-
-
-
pip3 install tensorflow
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

and/or if you use anaconda, just write (or install from the graphical user interface) -(current release of CPU-only TensorFlow) -

- - -
-
-
-
-
-
conda create -n tf tensorflow
-conda activate tf
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

To install the current release of GPU TensorFlow

- - -
-
-
-
-
-
conda create -n tf-gpu tensorflow-gpu
-conda activate tf-gpu
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Using Keras

- -

Keras is a high level neural network -that supports Tensorflow, CTNK and Theano as backends. -If you have Anaconda installed you may run the following command -

- - -
-
-
-
-
-
conda install keras
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

You can look up the instructions here for more information.

- -

We will to a large extent use keras in this course.

- -









-

Collect and pre-process data

- -

Let us look again at the MINST data set.

- - - -
-
-
-
-
-
# import necessary packages
-import numpy as np
-import matplotlib.pyplot as plt
-import tensorflow as tf
-from sklearn import datasets
-
-
-# ensure the same random numbers appear every time
-np.random.seed(0)
-
-# display images in notebook
-%matplotlib inline
-plt.rcParams['figure.figsize'] = (12,12)
-
-
-# download MNIST dataset
-digits = datasets.load_digits()
-
-# define inputs and labels
-inputs = digits.images
-labels = digits.target
-
-print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
-print("labels = (n_inputs) = " + str(labels.shape))
-
-
-# flatten the image
-# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
-n_inputs = len(inputs)
-inputs = inputs.reshape(n_inputs, -1)
-print("X = (n_inputs, n_features) = " + str(inputs.shape))
-
-
-# choose some random images to display
-indices = np.arange(n_inputs)
-random_indices = np.random.choice(indices, size=5)
-
-for i, image in enumerate(digits.images[random_indices]):
-    plt.subplot(1, 5, i+1)
-    plt.axis('off')
-    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
-    plt.title("Label: %d" % digits.target[random_indices[i]])
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
-from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
-from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
-from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
-from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
-
-from sklearn.model_selection import train_test_split
-
-# one-hot representation of labels
-labels = to_categorical(labels)
-
-# split into train and test data
-train_size = 0.8
-test_size = 1 - train_size
-X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
-                                                    test_size=test_size)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
epochs = 100
-batch_size = 100
-n_neurons_layer1 = 100
-n_neurons_layer2 = 50
-n_categories = 10
-eta_vals = np.logspace(-5, 1, 7)
-lmbd_vals = np.logspace(-5, 1, 7)
-def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
-    model = Sequential()
-    model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
-    model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
-    model.add(Dense(n_categories, activation='softmax'))
-    
-    sgd = optimizers.SGD(lr=eta)
-    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
-    
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-        
-for i, eta in enumerate(eta_vals):
-    for j, lmbd in enumerate(lmbd_vals):
-        DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
-                                         eta=eta, lmbd=lmbd)
-        DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
-        scores = DNN.evaluate(X_test, Y_test)
-        
-        DNN_keras[i][j] = DNN
-        
-        print("Learning rate = ", eta)
-        print("Lambda = ", lmbd)
-        print("Test accuracy: %.3f" % scores[1])
-        print()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
# optional
-# visual representation of grid search
-# uses seaborn heatmap, could probably do this in matplotlib
-import seaborn as sns
-
-sns.set()
-
-train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
-
-for i in range(len(eta_vals)):
-    for j in range(len(lmbd_vals)):
-        DNN = DNN_keras[i][j]
-
-        train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
-        test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
-
-        
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Training Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-fig, ax = plt.subplots(figsize = (10, 10))
-sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
-ax.set_title("Test Accuracy")
-ax.set_ylabel("$\eta$")
-ax.set_xlabel("$\lambda$")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

The Breast Cancer Data, now with Keras

- - - -
-
-
-
-
-
import tensorflow as tf
-from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
-from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
-from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
-from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
-from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
-import numpy as np
-import matplotlib.pyplot as plt
-import seaborn as sns
-from sklearn.model_selection import train_test_split as splitter
-from sklearn.datasets import load_breast_cancer
-import pickle
-import os 
-
-
-"""Load breast cancer dataset"""
-
-np.random.seed(0)        #create same seed for random number every time
-
-cancer=load_breast_cancer()      #Download breast cancer dataset
-
-inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
-outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
-labels=cancer.feature_names[0:30]
-
-print('The content of the breast cancer dataset is:')      #Print information about the datasets
-print(labels)
-print('-------------------------')
-print("inputs =  " + str(inputs.shape))
-print("outputs =  " + str(outputs.shape))
-print("labels =  "+ str(labels.shape))
-
-x=inputs      #Reassign the Feature and Label matrices to other variables
-y=outputs
-
-#%% 
-
-# Visualisation of dataset (for correlation analysis)
-
-plt.figure()
-plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean radius',fontweight='bold')
-plt.ylabel('Mean perimeter',fontweight='bold')
-plt.show()
-
-plt.figure()
-plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
-plt.xlabel('Mean compactness',fontweight='bold')
-plt.ylabel('Mean concavity',fontweight='bold')
-plt.show()
-
-
-plt.figure()
-plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean radius',fontweight='bold')
-plt.ylabel('Mean texture',fontweight='bold')
-plt.show()
-
-plt.figure()
-plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
-plt.xlabel('Mean perimeter',fontweight='bold')
-plt.ylabel('Mean compactness',fontweight='bold')
-plt.show()
-
-
-# Generate training and testing datasets
-
-#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
-#and add to input matrix
-
-temp1=np.reshape(x[:,1],(len(x[:,1]),1))
-temp2=np.reshape(x[:,2],(len(x[:,2]),1))
-X=np.hstack((temp1,temp2))      
-temp=np.reshape(x[:,5],(len(x[:,5]),1))
-X=np.hstack((X,temp))       
-temp=np.reshape(x[:,8],(len(x[:,8]),1))
-X=np.hstack((X,temp))       
-
-X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
-
-y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
-y_test=to_categorical(y_test)
-
-del temp1,temp2,temp
-
-# %%
-
-# Define tunable parameters"
-
-eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
-lamda=0.01                                  #Define hyperparameter
-n_layers=2                                  #Define number of hidden layers in the model
-n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
-epochs=100                                   #Number of reiterations over the input data
-batch_size=100                              #Number of samples per gradient update
-
-# %%
-
-"""Define function to return Deep Neural Network model"""
-
-def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
-    model=Sequential()      
-    for i in range(n_layers):       #Run loop to add hidden layers to the model
-        if (i==0):                  #First layer requires input dimensions
-            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
-        else:                       #Subsequent layers are capable of automatic shape inferencing
-            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
-    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
-    sgd=optimizers.SGD(lr=eta)
-    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
-    return model
-
-    
-Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
-Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
-
-for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
-    for j in range(len(eta)):      #accuracy scores 
-        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
-        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
-        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
-        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
-               
-
-def plot_data(x,y,data,title=None):
-
-    # plot results
-    fontsize=16
-
-
-    fig = plt.figure()
-    ax = fig.add_subplot(111)
-    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
-    
-    cbar=fig.colorbar(cax)
-    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
-    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
-    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
-
-    # put text on matrix elements
-    for i, x_val in enumerate(np.arange(len(x))):
-        for j, y_val in enumerate(np.arange(len(y))):
-            c = "${0:.1f}\\%$".format( 100*data[j,i])  
-            ax.text(x_val, y_val, c, va='center', ha='center')
-
-    # convert axis vaues to to string labels
-    x=[str(i) for i in x]
-    y=[str(i) for i in y]
-
-
-    ax.set_xticklabels(['']+x)
-    ax.set_yticklabels(['']+y)
-
-    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
-    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
-    if title is not None:
-        ax.set_title(title)
-
-    plt.tight_layout()
-
-    plt.show()
-    
-plot_data(eta,n_neuron,Train_accuracy, 'training')
-plot_data(eta,n_neuron,Test_accuracy, 'testing')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Building a neural network code

- -

Here we present a flexible object oriented codebase -for a feed forward neural network, along with a demonstration of how -to use it. Before we get into the details of the neural network, we -will first present some implementations of various schedulers, cost -functions and activation functions that can be used together with the -neural network. -

- -

The codes here were developed by Eric Reber and Gregor Kajda during spring 2023.

-

Learning rate methods

- -

The code below shows object oriented implementations of the Constant, -Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All -of the classes belong to the shared abstract Scheduler class, and -share the update_change() and reset() methods allowing for any of the -schedulers to be seamlessly used during the training stage, as will -later be shown in the fit() method of the neural -network. Update_change() only has one parameter, the gradient -(\( δ^l_ja^{l−1}_k \)), and returns the change which will be subtracted -from the weights. The reset() function takes no parameters, and resets -the desired variables. For Constant and Momentum, reset does nothing. -

- - - -
-
-
-
-
-
import autograd.numpy as np
-
-class Scheduler:
-    """
-    Abstract class for Schedulers
-    """
-
-    def __init__(self, eta):
-        self.eta = eta
-
-    # should be overwritten
-    def update_change(self, gradient):
-        raise NotImplementedError
-
-    # overwritten if needed
-    def reset(self):
-        pass
-
-
-class Constant(Scheduler):
-    def __init__(self, eta):
-        super().__init__(eta)
-
-    def update_change(self, gradient):
-        return self.eta * gradient
-    
-    def reset(self):
-        pass
-
-
-class Momentum(Scheduler):
-    def __init__(self, eta: float, momentum: float):
-        super().__init__(eta)
-        self.momentum = momentum
-        self.change = 0
-
-    def update_change(self, gradient):
-        self.change = self.momentum * self.change + self.eta * gradient
-        return self.change
-
-    def reset(self):
-        pass
-
-
-class Adagrad(Scheduler):
-    def __init__(self, eta):
-        super().__init__(eta)
-        self.G_t = None
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        if self.G_t is None:
-            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
-
-        self.G_t += gradient @ gradient.T
-
-        G_t_inverse = 1 / (
-            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
-        )
-        return self.eta * gradient * G_t_inverse
-
-    def reset(self):
-        self.G_t = None
-
-
-class AdagradMomentum(Scheduler):
-    def __init__(self, eta, momentum):
-        super().__init__(eta)
-        self.G_t = None
-        self.momentum = momentum
-        self.change = 0
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        if self.G_t is None:
-            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
-
-        self.G_t += gradient @ gradient.T
-
-        G_t_inverse = 1 / (
-            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
-        )
-        self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse
-        return self.change
-
-    def reset(self):
-        self.G_t = None
-
-
-class RMS_prop(Scheduler):
-    def __init__(self, eta, rho):
-        super().__init__(eta)
-        self.rho = rho
-        self.second = 0.0
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-        self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient
-        return self.eta * gradient / (np.sqrt(self.second + delta))
-
-    def reset(self):
-        self.second = 0.0
-
-
-class Adam(Scheduler):
-    def __init__(self, eta, rho, rho2):
-        super().__init__(eta)
-        self.rho = rho
-        self.rho2 = rho2
-        self.moment = 0
-        self.second = 0
-        self.n_epochs = 1
-
-    def update_change(self, gradient):
-        delta = 1e-8  # avoid division ny zero
-
-        self.moment = self.rho * self.moment + (1 - self.rho) * gradient
-        self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient
-
-        moment_corrected = self.moment / (1 - self.rho**self.n_epochs)
-        second_corrected = self.second / (1 - self.rho2**self.n_epochs)
-
-        return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))
-
-    def reset(self):
-        self.n_epochs += 1
-        self.moment = 0
-        self.second = 0
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Usage of the above learning rate schedulers

- -

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. -

- - - -
-
-
-
-
-
momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)
-adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Here is a small example for how a segment of code using schedulers -could look. Switching out the schedulers is simple. -

- - - -
-
-
-
-
-
weights = np.ones((3,3))
-print(f"Before scheduler:\n{weights=}")
-
-epochs = 10
-for e in range(epochs):
-    gradient = np.random.rand(3, 3)
-    change = adam_scheduler.update_change(gradient)
-    weights = weights - change
-    adam_scheduler.reset()
-
-print(f"\nAfter scheduler:\n{weights=}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Cost functions

- -

Here we discuss cost functions that can be used when creating the -neural network. Every cost function takes the target vector as its -parameter, and returns a function valued only at \( x \) such that it may -easily be differentiated. -

- - - -
-
-
-
-
-
import autograd.numpy as np
-
-def CostOLS(target):
-    
-    def func(X):
-        return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)
-
-    return func
-
-
-def CostLogReg(target):
-
-    def func(X):
-        
-        return -(1.0 / target.shape[0]) * np.sum(
-            (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))
-        )
-
-    return func
-
-
-def CostCrossEntropy(target):
-    
-    def func(X):
-        return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))
-
-    return func
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Below we give a short example of how these cost function may be used -to obtain results if you wish to test them out on your own using -AutoGrad's automatics differentiation. -

- - - -
-
-
-
-
-
from autograd import grad
-
-target = np.array([[1, 2, 3]]).T
-a = np.array([[4, 5, 6]]).T
-
-cost_func = CostCrossEntropy
-cost_func_derivative = grad(cost_func(target))
-
-valued_at_a = cost_func_derivative(a)
-print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Activation functions

- -

Finally, before we look at the neural network, we will look at the -activation functions which can be specified between the hidden layers -and as the output function. Each function can be valued for any given -vector or matrix X, and can be differentiated via derivate(). -

- - - -
-
-
-
-
-
import autograd.numpy as np
-from autograd import elementwise_grad
-
-def identity(X):
-    return X
-
-
-def sigmoid(X):
-    try:
-        return 1.0 / (1 + np.exp(-X))
-    except FloatingPointError:
-        return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))
-
-
-def softmax(X):
-    X = X - np.max(X, axis=-1, keepdims=True)
-    delta = 10e-10
-    return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)
-
-
-def RELU(X):
-    return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))
-
-
-def LRELU(X):
-    delta = 10e-4
-    return np.where(X > np.zeros(X.shape), X, delta * X)
-
-
-def derivate(func):
-    if func.__name__ == "RELU":
-
-        def func(X):
-            return np.where(X > 0, 1, 0)
-
-        return func
-
-    elif func.__name__ == "LRELU":
-
-        def func(X):
-            delta = 10e-4
-            return np.where(X > 0, 1, delta)
-
-        return func
-
-    else:
-        return elementwise_grad(func)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Below follows a short demonstration of how to use an activation -function. The derivative of the activation function will be important -when calculating the output delta term during backpropagation. Note -that derivate() can also be used for cost functions for a more -generalized approach. -

- - - -
-
-
-
-
-
z = np.array([[4, 5, 6]]).T
-print(f"Input to activation function:\n{z}")
-
-act_func = sigmoid
-a = act_func(z)
-print(f"\nOutput from {act_func.__name__} activation function:\n{a}")
-
-act_func_derivative = derivate(act_func)
-valued_at_z = act_func_derivative(a)
-print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

The Neural Network

- -

Now that we have gotten a good understanding of the implementation of -some important components, we can take a look at an object oriented -implementation of a feed forward neural network. The feed forward -neural network has been implemented as a class named FFNN, which can -be initiated as a regressor or classifier dependant on the choice of -cost function. The FFNN can have any number of input nodes, hidden -layers with any amount of hidden nodes, and any amount of output nodes -meaning it can perform multiclass classification as well as binary -classification and regression problems. Although there is a lot of -code present, it makes for an easy to use and generalizeable interface -for creating many types of neural networks as will be demonstrated -below. -

- - - -
-
-
-
-
-
import math
-import autograd.numpy as np
-import sys
-import warnings
-from autograd import grad, elementwise_grad
-from random import random, seed
-from copy import deepcopy, copy
-from typing import Tuple, Callable
-from sklearn.utils import resample
-
-warnings.simplefilter("error")
-
-
-class FFNN:
-    """
-    Description:
-    ------------
-        Feed Forward Neural Network with interface enabling flexible design of a
-        nerual networks architecture and the specification of activation function
-        in the hidden layers and output layer respectively. This model can be used
-        for both regression and classification problems, depending on the output function.
-
-    Attributes:
-    ------------
-        I   dimensions (tuple[int]): A list of positive integers, which specifies the
-            number of nodes in each of the networks layers. The first integer in the array
-            defines the number of nodes in the input layer, the second integer defines number
-            of nodes in the first hidden layer and so on until the last number, which
-            specifies the number of nodes in the output layer.
-        II  hidden_func (Callable): The activation function for the hidden layers
-        III output_func (Callable): The activation function for the output layer
-        IV  cost_func (Callable): Our cost function
-        V   seed (int): Sets random seed, makes results reproducible
-    """
-
-    def __init__(
-        self,
-        dimensions: tuple[int],
-        hidden_func: Callable = sigmoid,
-        output_func: Callable = lambda x: x,
-        cost_func: Callable = CostOLS,
-        seed: int = None,
-    ):
-        self.dimensions = dimensions
-        self.hidden_func = hidden_func
-        self.output_func = output_func
-        self.cost_func = cost_func
-        self.seed = seed
-        self.weights = list()
-        self.schedulers_weight = list()
-        self.schedulers_bias = list()
-        self.a_matrices = list()
-        self.z_matrices = list()
-        self.classification = None
-
-        self.reset_weights()
-        self._set_classification()
-
-    def fit(
-        self,
-        X: np.ndarray,
-        t: np.ndarray,
-        scheduler: Scheduler,
-        batches: int = 1,
-        epochs: int = 100,
-        lam: float = 0,
-        X_val: np.ndarray = None,
-        t_val: np.ndarray = None,
-    ):
-        """
-        Description:
-        ------------
-            This function performs the training the neural network by performing the feedforward and backpropagation
-            algorithm to update the networks weights.
-
-        Parameters:
-        ------------
-            I    X (np.ndarray) : training data
-            II   t (np.ndarray) : target data
-            III  scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)
-            IV   scheduler_args (list[int]) : list of all arguments necessary for scheduler
-
-        Optional Parameters:
-        ------------
-            V    batches (int) : number of batches the datasets are split into, default equal to 1
-            VI   epochs (int) : number of iterations used to train the network, default equal to 100
-            VII  lam (float) : regularization hyperparameter lambda
-            VIII X_val (np.ndarray) : validation set
-            IX   t_val (np.ndarray) : validation target set
-
-        Returns:
-        ------------
-            I   scores (dict) : A dictionary containing the performance metrics of the model.
-                The number of the metrics depends on the parameters passed to the fit-function.
-
-        """
-
-        # setup 
-        if self.seed is not None:
-            np.random.seed(self.seed)
-
-        val_set = False
-        if X_val is not None and t_val is not None:
-            val_set = True
-
-        # creating arrays for score metrics
-        train_errors = np.empty(epochs)
-        train_errors.fill(np.nan)
-        val_errors = np.empty(epochs)
-        val_errors.fill(np.nan)
-
-        train_accs = np.empty(epochs)
-        train_accs.fill(np.nan)
-        val_accs = np.empty(epochs)
-        val_accs.fill(np.nan)
-
-        self.schedulers_weight = list()
-        self.schedulers_bias = list()
-
-        batch_size = X.shape[0] // batches
-
-        X, t = resample(X, t)
-
-        # this function returns a function valued only at X
-        cost_function_train = self.cost_func(t)
-        if val_set:
-            cost_function_val = self.cost_func(t_val)
-
-        # create schedulers for each weight matrix
-        for i in range(len(self.weights)):
-            self.schedulers_weight.append(copy(scheduler))
-            self.schedulers_bias.append(copy(scheduler))
-
-        print(f"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}")
-
-        try:
-            for e in range(epochs):
-                for i in range(batches):
-                    # allows for minibatch gradient descent
-                    if i == batches - 1:
-                        # If the for loop has reached the last batch, take all thats left
-                        X_batch = X[i * batch_size :, :]
-                        t_batch = t[i * batch_size :, :]
-                    else:
-                        X_batch = X[i * batch_size : (i + 1) * batch_size, :]
-                        t_batch = t[i * batch_size : (i + 1) * batch_size, :]
-
-                    self._feedforward(X_batch)
-                    self._backpropagate(X_batch, t_batch, lam)
-
-                # reset schedulers for each epoch (some schedulers pass in this call)
-                for scheduler in self.schedulers_weight:
-                    scheduler.reset()
-
-                for scheduler in self.schedulers_bias:
-                    scheduler.reset()
-
-                # computing performance metrics
-                pred_train = self.predict(X)
-                train_error = cost_function_train(pred_train)
-
-                train_errors[e] = train_error
-                if val_set:
-                    
-                    pred_val = self.predict(X_val)
-                    val_error = cost_function_val(pred_val)
-                    val_errors[e] = val_error
-
-                if self.classification:
-                    train_acc = self._accuracy(self.predict(X), t)
-                    train_accs[e] = train_acc
-                    if val_set:
-                        val_acc = self._accuracy(pred_val, t_val)
-                        val_accs[e] = val_acc
-
-                # printing progress bar
-                progression = e / epochs
-                print_length = self._progress_bar(
-                    progression,
-                    train_error=train_errors[e],
-                    train_acc=train_accs[e],
-                    val_error=val_errors[e],
-                    val_acc=val_accs[e],
-                )
-        except KeyboardInterrupt:
-            # allows for stopping training at any point and seeing the result
-            pass
-
-        # visualization of training progression (similiar to tensorflow progression bar)
-        sys.stdout.write("\r" + " " * print_length)
-        sys.stdout.flush()
-        self._progress_bar(
-            1,
-            train_error=train_errors[e],
-            train_acc=train_accs[e],
-            val_error=val_errors[e],
-            val_acc=val_accs[e],
-        )
-        sys.stdout.write("")
-
-        # return performance metrics for the entire run
-        scores = dict()
-
-        scores["train_errors"] = train_errors
-
-        if val_set:
-            scores["val_errors"] = val_errors
-
-        if self.classification:
-            scores["train_accs"] = train_accs
-
-            if val_set:
-                scores["val_accs"] = val_accs
-
-        return scores
-
-    def predict(self, X: np.ndarray, *, threshold=0.5):
-        """
-         Description:
-         ------------
-             Performs prediction after training of the network has been finished.
-
-         Parameters:
-        ------------
-             I   X (np.ndarray): The design matrix, with n rows of p features each
-
-         Optional Parameters:
-         ------------
-             II  threshold (float) : sets minimal value for a prediction to be predicted as the positive class
-                 in classification problems
-
-         Returns:
-         ------------
-             I   z (np.ndarray): A prediction vector (row) for each row in our design matrix
-                 This vector is thresholded if regression=False, meaning that classification results
-                 in a vector of 1s and 0s, while regressions in an array of decimal numbers
-
-        """
-
-        predict = self._feedforward(X)
-
-        if self.classification:
-            return np.where(predict > threshold, 1, 0)
-        else:
-            return predict
-
-    def reset_weights(self):
-        """
-        Description:
-        ------------
-            Resets/Reinitializes the weights in order to train the network for a new problem.
-
-        """
-        if self.seed is not None:
-            np.random.seed(self.seed)
-
-        self.weights = list()
-        for i in range(len(self.dimensions) - 1):
-            weight_array = np.random.randn(
-                self.dimensions[i] + 1, self.dimensions[i + 1]
-            )
-            weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01
-
-            self.weights.append(weight_array)
-
-    def _feedforward(self, X: np.ndarray):
-        """
-        Description:
-        ------------
-            Calculates the activation of each layer starting at the input and ending at the output.
-            Each following activation is calculated from a weighted sum of each of the preceeding
-            activations (except in the case of the input layer).
-
-        Parameters:
-        ------------
-            I   X (np.ndarray): The design matrix, with n rows of p features each
-
-        Returns:
-        ------------
-            I   z (np.ndarray): A prediction vector (row) for each row in our design matrix
-        """
-
-        # reset matrices
-        self.a_matrices = list()
-        self.z_matrices = list()
-
-        # if X is just a vector, make it into a matrix
-        if len(X.shape) == 1:
-            X = X.reshape((1, X.shape[0]))
-
-        # Add a coloumn of zeros as the first coloumn of the design matrix, in order
-        # to add bias to our data
-        bias = np.ones((X.shape[0], 1)) * 0.01
-        X = np.hstack([bias, X])
-
-        # a^0, the nodes in the input layer (one a^0 for each row in X - where the
-        # exponent indicates layer number).
-        a = X
-        self.a_matrices.append(a)
-        self.z_matrices.append(a)
-
-        # The feed forward algorithm
-        for i in range(len(self.weights)):
-            if i < len(self.weights) - 1:
-                z = a @ self.weights[i]
-                self.z_matrices.append(z)
-                a = self.hidden_func(z)
-                # bias column again added to the data here
-                bias = np.ones((a.shape[0], 1)) * 0.01
-                a = np.hstack([bias, a])
-                self.a_matrices.append(a)
-            else:
-                try:
-                    # a^L, the nodes in our output layers
-                    z = a @ self.weights[i]
-                    a = self.output_func(z)
-                    self.a_matrices.append(a)
-                    self.z_matrices.append(z)
-                except Exception as OverflowError:
-                    print(
-                        "OverflowError in fit() in FFNN\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling"
-                    )
-
-        # this will be a^L
-        return a
-
-    def _backpropagate(self, X, t, lam):
-        """
-        Description:
-        ------------
-            Performs the backpropagation algorithm. In other words, this method
-            calculates the gradient of all the layers starting at the
-            output layer, and moving from right to left accumulates the gradient until
-            the input layer is reached. Each layers respective weights are updated while
-            the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).
-
-        Parameters:
-        ------------
-            I   X (np.ndarray): The design matrix, with n rows of p features each.
-            II  t (np.ndarray): The target vector, with n rows of p targets.
-            III lam (float32): regularization parameter used to punish the weights in case of overfitting
-
-        Returns:
-        ------------
-            No return value.
-
-        """
-        out_derivative = derivate(self.output_func)
-        hidden_derivative = derivate(self.hidden_func)
-
-        for i in range(len(self.weights) - 1, -1, -1):
-            # delta terms for output
-            if i == len(self.weights) - 1:
-                # for multi-class classification
-                if (
-                    self.output_func.__name__ == "softmax"
-                ):
-                    delta_matrix = self.a_matrices[i + 1] - t
-                # for single class classification
-                else:
-                    cost_func_derivative = grad(self.cost_func(t))
-                    delta_matrix = out_derivative(
-                        self.z_matrices[i + 1]
-                    ) * cost_func_derivative(self.a_matrices[i + 1])
-
-            # delta terms for hidden layer
-            else:
-                delta_matrix = (
-                    self.weights[i + 1][1:, :] @ delta_matrix.T
-                ).T * hidden_derivative(self.z_matrices[i + 1])
-
-            # calculate gradient
-            gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix
-            gradient_bias = np.sum(delta_matrix, axis=0).reshape(
-                1, delta_matrix.shape[1]
-            )
-
-            # regularization term
-            gradient_weights += self.weights[i][1:, :] * lam
-
-            # use scheduler
-            update_matrix = np.vstack(
-                [
-                    self.schedulers_bias[i].update_change(gradient_bias),
-                    self.schedulers_weight[i].update_change(gradient_weights),
-                ]
-            )
-
-            # update weights and bias
-            self.weights[i] -= update_matrix
-
-    def _accuracy(self, prediction: np.ndarray, target: np.ndarray):
-        """
-        Description:
-        ------------
-            Calculates accuracy of given prediction to target
-
-        Parameters:
-        ------------
-            I   prediction (np.ndarray): vector of predicitons output network
-                (1s and 0s in case of classification, and real numbers in case of regression)
-            II  target (np.ndarray): vector of true values (What the network ideally should predict)
-
-        Returns:
-        ------------
-            A floating point number representing the percentage of correctly classified instances.
-        """
-        assert prediction.size == target.size
-        return np.average((target == prediction))
-    def _set_classification(self):
-        """
-        Description:
-        ------------
-            Decides if FFNN acts as classifier (True) og regressor (False),
-            sets self.classification during init()
-        """
-        self.classification = False
-        if (
-            self.cost_func.__name__ == "CostLogReg"
-            or self.cost_func.__name__ == "CostCrossEntropy"
-        ):
-            self.classification = True
-
-    def _progress_bar(self, progression, **kwargs):
-        """
-        Description:
-        ------------
-            Displays progress of training
-        """
-        print_length = 40
-        num_equals = int(progression * print_length)
-        num_not = print_length - num_equals
-        arrow = ">" if num_equals > 0 else ""
-        bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]"
-        perc_print = self._format(progression * 100, decimals=5)
-        line = f"  {bar} {perc_print}% "
-
-        for key in kwargs:
-            if not np.isnan(kwargs[key]):
-                value = self._format(kwargs[key], decimals=4)
-                line += f"| {key}: {value} "
-        sys.stdout.write("\r" + line)
-        sys.stdout.flush()
-        return len(line)
-
-    def _format(self, value, decimals=4):
-        """
-        Description:
-        ------------
-            Formats decimal numbers for progress bar
-        """
-        if value > 0:
-            v = value
-        elif value < 0:
-            v = -10 * value
-        else:
-            v = 1
-        n = 1 + math.floor(math.log10(v))
-        if n >= decimals - 1:
-            return str(round(value))
-        return f"{value:.{decimals-n-1}f}"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Before we make a model, we will quickly generate a dataset we can use -for our linear regression problem as shown below -

- - - -
-
-
-
-
-
import autograd.numpy as np
-from sklearn.model_selection import train_test_split
-
-def SkrankeFunction(x, y):
-    return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)
-
-def create_X(x, y, n):
-    if len(x.shape) > 1:
-        x = np.ravel(x)
-        y = np.ravel(y)
-
-    N = len(x)
-    l = int((n + 1) * (n + 2) / 2)  # Number of elements in beta
-    X = np.ones((N, l))
-
-    for i in range(1, n + 1):
-        q = int((i) * (i + 1) / 2)
-        for k in range(i + 1):
-            X[:, q + k] = (x ** (i - k)) * (y**k)
-
-    return X
-
-step=0.5
-x = np.arange(0, 1, step)
-y = np.arange(0, 1, step)
-x, y = np.meshgrid(x, y)
-target = SkrankeFunction(x, y)
-target = target.reshape(target.shape[0], 1)
-
-poly_degree=3
-X = create_X(x, y, poly_degree)
-
-X_train, X_test, t_train, t_test = train_test_split(X, target)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now that we have our dataset ready for the regression, we can create -our regressor. Note that with the seed parameter, we can make sure our -results stay the same every time we run the neural network. For -inititialization, we simply specify the dimensions (we wish the amount -of input nodes to be equal to the datapoints, and the output to -predict one value). -

- - - -
-
-
-
-
-
input_nodes = X_train.shape[1]
-output_nodes = 1
-
-linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We then fit our model with our training data using the scheduler of our choice.

- - - -
-
-
-
-
-
linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Constant(eta=1e-3)
-scores = linear_regression.fit(X_train, t_train, scheduler)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Due to the progress bar we can see the MSE (train_error) throughout -the FFNN's training. Note that the fit() function has some optional -parameters with defualt arguments. For example, the regularization -hyperparameter can be left ignored if not needed, and equally the FFNN -will by default run for 100 epochs. These can easily be changed, such -as for example: -

- - - -
-
-
-
-
-
linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that given more epochs to train on, the regressor reaches a lower MSE.

- -

Let us then switch to a binary classification. We use a binary -classification dataset, and follow a similar setup to the regression -case. -

- - - -
-
-
-
-
-
from sklearn.datasets import load_breast_cancer
-from sklearn.preprocessing import MinMaxScaler
-
-wisconsin = load_breast_cancer()
-X = wisconsin.data
-target = wisconsin.target
-target = target.reshape(target.shape[0], 1)
-
-X_train, X_val, t_train, t_val = train_test_split(X, target)
-
-scaler = MinMaxScaler()
-scaler.fit(X_train)
-X_train = scaler.transform(X_train)
-X_val = scaler.transform(X_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
input_nodes = X_train.shape[1]
-output_nodes = 1
-
-logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We will now make use of our validation data by passing it into our fit function as a keyword argument

- - - -
-
-
-
-
-
logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
-scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Finally, we will create a neural network with 2 hidden layers with activation functions.

- - -
-
-
-
-
-
input_nodes = X_train.shape[1]
-hidden_nodes1 = 100
-hidden_nodes2 = 30
-output_nodes = 1
-
-dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
-
-neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
-scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

Multiclass classification

- -

Finally, we will demonstrate the use case of multiclass classification -using our FFNN with the famous MNIST dataset, which contain images of -digits between the range of 0 to 9. -

- - - -
-
-
-
-
-
from sklearn.datasets import load_digits
-
-def onehot(target: np.ndarray):
-    onehot = np.zeros((target.size, target.max() + 1))
-    onehot[np.arange(target.size), target] = 1
-    return onehot
-
-digits = load_digits()
-
-X = digits.data
-target = digits.target
-target = onehot(target)
-
-input_nodes = 64
-hidden_nodes1 = 100
-hidden_nodes2 = 30
-output_nodes = 10
-
-dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
-
-multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)
-
-multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-
-scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
-scores = multiclass.fit(X, target, scheduler, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Testing the XOR gate and other gates

- -

Let us now use our code to test the XOR gate.

- - - -
-
-
-
-
-
X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
-
-# The XOR gate
-yXOR = np.array( [[ 0], [1] ,[1], [0]])
-
-input_nodes = X.shape[1]
-output_nodes = 1
-
-logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
-logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights
-scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999)
-scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Not bad, but the results depend strongly on the learning reate. Try different learning rates.

- -
- © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - diff --git a/doc/src/week42/week42.ipynb b/doc/src/week42/week42.ipynb deleted file mode 100644 index ff791c9a6..000000000 --- a/doc/src/week42/week42.ipynb +++ /dev/null @@ -1,6133 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "eeb3000a", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "c5c0c27f", - "metadata": { - "editable": true - }, - "source": [ - "# Week 42 Constructing a Neural Network code with examples\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: **October 14-18, 2024**" - ] - }, - { - "cell_type": "markdown", - "id": "af228a9b", - "metadata": { - "editable": true - }, - "source": [ - "## Lecture October 14, 2024\n", - "1. Building our own Feed-forward Neural Network and discussion of project 2\n", - "\n", - "**Readings and videos.**\n", - "\n", - "1. These lecture notes\n", - "\n", - "\n", - "\n", - "2. For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. \n", - "\n", - "3. Neural Networks demystified at \n", - "\n", - "4. Building Neural Networks from scratch at \n", - "\n", - "5. Video on Neural Networks at \n", - "\n", - "6. Video on the back propagation algorithm at \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": "750557ba", - "metadata": { - "editable": true - }, - "source": [ - "## Material for the active learning sessions on Tuesday and Wednesday\n", - " * Exercise on starting to write a code for neural networks, feed forward part. We will also continue ur discussions of gradient descent methods from last week. If you have time, start considering the back-propagation part as well (exercises for next week)\n", - "\n", - " * Discussion of project 2\n", - "\n", - " \n", - "\n", - "**Note**: some of the codes will also be discussed next week in connection with the solution of differential equations." - ] - }, - { - "cell_type": "markdown", - "id": "35c84973", - "metadata": { - "editable": true - }, - "source": [ - "## Writing a code which implements a feed-forward neural network\n", - "\n", - "Last week we discussed the basics of neural networks and deep learning\n", - "and the basics of automatic differentiation. We looked also at\n", - "examples on how compute the parameters of a simple network with scalar\n", - "inputs and ouputs and no or just one hidden layers.\n", - "\n", - "We ended our discussions with the derivation of the equations for a\n", - "neural network with one hidden layers and two input variables and two\n", - "hidden nodes but only one output node." - ] - }, - { - "cell_type": "markdown", - "id": "ddc4c89d", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematics of deep learning\n", - "\n", - "**Two recent books online.**\n", - "\n", - "1. [The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen](https://arxiv.org/abs/2105.04026), published as [Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022](https://doi.org/10.1017/9781009025096.002)\n", - "\n", - "2. [Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger](https://doi.org/10.48550/arXiv.2310.20360)" - ] - }, - { - "cell_type": "markdown", - "id": "ac3c5024", - "metadata": { - "editable": true - }, - "source": [ - "## Reminder on books with hands-on material and codes\n", - "* [Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch](https://sebastianraschka.com/blog/2022/ml-pytorch-book.html)" - ] - }, - { - "cell_type": "markdown", - "id": "11b95652", - "metadata": { - "editable": true - }, - "source": [ - "## Reading recommendations\n", - "\n", - "1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from [GitHub](https://github.com/rasbt/machine-learning-book)\n", - "\n", - "2. Goodfellow et al, chapter 6 and 7 contain most of the neural network background." - ] - }, - { - "cell_type": "markdown", - "id": "b6e2e459", - "metadata": { - "editable": true - }, - "source": [ - "## First network example, simple percepetron with one input\n", - "\n", - "As yet another example we define now a simple perceptron model with\n", - "all quantities given by scalars. We consider only one input variable\n", - "$x$ and one target value $y$. We define an activation function\n", - "$\\sigma_1$ which takes as input" - ] - }, - { - "cell_type": "markdown", - "id": "1409dab2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_1 = w_1x+b_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9a1cfa21", - "metadata": { - "editable": true - }, - "source": [ - "where $w_1$ is the weight and $b_1$ is the bias. These are the\n", - "parameters we want to optimize. The output is $a_1=\\sigma(z_1)$ (see\n", - "graph from whiteboard notes). This output is then fed into the\n", - "**cost/loss** function, which we here for the sake of simplicity just\n", - "define as the squared error" - ] - }, - { - "cell_type": "markdown", - "id": "745f5eb1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(x;w_1,b_1)=\\frac{1}{2}(a_1-y)^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "44b74d07", - "metadata": { - "editable": true - }, - "source": [ - "## Layout of a simple neural network with no hidden layer\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "5a549fa5", - "metadata": { - "editable": true - }, - "source": [ - "## Optimizing the parameters\n", - "\n", - "In setting up the feed forward and back propagation parts of the\n", - "algorithm, we need now the derivative of the various variables we want\n", - "to train.\n", - "\n", - "We need" - ] - }, - { - "cell_type": "markdown", - "id": "c2276f01", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_1} \\hspace{0.1cm}\\mathrm{and}\\hspace{0.1cm}\\frac{\\partial C}{\\partial b_1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "961fdf59", - "metadata": { - "editable": true - }, - "source": [ - "Using the chain rule we find" - ] - }, - { - "cell_type": "markdown", - "id": "fbbebd7f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_1}=\\frac{\\partial C}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}\\frac{\\partial z_1}{\\partial w_1}=(a_1-y)\\sigma_1'x,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ad4d526c", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "950ff3dc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_1}=\\frac{\\partial C}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}\\frac{\\partial z_1}{\\partial b_1}=(a_1-y)\\sigma_1',\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c1fc8822", - "metadata": { - "editable": true - }, - "source": [ - "which we later will just define as" - ] - }, - { - "cell_type": "markdown", - "id": "4a04f7f7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}=\\delta_1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "26430ee8", - "metadata": { - "editable": true - }, - "source": [ - "## Adding a hidden layer\n", - "\n", - "We change our simple model to (see graph)\n", - "a network with just one hidden layer but with scalar variables only.\n", - "\n", - "Our output variable changes to $a_2$ and $a_1$ is now the output from the hidden node and $a_0=x$.\n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "id": "cb0b0c94", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_1 = w_1a_0+b_1 \\hspace{0.1cm} \\wedge a_1 = \\sigma_1(z_1),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0288d581", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_2 = w_2a_1+b_2 \\hspace{0.1cm} \\wedge a_2 = \\sigma_2(z_2),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b1e21087", - "metadata": { - "editable": true - }, - "source": [ - "and the cost function" - ] - }, - { - "cell_type": "markdown", - "id": "81523a1c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(x;\\boldsymbol{\\Theta})=\\frac{1}{2}(a_2-y)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b2f1a06b", - "metadata": { - "editable": true - }, - "source": [ - "with $\\boldsymbol{\\Theta}=[w_1,w_2,b_1,b_2]$." - ] - }, - { - "cell_type": "markdown", - "id": "a769001e", - "metadata": { - "editable": true - }, - "source": [ - "## Layout of a simple neural network with one hidden layer\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "c84fadb6", - "metadata": { - "editable": true - }, - "source": [ - "## The derivatives\n", - "\n", - "The derivatives are now, using the chain rule again" - ] - }, - { - "cell_type": "markdown", - "id": "481d95b7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_2}=\\frac{\\partial C}{\\partial a_2}\\frac{\\partial a_2}{\\partial z_2}\\frac{\\partial z_2}{\\partial w_2}=(a_2-y)\\sigma_2'a_1=\\delta_2a_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5f75ab21", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_2}=\\frac{\\partial C}{\\partial a_2}\\frac{\\partial a_2}{\\partial z_2}\\frac{\\partial z_2}{\\partial b_2}=(a_2-y)\\sigma_2'=\\delta_2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "587d754d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_1}=\\frac{\\partial C}{\\partial a_2}\\frac{\\partial a_2}{\\partial z_2}\\frac{\\partial z_2}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}\\frac{\\partial z_1}{\\partial w_1}=(a_2-y)\\sigma_2'a_1\\sigma_1'a_0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2fb1fdf5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_1}=\\frac{\\partial C}{\\partial a_2}\\frac{\\partial a_2}{\\partial z_2}\\frac{\\partial z_2}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}\\frac{\\partial z_1}{\\partial b_1}=(a_2-y)\\sigma_2'\\sigma_1'=\\delta_1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7a5e05db", - "metadata": { - "editable": true - }, - "source": [ - "Can you generalize this to more than one hidden layer?" - ] - }, - { - "cell_type": "markdown", - "id": "01ca79e1", - "metadata": { - "editable": true - }, - "source": [ - "## Important observations\n", - "\n", - "From the above equations we see that the derivatives of the activation\n", - "functions play a central role. If they vanish, the training may\n", - "stop. This is called the vanishing gradient problem, see discussions below. If they become\n", - "large, the parameters $w_i$ and $b_i$ may simply go to infinity. This\n", - "is referenced as the exploding gradient problem." - ] - }, - { - "cell_type": "markdown", - "id": "3fcd5865", - "metadata": { - "editable": true - }, - "source": [ - "## The training\n", - "\n", - "The training of the parameters is done through various gradient descent approximations with" - ] - }, - { - "cell_type": "markdown", - "id": "c4fea209", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{i}\\leftarrow w_{i}- \\eta \\delta_i a_{i-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a1347ae3", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "7dcd110f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "b_i \\leftarrow b_i-\\eta \\delta_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "81d126e1", - "metadata": { - "editable": true - }, - "source": [ - "with $\\eta$ is the learning rate.\n", - "\n", - "One iteration consists of one feed forward step and one back-propagation step. Each back-propagation step does one update of the parameters $\\boldsymbol{\\Theta}$.\n", - "\n", - "For the first hidden layer $a_{i-1}=a_0=x$ for this simple model." - ] - }, - { - "cell_type": "markdown", - "id": "9a53fc82", - "metadata": { - "editable": true - }, - "source": [ - "## Code example\n", - "\n", - "The code here implements the above model with one hidden layer and\n", - "scalar variables for the same function we studied in the previous\n", - "example. The code is however set up so that we can add multiple\n", - "inputs $x$ and target values $y$. Note also that we have the\n", - "possibility of defining a feature matrix $\\boldsymbol{X}$ with more than just\n", - "one column for the input values. This will turn useful in our next example. We have also defined matrices and vectors for all of our operations although it is not necessary here." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "0f334c42", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# We use the Sigmoid function as activation function\n", - "def sigmoid(z):\n", - " return 1.0/(1.0+np.exp(-z))\n", - "\n", - "def forwardpropagation(x):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_1 = np.matmul(x, w_1) + b_1\n", - " # activation in the hidden layer\n", - " a_1 = sigmoid(z_1)\n", - " # weighted sum of inputs to the output layer\n", - " z_2 = np.matmul(a_1, w_2) + b_2\n", - " a_2 = z_2\n", - " return a_1, a_2\n", - "\n", - "def backpropagation(x, y):\n", - " a_1, a_2 = forwardpropagation(x)\n", - " # parameter delta for the output layer, note that a_2=z_2 and its derivative wrt z_2 is just 1\n", - " delta_2 = a_2 - y\n", - " print(0.5*((a_2-y)**2))\n", - " # delta for the hidden layer\n", - " delta_1 = np.matmul(delta_2, w_2.T) * a_1 * (1 - a_1)\n", - " # gradients for the output layer\n", - " output_weights_gradient = np.matmul(a_1.T, delta_2)\n", - " output_bias_gradient = np.sum(delta_2, axis=0)\n", - " # gradient for the hidden layer\n", - " hidden_weights_gradient = np.matmul(x.T, delta_1)\n", - " hidden_bias_gradient = np.sum(delta_1, axis=0)\n", - " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "# Input variable\n", - "x = np.array([4.0],dtype=np.float64)\n", - "# Target values\n", - "y = 2*x+1.0 \n", - "\n", - "# Defining the neural network, only scalars here\n", - "n_inputs = x.shape\n", - "n_features = 1\n", - "n_hidden_neurons = 1\n", - "n_outputs = 1\n", - "\n", - "# Initialize the network\n", - "# weights and bias in the hidden layer\n", - "w_1 = np.random.randn(n_features, n_hidden_neurons)\n", - "b_1 = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "w_2 = np.random.randn(n_hidden_neurons, n_outputs)\n", - "b_2 = np.zeros(n_outputs) + 0.01\n", - "\n", - "eta = 0.1\n", - "for i in range(50):\n", - " # calculate gradients\n", - " derivW2, derivB2, derivW1, derivB1 = backpropagation(x, y)\n", - " # update weights and biases\n", - " w_2 -= eta * derivW2\n", - " b_2 -= eta * derivB2\n", - " w_1 -= eta * derivW1\n", - " b_1 -= eta * derivB1" - ] - }, - { - "cell_type": "markdown", - "id": "da20ec8b", - "metadata": { - "editable": true - }, - "source": [ - "We see that after some few iterations (the results do depend on the learning rate however), we get an error which is rather small." - ] - }, - { - "cell_type": "markdown", - "id": "fe320615", - "metadata": { - "editable": true - }, - "source": [ - "## Simple neural network and the back propagation equations\n", - "\n", - "Let us now try to increase our level of ambition and attempt at setting \n", - "up the equations for a neural network with two input nodes, one hidden\n", - "layer with two hidden nodes and one output layer with one output node/neuron only (see graph)..\n", - "\n", - "We need to define the following parameters and variables with the input layer (layer $(0)$) \n", - "where we label the nodes $x_0$ and $x_1$" - ] - }, - { - "cell_type": "markdown", - "id": "ec803247", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "x_0 = a_0^{(0)} \\wedge x_1 = a_1^{(0)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a5188847", - "metadata": { - "editable": true - }, - "source": [ - "The hidden layer (layer $(1)$) has nodes which yield the outputs $a_0^{(1)}$ and $a_1^{(1)}$) with weight $\\boldsymbol{w}$ and bias $\\boldsymbol{b}$ parameters" - ] - }, - { - "cell_type": "markdown", - "id": "dbc0051b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{ij}^{(1)}=\\left\\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\\right\\} \\wedge b^{(1)}=\\left\\{b_0^{(1)},b_1^{(1)}\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9a086cbe", - "metadata": { - "editable": true - }, - "source": [ - "## Layout of a simple neural network with two input nodes, one hidden layer with two hidden noeds and one output node\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "55691e04", - "metadata": { - "editable": true - }, - "source": [ - "## The ouput layer\n", - "\n", - "We have the ouput layer given by layer label $(2)$ with output $a^{(2)}$ and weights and biases to be determined given by the variables" - ] - }, - { - "cell_type": "markdown", - "id": "1aa3e85c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{i}^{(2)}=\\left\\{w_{1}^{(2)},w_{2}^{(2)}\\right\\} \\wedge b^{(2)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "04fd1c47", - "metadata": { - "editable": true - }, - "source": [ - "Our output is $\\tilde{y}=a^{(2)}$ and we define a generic cost function $C(a^{(2)},y;\\boldsymbol{\\Theta})$ where $y$ is the target value (a scalar here).\n", - "The parameters we need to optimize are given by" - ] - }, - { - "cell_type": "markdown", - "id": "628a64e0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Theta}=\\left\\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)},w_{1}^{(2)},w_{2}^{(2)},b_1^{(1)},b_2^{(1)},b^{(2)}\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3856c61f", - "metadata": { - "editable": true - }, - "source": [ - "## Compact expressions\n", - "\n", - "We can define the inputs to the activation functions for the various layers in terms of various matrix-vector multiplications and vector additions.\n", - "The inputs to the first hidden layer are" - ] - }, - { - "cell_type": "markdown", - "id": "bf06c970", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{bmatrix}z_1^{(1)} \\\\ z_2^{(1)} \\end{bmatrix}=\\left(\\begin{bmatrix}w_{11}^{(1)} & w_{12}^{(1)}\\\\ w_{21}^{(1)} &w_{22}^{(1)} \\end{bmatrix}\\right)^{T}\\begin{bmatrix}a_1^{(0)} \\\\ a_2^{(0)} \\end{bmatrix}+\\begin{bmatrix}b_1^{(1)} \\\\ b_2^{(1)} \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "15c61190", - "metadata": { - "editable": true - }, - "source": [ - "with outputs" - ] - }, - { - "cell_type": "markdown", - "id": "d675d2b5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{bmatrix}a_1^{(1)} \\\\ a_2^{(1)} \\end{bmatrix}=\\begin{bmatrix}\\sigma^{(1)}(z_1^{(1)}) \\\\ \\sigma^{(1)}(z_2^{(1)}) \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ed858ea7", - "metadata": { - "editable": true - }, - "source": [ - "## Output layer\n", - "\n", - "For the final output layer we have the inputs to the final activation function" - ] - }, - { - "cell_type": "markdown", - "id": "151b4f5e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z^{(2)} = w_{1}^{(2)}a_1^{(1)} +w_{2}^{(2)}a_2^{(1)}+b^{(2)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3ea32b93", - "metadata": { - "editable": true - }, - "source": [ - "resulting in the output" - ] - }, - { - "cell_type": "markdown", - "id": "257efa71", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "a^{(2)}=\\sigma^{(2)}(z^{(2)}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e97f52ba", - "metadata": { - "editable": true - }, - "source": [ - "## Explicit derivatives\n", - "\n", - "In total we have nine parameters which we need to train. Using the\n", - "chain rule (or just the back-propagation algorithm) we can find all\n", - "derivatives. Since we will use automatic differentiation in reverse\n", - "mode, we start with the derivatives of the cost function with respect\n", - "to the parameters of the output layer, namely" - ] - }, - { - "cell_type": "markdown", - "id": "c48537ec", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{i}^{(2)}}=\\frac{\\partial C}{\\partial a^{(2)}}\\frac{\\partial a^{(2)}}{\\partial z^{(2)}}\\frac{\\partial z^{(2)}}{\\partial w_{i}^{(2)}}=\\delta^{(2)}a_i^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "132f1c81", - "metadata": { - "editable": true - }, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "id": "5bca9598", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta^{(2)}=\\frac{\\partial C}{\\partial a^{(2)}}\\frac{\\partial a^{(2)}}{\\partial z^{(2)}}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c8065eb2", - "metadata": { - "editable": true - }, - "source": [ - "and finally" - ] - }, - { - "cell_type": "markdown", - "id": "e14472e4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b^{(2)}}=\\frac{\\partial C}{\\partial a^{(2)}}\\frac{\\partial a^{(2)}}{\\partial z^{(2)}}\\frac{\\partial z^{(2)}}{\\partial b^{(2)}}=\\delta^{(2)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e6a4b016", - "metadata": { - "editable": true - }, - "source": [ - "## Derivatives of the hidden layer\n", - "\n", - "Using the chain rule we have the following expressions for say one of the weight parameters (it is easy to generalize to the other weight parameters)" - ] - }, - { - "cell_type": "markdown", - "id": "1b2a2eb8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{11}^{(1)}}=\\frac{\\partial C}{\\partial a^{(2)}}\\frac{\\partial a^{(2)}}{\\partial z^{(2)}}\n", - "\\frac{\\partial z^{(2)}}{\\partial z_1^{(1)}}\\frac{\\partial z_1^{(1)}}{\\partial w_{11}^{(1)}}= \\delta^{(2)}\\frac{\\partial z^{(2)}}{\\partial z_1^{(1)}}\\frac{\\partial z_1^{(1)}}{\\partial w_{11}^{(1)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bfe4686c", - "metadata": { - "editable": true - }, - "source": [ - "which, noting that" - ] - }, - { - "cell_type": "markdown", - "id": "26e1d8dc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z^{(2)} =w_1^{(2)}a_1^{(1)}+w_2^{(2)}a_2^{(1)}+b^{(2)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3b1c1b35", - "metadata": { - "editable": true - }, - "source": [ - "allows us to rewrite" - ] - }, - { - "cell_type": "markdown", - "id": "4e24a907", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial z^{(2)}}{\\partial z_1^{(1)}}\\frac{\\partial z_1^{(1)}}{\\partial w_{11}^{(1)}}=w_1^{(2)}\\frac{\\partial a_1^{(1)}}{\\partial z_1^{(1)}}a_1^{(1)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "674e3b94", - "metadata": { - "editable": true - }, - "source": [ - "## Final expression\n", - "Defining" - ] - }, - { - "cell_type": "markdown", - "id": "5da27439", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_1^{(1)}=w_1^{(2)}\\frac{\\partial a_1^{(1)}}{\\partial z_1^{(1)}}\\delta^{(2)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "145df32f", - "metadata": { - "editable": true - }, - "source": [ - "we have" - ] - }, - { - "cell_type": "markdown", - "id": "e2b358af", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{11}^{(1)}}=\\delta_1^{(1)}a_1^{(1)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "36176956", - "metadata": { - "editable": true - }, - "source": [ - "Similarly, we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "622c2850", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{12}^{(1)}}=\\delta_1^{(1)}a_2^{(1)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c4f7f75a", - "metadata": { - "editable": true - }, - "source": [ - "## Completing the list\n", - "\n", - "Similarly, we find" - ] - }, - { - "cell_type": "markdown", - "id": "5b9e0d5b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{21}^{(1)}}=\\delta_2^{(1)}a_1^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ea608c40", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "6d8ca0aa", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{22}^{(1)}}=\\delta_2^{(1)}a_2^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "69f842d7", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined" - ] - }, - { - "cell_type": "markdown", - "id": "1d6268de", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_2^{(1)}=w_2^{(2)}\\frac{\\partial a_2^{(1)}}{\\partial z_2^{(1)}}\\delta^{(2)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dbfc1af0", - "metadata": { - "editable": true - }, - "source": [ - "## Final expressions for the biases of the hidden layer\n", - "\n", - "For the sake of completeness, we list the derivatives of the biases, which are" - ] - }, - { - "cell_type": "markdown", - "id": "7efc04c4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_{1}^{(1)}}=\\delta_1^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0233ba94", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "07b0c80c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_{2}^{(1)}}=\\delta_2^{(1)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d1064240", - "metadata": { - "editable": true - }, - "source": [ - "As we will see below, these expressions can be generalized in a more compact form." - ] - }, - { - "cell_type": "markdown", - "id": "f69fc276", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient expressions\n", - "\n", - "For this specific model, with just one output node and two hidden\n", - "nodes, the gradient descent equations take the following form for output layer" - ] - }, - { - "cell_type": "markdown", - "id": "f35ac459", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{i}^{(2)}\\leftarrow w_{i}^{(2)}- \\eta \\delta^{(2)} a_{i}^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f4cee470", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "6f416b41", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "b^{(2)} \\leftarrow b^{(2)}-\\eta \\delta^{(2)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3de1cb99", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "109542b5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{ij}^{(1)}\\leftarrow w_{ij}^{(1)}- \\eta \\delta_{i}^{(1)} a_{j}^{(0)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bd937e5b", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "f91328b7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "b_{i}^{(1)} \\leftarrow b_{i}^{(1)}-\\eta \\delta_{i}^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d00bddec", - "metadata": { - "editable": true - }, - "source": [ - "where $\\eta$ is the learning rate." - ] - }, - { - "cell_type": "markdown", - "id": "872c3ff1", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the equations for a neural network\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 and biases?\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": "6d2ff831", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\cal C}(\\boldsymbol{\\Theta}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - \\tilde{y}_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f1ef66e0", - "metadata": { - "editable": true - }, - "source": [ - "where the $y_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 $\\boldsymbol{x}$ are given by $\\boldsymbol{\\tilde{y}}_i$." - ] - }, - { - "cell_type": "markdown", - "id": "83c547c3", - "metadata": { - "editable": true - }, - "source": [ - "## Layout of a neural network with three hidden layers (last later = $l=L=4$, first layer $l=0$)\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "895eb8e2", - "metadata": { - "editable": true - }, - "source": [ - "## Definitions\n", - "\n", - "With our definition of the targets $\\boldsymbol{y}$, the outputs of the\n", - "network $\\boldsymbol{\\tilde{y}}$ and the inputs $\\boldsymbol{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", - "$\\boldsymbol{a}^{l-1}$ from the previous layer as" - ] - }, - { - "cell_type": "markdown", - "id": "32c90a46", - "metadata": { - "editable": true - }, - "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": "a2f5143d", - "metadata": { - "editable": true - }, - "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 in the whiteboard notes 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": "aeb197f1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{z}^l = \\left(\\boldsymbol{W}^l\\right)^T\\boldsymbol{a}^{l-1}+\\boldsymbol{b}^l.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "18771f50", - "metadata": { - "editable": true - }, - "source": [ - "## Inputs to the activation function\n", - "\n", - "With the activation values $\\boldsymbol{z}^l$ we can in turn define the\n", - "output of layer $l$ as $\\boldsymbol{a}^l = \\sigma(\\boldsymbol{z}^l)$ where $\\sigma$ 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 $\\sigma$ for all layers\n", - "and their nodes. It means we have" - ] - }, - { - "cell_type": "markdown", - "id": "ecb1436d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "a_j^l = \\sigma(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9677173f", - "metadata": { - "editable": true - }, - "source": [ - "## Layout of input to first hidden layer $l=1$ from input layer $l=0$\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "dfbd401d", - "metadata": { - "editable": true - }, - "source": [ - "## Derivatives and the chain rule\n", - "\n", - "From the definition of the input variable to the activation function, that is $z_j^l$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "0e5b891e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "75554797", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "71553e68", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a3761904", - "metadata": { - "editable": true - }, - "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": "1a5221dc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial a_j^l}{\\partial z_j^{l}} = a_j^l(1-a_j^l)=\\sigma(z_j^l)(1-\\sigma(z_j^l)).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a18b7cd9", - "metadata": { - "editable": true - }, - "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": "252a444e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\cal C}(\\boldsymbol{\\Theta}^L) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - \\tilde{y}_i\\right)^2=\\frac{1}{2}\\sum_{i=1}^n\\left(a_i^L - y_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6f7b45e3", - "metadata": { - "editable": true - }, - "source": [ - "The derivative of this function with respect to the weights is" - ] - }, - { - "cell_type": "markdown", - "id": "d4cc4b41", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}(\\boldsymbol{\\Theta}^L)}{\\partial w_{ij}^L} = \\left(a_j^L - y_j\\right)\\frac{\\partial a_j^L}{\\partial w_{ij}^{L}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d3411c54", - "metadata": { - "editable": true - }, - "source": [ - "The last partial derivative can easily be computed and reads (by applying the chain rule)" - ] - }, - { - "cell_type": "markdown", - "id": "3d01d63a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial a_j^L}{\\partial w_{ij}^{L}} = \\frac{\\partial a_j^L}{\\partial z_{j}^{L}}\\frac{\\partial z_j^L}{\\partial w_{ij}^{L}}=a_j^L(1-a_j^L)a_i^{L-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8ef8b814", - "metadata": { - "editable": true - }, - "source": [ - "## The back propagation equations for a neural network\n", - "\n", - "We have thus" - ] - }, - { - "cell_type": "markdown", - "id": "14a70a29", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}((\\boldsymbol{\\Theta}^L)}{\\partial w_{ij}^L} = \\left(a_j^L - y_j\\right)a_j^L(1-a_j^L)a_i^{L-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "905ac02a", - "metadata": { - "editable": true - }, - "source": [ - "Defining" - ] - }, - { - "cell_type": "markdown", - "id": "a13234b9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^L = a_j^L(1-a_j^L)\\left(a_j^L - y_j\\right) = \\sigma'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a3a48110", - "metadata": { - "editable": true - }, - "source": [ - "and using the Hadamard product of two vectors we can write this as" - ] - }, - { - "cell_type": "markdown", - "id": "aa50c29e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\delta}^L = \\sigma'(\\boldsymbol{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\boldsymbol{a}^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "87104468", - "metadata": { - "editable": true - }, - "source": [ - "## Analyzing the last results\n", - "\n", - "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$." - ] - }, - { - "cell_type": "markdown", - "id": "8a9aec64", - "metadata": { - "editable": true - }, - "source": [ - "## More considerations\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", - "$\\sigma'(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": "425a6241", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f0b54a14", - "metadata": { - "editable": true - }, - "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": "56ecf740", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}}{\\partial w_{ij}^L} = \\delta_j^La_i^{L-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "12008dc0", - "metadata": { - "editable": true - }, - "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": "fb92f522", - "metadata": { - "editable": true - }, - "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": "3ec8475f", - "metadata": { - "editable": true - }, - "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": "f45052da", - "metadata": { - "editable": true - }, - "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": "927e0716", - "metadata": { - "editable": true - }, - "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": "6ce4a56f", - "metadata": { - "editable": true - }, - "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" - ] - }, - { - "cell_type": "markdown", - "id": "0ace7815", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\frac{\\partial{\\cal C}(\\boldsymbol{W^L})}{\\partial w_{ij}^L} = \\delta_j^La_i^{L-1},\n", - "\\label{_auto1} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "56b08cf1", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "5230a333", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\delta_j^L = \\sigma'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", - "\\label{_auto2} \\tag{2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6deeed25", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "20f2b16b", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", - "\\label{_auto3} \\tag{3}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "05d1f509", - "metadata": { - "editable": true - }, - "source": [ - "## Final back propagating equation\n", - "\n", - "We have that (replacing $L$ with a general layer $l$)" - ] - }, - { - "cell_type": "markdown", - "id": "78aa987f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cfec91fb", - "metadata": { - "editable": true - }, - "source": [ - "We want to express this in terms of the equations for layer $l+1$." - ] - }, - { - "cell_type": "markdown", - "id": "0b9f61b7", - "metadata": { - "editable": true - }, - "source": [ - "## Using the chain rule and summing over all $k$ entries\n", - "\n", - "We obtain" - ] - }, - { - "cell_type": "markdown", - "id": "7bf04564", - "metadata": { - "editable": true - }, - "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": "ca86cf07", - "metadata": { - "editable": true - }, - "source": [ - "and recalling that" - ] - }, - { - "cell_type": "markdown", - "id": "3a0f1b25", - "metadata": { - "editable": true - }, - "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": "632562ae", - "metadata": { - "editable": true - }, - "source": [ - "with $M_l$ being the number of nodes in layer $l$, we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "12ea4e17", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^l =\\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4b8b66a0", - "metadata": { - "editable": true - }, - "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": "403e4837", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations\n", - "\n", - "**The architecture (our model).**\n", - "\n", - "1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)\n", - "\n", - "2. Define the number of hidden layers and hidden nodes\n", - "\n", - "3. Define activation functions for hidden layers and output layers\n", - "\n", - "4. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates\n", - "\n", - "5. Define cost function and possible regularization terms with hyperparameters\n", - "\n", - "6. Initialize weights and biases\n", - "\n", - "7. Fix number of iterations for the feed forward part and back propagation part" - ] - }, - { - "cell_type": "markdown", - "id": "651cc192", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the back propagation algorithm, part 1\n", - "\n", - "The four equations provide us with a way of computing the gradients 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=1,2,3,\\dots,L$.\n", - "\n", - "**Notation**: The first hidden layer has $l=1$ as label and the final output layer has $l=L$." - ] - }, - { - "cell_type": "markdown", - "id": "8480c1cd", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the back propagation algorithm, part 2\n", - "\n", - "Thereafter we compute the ouput error $\\boldsymbol{\\delta}^L$ by computing all" - ] - }, - { - "cell_type": "markdown", - "id": "f0a2c0b3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^L = \\sigma'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bc0b65ac", - "metadata": { - "editable": true - }, - "source": [ - "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,1$ as" - ] - }, - { - "cell_type": "markdown", - "id": "7e70f36c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1e77d7c3", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the Back propagation algorithm, part 3\n", - "\n", - "Finally, we update the weights and the biases using gradient descent\n", - "for each $l=L-1,L-2,\\dots,1$ (the first hidden layer) and update the weights and biases\n", - "according to the rules" - ] - }, - { - "cell_type": "markdown", - "id": "2d0867fe", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{ij}^l\\leftarrow = w_{ij}^l- \\eta \\delta_j^la_i^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fcedd3da", - "metadata": { - "editable": true - }, - "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": "7b61d89e", - "metadata": { - "editable": true - }, - "source": [ - "with $\\eta$ being the learning rate." - ] - }, - { - "cell_type": "markdown", - "id": "001fbe19", - "metadata": { - "editable": true - }, - "source": [ - "## Updating the gradients\n", - "\n", - "With the back propagate error for each $l=L-1,L-2,\\dots,1$ as" - ] - }, - { - "cell_type": "markdown", - "id": "4069ec72", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "43911e1b", - "metadata": { - "editable": true - }, - "source": [ - "we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,1$ and update the weights and biases according to the rules" - ] - }, - { - "cell_type": "markdown", - "id": "b1dbae91", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{ij}^l\\leftarrow = w_{ij}^l- \\eta \\delta_j^la_i^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "93839b4c", - "metadata": { - "editable": true - }, - "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": "aecfea5f", - "metadata": { - "editable": true - }, - "source": [ - "## Activation functions\n", - "\n", - "A property that characterizes a neural network, other than its\n", - "connectivity, is the choice of activation function(s). The following\n", - "restrictions are imposed on an activation function for an FFNN to\n", - "fulfill the universal approximation theorem\n", - "\n", - " * Non-constant\n", - "\n", - " * Bounded\n", - "\n", - " * Monotonically-increasing\n", - "\n", - " * Continuous" - ] - }, - { - "cell_type": "markdown", - "id": "99e7343d", - "metadata": { - "editable": true - }, - "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": "2505f9b3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma(x) = \\frac{1}{1 + e^{-x}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "66dd8f27", - "metadata": { - "editable": true - }, - "source": [ - "and the *hyperbolic tangent* function" - ] - }, - { - "cell_type": "markdown", - "id": "4ee0dfc6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma(x) = \\tanh(x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3a306198", - "metadata": { - "editable": true - }, - "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": 2, - "id": "cc546550", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "\"\"\"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": "4ced1878", - "metadata": { - "editable": true - }, - "source": [ - "## Vanishing gradients\n", - "\n", - "The Back propagation algorithm we derived above works by going from\n", - "the output layer to the input layer, propagating the error gradient on\n", - "the way. Once the algorithm has computed the gradient of the cost\n", - "function with regards to each parameter in the network, it uses these\n", - "gradients to update each parameter with a Gradient Descent (GD) step.\n", - "\n", - "Unfortunately for us, the gradients often get smaller and smaller as\n", - "the algorithm progresses down to the first hidden layers. As a result,\n", - "the GD update leaves the lower layer connection weights virtually\n", - "unchanged, and training never converges to a good solution. This is\n", - "known in the literature as **the vanishing gradients problem**." - ] - }, - { - "cell_type": "markdown", - "id": "7ea86243", - "metadata": { - "editable": true - }, - "source": [ - "## Exploding gradients\n", - "\n", - "In other cases, the opposite can happen, namely the the gradients can\n", - "grow bigger and bigger. The result is that many of the layers get\n", - "large updates of the weights the algorithm diverges. This is the\n", - "**exploding gradients problem**, which is mostly encountered in\n", - "recurrent neural networks. More generally, deep neural networks suffer\n", - "from unstable gradients, different layers may learn at widely\n", - "different speeds" - ] - }, - { - "cell_type": "markdown", - "id": "511380e2", - "metadata": { - "editable": true - }, - "source": [ - "## Is the Logistic activation function (Sigmoid) our choice?\n", - "\n", - "Although this unfortunate behavior has been empirically observed for\n", - "quite a while (it was one of the reasons why deep neural networks were\n", - "mostly abandoned for a long time), it is only around 2010 that\n", - "significant progress was made in understanding it.\n", - "\n", - "A paper titled [Understanding the Difficulty of Training Deep\n", - "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n", - "the problems with the popular logistic\n", - "sigmoid activation function and the weight initialization technique\n", - "that was most popular at the time, namely random initialization using\n", - "a normal distribution with a mean of 0 and a standard deviation of\n", - "1." - ] - }, - { - "cell_type": "markdown", - "id": "22b40132", - "metadata": { - "editable": true - }, - "source": [ - "## Logistic function as the root of problems\n", - "\n", - "They showed that with this activation function and this\n", - "initialization scheme, the variance of the outputs of each layer is\n", - "much greater than the variance of its inputs. Going forward in the\n", - "network, the variance keeps increasing after each layer until the\n", - "activation function saturates at the top layers. This is actually made\n", - "worse by the fact that the logistic function has a mean of 0.5, not 0\n", - "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n", - "better than the logistic function in deep networks)." - ] - }, - { - "cell_type": "markdown", - "id": "ee4c79cc", - "metadata": { - "editable": true - }, - "source": [ - "## The derivative of the Logistic funtion\n", - "\n", - "Looking at the logistic activation function, when inputs become large\n", - "(negative or positive), the function saturates at 0 or 1, with a\n", - "derivative extremely close to 0. Thus when backpropagation kicks in,\n", - "it has virtually no gradient to propagate back through the network,\n", - "and what little gradient exists keeps getting diluted as\n", - "backpropagation progresses down through the top layers, so there is\n", - "really nothing left for the lower layers.\n", - "\n", - "In their paper, Glorot and Bengio propose a way to significantly\n", - "alleviate this problem. We need the signal to flow properly in both\n", - "directions: in the forward direction when making predictions, and in\n", - "the reverse direction when backpropagating gradients. We don’t want\n", - "the signal to die out, nor do we want it to explode and saturate. For\n", - "the signal to flow properly, the authors argue that we need the\n", - "variance of the outputs of each layer to be equal to the variance of\n", - "its inputs, and we also need the gradients to have equal variance\n", - "before and after flowing through a layer in the reverse direction." - ] - }, - { - "cell_type": "markdown", - "id": "27f52200", - "metadata": { - "editable": true - }, - "source": [ - "## Insights from the paper by Glorot and Bengio\n", - "\n", - "One of the insights in the 2010 paper by Glorot and Bengio was that\n", - "the vanishing/exploding gradients problems were in part due to a poor\n", - "choice of activation function. Until then most people had assumed that\n", - "if Nature had chosen to use roughly sigmoid activation functions in\n", - "biological neurons, they must be an excellent choice. But it turns out\n", - "that other activation functions behave much better in deep neural\n", - "networks, in particular the ReLU activation function, mostly because\n", - "it does not saturate for positive values (and also because it is quite\n", - "fast to compute)." - ] - }, - { - "cell_type": "markdown", - "id": "b8b9d46c", - "metadata": { - "editable": true - }, - "source": [ - "## The RELU function family\n", - "\n", - "The ReLU activation function suffers from a problem known as the dying\n", - "ReLUs: during training, some neurons effectively die, meaning they\n", - "stop outputting anything other than 0.\n", - "\n", - "In some cases, you may find that half of your network’s neurons are\n", - "dead, especially if you used a large learning rate. During training,\n", - "if a neuron’s weights get updated such that the weighted sum of the\n", - "neuron’s inputs is negative, it will start outputting 0. When this\n", - "happen, the neuron is unlikely to come back to life since the gradient\n", - "of the ReLU function is 0 when its input is negative." - ] - }, - { - "cell_type": "markdown", - "id": "3d0c5b2b", - "metadata": { - "editable": true - }, - "source": [ - "## ELU function\n", - "\n", - "To solve this problem, nowadays practitioners use a variant of the\n", - "ReLU function, such as the leaky ReLU discussed above or the so-called\n", - "exponential linear unit (ELU) function" - ] - }, - { - "cell_type": "markdown", - "id": "a1ae341a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cc1fca15", - "metadata": { - "editable": true - }, - "source": [ - "## Which activation function should we use?\n", - "\n", - "In general it seems that the ELU activation function is better than\n", - "the leaky ReLU function (and its variants), which is better than\n", - "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", - "than the logistic function.\n", - "\n", - "If runtime performance is an issue, then you may opt for the leaky\n", - "ReLU function over the ELU function If you don’t want to tweak yet\n", - "another hyperparameter, you may just use the default $\\alpha$ of\n", - "$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and\n", - "computing power, you can use cross-validation or bootstrap to evaluate\n", - "other activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "53768e88", - "metadata": { - "editable": true - }, - "source": [ - "## More on activation functions, output layers\n", - "\n", - "In most cases you can use the ReLU activation function in the hidden\n", - "layers (or one of its variants).\n", - "\n", - "It is a bit faster to compute than other activation functions, and the\n", - "gradient descent optimization does in general not get stuck.\n", - "\n", - "**For the output layer:**\n", - "\n", - "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n", - "\n", - "* For regression tasks, you can simply use no activation function at all." - ] - }, - { - "cell_type": "markdown", - "id": "82acd79b", - "metadata": { - "editable": true - }, - "source": [ - "## Fine-tuning neural network hyperparameters\n", - "\n", - "The flexibility of neural networks is also one of their main\n", - "drawbacks: there are many hyperparameters to tweak. Not only can you\n", - "use any imaginable network topology (how neurons/nodes are\n", - "interconnected), but even in a simple FFNN you can change the number\n", - "of layers, the number of neurons per layer, the type of activation\n", - "function to use in each layer, the weight initialization logic, the\n", - "stochastic gradient optmized and much more. How do you know what\n", - "combination of hyperparameters is the best for your task?\n", - "\n", - "* You can use grid search with cross-validation to find the right hyperparameters.\n", - "\n", - "However,since there are many hyperparameters to tune, and since\n", - "training a neural network on a large dataset takes a lot of time, you\n", - "will only be able to explore a tiny part of the hyperparameter space.\n", - "\n", - "* You can use randomized search.\n", - "\n", - "* Or use tools like [Oscar](http://oscar.calldesk.ai/), which implements more complex algorithms to help you find a good set of hyperparameters quickly." - ] - }, - { - "cell_type": "markdown", - "id": "a75c544a", - "metadata": { - "editable": true - }, - "source": [ - "## Hidden layers\n", - "\n", - "For many problems you can start with just one or two hidden layers and\n", - "it will work just fine. For the MNIST data set discussed below you can easily get a\n", - "high accuracy using just one hidden layer with a few hundred neurons.\n", - "You can reach for this data set above 98% accuracy using two hidden\n", - "layers with the same total amount of neurons, in roughly the same\n", - "amount of training time.\n", - "\n", - "For more complex problems, you can gradually ramp up the number of\n", - "hidden layers, until you start overfitting the training set. Very\n", - "complex tasks, such as large image classification or speech\n", - "recognition, typically require networks with dozens of layers and they\n", - "need a huge amount of training data. However, you will rarely have to\n", - "train such networks from scratch: it is much more common to reuse\n", - "parts of a pretrained state-of-the-art network that performs a similar\n", - "task." - ] - }, - { - "cell_type": "markdown", - "id": "db855fb4", - "metadata": { - "editable": true - }, - "source": [ - "## Batch Normalization\n", - "\n", - "Batch Normalization aims to address the vanishing/exploding gradients\n", - "problems, and more generally the problem that the distribution of each\n", - "layer’s inputs changes during training, as the parameters of the\n", - "previous layers change.\n", - "\n", - "The technique consists of adding an operation in the model just before\n", - "the activation function of each layer, simply zero-centering and\n", - "normalizing the inputs, then scaling and shifting the result using two\n", - "new parameters per layer (one for scaling, the other for shifting). In\n", - "other words, this operation lets the model learn the optimal scale and\n", - "mean of the inputs for each layer. In order to zero-center and\n", - "normalize the inputs, the algorithm needs to estimate the inputs’ mean\n", - "and standard deviation. It does so by evaluating the mean and standard\n", - "deviation of the inputs over the current mini-batch, from this the\n", - "name batch normalization." - ] - }, - { - "cell_type": "markdown", - "id": "7d9639b2", - "metadata": { - "editable": true - }, - "source": [ - "## Dropout\n", - "\n", - "It is a fairly simple algorithm: at every training step, every neuron\n", - "(including the input neurons but excluding the output neurons) has a\n", - "probability $p$ of being temporarily dropped out, meaning it will be\n", - "entirely ignored during this training step, but it may be active\n", - "during the next step.\n", - "\n", - "The hyperparameter $p$ is called the dropout rate, and it is typically\n", - "set to 50%. After training, the neurons are not dropped anymore. It\n", - "is viewed as one of the most popular regularization techniques." - ] - }, - { - "cell_type": "markdown", - "id": "4a509ed7", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient Clipping\n", - "\n", - "A popular technique to lessen the exploding gradients problem is to\n", - "simply clip the gradients during backpropagation so that they never\n", - "exceed some threshold (this is mostly useful for recurrent neural\n", - "networks).\n", - "\n", - "This technique is called Gradient Clipping.\n", - "\n", - "In general however, Batch\n", - "Normalization is preferred." - ] - }, - { - "cell_type": "markdown", - "id": "db3b3c93", - "metadata": { - "editable": true - }, - "source": [ - "## A top-down perspective on Neural networks\n", - "\n", - "The first thing we would like to do is divide the data into two or\n", - "three parts. A training set, a validation or dev (development) set,\n", - "and a test set. The test set is the data on which we want to make\n", - "predictions. The dev set is a subset of the training data we use to\n", - "check how well we are doing out-of-sample, after training the model on\n", - "the training dataset. We use the validation error as a proxy for the\n", - "test error in order to make tweaks to our model. It is crucial that we\n", - "do not use any of the test data to train the algorithm. This is a\n", - "cardinal sin in ML. Then:\n", - "\n", - "1. Estimate optimal error rate\n", - "\n", - "2. Minimize underfitting (bias) on training data set.\n", - "\n", - "3. Make sure you are not overfitting." - ] - }, - { - "cell_type": "markdown", - "id": "98a721de", - "metadata": { - "editable": true - }, - "source": [ - "## More top-down perspectives\n", - "\n", - "If the validation and test sets are drawn from the same distributions,\n", - "then a good performance on the validation set should lead to similarly\n", - "good performance on the test set. \n", - "\n", - "However, sometimes\n", - "the training data and test data differ in subtle ways because, for\n", - "example, they are collected using slightly different methods, or\n", - "because it is cheaper to collect data in one way versus another. In\n", - "this case, there can be a mismatch between the training and test\n", - "data. This can lead to the neural network overfitting these small\n", - "differences between the test and training sets, and a poor performance\n", - "on the test set despite having a good performance on the validation\n", - "set. To rectify this, Andrew Ng suggests making two validation or dev\n", - "sets, one constructed from the training data and one constructed from\n", - "the test data. The difference between the performance of the algorithm\n", - "on these two validation sets quantifies the train-test mismatch. This\n", - "can serve as another important diagnostic when using DNNs for\n", - "supervised learning." - ] - }, - { - "cell_type": "markdown", - "id": "6edf83c0", - "metadata": { - "editable": true - }, - "source": [ - "## Limitations of supervised learning with deep networks\n", - "\n", - "Like all statistical methods, supervised learning using neural\n", - "networks has important limitations. This is especially important when\n", - "one seeks to apply these methods, especially to physics problems. Like\n", - "all tools, DNNs are not a universal solution. Often, the same or\n", - "better performance on a task can be achieved by using a few\n", - "hand-engineered features (or even a collection of random\n", - "features)." - ] - }, - { - "cell_type": "markdown", - "id": "175a12ef", - "metadata": { - "editable": true - }, - "source": [ - "## Limitations of NNs\n", - "\n", - "Here we list some of the important limitations of supervised neural network based models. \n", - "\n", - "* **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).\n", - "\n", - "* **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs." - ] - }, - { - "cell_type": "markdown", - "id": "32058465", - "metadata": { - "editable": true - }, - "source": [ - "## Homogeneous data\n", - "\n", - "* **Homogeneous data.** Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types." - ] - }, - { - "cell_type": "markdown", - "id": "93409885", - "metadata": { - "editable": true - }, - "source": [ - "## More limitations\n", - "\n", - "* **Many problems are not about prediction.** In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.\n", - "\n", - "Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems." - ] - }, - { - "cell_type": "markdown", - "id": "6008f899", - "metadata": { - "editable": true - }, - "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": "95440f53", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = \\frac{1}{1 + \\exp{(- \\boldsymbol{x}})} ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0702b971", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "a6f77a09", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "P(y = 1 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = 1 - P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1ca3e1b7", - "metadata": { - "editable": true - }, - "source": [ - "where $y \\in \\{0, 1\\}$ and $\\boldsymbol{\\theta}$ represents the weights and biases\n", - "of our network." - ] - }, - { - "cell_type": "markdown", - "id": "32065169", - "metadata": { - "editable": true - }, - "source": [ - "## Defining the cost function\n", - "\n", - "Our cost function is given as (see the Logistic regression lectures)" - ] - }, - { - "cell_type": "markdown", - "id": "cbbd02a7", - "metadata": { - "editable": true - }, - "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": "41c433a4", - "metadata": { - "editable": true - }, - "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": "651f5b04", - "metadata": { - "editable": true - }, - "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": "1effdc88", - "metadata": { - "editable": true - }, - "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": "11fca2c0", - "metadata": { - "editable": true - }, - "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": "a99bf23b", - "metadata": { - "editable": true - }, - "source": [ - "Again we take the negative log-likelihood to define our cost function:" - ] - }, - { - "cell_type": "markdown", - "id": "e78b0dba", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\boldsymbol{\\theta})}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d9ae883b", - "metadata": { - "editable": true - }, - "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": "792b7d30", - "metadata": { - "editable": true - }, - "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": "94a824ec", - "metadata": { - "editable": true - }, - "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": "03fc0202", - "metadata": { - "editable": true - }, - "source": [ - "where we had defined the logistic (sigmoid) function" - ] - }, - { - "cell_type": "markdown", - "id": "d22d0454", - "metadata": { - "editable": true - }, - "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": "05b6e8f3", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "b27f84e2", - "metadata": { - "editable": true - }, - "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": "6713cccf", - "metadata": { - "editable": true - }, - "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": "5613ad7a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ff5f4e47", - "metadata": { - "editable": true - }, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "id": "addea11c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6abca84d", - "metadata": { - "editable": true - }, - "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": "d3a1b69c", - "metadata": { - "editable": true - }, - "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": "918afb75", - "metadata": { - "editable": true - }, - "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": "64c9a4f5", - "metadata": { - "editable": true - }, - "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": "9f1923dc", - "metadata": { - "editable": true - }, - "source": [ - "In case we use another activation function than the logistic one, we need to evaluate other derivatives." - ] - }, - { - "cell_type": "markdown", - "id": "8f270399", - "metadata": { - "editable": true - }, - "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": "8de704ac", - "metadata": { - "editable": true - }, - "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": "59087524", - "metadata": { - "editable": true - }, - "source": [ - "For the Softmax function we have" - ] - }, - { - "cell_type": "markdown", - "id": "7f665678", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2d2c4d5d", - "metadata": { - "editable": true - }, - "source": [ - "Its derivative with respect to $z_j^l$ gives" - ] - }, - { - "cell_type": "markdown", - "id": "b0fcad75", - "metadata": { - "editable": true - }, - "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": "1ffab0fd", - "metadata": { - "editable": true - }, - "source": [ - "which in case of the simply binary model reduces to having $i=j$." - ] - }, - { - "cell_type": "markdown", - "id": "2d93613f", - "metadata": { - "editable": true - }, - "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": "67a188b1", - "metadata": { - "editable": true - }, - "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": 3, - "id": "2d2dca8e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "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": "c309c653", - "metadata": { - "editable": true - }, - "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": 4, - "id": "7a7b60e2", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "4f9ea146", - "metadata": { - "editable": true - }, - "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": "1ac702f1", - "metadata": { - "editable": true - }, - "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": "8e01b66f", - "metadata": { - "editable": true - }, - "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": 5, - "id": "89e89f6b", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "c8263d0b", - "metadata": { - "editable": true - }, - "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": "fe4e2d27", - "metadata": { - "editable": true - }, - "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": 6, - "id": "441d2f83", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "d3b6dfd7", - "metadata": { - "editable": true - }, - "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": "e72cf1e3", - "metadata": { - "editable": true - }, - "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": "eb188032", - "metadata": { - "editable": true - }, - "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": "a728bad0", - "metadata": { - "editable": true - }, - "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": 7, - "id": "e0c7221a", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "78be309a", - "metadata": { - "editable": true - }, - "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": "e58fe912", - "metadata": { - "editable": true - }, - "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": 8, - "id": "264331ef", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "89119105", - "metadata": { - "editable": true - }, - "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": 9, - "id": "84f5192d", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "62ccfca8", - "metadata": { - "editable": true - }, - "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": 10, - "id": "d7836d26", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "0f12323a", - "metadata": { - "editable": true - }, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "e7e0fd6b", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "e497e447", - "metadata": { - "editable": true - }, - "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": 12, - "id": "d50de16a", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "7994d203", - "metadata": { - "editable": true - }, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "7403a1d9", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "c91fafb3", - "metadata": { - "editable": true - }, - "source": [ - "## Building neural networks in Tensorflow and Keras\n", - "\n", - "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", - "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", - "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", - "\n", - "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", - "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", - "NumPy arrays." - ] - }, - { - "cell_type": "markdown", - "id": "de877dec", - "metadata": { - "editable": true - }, - "source": [ - "## Tensorflow\n", - "\n", - "Tensorflow is an open source library machine learning library\n", - "developed by the Google Brain team for internal use. It was released\n", - "under the Apache 2.0 open source license in November 9, 2015.\n", - "\n", - "Tensorflow is a computational framework that allows you to construct\n", - "machine learning models at different levels of abstraction, from\n", - "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", - "that Tensorflow is built upon. The higher levels of abstraction are\n", - "simpler to use, but less flexible, and our choice of implementation\n", - "should reflect the problems we are trying to solve.\n", - "\n", - "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", - "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", - "to represent your model, and then create a Tensorflow *session* to run the graph.\n", - "\n", - "In this guide we will analyze the same data as we did in our NumPy and\n", - "scikit-learn tutorial, gathered from the MNIST database of images. We\n", - "will give an introduction to the lower level Python Application\n", - "Program Interfaces (APIs), and see how we use them to build our graph.\n", - "Then we will build (effectively) the same graph in Keras, to see just\n", - "how simple solving a machine learning problem can be.\n", - "\n", - "To install tensorflow on Unix/Linux systems, use pip as" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "174b34a1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "pip3 install tensorflow" - ] - }, - { - "cell_type": "markdown", - "id": "b24e37a3", - "metadata": { - "editable": true - }, - "source": [ - "and/or if you use **anaconda**, just write (or install from the graphical user interface)\n", - "(current release of CPU-only TensorFlow)" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "120502b3", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "conda create -n tf tensorflow\n", - "conda activate tf" - ] - }, - { - "cell_type": "markdown", - "id": "f315598a", - "metadata": { - "editable": true - }, - "source": [ - "To install the current release of GPU TensorFlow" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "30c4aecf", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "conda create -n tf-gpu tensorflow-gpu\n", - "conda activate tf-gpu" - ] - }, - { - "cell_type": "markdown", - "id": "80c81210", - "metadata": { - "editable": true - }, - "source": [ - "## Using Keras\n", - "\n", - "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", - "that supports Tensorflow, CTNK and Theano as backends. \n", - "If you have Anaconda installed you may run the following command" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "9273bbaa", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "conda install keras" - ] - }, - { - "cell_type": "markdown", - "id": "470fb33d", - "metadata": { - "editable": true - }, - "source": [ - "You can look up the [instructions here](https://keras.io/) for more information.\n", - "\n", - "We will to a large extent use **keras** in this course." - ] - }, - { - "cell_type": "markdown", - "id": "534f68d4", - "metadata": { - "editable": true - }, - "source": [ - "## Collect and pre-process data\n", - "\n", - "Let us look again at the MINST data set." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "00ce07a1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import tensorflow as tf\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": "code", - "execution_count": 19, - "id": "e3a94eef", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "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", - "\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-hot representation of labels\n", - "labels = to_categorical(labels)\n", - "\n", - "# split into train and test data\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "8ebd406f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "epochs = 100\n", - "batch_size = 100\n", - "n_neurons_layer1 = 100\n", - "n_neurons_layer2 = 50\n", - "n_categories = 10\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", - " model = Sequential()\n", - " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(Dense(n_categories, activation='softmax'))\n", - " \n", - " sgd = optimizers.SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", - " \n", - " return model" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "1c44ca1b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "DNN_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", - " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", - " eta=eta, lmbd=lmbd)\n", - " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", - " scores = DNN.evaluate(X_test, Y_test)\n", - " \n", - " DNN_keras[i][j] = DNN\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Test accuracy: %.3f\" % scores[1])\n", - " print()" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "547bb452", - "metadata": { - "collapsed": false, - "editable": true - }, - "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_keras[i][j]\n", - "\n", - " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", - " test_accuracy[i][j] = DNN.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": "75957f82", - "metadata": { - "editable": true - }, - "source": [ - "## The Breast Cancer Data, now with Keras" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "94525555", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "import tensorflow as tf\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", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import seaborn as sns\n", - "from sklearn.model_selection import train_test_split as splitter\n", - "from sklearn.datasets import load_breast_cancer\n", - "import pickle\n", - "import os \n", - "\n", - "\n", - "\"\"\"Load breast cancer dataset\"\"\"\n", - "\n", - "np.random.seed(0) #create same seed for random number every time\n", - "\n", - "cancer=load_breast_cancer() #Download breast cancer dataset\n", - "\n", - "inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters)\n", - "outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant)\n", - "labels=cancer.feature_names[0:30]\n", - "\n", - "print('The content of the breast cancer dataset is:') #Print information about the datasets\n", - "print(labels)\n", - "print('-------------------------')\n", - "print(\"inputs = \" + str(inputs.shape))\n", - "print(\"outputs = \" + str(outputs.shape))\n", - "print(\"labels = \"+ str(labels.shape))\n", - "\n", - "x=inputs #Reassign the Feature and Label matrices to other variables\n", - "y=outputs\n", - "\n", - "#%% \n", - "\n", - "# Visualisation of dataset (for correlation analysis)\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean perimeter',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean compactness',fontweight='bold')\n", - "plt.ylabel('Mean concavity',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean texture',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean perimeter',fontweight='bold')\n", - "plt.ylabel('Mean compactness',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "# Generate training and testing datasets\n", - "\n", - "#Select features relevant to classification (texture,perimeter,compactness and symmetery) \n", - "#and add to input matrix\n", - "\n", - "temp1=np.reshape(x[:,1],(len(x[:,1]),1))\n", - "temp2=np.reshape(x[:,2],(len(x[:,2]),1))\n", - "X=np.hstack((temp1,temp2)) \n", - "temp=np.reshape(x[:,5],(len(x[:,5]),1))\n", - "X=np.hstack((X,temp)) \n", - "temp=np.reshape(x[:,8],(len(x[:,8]),1))\n", - "X=np.hstack((X,temp)) \n", - "\n", - "X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing\n", - "\n", - "y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy\n", - "y_test=to_categorical(y_test)\n", - "\n", - "del temp1,temp2,temp\n", - "\n", - "# %%\n", - "\n", - "# Define tunable parameters\"\n", - "\n", - "eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser)\n", - "lamda=0.01 #Define hyperparameter\n", - "n_layers=2 #Define number of hidden layers in the model\n", - "n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer\n", - "epochs=100 #Number of reiterations over the input data\n", - "batch_size=100 #Number of samples per gradient update\n", - "\n", - "# %%\n", - "\n", - "\"\"\"Define function to return Deep Neural Network model\"\"\"\n", - "\n", - "def NN_model(inputsize,n_layers,n_neuron,eta,lamda):\n", - " model=Sequential() \n", - " for i in range(n_layers): #Run loop to add hidden layers to the model\n", - " if (i==0): #First layer requires input dimensions\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))\n", - " else: #Subsequent layers are capable of automatic shape inferencing\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))\n", - " model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob)\n", - " sgd=optimizers.SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])\n", - " return model\n", - "\n", - " \n", - "Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function\n", - "Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for \n", - "\n", - "for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate \n", - " for j in range(len(eta)): #accuracy scores \n", - " DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)\n", - " DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)\n", - " Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]\n", - " Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]\n", - " \n", - "\n", - "def plot_data(x,y,data,title=None):\n", - "\n", - " # plot results\n", - " fontsize=16\n", - "\n", - "\n", - " fig = plt.figure()\n", - " ax = fig.add_subplot(111)\n", - " cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)\n", - " \n", - " cbar=fig.colorbar(cax)\n", - " cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)\n", - " cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])\n", - " cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])\n", - "\n", - " # put text on matrix elements\n", - " for i, x_val in enumerate(np.arange(len(x))):\n", - " for j, y_val in enumerate(np.arange(len(y))):\n", - " c = \"${0:.1f}\\\\%$\".format( 100*data[j,i]) \n", - " ax.text(x_val, y_val, c, va='center', ha='center')\n", - "\n", - " # convert axis vaues to to string labels\n", - " x=[str(i) for i in x]\n", - " y=[str(i) for i in y]\n", - "\n", - "\n", - " ax.set_xticklabels(['']+x)\n", - " ax.set_yticklabels(['']+y)\n", - "\n", - " ax.set_xlabel('$\\\\mathrm{learning\\\\ rate}$',fontsize=fontsize)\n", - " ax.set_ylabel('$\\\\mathrm{hidden\\\\ neurons}$',fontsize=fontsize)\n", - " if title is not None:\n", - " ax.set_title(title)\n", - "\n", - " plt.tight_layout()\n", - "\n", - " plt.show()\n", - " \n", - "plot_data(eta,n_neuron,Train_accuracy, 'training')\n", - "plot_data(eta,n_neuron,Test_accuracy, 'testing')" - ] - }, - { - "cell_type": "markdown", - "id": "a1785215", - "metadata": { - "editable": true - }, - "source": [ - "## Building a neural network code\n", - "\n", - "Here we present a flexible object oriented codebase\n", - "for a feed forward neural network, along with a demonstration of how\n", - "to use it. Before we get into the details of the neural network, we\n", - "will first present some implementations of various schedulers, cost\n", - "functions and activation functions that can be used together with the\n", - "neural network.\n", - "\n", - "The codes here were developed by Eric Reber and Gregor Kajda during spring 2023." - ] - }, - { - "cell_type": "markdown", - "id": "9c17c7d6", - "metadata": { - "editable": true - }, - "source": [ - "### Learning rate methods\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", - "($δ^l_ja^{l−1}_k$), and returns the change which will be subtracted\n", - "from the weights. The reset() function takes no parameters, and resets\n", - "the desired variables. For Constant and Momentum, reset does nothing." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "f9227a16", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "131c32f5", - "metadata": { - "editable": true - }, - "source": [ - "### Usage of the above learning rate schedulers\n", - "\n", - "To initalize a scheduler, simply create the object and pass in the\n", - "necessary parameters such as the learning rate and the momentum as\n", - "shown below. As the Scheduler class is an abstract class it should not\n", - "called directly, and will raise an error upon usage." - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "1d9eeefd", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "33286bbb", - "metadata": { - "editable": true - }, - "source": [ - "Here is a small example for how a segment of code using schedulers\n", - "could look. Switching out the schedulers is simple." - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "6a604d44", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "a3da1579", - "metadata": { - "editable": true - }, - "source": [ - "### Cost functions\n", - "\n", - "Here we discuss cost functions that can be used when creating the\n", - "neural network. Every cost function takes the target vector as its\n", - "parameter, and returns a function valued only at $x$ such that it may\n", - "easily be differentiated." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "3252d0f9", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "\n", - "def CostOLS(target):\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", - " def func(X):\n", - " \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", - " 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": "4b975b6f", - "metadata": { - "editable": true - }, - "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", - "AutoGrad's automatics differentiation." - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "8766a22e", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "f066034a", - "metadata": { - "editable": true - }, - "source": [ - "### Activation functions\n", - "\n", - "Finally, before we look at the neural network, we will look at the\n", - "activation functions which can be specified between the hidden layers\n", - "and as the output function. Each function can be valued for any given\n", - "vector or matrix X, and can be differentiated via derivate()." - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "a83127b5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "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": "9e044132", - "metadata": { - "editable": true - }, - "source": [ - "Below follows 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": 30, - "id": "ee834194", - "metadata": { - "collapsed": false, - "editable": true - }, - "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": "cbe89495", - "metadata": { - "editable": true - }, - "source": [ - "### The Neural Network\n", - "\n", - "Now that we have gotten a good understanding of the implementation of\n", - "some important components, we can take a look at an object oriented\n", - "implementation of a feed forward neural network. The feed forward\n", - "neural network has been implemented as a class named FFNN, which can\n", - "be initiated as a regressor or classifier dependant on the choice of\n", - "cost function. The FFNN can have any number of input nodes, hidden\n", - "layers with any amount of hidden nodes, and any amount of output nodes\n", - "meaning it can perform multiclass classification as well as binary\n", - "classification and regression problems. Although there is a lot of\n", - "code present, it makes for an easy to use and generalizeable interface\n", - "for creating many types of neural networks as will be demonstrated\n", - "below." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "0b542b4f", - "metadata": { - "collapsed": false, - "editable": true - }, - "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, copy\n", - "from typing import Tuple, Callable\n", - "from sklearn.utils import resample\n", - "\n", - "warnings.simplefilter(\"error\")\n", - "\n", - "\n", - "class FFNN:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Feed Forward Neural Network with interface enabling flexible design of a\n", - " nerual networks architecture and the specification of activation function\n", - " in the hidden layers and output layer respectively. This model can be used\n", - " for both regression and classification problems, depending on the output function.\n", - "\n", - " Attributes:\n", - " ------------\n", - " I dimensions (tuple[int]): A list of positive integers, which specifies the\n", - " number of nodes in each of the networks layers. The first integer in the array\n", - " defines the number of nodes in the input layer, the second integer defines number\n", - " of nodes in the first hidden layer and so on until the last number, which\n", - " specifies the number of nodes in the output layer.\n", - " II hidden_func (Callable): The activation function for the hidden layers\n", - " III output_func (Callable): The activation function for the output layer\n", - " IV cost_func (Callable): Our cost function\n", - " V seed (int): Sets random seed, makes results reproducible\n", - " \"\"\"\n", - "\n", - " def __init__(\n", - " self,\n", - " dimensions: tuple[int],\n", - " hidden_func: Callable = sigmoid,\n", - " output_func: Callable = lambda x: x,\n", - " cost_func: Callable = CostOLS,\n", - " seed: int = None,\n", - " ):\n", - " self.dimensions = dimensions\n", - " self.hidden_func = hidden_func\n", - " self.output_func = output_func\n", - " self.cost_func = cost_func\n", - " self.seed = seed\n", - " self.weights = list()\n", - " self.schedulers_weight = list()\n", - " self.schedulers_bias = list()\n", - " self.a_matrices = list()\n", - " self.z_matrices = list()\n", - " self.classification = None\n", - "\n", - " self.reset_weights()\n", - " self._set_classification()\n", - "\n", - " def fit(\n", - " self,\n", - " X: np.ndarray,\n", - " t: np.ndarray,\n", - " scheduler: Scheduler,\n", - " batches: int = 1,\n", - " epochs: int = 100,\n", - " lam: float = 0,\n", - " X_val: np.ndarray = None,\n", - " t_val: np.ndarray = None,\n", - " ):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " This function performs the training the neural network by performing the feedforward and backpropagation\n", - " algorithm to update the networks weights.\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray) : training data\n", - " II t (np.ndarray) : target data\n", - " III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)\n", - " IV scheduler_args (list[int]) : list of all arguments necessary for scheduler\n", - "\n", - " Optional Parameters:\n", - " ------------\n", - " V batches (int) : number of batches the datasets are split into, default equal to 1\n", - " VI epochs (int) : number of iterations used to train the network, default equal to 100\n", - " VII lam (float) : regularization hyperparameter lambda\n", - " VIII X_val (np.ndarray) : validation set\n", - " IX t_val (np.ndarray) : validation target set\n", - "\n", - " Returns:\n", - " ------------\n", - " I scores (dict) : A dictionary containing the performance metrics of the model.\n", - " The number of the metrics depends on the parameters passed to the fit-function.\n", - "\n", - " \"\"\"\n", - "\n", - " # setup \n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " val_set = False\n", - " if X_val is not None and t_val is not None:\n", - " val_set = True\n", - "\n", - " # creating arrays for score metrics\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", - " self.schedulers_weight = list()\n", - " self.schedulers_bias = list()\n", - "\n", - " batch_size = X.shape[0] // batches\n", - "\n", - " X, t = resample(X, t)\n", - "\n", - " # this function returns a function valued only at X\n", - " cost_function_train = self.cost_func(t)\n", - " if val_set:\n", - " cost_function_val = self.cost_func(t_val)\n", - "\n", - " # create schedulers for each weight matrix\n", - " for i in range(len(self.weights)):\n", - " self.schedulers_weight.append(copy(scheduler))\n", - " self.schedulers_bias.append(copy(scheduler))\n", - "\n", - " print(f\"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}\")\n", - "\n", - " try:\n", - " for e in range(epochs):\n", - " for i in range(batches):\n", - " # allows for minibatch gradient descent\n", - " if i == batches - 1:\n", - " # If the for loop has reached the last batch, take all thats left\n", - " X_batch = X[i * batch_size :, :]\n", - " t_batch = t[i * batch_size :, :]\n", - " else:\n", - " X_batch = X[i * batch_size : (i + 1) * batch_size, :]\n", - " t_batch = t[i * batch_size : (i + 1) * batch_size, :]\n", - "\n", - " self._feedforward(X_batch)\n", - " self._backpropagate(X_batch, t_batch, lam)\n", - "\n", - " # reset schedulers for each epoch (some schedulers pass in this call)\n", - " for scheduler in self.schedulers_weight:\n", - " scheduler.reset()\n", - "\n", - " for scheduler in self.schedulers_bias:\n", - " scheduler.reset()\n", - "\n", - " # computing performance metrics\n", - " pred_train = self.predict(X)\n", - " train_error = cost_function_train(pred_train)\n", - "\n", - " train_errors[e] = train_error\n", - " if val_set:\n", - " \n", - " pred_val = self.predict(X_val)\n", - " val_error = cost_function_val(pred_val)\n", - " val_errors[e] = val_error\n", - "\n", - " if self.classification:\n", - " train_acc = self._accuracy(self.predict(X), t)\n", - " train_accs[e] = train_acc\n", - " if val_set:\n", - " val_acc = self._accuracy(pred_val, t_val)\n", - " val_accs[e] = val_acc\n", - "\n", - " # printing progress bar\n", - " progression = e / epochs\n", - " print_length = self._progress_bar(\n", - " progression,\n", - " train_error=train_errors[e],\n", - " train_acc=train_accs[e],\n", - " val_error=val_errors[e],\n", - " val_acc=val_accs[e],\n", - " )\n", - " except KeyboardInterrupt:\n", - " # allows for stopping training at any point and seeing the result\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", - " 1,\n", - " train_error=train_errors[e],\n", - " train_acc=train_accs[e],\n", - " val_error=val_errors[e],\n", - " val_acc=val_accs[e],\n", - " )\n", - " sys.stdout.write(\"\")\n", - "\n", - " # return performance metrics for the entire run\n", - " scores = dict()\n", - "\n", - " scores[\"train_errors\"] = train_errors\n", - "\n", - " if val_set:\n", - " scores[\"val_errors\"] = val_errors\n", - "\n", - " if self.classification:\n", - " scores[\"train_accs\"] = train_accs\n", - "\n", - " if val_set:\n", - " scores[\"val_accs\"] = val_accs\n", - "\n", - " return scores\n", - "\n", - " def predict(self, X: np.ndarray, *, threshold=0.5):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs prediction after training of the network has been finished.\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each\n", - "\n", - " Optional Parameters:\n", - " ------------\n", - " II threshold (float) : sets minimal value for a prediction to be predicted as the positive class\n", - " in classification problems\n", - "\n", - " Returns:\n", - " ------------\n", - " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", - " This vector is thresholded if regression=False, meaning that classification results\n", - " in a vector of 1s and 0s, while regressions in an array of decimal numbers\n", - "\n", - " \"\"\"\n", - "\n", - " predict = self._feedforward(X)\n", - "\n", - " if self.classification:\n", - " return np.where(predict > threshold, 1, 0)\n", - " else:\n", - " return predict\n", - "\n", - " def reset_weights(self):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Resets/Reinitializes the weights in order to train the network for a new problem.\n", - "\n", - " \"\"\"\n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " self.weights = list()\n", - " for i in range(len(self.dimensions) - 1):\n", - " weight_array = np.random.randn(\n", - " self.dimensions[i] + 1, self.dimensions[i + 1]\n", - " )\n", - " weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01\n", - "\n", - " self.weights.append(weight_array)\n", - "\n", - " def _feedforward(self, X: np.ndarray):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Calculates the activation of each layer starting at the input and ending at the output.\n", - " Each following activation is calculated from a weighted sum of each of the preceeding\n", - " activations (except in the case of the input layer).\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each\n", - "\n", - " Returns:\n", - " ------------\n", - " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", - " \"\"\"\n", - "\n", - " # reset matrices\n", - " self.a_matrices = list()\n", - " self.z_matrices = list()\n", - "\n", - " # if X is just a vector, make it into a matrix\n", - " if len(X.shape) == 1:\n", - " X = X.reshape((1, X.shape[0]))\n", - "\n", - " # Add a coloumn of zeros as the first coloumn of the design matrix, in order\n", - " # to add bias to our data\n", - " bias = np.ones((X.shape[0], 1)) * 0.01\n", - " X = np.hstack([bias, X])\n", - "\n", - " # a^0, the nodes in the input layer (one a^0 for each row in X - where the\n", - " # exponent indicates layer number).\n", - " a = X\n", - " self.a_matrices.append(a)\n", - " self.z_matrices.append(a)\n", - "\n", - " # The feed forward algorithm\n", - " for i in range(len(self.weights)):\n", - " if i < len(self.weights) - 1:\n", - " z = a @ self.weights[i]\n", - " self.z_matrices.append(z)\n", - " a = self.hidden_func(z)\n", - " # bias column again added to the data here\n", - " bias = np.ones((a.shape[0], 1)) * 0.01\n", - " a = np.hstack([bias, a])\n", - " self.a_matrices.append(a)\n", - " else:\n", - " try:\n", - " # a^L, the nodes in our output layers\n", - " z = a @ self.weights[i]\n", - " a = self.output_func(z)\n", - " self.a_matrices.append(a)\n", - " self.z_matrices.append(z)\n", - " except Exception as OverflowError:\n", - " print(\n", - " \"OverflowError in fit() in FFNN\\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling\"\n", - " )\n", - "\n", - " # this will be a^L\n", - " return a\n", - "\n", - " def _backpropagate(self, X, t, lam):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs the backpropagation algorithm. In other words, this method\n", - " calculates the gradient of all the layers starting at the\n", - " output layer, and moving from right to left accumulates the gradient until\n", - " the input layer is reached. Each layers respective weights are updated while\n", - " the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each.\n", - " II t (np.ndarray): The target vector, with n rows of p targets.\n", - " III lam (float32): regularization parameter used to punish the weights in case of overfitting\n", - "\n", - " Returns:\n", - " ------------\n", - " No return value.\n", - "\n", - " \"\"\"\n", - " out_derivative = derivate(self.output_func)\n", - " hidden_derivative = derivate(self.hidden_func)\n", - "\n", - " for i in range(len(self.weights) - 1, -1, -1):\n", - " # delta terms for output\n", - " if i == len(self.weights) - 1:\n", - " # for multi-class classification\n", - " if (\n", - " self.output_func.__name__ == \"softmax\"\n", - " ):\n", - " delta_matrix = self.a_matrices[i + 1] - t\n", - " # for single class classification\n", - " else:\n", - " cost_func_derivative = grad(self.cost_func(t))\n", - " delta_matrix = out_derivative(\n", - " self.z_matrices[i + 1]\n", - " ) * cost_func_derivative(self.a_matrices[i + 1])\n", - "\n", - " # delta terms for hidden layer\n", - " else:\n", - " delta_matrix = (\n", - " self.weights[i + 1][1:, :] @ delta_matrix.T\n", - " ).T * hidden_derivative(self.z_matrices[i + 1])\n", - "\n", - " # calculate gradient\n", - " gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix\n", - " gradient_bias = np.sum(delta_matrix, axis=0).reshape(\n", - " 1, delta_matrix.shape[1]\n", - " )\n", - "\n", - " # regularization term\n", - " gradient_weights += self.weights[i][1:, :] * lam\n", - "\n", - " # use scheduler\n", - " update_matrix = np.vstack(\n", - " [\n", - " self.schedulers_bias[i].update_change(gradient_bias),\n", - " self.schedulers_weight[i].update_change(gradient_weights),\n", - " ]\n", - " )\n", - "\n", - " # update weights and bias\n", - " self.weights[i] -= update_matrix\n", - "\n", - " def _accuracy(self, prediction: np.ndarray, target: np.ndarray):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Calculates accuracy of given prediction to target\n", - "\n", - " Parameters:\n", - " ------------\n", - " I prediction (np.ndarray): vector of predicitons output network\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 ideally 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", - " def _set_classification(self):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Decides if FFNN acts as classifier (True) og regressor (False),\n", - " sets self.classification during init()\n", - " \"\"\"\n", - " self.classification = False\n", - " if (\n", - " self.cost_func.__name__ == \"CostLogReg\"\n", - " or self.cost_func.__name__ == \"CostCrossEntropy\"\n", - " ):\n", - " self.classification = True\n", - "\n", - " def _progress_bar(self, progression, **kwargs):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Displays progress of training\n", - " \"\"\"\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._format(progression * 100, decimals=5)\n", - " line = f\" {bar} {perc_print}% \"\n", - "\n", - " for key in kwargs:\n", - " if not np.isnan(kwargs[key]):\n", - " value = self._format(kwargs[key], decimals=4)\n", - " line += f\"| {key}: {value} \"\n", - " sys.stdout.write(\"\\r\" + line)\n", - " sys.stdout.flush()\n", - " return len(line)\n", - "\n", - " def _format(self, value, decimals=4):\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 >= decimals - 1:\n", - " return str(round(value))\n", - " return f\"{value:.{decimals-n-1}f}\"" - ] - }, - { - "cell_type": "markdown", - "id": "d1a70256", - "metadata": { - "editable": true - }, - "source": [ - "Before we make a model, we will quickly generate a dataset we can use\n", - "for our linear regression problem as shown below" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "6065cbb1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "def SkrankeFunction(x, y):\n", - " return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)\n", - "\n", - "def create_X(x, y, n):\n", - " if len(x.shape) > 1:\n", - " x = np.ravel(x)\n", - " y = np.ravel(y)\n", - "\n", - " N = len(x)\n", - " l = int((n + 1) * (n + 2) / 2) # Number of elements in beta\n", - " X = np.ones((N, l))\n", - "\n", - " for i in range(1, n + 1):\n", - " q = int((i) * (i + 1) / 2)\n", - " for k in range(i + 1):\n", - " X[:, q + k] = (x ** (i - k)) * (y**k)\n", - "\n", - " return X\n", - "\n", - "step=0.5\n", - "x = np.arange(0, 1, step)\n", - "y = np.arange(0, 1, step)\n", - "x, y = np.meshgrid(x, y)\n", - "target = SkrankeFunction(x, y)\n", - "target = target.reshape(target.shape[0], 1)\n", - "\n", - "poly_degree=3\n", - "X = create_X(x, y, poly_degree)\n", - "\n", - "X_train, X_test, t_train, t_test = train_test_split(X, target)" - ] - }, - { - "cell_type": "markdown", - "id": "079f4466", - "metadata": { - "editable": true - }, - "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", - "results stay the same every time we run the neural network. For\n", - "inititialization, we simply specify the dimensions (we wish the amount\n", - "of input nodes to be equal to the datapoints, and the output to\n", - "predict one value)." - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "3d0cbbdc", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "output_nodes = 1\n", - "\n", - "linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)" - ] - }, - { - "cell_type": "markdown", - "id": "3b2c61b3", - "metadata": { - "editable": true - }, - "source": [ - "We then fit our model with our training data using the scheduler of our choice." - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "7b0a3f82", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Constant(eta=1e-3)\n", - "scores = linear_regression.fit(X_train, t_train, scheduler)" - ] - }, - { - "cell_type": "markdown", - "id": "3b3643a5", - "metadata": { - "editable": true - }, - "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", - "parameters with defualt arguments. For example, the regularization\n", - "hyperparameter can be left ignored if not needed, and equally the FFNN\n", - "will by default run for 100 epochs. These can easily be changed, such\n", - "as for example:" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "86c8aae2", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "4e8f19e1", - "metadata": { - "editable": true - }, - "source": [ - "We see that given more epochs to train on, the regressor reaches a lower MSE.\n", - "\n", - "Let us then switch to a binary classification. We use a binary\n", - "classification dataset, and follow a similar setup to the regression\n", - "case." - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "dda49b53", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.preprocessing import MinMaxScaler\n", - "\n", - "wisconsin = load_breast_cancer()\n", - "X = wisconsin.data\n", - "target = wisconsin.target\n", - "target = target.reshape(target.shape[0], 1)\n", - "\n", - "X_train, X_val, t_train, t_val = train_test_split(X, target)\n", - "\n", - "scaler = MinMaxScaler()\n", - "scaler.fit(X_train)\n", - "X_train = scaler.transform(X_train)\n", - "X_val = scaler.transform(X_val)" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "a5816f25", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "output_nodes = 1\n", - "\n", - "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)" - ] - }, - { - "cell_type": "markdown", - "id": "a51f22b7", - "metadata": { - "editable": true - }, - "source": [ - "We will now make use of our validation data by passing it into our fit function as a keyword argument" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "7d8852f0", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", - "scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" - ] - }, - { - "cell_type": "markdown", - "id": "6675f462", - "metadata": { - "editable": true - }, - "source": [ - "Finally, we will create a neural network with 2 hidden layers with activation functions." - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "55a4e205", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "hidden_nodes1 = 100\n", - "hidden_nodes2 = 30\n", - "output_nodes = 1\n", - "\n", - "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", - "\n", - "neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "d29aef95", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", - "scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" - ] - }, - { - "cell_type": "markdown", - "id": "4816b115", - "metadata": { - "editable": true - }, - "source": [ - "### Multiclass classification\n", - "\n", - "Finally, we will demonstrate the use case of multiclass classification\n", - "using our FFNN with the famous MNIST dataset, which contain images of\n", - "digits between the range of 0 to 9." - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "2ce1d25b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.datasets import load_digits\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", - "digits = load_digits()\n", - "\n", - "X = digits.data\n", - "target = digits.target\n", - "target = onehot(target)\n", - "\n", - "input_nodes = 64\n", - "hidden_nodes1 = 100\n", - "hidden_nodes2 = 30\n", - "output_nodes = 10\n", - "\n", - "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", - "\n", - "multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)\n", - "\n", - "multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", - "scores = multiclass.fit(X, target, scheduler, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "c9b9150b", - "metadata": { - "editable": true - }, - "source": [ - "## Testing the XOR gate and other gates\n", - "\n", - "Let us now use our code to test the XOR gate." - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "id": "0e8eea1f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "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", - "\n", - "input_nodes = X.shape[1]\n", - "output_nodes = 1\n", - "\n", - "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)\n", - "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999)\n", - "scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "55edaac4", - "metadata": { - "editable": true - }, - "source": [ - "Not bad, but the results depend strongly on the learning reate. Try different learning rates." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -}