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 \)
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 \)
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
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 \)
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 \)
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
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.
-
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
-
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.
-
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.
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.
-
-
-
-
-
-
-
-
-
-
importnumpyasnp
-# We use the Sigmoid function as activation function
-defsigmoid(z):
- return1.0/(1.0+np.exp(-z))
-
-defforwardpropagation(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
-
-defbackpropagation(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 inrange(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 \)
-
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
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
-
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
-
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
-
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
-
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 \).
-
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
-
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,
-
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
-
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 \).
-
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
-
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
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 \).
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
-
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
-
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
-
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."""
-
-importnumpy
-importmatplotlib.pyplotasplt
-importmathasmt
-
-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.0if z >=0.0else0.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()
-
The Back propagation algorithm we derived above works by going from
-the output layer to the input layer, propagating the error gradient on
-the way. Once the algorithm has computed the gradient of the cost
-function with regards to each parameter in the network, it uses these
-gradients to update each parameter with a Gradient Descent (GD) step.
-
-
-
Unfortunately for us, the gradients often get smaller and smaller as
-the algorithm progresses down to the first hidden layers. As a result,
-the GD update leaves the lower layer connection weights virtually
-unchanged, and training never converges to a good solution. This is
-known in the literature as the vanishing gradients problem.
-
In other cases, the opposite can happen, namely the the gradients can
-grow bigger and bigger. The result is that many of the layers get
-large updates of the weights the algorithm diverges. This is the
-exploding gradients problem, which is mostly encountered in
-recurrent neural networks. More generally, deep neural networks suffer
-from unstable gradients, different layers may learn at widely
-different speeds
-
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.
-
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).
-
Looking at the logistic activation function, when inputs become large
-(negative or positive), the function saturates at 0 or 1, with a
-derivative extremely close to 0. Thus when backpropagation kicks in,
-it has virtually no gradient to propagate back through the network,
-and what little gradient exists keeps getting diluted as
-backpropagation progresses down through the top layers, so there is
-really nothing left for the lower layers.
-
-
-
In their paper, Glorot and Bengio propose a way to significantly
-alleviate this problem. We need the signal to flow properly in both
-directions: in the forward direction when making predictions, and in
-the reverse direction when backpropagating gradients. We don’t want
-the signal to die out, nor do we want it to explode and saturate. For
-the signal to flow properly, the authors argue that we need the
-variance of the outputs of each layer to be equal to the variance of
-its inputs, and we also need the gradients to have equal variance
-before and after flowing through a layer in the reverse direction.
-
One of the insights in the 2010 paper by Glorot and Bengio was that
-the vanishing/exploding gradients problems were in part due to a poor
-choice of activation function. Until then most people had assumed that
-if Nature had chosen to use roughly sigmoid activation functions in
-biological neurons, they must be an excellent choice. But it turns out
-that other activation functions behave much better in deep neural
-networks, in particular the ReLU activation function, mostly because
-it does not saturate for positive values (and also because it is quite
-fast to compute).
-
The ReLU activation function suffers from a problem known as the dying
-ReLUs: during training, some neurons effectively die, meaning they
-stop outputting anything other than 0.
-
-
-
In some cases, you may find that half of your network’s neurons are
-dead, especially if you used a large learning rate. During training,
-if a neuron’s weights get updated such that the weighted sum of the
-neuron’s inputs is negative, it will start outputting 0. When this
-happen, the neuron is unlikely to come back to life since the gradient
-of the ReLU function is 0 when its input is negative.
-
To solve this problem, nowadays practitioners use a variant of the
-ReLU function, such as the leaky ReLU discussed above or the so-called
-exponential linear unit (ELU) function
-
-
-$$
-ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right.
-$$
-
-
-
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.
-
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.
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 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.
-
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.
-
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.
-
The first thing we would like to do is divide the data into two or
-three parts. A training set, a validation or dev (development) set,
-and a test set. The test set is the data on which we want to make
-predictions. The dev set is a subset of the training data we use to
-check how well we are doing out-of-sample, after training the model on
-the training dataset. We use the validation error as a proxy for the
-test error in order to make tweaks to our model. It is crucial that we
-do not use any of the test data to train the algorithm. This is a
-cardinal sin in ML. Then:
-
-
-
-
Estimate optimal error rate
-
Minimize underfitting (bias) on training data set.
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).
-
Here we list some of the important limitations of supervised neural network based models.
-
-
-
Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
-
Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
-
-
Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.
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
-
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:
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:
-
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!
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
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
-
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
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
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:
-
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
-importnumpyasnp
-importmatplotlib.pyplotasplt
-fromsklearnimport 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 inenumerate(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()
-
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.
-
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:
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.
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:
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.
-
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
-
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 \):
-
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} \):
-
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:
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.
-
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
-
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:
-
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:
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.
-
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,
-
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
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:
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.
-
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.
-
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 \).
-
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 inenumerate(eta_vals):
- for j, lmbd inenumerate(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()
-
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.
-
-
-
-
-
-
-
-
-
-
fromsklearn.neural_networkimport MLPClassifier
-# store models for later use
-DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
-
-for i, eta inenumerate(eta_vals):
- for j, lmbd inenumerate(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()
-
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 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)
-
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
-
importtensorflowastf
-fromtensorflow.keras.layersimport Input
-fromtensorflow.keras.modelsimport Sequential #This allows appending layers to existing models
-fromtensorflow.keras.layersimport Dense #This allows defining the characteristics of a particular layer
-fromtensorflow.kerasimport optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)
-fromtensorflow.kerasimport regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)
-fromtensorflow.keras.utilsimport to_categorical #This allows using categorical cross entropy as the cost function
-importnumpyasnp
-importmatplotlib.pyplotasplt
-importseabornassns
-fromsklearn.model_selectionimport train_test_split as splitter
-fromsklearn.datasetsimport load_breast_cancer
-importpickle
-importos
-
-
-"""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"""
-
-defNN_model(inputsize,n_layers,n_neuron,eta,lamda):
- model=Sequential()
- for i inrange(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 inrange(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate
- for j inrange(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]
-
-
-defplot_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 inenumerate(np.arange(len(x))):
- for j, y_val inenumerate(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 isnotNone:
- 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')
-
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.
-
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.
-
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.
-
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.
-
-
-
-
-
-
-
-
-
-
fromautogradimport 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().
-
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.
-
-
-
-
-
-
-
-
-
-
importmath
-importautograd.numpyasnp
-importsys
-importwarnings
-fromautogradimport grad, elementwise_grad
-fromrandomimport random, seed
-fromcopyimport deepcopy, copy
-fromtypingimport Tuple, Callable
-fromsklearn.utilsimport resample
-
-warnings.simplefilter("error")
-
-
-classFFNN:
- """
- 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()
-
- deffit(
- 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
- ifself.seed isnotNone:
- np.random.seed(self.seed)
-
- val_set =False
- if X_val isnotNoneand t_val isnotNone:
- 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 inrange(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 inrange(epochs):
- for i inrange(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 inself.schedulers_weight:
- scheduler.reset()
-
- for scheduler inself.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
-
- ifself.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],
- )
- exceptKeyboardInterrupt:
- # 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
-
- ifself.classification:
- scores["train_accs"] = train_accs
-
- if val_set:
- scores["val_accs"] = val_accs
-
- return scores
-
- defpredict(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)
-
- ifself.classification:
- return np.where(predict > threshold, 1, 0)
- else:
- return predict
-
- defreset_weights(self):
- """
- Description:
- ------------
- Resets/Reinitializes the weights in order to train the network for a new problem.
-
- """
- ifself.seed isnotNone:
- np.random.seed(self.seed)
-
- self.weights =list()
- for i inrange(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
- iflen(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 inrange(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)
- exceptExceptionasOverflowError:
- 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 inrange(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"
- orself.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 >0else""
- bar ="["+"="* (num_equals -1) + arrow +"-"* num_not +"]"
- perc_print =self._format(progression *100, decimals=5)
- line =f" {bar}{perc_print}% "
-
- for key in kwargs:
- ifnot np.isnan(kwargs[key]):
- value =self._format(kwargs[key], decimals=4)
- line +=f"| {key}: {value} "
- sys.stdout.write("\r"+ line)
- sys.stdout.flush()
- returnlen(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:
- returnstr(round(value))
- returnf"{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
-
-
-
-
-
-
-
-
-
-
importautograd.numpyasnp
-fromsklearn.model_selectionimport train_test_split
-
-defSkrankeFunction(x, y):
- return np.ravel(0+1*x +2*y +3*x**2+4*x*y +5*y**2)
-
-defcreate_X(x, y, n):
- iflen(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 inrange(1, n +1):
- q =int((i) * (i +1) /2)
- for k inrange(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).
-
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.
-
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.
-
-
-
-
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 [](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
-
-```
-
-### 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!