diff --git a/doc/pub/week41/html/week41-bs.html b/doc/pub/week41/html/week41-bs.html index db266a362..0232fecde 100644 --- a/doc/pub/week41/html/week41-bs.html +++ b/doc/pub/week41/html/week41-bs.html @@ -547,9 +547,11 @@ MathJax.Hub.Config({

Material for the lecture on Monday October 7, 2024

  1. Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
  2. -
  3. Building our own Feed-forward Neural Network - -
  4. +
  5. Building our own Feed-forward Neural Network
  6. +
diff --git a/doc/pub/week41/html/week41-reveal.html b/doc/pub/week41/html/week41-reveal.html index 34be85e14..6633308c2 100644 --- a/doc/pub/week41/html/week41-reveal.html +++ b/doc/pub/week41/html/week41-reveal.html @@ -199,9 +199,14 @@ MathJax.Hub.Config({

Material for the lecture on Monday October 7, 2024

  1. Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
  2. -

  3. Building our own Feed-forward Neural Network - -
  4. +

  5. Building our own Feed-forward Neural Network
  6. + +

diff --git a/doc/pub/week41/html/week41-solarized.html b/doc/pub/week41/html/week41-solarized.html index c22ccca46..dc13a412e 100644 --- a/doc/pub/week41/html/week41-solarized.html +++ b/doc/pub/week41/html/week41-solarized.html @@ -434,9 +434,11 @@ MathJax.Hub.Config({

Material for the lecture on Monday October 7, 2024

  1. Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
  2. -
  3. Building our own Feed-forward Neural Network - -
  4. +
  5. Building our own Feed-forward Neural Network
  6. +
Readings and Videos: diff --git a/doc/pub/week41/html/week41.html b/doc/pub/week41/html/week41.html index 36ac3704e..c320e3d98 100644 --- a/doc/pub/week41/html/week41.html +++ b/doc/pub/week41/html/week41.html @@ -511,9 +511,11 @@ MathJax.Hub.Config({

Material for the lecture on Monday October 7, 2024

  1. Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
  2. -
  3. Building our own Feed-forward Neural Network - -
  4. +
  5. Building our own Feed-forward Neural Network
  6. +
Readings and Videos: diff --git a/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz b/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz index fd2fe62c3..9050fa53f 100644 Binary files a/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz and b/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz differ diff --git a/doc/pub/week41/ipynb/week41.ipynb b/doc/pub/week41/ipynb/week41.ipynb index 5f563d4fd..8d2109293 100644 --- a/doc/pub/week41/ipynb/week41.ipynb +++ b/doc/pub/week41/ipynb/week41.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "4411828b", + "id": "5bf96c8a", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "c234e82d", + "id": "e3d91be4", "metadata": { "editable": true }, @@ -27,7 +27,7 @@ }, { "cell_type": "markdown", - "id": "e602572c", + "id": "6ba7a03a", "metadata": { "editable": true }, @@ -37,7 +37,7 @@ }, { "cell_type": "markdown", - "id": "8c040a6e", + "id": "e8ee6c3d", "metadata": { "editable": true }, @@ -46,8 +46,10 @@ "1. Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.\n", "\n", "2. Building our own Feed-forward Neural Network\n", - "\n", - "\n", + "\n", + " * Video of lecture notes at \n", + "\n", + " * Whiteboard notes at \n", "\n", "**Readings and Videos:**\n", "\n", @@ -70,7 +72,7 @@ }, { "cell_type": "markdown", - "id": "d7c3f47c", + "id": "f1d45fb2", "metadata": { "editable": true }, @@ -87,7 +89,7 @@ }, { "cell_type": "markdown", - "id": "ee26bc0e", + "id": "d4e77966", "metadata": { "editable": true }, @@ -97,7 +99,7 @@ }, { "cell_type": "markdown", - "id": "604a7680", + "id": "e53c7266", "metadata": { "editable": true }, @@ -115,7 +117,7 @@ }, { "cell_type": "markdown", - "id": "df00fb0e", + "id": "bc8b8894", "metadata": { "editable": true }, @@ -139,7 +141,7 @@ }, { "cell_type": "markdown", - "id": "b60314ed", + "id": "7822604f", "metadata": { "editable": true }, @@ -157,7 +159,7 @@ }, { "cell_type": "markdown", - "id": "9d2e1d85", + "id": "e1b48997", "metadata": { "editable": true }, @@ -197,7 +199,7 @@ }, { "cell_type": "markdown", - "id": "c6af91e7", + "id": "17881d26", "metadata": { "editable": true }, @@ -226,7 +228,7 @@ }, { "cell_type": "markdown", - "id": "1b2b8e1c", + "id": "64134ea5", "metadata": { "editable": true }, @@ -247,7 +249,7 @@ }, { "cell_type": "markdown", - "id": "db4860d5", + "id": "d1b8101c", "metadata": { "editable": true }, @@ -276,7 +278,7 @@ }, { "cell_type": "markdown", - "id": "4c21c5ca", + "id": "ee76d630", "metadata": { "editable": true }, @@ -297,7 +299,7 @@ }, { "cell_type": "markdown", - "id": "4314d49c", + "id": "77292572", "metadata": { "editable": true }, @@ -318,7 +320,7 @@ }, { "cell_type": "markdown", - "id": "94acdaed", + "id": "31229c23", "metadata": { "editable": true }, @@ -335,7 +337,7 @@ }, { "cell_type": "markdown", - "id": "5c342880", + "id": "8ef64a1c", "metadata": { "editable": true }, @@ -356,7 +358,7 @@ }, { "cell_type": "markdown", - "id": "f8e04154", + "id": "8a05aae8", "metadata": { "editable": true }, @@ -372,7 +374,7 @@ }, { "cell_type": "markdown", - "id": "80e11a79", + "id": "53553bc4", "metadata": { "editable": true }, @@ -389,7 +391,7 @@ { "cell_type": "code", "execution_count": 1, - "id": "60cf9550", + "id": "bd160078", "metadata": { "collapsed": false, "editable": true @@ -430,7 +432,7 @@ }, { "cell_type": "markdown", - "id": "72e221bf", + "id": "8dc03535", "metadata": { "editable": true }, @@ -440,7 +442,7 @@ }, { "cell_type": "markdown", - "id": "67d0709a", + "id": "0f612b2a", "metadata": { "editable": true }, @@ -451,7 +453,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "4afcb37f", + "id": "b2c26240", "metadata": { "collapsed": false, "editable": true @@ -513,7 +515,7 @@ }, { "cell_type": "markdown", - "id": "ac931e42", + "id": "f5dc459e", "metadata": { "editable": true }, @@ -523,7 +525,7 @@ }, { "cell_type": "markdown", - "id": "e5455ad8", + "id": "b2ad997b", "metadata": { "editable": true }, @@ -534,7 +536,7 @@ { "cell_type": "code", "execution_count": 3, - "id": "cfbed3e7", + "id": "df5c9c62", "metadata": { "collapsed": false, "editable": true @@ -554,7 +556,7 @@ }, { "cell_type": "markdown", - "id": "a619dfb2", + "id": "40a0930e", "metadata": { "editable": true }, @@ -570,7 +572,7 @@ }, { "cell_type": "markdown", - "id": "2cc88c73", + "id": "decd7409", "metadata": { "editable": true }, @@ -581,7 +583,7 @@ }, { "cell_type": "markdown", - "id": "233d2972", + "id": "e2a4d61c", "metadata": { "editable": true }, @@ -595,7 +597,7 @@ }, { "cell_type": "markdown", - "id": "27cc80b0", + "id": "16723d55", "metadata": { "editable": true }, @@ -614,7 +616,7 @@ }, { "cell_type": "markdown", - "id": "ea3a3c02", + "id": "902a802b", "metadata": { "editable": true }, @@ -638,7 +640,7 @@ }, { "cell_type": "markdown", - "id": "502d4ad7", + "id": "fbd06338", "metadata": { "editable": true }, @@ -665,7 +667,7 @@ }, { "cell_type": "markdown", - "id": "9182519a", + "id": "0e9e449b", "metadata": { "editable": true }, @@ -682,7 +684,7 @@ }, { "cell_type": "markdown", - "id": "15b78cfd", + "id": "b06ad67d", "metadata": { "editable": true }, @@ -694,7 +696,7 @@ }, { "cell_type": "markdown", - "id": "093b77f1", + "id": "aa068f3c", "metadata": { "editable": true }, @@ -705,7 +707,7 @@ }, { "cell_type": "markdown", - "id": "b6c8a224", + "id": "2977103a", "metadata": { "editable": true }, @@ -723,7 +725,7 @@ }, { "cell_type": "markdown", - "id": "f30d7e81", + "id": "3cd55846", "metadata": { "editable": true }, @@ -752,7 +754,7 @@ }, { "cell_type": "markdown", - "id": "5089007e", + "id": "66def2af", "metadata": { "editable": true }, @@ -766,7 +768,7 @@ }, { "cell_type": "markdown", - "id": "3f9eedcb", + "id": "1dfc75e0", "metadata": { "editable": true }, @@ -782,7 +784,7 @@ }, { "cell_type": "markdown", - "id": "ac052134", + "id": "db4ec583", "metadata": { "editable": true }, @@ -794,7 +796,7 @@ }, { "cell_type": "markdown", - "id": "c0e639b1", + "id": "e6b6f0e5", "metadata": { "editable": true }, @@ -808,7 +810,7 @@ }, { "cell_type": "markdown", - "id": "6d2878d4", + "id": "82c4e644", "metadata": { "editable": true }, @@ -820,7 +822,7 @@ }, { "cell_type": "markdown", - "id": "dbb5133d", + "id": "4d8b622d", "metadata": { "editable": true }, @@ -836,7 +838,7 @@ }, { "cell_type": "markdown", - "id": "0da134a5", + "id": "8d93823d", "metadata": { "editable": true }, @@ -852,7 +854,7 @@ }, { "cell_type": "markdown", - "id": "5346e8a0", + "id": "087fd46d", "metadata": { "editable": true }, @@ -864,7 +866,7 @@ }, { "cell_type": "markdown", - "id": "36737d10", + "id": "7547efaa", "metadata": { "editable": true }, @@ -874,7 +876,7 @@ }, { "cell_type": "markdown", - "id": "d81b95ba", + "id": "65071f00", "metadata": { "editable": true }, @@ -886,7 +888,7 @@ }, { "cell_type": "markdown", - "id": "8432cac2", + "id": "7a8ecd20", "metadata": { "editable": true }, @@ -904,7 +906,7 @@ }, { "cell_type": "markdown", - "id": "04d4d751", + "id": "41ed53e6", "metadata": { "editable": true }, @@ -917,7 +919,7 @@ }, { "cell_type": "markdown", - "id": "df8f957e", + "id": "2b83edda", "metadata": { "editable": true }, @@ -934,7 +936,7 @@ }, { "cell_type": "markdown", - "id": "0fc51d93", + "id": "d27eb1c2", "metadata": { "editable": true }, @@ -946,7 +948,7 @@ }, { "cell_type": "markdown", - "id": "fc372df4", + "id": "f83f5909", "metadata": { "editable": true }, @@ -958,7 +960,7 @@ }, { "cell_type": "markdown", - "id": "e1cbafd1", + "id": "693f1f94", "metadata": { "editable": true }, @@ -974,7 +976,7 @@ }, { "cell_type": "markdown", - "id": "aadba1e0", + "id": "c4473918", "metadata": { "editable": true }, @@ -991,7 +993,7 @@ }, { "cell_type": "markdown", - "id": "4f0a354f", + "id": "80c49202", "metadata": { "editable": true }, @@ -1003,7 +1005,7 @@ }, { "cell_type": "markdown", - "id": "5b489754", + "id": "b95ea794", "metadata": { "editable": true }, @@ -1016,7 +1018,7 @@ }, { "cell_type": "markdown", - "id": "109a6626", + "id": "7468be96", "metadata": { "editable": true }, @@ -1028,7 +1030,7 @@ }, { "cell_type": "markdown", - "id": "d075c31b", + "id": "82d9ddc5", "metadata": { "editable": true }, @@ -1044,7 +1046,7 @@ }, { "cell_type": "markdown", - "id": "ea32a509", + "id": "611a8aaf", "metadata": { "editable": true }, @@ -1056,7 +1058,7 @@ }, { "cell_type": "markdown", - "id": "8ac36725", + "id": "adfdba0b", "metadata": { "editable": true }, @@ -1068,7 +1070,7 @@ }, { "cell_type": "markdown", - "id": "f3600e09", + "id": "6b23deb7", "metadata": { "editable": true }, @@ -1080,7 +1082,7 @@ }, { "cell_type": "markdown", - "id": "3e537038", + "id": "3dbf8b63", "metadata": { "editable": true }, @@ -1090,7 +1092,7 @@ }, { "cell_type": "markdown", - "id": "34b99ae7", + "id": "b3228dee", "metadata": { "editable": true }, @@ -1102,7 +1104,7 @@ }, { "cell_type": "markdown", - "id": "e4faa2f2", + "id": "52be372b", "metadata": { "editable": true }, @@ -1112,7 +1114,7 @@ }, { "cell_type": "markdown", - "id": "b4243031", + "id": "8e1cfc96", "metadata": { "editable": true }, @@ -1124,7 +1126,7 @@ }, { "cell_type": "markdown", - "id": "b528c44c", + "id": "79b3ab6b", "metadata": { "editable": true }, @@ -1138,7 +1140,7 @@ }, { "cell_type": "markdown", - "id": "602e81ab", + "id": "4541109b", "metadata": { "editable": true }, @@ -1150,7 +1152,7 @@ }, { "cell_type": "markdown", - "id": "4ac5e382", + "id": "ada15490", "metadata": { "editable": true }, @@ -1160,7 +1162,7 @@ }, { "cell_type": "markdown", - "id": "02edfab2", + "id": "ef1846b1", "metadata": { "editable": true }, @@ -1172,7 +1174,7 @@ }, { "cell_type": "markdown", - "id": "02fffe9d", + "id": "2bcae885", "metadata": { "editable": true }, @@ -1182,7 +1184,7 @@ }, { "cell_type": "markdown", - "id": "f4d679cc", + "id": "14438533", "metadata": { "editable": true }, @@ -1194,7 +1196,7 @@ }, { "cell_type": "markdown", - "id": "3638d432", + "id": "1ea04dc6", "metadata": { "editable": true }, @@ -1209,7 +1211,7 @@ }, { "cell_type": "markdown", - "id": "d3039347", + "id": "2c1d3d23", "metadata": { "editable": true }, @@ -1221,7 +1223,7 @@ }, { "cell_type": "markdown", - "id": "f48bfb76", + "id": "0a784486", "metadata": { "editable": true }, @@ -1233,7 +1235,7 @@ }, { "cell_type": "markdown", - "id": "63176c54", + "id": "91a6fac4", "metadata": { "editable": true }, @@ -1245,7 +1247,7 @@ }, { "cell_type": "markdown", - "id": "f966f6f1", + "id": "64245345", "metadata": { "editable": true }, @@ -1257,7 +1259,7 @@ }, { "cell_type": "markdown", - "id": "b0a5a64e", + "id": "8f42f6ef", "metadata": { "editable": true }, @@ -1267,7 +1269,7 @@ }, { "cell_type": "markdown", - "id": "fedfd000", + "id": "23f3f62a", "metadata": { "editable": true }, @@ -1279,7 +1281,7 @@ }, { "cell_type": "markdown", - "id": "49281876", + "id": "31db67ce", "metadata": { "editable": true }, @@ -1289,7 +1291,7 @@ }, { "cell_type": "markdown", - "id": "78dc9b72", + "id": "54f91226", "metadata": { "editable": true }, @@ -1301,7 +1303,7 @@ }, { "cell_type": "markdown", - "id": "bf854510", + "id": "551bf4e9", "metadata": { "editable": true }, @@ -1321,7 +1323,7 @@ }, { "cell_type": "markdown", - "id": "35771431", + "id": "1d4117b4", "metadata": { "editable": true }, @@ -1333,7 +1335,7 @@ }, { "cell_type": "markdown", - "id": "6570ba80", + "id": "402669ea", "metadata": { "editable": true }, @@ -1345,7 +1347,7 @@ }, { "cell_type": "markdown", - "id": "c30b4d72", + "id": "ec119701", "metadata": { "editable": true }, @@ -1355,7 +1357,7 @@ }, { "cell_type": "markdown", - "id": "183d5f0b", + "id": "bcb30e6f", "metadata": { "editable": true }, @@ -1367,7 +1369,7 @@ }, { "cell_type": "markdown", - "id": "b2363c0a", + "id": "2a7acb6e", "metadata": { "editable": true }, @@ -1378,7 +1380,7 @@ { "cell_type": "code", "execution_count": 4, - "id": "0b51ea21", + "id": "044e79d9", "metadata": { "collapsed": false, "editable": true @@ -1397,7 +1399,7 @@ }, { "cell_type": "markdown", - "id": "07e24343", + "id": "1c3cb722", "metadata": { "editable": true }, @@ -1408,7 +1410,7 @@ }, { "cell_type": "markdown", - "id": "1337dd0f", + "id": "808a017a", "metadata": { "editable": true }, @@ -1420,7 +1422,7 @@ }, { "cell_type": "markdown", - "id": "a7589947", + "id": "2330f35c", "metadata": { "editable": true }, @@ -1430,7 +1432,7 @@ }, { "cell_type": "markdown", - "id": "3586c972", + "id": "c0b17b83", "metadata": { "editable": true }, @@ -1442,7 +1444,7 @@ }, { "cell_type": "markdown", - "id": "0ac52a19", + "id": "9129586e", "metadata": { "editable": true }, @@ -1455,7 +1457,7 @@ }, { "cell_type": "markdown", - "id": "18b67b7b", + "id": "83209806", "metadata": { "editable": true }, @@ -1467,7 +1469,7 @@ }, { "cell_type": "markdown", - "id": "75f72d6b", + "id": "1e04f023", "metadata": { "editable": true }, @@ -1479,7 +1481,7 @@ }, { "cell_type": "markdown", - "id": "ff72bef0", + "id": "4015de5c", "metadata": { "editable": true }, @@ -1496,7 +1498,7 @@ }, { "cell_type": "markdown", - "id": "ef55737f", + "id": "cfd489e0", "metadata": { "editable": true }, @@ -1508,7 +1510,7 @@ }, { "cell_type": "markdown", - "id": "35ab7175", + "id": "abcfa23a", "metadata": { "editable": true }, @@ -1520,7 +1522,7 @@ }, { "cell_type": "markdown", - "id": "edc79b33", + "id": "67bcaa0e", "metadata": { "editable": true }, @@ -1530,7 +1532,7 @@ }, { "cell_type": "markdown", - "id": "4dc12ed8", + "id": "d4e12796", "metadata": { "editable": true }, @@ -1542,7 +1544,7 @@ }, { "cell_type": "markdown", - "id": "bc945b59", + "id": "e74eed87", "metadata": { "editable": true }, @@ -1552,7 +1554,7 @@ }, { "cell_type": "markdown", - "id": "68eac5d0", + "id": "5b626985", "metadata": { "editable": true }, @@ -1564,7 +1566,7 @@ }, { "cell_type": "markdown", - "id": "6ea49d77", + "id": "4b91e7a2", "metadata": { "editable": true }, @@ -1574,7 +1576,7 @@ }, { "cell_type": "markdown", - "id": "4a65d6fd", + "id": "6da09721", "metadata": { "editable": true }, @@ -1586,7 +1588,7 @@ }, { "cell_type": "markdown", - "id": "c66da8ef", + "id": "1ed5c66b", "metadata": { "editable": true }, @@ -1596,7 +1598,7 @@ }, { "cell_type": "markdown", - "id": "b055e013", + "id": "6157ca77", "metadata": { "editable": true }, @@ -1608,7 +1610,7 @@ }, { "cell_type": "markdown", - "id": "006ef4f0", + "id": "d47f8037", "metadata": { "editable": true }, @@ -1620,7 +1622,7 @@ }, { "cell_type": "markdown", - "id": "99fd1e13", + "id": "7a7bbc5d", "metadata": { "editable": true }, @@ -1630,7 +1632,7 @@ }, { "cell_type": "markdown", - "id": "d711ba8b", + "id": "427cb024", "metadata": { "editable": true }, @@ -1642,7 +1644,7 @@ }, { "cell_type": "markdown", - "id": "394f38fd", + "id": "57a1aaa6", "metadata": { "editable": true }, @@ -1652,7 +1654,7 @@ }, { "cell_type": "markdown", - "id": "2f589cea", + "id": "a8faabb8", "metadata": { "editable": true }, @@ -1664,7 +1666,7 @@ }, { "cell_type": "markdown", - "id": "783c3588", + "id": "bb053125", "metadata": { "editable": true }, @@ -1682,7 +1684,7 @@ }, { "cell_type": "markdown", - "id": "d1627f43", + "id": "6d58682a", "metadata": { "editable": true }, @@ -1694,7 +1696,7 @@ }, { "cell_type": "markdown", - "id": "53035043", + "id": "e26f3e58", "metadata": { "editable": true }, @@ -1706,7 +1708,7 @@ }, { "cell_type": "markdown", - "id": "f3293e4c", + "id": "bd6d2ab5", "metadata": { "editable": true }, @@ -1716,7 +1718,7 @@ }, { "cell_type": "markdown", - "id": "b6087529", + "id": "4df7d922", "metadata": { "editable": true }, @@ -1728,7 +1730,7 @@ }, { "cell_type": "markdown", - "id": "9a91562c", + "id": "451135b1", "metadata": { "editable": true }, @@ -1739,7 +1741,7 @@ { "cell_type": "code", "execution_count": 5, - "id": "49153549", + "id": "a0c4f830", "metadata": { "collapsed": false, "editable": true @@ -1758,7 +1760,7 @@ }, { "cell_type": "markdown", - "id": "3f8e08c9", + "id": "dd8fb453", "metadata": { "editable": true }, @@ -1774,7 +1776,7 @@ }, { "cell_type": "markdown", - "id": "9479dadf", + "id": "4a4d0c85", "metadata": { "editable": true }, @@ -1787,7 +1789,7 @@ }, { "cell_type": "markdown", - "id": "9e5f867e", + "id": "6216f527", "metadata": { "editable": true }, @@ -1799,7 +1801,7 @@ }, { "cell_type": "markdown", - "id": "21ee2a8a", + "id": "36fa3364", "metadata": { "editable": true }, @@ -1809,7 +1811,7 @@ }, { "cell_type": "markdown", - "id": "e09cf187", + "id": "d7936338", "metadata": { "editable": true }, @@ -1821,7 +1823,7 @@ }, { "cell_type": "markdown", - "id": "c999c36b", + "id": "b3c1cf2e", "metadata": { "editable": true }, @@ -1831,7 +1833,7 @@ }, { "cell_type": "markdown", - "id": "8fbf66c6", + "id": "3045f2f3", "metadata": { "editable": true }, @@ -1843,7 +1845,7 @@ }, { "cell_type": "markdown", - "id": "dd11cc6a", + "id": "c62d9b4f", "metadata": { "editable": true }, @@ -1853,7 +1855,7 @@ }, { "cell_type": "markdown", - "id": "69e9e950", + "id": "cc00424b", "metadata": { "editable": true }, @@ -1865,7 +1867,7 @@ }, { "cell_type": "markdown", - "id": "970b6167", + "id": "2880b26d", "metadata": { "editable": true }, @@ -1877,7 +1879,7 @@ }, { "cell_type": "markdown", - "id": "5655fa59", + "id": "6995073b", "metadata": { "editable": true }, @@ -1889,7 +1891,7 @@ }, { "cell_type": "markdown", - "id": "1c8a1f68", + "id": "3025c95c", "metadata": { "editable": true }, @@ -1899,7 +1901,7 @@ }, { "cell_type": "markdown", - "id": "edaf4340", + "id": "eadbab8c", "metadata": { "editable": true }, @@ -1911,7 +1913,7 @@ }, { "cell_type": "markdown", - "id": "f39563ef", + "id": "3b92e291", "metadata": { "editable": true }, @@ -1921,7 +1923,7 @@ }, { "cell_type": "markdown", - "id": "c3fad1fe", + "id": "61abe762", "metadata": { "editable": true }, @@ -1933,7 +1935,7 @@ }, { "cell_type": "markdown", - "id": "2f26318c", + "id": "b9ed2e77", "metadata": { "editable": true }, @@ -1943,7 +1945,7 @@ }, { "cell_type": "markdown", - "id": "75e08a4f", + "id": "3dc26776", "metadata": { "editable": true }, @@ -1955,7 +1957,7 @@ }, { "cell_type": "markdown", - "id": "2729f6dc", + "id": "8092c5dc", "metadata": { "editable": true }, @@ -1965,7 +1967,7 @@ }, { "cell_type": "markdown", - "id": "7ccfc31a", + "id": "3408773c", "metadata": { "editable": true }, @@ -1977,7 +1979,7 @@ }, { "cell_type": "markdown", - "id": "1e39402f", + "id": "547d309c", "metadata": { "editable": true }, @@ -1987,7 +1989,7 @@ }, { "cell_type": "markdown", - "id": "a8313c23", + "id": "3885960f", "metadata": { "editable": true }, @@ -1999,7 +2001,7 @@ }, { "cell_type": "markdown", - "id": "64f5a96d", + "id": "094da560", "metadata": { "editable": true }, @@ -2010,7 +2012,7 @@ }, { "cell_type": "markdown", - "id": "e087f8b8", + "id": "5e7784ef", "metadata": { "editable": true }, @@ -2022,7 +2024,7 @@ }, { "cell_type": "markdown", - "id": "ab9adb45", + "id": "da55dc29", "metadata": { "editable": true }, @@ -2034,7 +2036,7 @@ }, { "cell_type": "markdown", - "id": "e7125560", + "id": "1521da52", "metadata": { "editable": true }, @@ -2047,7 +2049,7 @@ }, { "cell_type": "markdown", - "id": "6c4ad559", + "id": "c585cfc1", "metadata": { "editable": true }, @@ -2057,7 +2059,7 @@ }, { "cell_type": "markdown", - "id": "b42e32a4", + "id": "49baac68", "metadata": { "editable": true }, @@ -2069,7 +2071,7 @@ }, { "cell_type": "markdown", - "id": "40de97ba", + "id": "90c1b377", "metadata": { "editable": true }, @@ -2079,7 +2081,7 @@ }, { "cell_type": "markdown", - "id": "22d0d252", + "id": "dfd1e5f5", "metadata": { "editable": true }, @@ -2091,7 +2093,7 @@ }, { "cell_type": "markdown", - "id": "be68a064", + "id": "01027588", "metadata": { "editable": true }, @@ -2101,7 +2103,7 @@ }, { "cell_type": "markdown", - "id": "ed92fb3c", + "id": "faf9a7f4", "metadata": { "editable": true }, @@ -2117,7 +2119,7 @@ }, { "cell_type": "markdown", - "id": "b565b39a", + "id": "c8a60c3c", "metadata": { "editable": true }, @@ -2134,7 +2136,7 @@ }, { "cell_type": "markdown", - "id": "587ae22d", + "id": "bebf89c4", "metadata": { "editable": true }, @@ -2146,7 +2148,7 @@ }, { "cell_type": "markdown", - "id": "a54b74ca", + "id": "c8e55af0", "metadata": { "editable": true }, @@ -2159,7 +2161,7 @@ }, { "cell_type": "markdown", - "id": "bcfc076a", + "id": "4b69aacb", "metadata": { "editable": true }, @@ -2172,7 +2174,7 @@ }, { "cell_type": "markdown", - "id": "b4194098", + "id": "c0d54321", "metadata": { "editable": true }, @@ -2184,7 +2186,7 @@ }, { "cell_type": "markdown", - "id": "acc7030d", + "id": "8486d91e", "metadata": { "editable": true }, @@ -2194,7 +2196,7 @@ }, { "cell_type": "markdown", - "id": "02f92f41", + "id": "de5e8a70", "metadata": { "editable": true }, @@ -2206,7 +2208,7 @@ }, { "cell_type": "markdown", - "id": "5541dfd1", + "id": "42dc3f26", "metadata": { "editable": true }, @@ -2221,7 +2223,7 @@ }, { "cell_type": "markdown", - "id": "f73cf263", + "id": "133e16c7", "metadata": { "editable": true }, @@ -2236,7 +2238,7 @@ }, { "cell_type": "markdown", - "id": "4b8722cb", + "id": "1fd248a5", "metadata": { "editable": true }, @@ -2248,7 +2250,7 @@ }, { "cell_type": "markdown", - "id": "a604334f", + "id": "321220a1", "metadata": { "editable": true }, @@ -2262,7 +2264,7 @@ }, { "cell_type": "markdown", - "id": "0017f42e", + "id": "d4ef8cda", "metadata": { "editable": true }, @@ -2274,7 +2276,7 @@ }, { "cell_type": "markdown", - "id": "8c47d806", + "id": "c83257a3", "metadata": { "editable": true }, @@ -2290,7 +2292,7 @@ }, { "cell_type": "markdown", - "id": "df503def", + "id": "41976e3b", "metadata": { "editable": true }, @@ -2306,7 +2308,7 @@ }, { "cell_type": "markdown", - "id": "bdc97982", + "id": "daeda85f", "metadata": { "editable": true }, @@ -2318,7 +2320,7 @@ }, { "cell_type": "markdown", - "id": "42716985", + "id": "cfd25fda", "metadata": { "editable": true }, @@ -2328,7 +2330,7 @@ }, { "cell_type": "markdown", - "id": "6df9aa60", + "id": "8d695dcf", "metadata": { "editable": true }, @@ -2340,7 +2342,7 @@ }, { "cell_type": "markdown", - "id": "30f9e077", + "id": "dcc2f332", "metadata": { "editable": true }, @@ -2350,7 +2352,7 @@ }, { "cell_type": "markdown", - "id": "77e9d494", + "id": "cb53a1ce", "metadata": { "editable": true }, @@ -2362,7 +2364,7 @@ }, { "cell_type": "markdown", - "id": "1136c644", + "id": "b547af4b", "metadata": { "editable": true }, @@ -2372,7 +2374,7 @@ }, { "cell_type": "markdown", - "id": "b9f253ba", + "id": "e05ad1a5", "metadata": { "editable": true }, @@ -2384,7 +2386,7 @@ }, { "cell_type": "markdown", - "id": "14d41c44", + "id": "e841d792", "metadata": { "editable": true }, @@ -2400,7 +2402,7 @@ }, { "cell_type": "markdown", - "id": "d7c607f5", + "id": "7d0be7a7", "metadata": { "editable": true }, @@ -2412,7 +2414,7 @@ }, { "cell_type": "markdown", - "id": "609e28e0", + "id": "99d7e794", "metadata": { "editable": true }, @@ -2424,7 +2426,7 @@ }, { "cell_type": "markdown", - "id": "494580d5", + "id": "b5a9ccd1", "metadata": { "editable": true }, @@ -2434,7 +2436,7 @@ }, { "cell_type": "markdown", - "id": "03665a6f", + "id": "97e1f77a", "metadata": { "editable": true }, @@ -2446,7 +2448,7 @@ }, { "cell_type": "markdown", - "id": "911b5d2c", + "id": "129d6040", "metadata": { "editable": true }, @@ -2456,7 +2458,7 @@ }, { "cell_type": "markdown", - "id": "91e4f869", + "id": "cd905c05", "metadata": { "editable": true }, @@ -2472,7 +2474,7 @@ }, { "cell_type": "markdown", - "id": "43efdd27", + "id": "dc3ee985", "metadata": { "editable": true }, @@ -2484,7 +2486,7 @@ }, { "cell_type": "markdown", - "id": "25d99018", + "id": "6b21de52", "metadata": { "editable": true }, @@ -2496,7 +2498,7 @@ }, { "cell_type": "markdown", - "id": "6924f790", + "id": "04bef693", "metadata": { "editable": true }, @@ -2508,7 +2510,7 @@ }, { "cell_type": "markdown", - "id": "f457fe37", + "id": "6e9a9575", "metadata": { "editable": true }, @@ -2520,7 +2522,7 @@ }, { "cell_type": "markdown", - "id": "81e40678", + "id": "c65ff641", "metadata": { "editable": true }, @@ -2532,7 +2534,7 @@ }, { "cell_type": "markdown", - "id": "c954b1f9", + "id": "f67e1353", "metadata": { "editable": true }, @@ -2542,7 +2544,7 @@ }, { "cell_type": "markdown", - "id": "87d10fa3", + "id": "7476ad06", "metadata": { "editable": true }, @@ -2558,7 +2560,7 @@ }, { "cell_type": "markdown", - "id": "c20ef010", + "id": "520d8a90", "metadata": { "editable": true }, @@ -2570,7 +2572,7 @@ }, { "cell_type": "markdown", - "id": "e9de19ea", + "id": "d57d0f1d", "metadata": { "editable": true }, @@ -2582,7 +2584,7 @@ }, { "cell_type": "markdown", - "id": "3487e8b8", + "id": "97925a47", "metadata": { "editable": true }, @@ -2592,7 +2594,7 @@ }, { "cell_type": "markdown", - "id": "7baa62bc", + "id": "21bf2445", "metadata": { "editable": true }, @@ -2604,7 +2606,7 @@ }, { "cell_type": "markdown", - "id": "a3c1590a", + "id": "de7f0e7b", "metadata": { "editable": true }, @@ -2618,7 +2620,7 @@ }, { "cell_type": "markdown", - "id": "3c3dc625", + "id": "4060cfa4", "metadata": { "editable": true }, @@ -2636,7 +2638,7 @@ { "cell_type": "code", "execution_count": 6, - "id": "e9fb1fc9", + "id": "1248e89b", "metadata": { "collapsed": false, "editable": true @@ -2709,7 +2711,7 @@ }, { "cell_type": "markdown", - "id": "351debb8", + "id": "eabe6b42", "metadata": { "editable": true }, @@ -2719,7 +2721,7 @@ }, { "cell_type": "markdown", - "id": "c6579e36", + "id": "35974e2d", "metadata": { "editable": true }, @@ -2737,7 +2739,7 @@ }, { "cell_type": "markdown", - "id": "2c80a4b1", + "id": "eebf9d30", "metadata": { "editable": true }, @@ -2754,7 +2756,7 @@ }, { "cell_type": "markdown", - "id": "c834edc8", + "id": "2f079f0b", "metadata": { "editable": true }, @@ -2766,7 +2768,7 @@ }, { "cell_type": "markdown", - "id": "79bd199b", + "id": "50b799fe", "metadata": { "editable": true }, @@ -2776,7 +2778,7 @@ }, { "cell_type": "markdown", - "id": "0a856855", + "id": "9eeeddd7", "metadata": { "editable": true }, @@ -2788,7 +2790,7 @@ }, { "cell_type": "markdown", - "id": "54280198", + "id": "89d239c6", "metadata": { "editable": true }, @@ -2804,7 +2806,7 @@ }, { "cell_type": "markdown", - "id": "b2cee09c", + "id": "bdbf35b5", "metadata": { "editable": true }, @@ -2816,7 +2818,7 @@ }, { "cell_type": "markdown", - "id": "710131c9", + "id": "4e4ff5e9", "metadata": { "editable": true }, @@ -2828,7 +2830,7 @@ }, { "cell_type": "markdown", - "id": "cd8b54e5", + "id": "0d262c6f", "metadata": { "editable": true }, @@ -2839,7 +2841,7 @@ }, { "cell_type": "markdown", - "id": "8998ad11", + "id": "bc03ac5a", "metadata": { "editable": true }, @@ -2851,7 +2853,7 @@ }, { "cell_type": "markdown", - "id": "7d430cf7", + "id": "59f909e2", "metadata": { "editable": true }, @@ -2864,7 +2866,7 @@ }, { "cell_type": "markdown", - "id": "9b5a6c95", + "id": "7eb0a44d", "metadata": { "editable": true }, @@ -2876,7 +2878,7 @@ }, { "cell_type": "markdown", - "id": "31d044d8", + "id": "07d8d778", "metadata": { "editable": true }, @@ -2886,7 +2888,7 @@ }, { "cell_type": "markdown", - "id": "f5125cb7", + "id": "60368bf9", "metadata": { "editable": true }, @@ -2898,7 +2900,7 @@ }, { "cell_type": "markdown", - "id": "0eed1fab", + "id": "79853185", "metadata": { "editable": true }, @@ -2910,7 +2912,7 @@ }, { "cell_type": "markdown", - "id": "9a9811d2", + "id": "e84489fb", "metadata": { "editable": true }, @@ -2922,7 +2924,7 @@ }, { "cell_type": "markdown", - "id": "98bf5097", + "id": "10ac6ea6", "metadata": { "editable": true }, @@ -2932,7 +2934,7 @@ }, { "cell_type": "markdown", - "id": "e749c895", + "id": "4bb215d6", "metadata": { "editable": true }, @@ -2944,7 +2946,7 @@ }, { "cell_type": "markdown", - "id": "ea6692ce", + "id": "0389c02c", "metadata": { "editable": true }, @@ -2960,7 +2962,7 @@ }, { "cell_type": "markdown", - "id": "bf74eae4", + "id": "bd9a8665", "metadata": { "editable": true }, @@ -2972,7 +2974,7 @@ }, { "cell_type": "markdown", - "id": "d590dc50", + "id": "904eef6d", "metadata": { "editable": true }, @@ -2982,7 +2984,7 @@ }, { "cell_type": "markdown", - "id": "eb0b8e3c", + "id": "f422cd5d", "metadata": { "editable": true }, @@ -2994,7 +2996,7 @@ }, { "cell_type": "markdown", - "id": "7928cd11", + "id": "0827f570", "metadata": { "editable": true }, @@ -3004,7 +3006,7 @@ }, { "cell_type": "markdown", - "id": "8fc852e0", + "id": "0caae8eb", "metadata": { "editable": true }, @@ -3016,7 +3018,7 @@ }, { "cell_type": "markdown", - "id": "634713ba", + "id": "2f4011e7", "metadata": { "editable": true }, @@ -3028,7 +3030,7 @@ }, { "cell_type": "markdown", - "id": "0f6ca3e6", + "id": "4614eb63", "metadata": { "editable": true }, @@ -3041,7 +3043,7 @@ }, { "cell_type": "markdown", - "id": "3b54e63f", + "id": "954403b8", "metadata": { "editable": true }, @@ -3051,7 +3053,7 @@ }, { "cell_type": "markdown", - "id": "a69c61ff", + "id": "d0f5c05f", "metadata": { "editable": true }, @@ -3063,7 +3065,7 @@ }, { "cell_type": "markdown", - "id": "a73b8fe2", + "id": "ac8c2f66", "metadata": { "editable": true }, @@ -3073,7 +3075,7 @@ }, { "cell_type": "markdown", - "id": "093c845d", + "id": "9bcf7c0d", "metadata": { "editable": true }, @@ -3085,7 +3087,7 @@ }, { "cell_type": "markdown", - "id": "dcd12209", + "id": "4c2c5c00", "metadata": { "editable": true }, @@ -3096,7 +3098,7 @@ }, { "cell_type": "markdown", - "id": "5d5e8985", + "id": "eed00134", "metadata": { "editable": true }, @@ -3108,7 +3110,7 @@ }, { "cell_type": "markdown", - "id": "506f74bf", + "id": "21d53946", "metadata": { "editable": true }, @@ -3118,7 +3120,7 @@ }, { "cell_type": "markdown", - "id": "b474afaa", + "id": "4fbe8642", "metadata": { "editable": true }, @@ -3130,7 +3132,7 @@ }, { "cell_type": "markdown", - "id": "7d14d370", + "id": "2325e21d", "metadata": { "editable": true }, @@ -3140,7 +3142,7 @@ }, { "cell_type": "markdown", - "id": "ca679e05", + "id": "14edd073", "metadata": { "editable": true }, @@ -3152,7 +3154,7 @@ }, { "cell_type": "markdown", - "id": "251a03fd", + "id": "52bbf902", "metadata": { "editable": true }, @@ -3164,7 +3166,7 @@ }, { "cell_type": "markdown", - "id": "b7575ec0", + "id": "98a6ed3a", "metadata": { "editable": true }, @@ -3176,7 +3178,7 @@ }, { "cell_type": "markdown", - "id": "02453de3", + "id": "6ab03495", "metadata": { "editable": true }, @@ -3186,7 +3188,7 @@ }, { "cell_type": "markdown", - "id": "4e989854", + "id": "dcda9d7d", "metadata": { "editable": true }, @@ -3198,7 +3200,7 @@ }, { "cell_type": "markdown", - "id": "05a25565", + "id": "46ec3534", "metadata": { "editable": true }, @@ -3208,7 +3210,7 @@ }, { "cell_type": "markdown", - "id": "d9e571d7", + "id": "f10c20da", "metadata": { "editable": true }, @@ -3220,7 +3222,7 @@ }, { "cell_type": "markdown", - "id": "f96632e9", + "id": "c3c477be", "metadata": { "editable": true }, @@ -3232,7 +3234,7 @@ }, { "cell_type": "markdown", - "id": "e15002e0", + "id": "0c915c97", "metadata": { "editable": true }, @@ -3244,7 +3246,7 @@ }, { "cell_type": "markdown", - "id": "8c683755", + "id": "646d8351", "metadata": { "editable": true }, @@ -3254,7 +3256,7 @@ }, { "cell_type": "markdown", - "id": "da56a290", + "id": "4ce93a76", "metadata": { "editable": true }, @@ -3266,7 +3268,7 @@ }, { "cell_type": "markdown", - "id": "e42a9d6c", + "id": "ee7a38ed", "metadata": { "editable": true }, @@ -3276,7 +3278,7 @@ }, { "cell_type": "markdown", - "id": "21dd6563", + "id": "abdb541d", "metadata": { "editable": true }, @@ -3289,7 +3291,7 @@ }, { "cell_type": "markdown", - "id": "67fc0189", + "id": "410de8d4", "metadata": { "editable": true }, @@ -3301,7 +3303,7 @@ }, { "cell_type": "markdown", - "id": "daddd95e", + "id": "ca1d6736", "metadata": { "editable": true }, @@ -3311,7 +3313,7 @@ }, { "cell_type": "markdown", - "id": "5bf8af85", + "id": "d43c2266", "metadata": { "editable": true }, @@ -3323,7 +3325,7 @@ }, { "cell_type": "markdown", - "id": "5a72ea0a", + "id": "56457d52", "metadata": { "editable": true }, @@ -3333,7 +3335,7 @@ }, { "cell_type": "markdown", - "id": "edd32da2", + "id": "1ddc19f1", "metadata": { "editable": true }, @@ -3345,7 +3347,7 @@ }, { "cell_type": "markdown", - "id": "75c31af5", + "id": "de8c80cd", "metadata": { "editable": true }, @@ -3355,7 +3357,7 @@ }, { "cell_type": "markdown", - "id": "c037d92b", + "id": "db88453a", "metadata": { "editable": true }, @@ -3367,7 +3369,7 @@ }, { "cell_type": "markdown", - "id": "5937fd51", + "id": "f61958e4", "metadata": { "editable": true }, @@ -3377,7 +3379,7 @@ }, { "cell_type": "markdown", - "id": "3f0f6cd3", + "id": "7ef82615", "metadata": { "editable": true }, @@ -3389,7 +3391,7 @@ }, { "cell_type": "markdown", - "id": "057366c1", + "id": "f65323bf", "metadata": { "editable": true }, @@ -3401,7 +3403,7 @@ }, { "cell_type": "markdown", - "id": "293fa11b", + "id": "96734d00", "metadata": { "editable": true }, @@ -3411,7 +3413,7 @@ }, { "cell_type": "markdown", - "id": "d652c45d", + "id": "f776f53c", "metadata": { "editable": true }, @@ -3423,7 +3425,7 @@ }, { "cell_type": "markdown", - "id": "8ca9d167", + "id": "bbf2e007", "metadata": { "editable": true }, @@ -3436,7 +3438,7 @@ }, { "cell_type": "markdown", - "id": "8fed1e03", + "id": "9d6d0a32", "metadata": { "editable": true }, @@ -3450,7 +3452,7 @@ }, { "cell_type": "markdown", - "id": "6394a2a5", + "id": "6720dd98", "metadata": { "editable": true }, @@ -3462,7 +3464,7 @@ }, { "cell_type": "markdown", - "id": "c2e22893", + "id": "759eb99f", "metadata": { "editable": true }, @@ -3472,7 +3474,7 @@ }, { "cell_type": "markdown", - "id": "5e054d69", + "id": "294cc167", "metadata": { "editable": true }, @@ -3484,7 +3486,7 @@ }, { "cell_type": "markdown", - "id": "dd5f9a8d", + "id": "3311576a", "metadata": { "editable": true }, @@ -3494,7 +3496,7 @@ }, { "cell_type": "markdown", - "id": "ff6e8f86", + "id": "892ab641", "metadata": { "editable": true }, @@ -3506,7 +3508,7 @@ }, { "cell_type": "markdown", - "id": "6e186667", + "id": "e126a949", "metadata": { "editable": true }, @@ -3524,7 +3526,7 @@ }, { "cell_type": "markdown", - "id": "0e0a514f", + "id": "0640b440", "metadata": { "editable": true }, @@ -3542,7 +3544,7 @@ }, { "cell_type": "markdown", - "id": "e8259ee9", + "id": "780544e8", "metadata": { "editable": true }, @@ -3554,7 +3556,7 @@ }, { "cell_type": "markdown", - "id": "3c817881", + "id": "5ed8c781", "metadata": { "editable": true }, @@ -3564,7 +3566,7 @@ }, { "cell_type": "markdown", - "id": "0f3e5b1c", + "id": "9a9568a1", "metadata": { "editable": true }, @@ -3576,7 +3578,7 @@ }, { "cell_type": "markdown", - "id": "4e14ef60", + "id": "29ac7458", "metadata": { "editable": true }, @@ -3588,7 +3590,7 @@ }, { "cell_type": "markdown", - "id": "886fbebf", + "id": "693c53ac", "metadata": { "editable": true }, @@ -3600,7 +3602,7 @@ }, { "cell_type": "markdown", - "id": "16d62157", + "id": "650e4dea", "metadata": { "editable": true }, @@ -3610,7 +3612,7 @@ }, { "cell_type": "markdown", - "id": "4a81d6b5", + "id": "4fbf17cf", "metadata": { "editable": true }, @@ -3622,7 +3624,7 @@ }, { "cell_type": "markdown", - "id": "0bcee50c", + "id": "a7869a22", "metadata": { "editable": true }, @@ -3632,7 +3634,7 @@ }, { "cell_type": "markdown", - "id": "0ed7f7a0", + "id": "cfd6c9d7", "metadata": { "editable": true }, @@ -3644,7 +3646,7 @@ }, { "cell_type": "markdown", - "id": "a502b908", + "id": "73360f7e", "metadata": { "editable": true }, @@ -3662,7 +3664,7 @@ }, { "cell_type": "markdown", - "id": "fa4de05b", + "id": "2685bc86", "metadata": { "editable": true }, @@ -3672,7 +3674,7 @@ }, { "cell_type": "markdown", - "id": "cea42eaf", + "id": "ff174cf5", "metadata": { "editable": true }, @@ -3690,7 +3692,7 @@ }, { "cell_type": "markdown", - "id": "d04fa6e6", + "id": "1c97902a", "metadata": { "editable": true }, @@ -3700,7 +3702,7 @@ }, { "cell_type": "markdown", - "id": "8716ad2e", + "id": "d70e9292", "metadata": { "editable": true }, @@ -3718,7 +3720,7 @@ }, { "cell_type": "markdown", - "id": "f64753b2", + "id": "ffcecfbe", "metadata": { "editable": true }, @@ -3730,7 +3732,7 @@ }, { "cell_type": "markdown", - "id": "4ad6d6d3", + "id": "e49c2a4e", "metadata": { "editable": true }, @@ -3742,7 +3744,7 @@ }, { "cell_type": "markdown", - "id": "a8d42ee3", + "id": "4c706310", "metadata": { "editable": true }, @@ -3752,7 +3754,7 @@ }, { "cell_type": "markdown", - "id": "0628c4b8", + "id": "301cfb1f", "metadata": { "editable": true }, @@ -3764,7 +3766,7 @@ }, { "cell_type": "markdown", - "id": "0868f3d3", + "id": "5dc4f3ba", "metadata": { "editable": true }, @@ -3776,7 +3778,7 @@ }, { "cell_type": "markdown", - "id": "89190c24", + "id": "3dfdac72", "metadata": { "editable": true }, @@ -3786,7 +3788,7 @@ }, { "cell_type": "markdown", - "id": "96af414a", + "id": "c04afa91", "metadata": { "editable": true }, @@ -3798,7 +3800,7 @@ }, { "cell_type": "markdown", - "id": "fe790abf", + "id": "b7a22173", "metadata": { "editable": true }, @@ -3808,7 +3810,7 @@ }, { "cell_type": "markdown", - "id": "ece1f6fe", + "id": "fa9ff041", "metadata": { "editable": true }, @@ -3820,7 +3822,7 @@ }, { "cell_type": "markdown", - "id": "9cafdde6", + "id": "a1648ab9", "metadata": { "editable": true }, @@ -3832,7 +3834,7 @@ }, { "cell_type": "markdown", - "id": "0766f482", + "id": "24569ace", "metadata": { "editable": true }, @@ -3855,7 +3857,7 @@ }, { "cell_type": "markdown", - "id": "e29ae382", + "id": "478d8aec", "metadata": { "editable": true }, @@ -3867,7 +3869,7 @@ }, { "cell_type": "markdown", - "id": "518b6578", + "id": "a17614e1", "metadata": { "editable": true }, @@ -3879,7 +3881,7 @@ }, { "cell_type": "markdown", - "id": "4f804851", + "id": "2bc63b98", "metadata": { "editable": true }, @@ -3889,7 +3891,7 @@ }, { "cell_type": "markdown", - "id": "359aae81", + "id": "060a6a00", "metadata": { "editable": true }, @@ -3901,7 +3903,7 @@ }, { "cell_type": "markdown", - "id": "70123228", + "id": "f73677e1", "metadata": { "editable": true }, @@ -3915,7 +3917,7 @@ }, { "cell_type": "markdown", - "id": "2df5a3de", + "id": "b0faa8a5", "metadata": { "editable": true }, @@ -3927,7 +3929,7 @@ }, { "cell_type": "markdown", - "id": "8081e4e4", + "id": "4f0820e6", "metadata": { "editable": true }, @@ -3939,7 +3941,7 @@ }, { "cell_type": "markdown", - "id": "3c40603c", + "id": "72ac45e2", "metadata": { "editable": true }, @@ -3949,7 +3951,7 @@ }, { "cell_type": "markdown", - "id": "26de0b47", + "id": "53cbf551", "metadata": { "editable": true }, @@ -3961,7 +3963,7 @@ }, { "cell_type": "markdown", - "id": "a172a64a", + "id": "8a9433ea", "metadata": { "editable": true }, @@ -3973,7 +3975,7 @@ }, { "cell_type": "markdown", - "id": "dfd6fc88", + "id": "07c92792", "metadata": { "editable": true }, @@ -3983,7 +3985,7 @@ }, { "cell_type": "markdown", - "id": "a7df4398", + "id": "efa48fd7", "metadata": { "editable": true }, @@ -3995,7 +3997,7 @@ }, { "cell_type": "markdown", - "id": "cfd24fc1", + "id": "6c4db201", "metadata": { "editable": true }, @@ -4007,7 +4009,7 @@ }, { "cell_type": "markdown", - "id": "869c3364", + "id": "19ae4f4e", "metadata": { "editable": true }, @@ -4030,7 +4032,7 @@ }, { "cell_type": "markdown", - "id": "91102a3c", + "id": "c478ce3c", "metadata": { "editable": true }, @@ -4049,7 +4051,7 @@ }, { "cell_type": "markdown", - "id": "9609f422", + "id": "5142ca2b", "metadata": { "editable": true }, @@ -4061,7 +4063,7 @@ }, { "cell_type": "markdown", - "id": "cdd8d562", + "id": "9c4a44fb", "metadata": { "editable": true }, @@ -4071,7 +4073,7 @@ }, { "cell_type": "markdown", - "id": "118a47f2", + "id": "74fded03", "metadata": { "editable": true }, @@ -4083,7 +4085,7 @@ }, { "cell_type": "markdown", - "id": "5d6387b5", + "id": "fefab641", "metadata": { "editable": true }, @@ -4100,7 +4102,7 @@ { "cell_type": "code", "execution_count": 7, - "id": "33449cca", + "id": "56c89538", "metadata": { "collapsed": false, "editable": true @@ -4182,7 +4184,7 @@ }, { "cell_type": "markdown", - "id": "e8fafa8a", + "id": "21bdb71c", "metadata": { "editable": true }, @@ -4211,7 +4213,7 @@ }, { "cell_type": "markdown", - "id": "00965f5d", + "id": "82072ebe", "metadata": { "editable": true }, @@ -4237,7 +4239,7 @@ }, { "cell_type": "markdown", - "id": "d90316a8", + "id": "8bfa5b96", "metadata": { "editable": true }, @@ -4259,7 +4261,7 @@ }, { "cell_type": "markdown", - "id": "441fe8d9", + "id": "a52a67bd", "metadata": { "editable": true }, @@ -4277,7 +4279,7 @@ }, { "cell_type": "markdown", - "id": "ae55ad1c", + "id": "052308cd", "metadata": { "editable": true }, @@ -4300,7 +4302,7 @@ }, { "cell_type": "markdown", - "id": "96bbf798", + "id": "2c943852", "metadata": { "editable": true }, @@ -4319,7 +4321,7 @@ }, { "cell_type": "markdown", - "id": "4b03e108", + "id": "09e98546", "metadata": { "editable": true }, @@ -4347,7 +4349,7 @@ }, { "cell_type": "markdown", - "id": "2898691d", + "id": "89458b0d", "metadata": { "editable": true }, @@ -4367,7 +4369,7 @@ }, { "cell_type": "markdown", - "id": "4ac964f3", + "id": "bb787cf2", "metadata": { "editable": true }, @@ -4388,7 +4390,7 @@ }, { "cell_type": "markdown", - "id": "c18a90e1", + "id": "8d6d8c18", "metadata": { "editable": true }, @@ -4402,7 +4404,7 @@ }, { "cell_type": "markdown", - "id": "eed9db84", + "id": "52c4e6b6", "metadata": { "editable": true }, @@ -4414,7 +4416,7 @@ }, { "cell_type": "markdown", - "id": "b375c182", + "id": "d0dad2c7", "metadata": { "editable": true }, @@ -4436,7 +4438,7 @@ }, { "cell_type": "markdown", - "id": "edb42800", + "id": "31d1148a", "metadata": { "editable": true }, @@ -4458,7 +4460,7 @@ }, { "cell_type": "markdown", - "id": "1a8fafc0", + "id": "d6d621a7", "metadata": { "editable": true }, @@ -4484,7 +4486,7 @@ }, { "cell_type": "markdown", - "id": "feef1d4d", + "id": "379983d5", "metadata": { "editable": true }, @@ -4504,7 +4506,7 @@ }, { "cell_type": "markdown", - "id": "9428c225", + "id": "b769aa51", "metadata": { "editable": true }, @@ -4524,7 +4526,7 @@ }, { "cell_type": "markdown", - "id": "504b21ae", + "id": "abeef409", "metadata": { "editable": true }, @@ -4550,7 +4552,7 @@ }, { "cell_type": "markdown", - "id": "c51837a9", + "id": "75165741", "metadata": { "editable": true }, @@ -4579,7 +4581,7 @@ }, { "cell_type": "markdown", - "id": "a7357657", + "id": "14f22927", "metadata": { "editable": true }, @@ -4597,7 +4599,7 @@ }, { "cell_type": "markdown", - "id": "e92c8a84", + "id": "f5ad6d66", "metadata": { "editable": true }, @@ -4613,7 +4615,7 @@ }, { "cell_type": "markdown", - "id": "793aee7d", + "id": "82f3c1c1", "metadata": { "editable": true }, @@ -4625,7 +4627,7 @@ }, { "cell_type": "markdown", - "id": "739960d6", + "id": "01fba9a0", "metadata": { "editable": true }, diff --git a/doc/src/week41/_minted-week41/8F742E4CFCF99BA69821AA2655DBFD5ABBBAD84E10F49A5F4278A7252110B6CA.pygtex b/doc/src/week41/_minted-week41/8F742E4CFCF99BA69821AA2655DBFD5ABBBAD84E10F49A5F4278A7252110B6CA.pygtex deleted file mode 100644 index 091dde585..000000000 --- a/doc/src/week41/_minted-week41/8F742E4CFCF99BA69821AA2655DBFD5ABBBAD84E10F49A5F4278A7252110B6CA.pygtex +++ /dev/null @@ -1,52 +0,0 @@ -\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}] -\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}} -\PYG{l+s+sd}{Simple code that tests XOR and OR gates with linear regression} -\PYG{l+s+sd}{and logistic regression} -\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}} - -\PYG{k+kn}{import} \PYG{n+nn}{matplotlib.pyplot} \PYG{k}{as} \PYG{n+nn}{plt} -\PYG{k+kn}{from} \PYG{n+nn}{sklearn.linear\PYGZus{}model} \PYG{k+kn}{import} \PYG{n}{LogisticRegression} -\PYG{k+kn}{import} \PYG{n+nn}{numpy} \PYG{k}{as} \PYG{n+nn}{np} - -\PYG{c+c1}{\PYGZsh{} Design matrix} -\PYG{n}{X} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{([} \PYG{p}{[}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{],} \PYG{p}{[}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{],} \PYG{p}{[}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{],[}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{]],}\PYG{n}{dtype}\PYG{o}{=}\PYG{n}{np}\PYG{o}{.}\PYG{n}{float64}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The X.TX matrix:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{X}\PYG{o}{.}\PYG{n}{T}\PYG{+w}{ }\PYG{o}{@}\PYG{+w}{ }\PYG{n}{X}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} -\PYG{n}{Xinv} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{linalg}\PYG{o}{.}\PYG{n}{pinv}\PYG{p}{(}\PYG{n}{X}\PYG{o}{.}\PYG{n}{T} \PYG{o}{@} \PYG{n}{X}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The invers of X.TX matrix:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{Xinv}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} - -\PYG{c+c1}{\PYGZsh{} The XOR gate} -\PYG{n}{yXOR} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{(} \PYG{p}{[} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{1} \PYG{p}{,}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{])} -\PYG{n}{ThetaXOR} \PYG{o}{=} \PYG{n}{Xinv} \PYG{o}{@} \PYG{n}{X}\PYG{o}{.}\PYG{n}{T} \PYG{o}{@} \PYG{n}{yXOR} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The values of theta for the XOR gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{ThetaXOR}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The linear regression prediction for the XOR gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{X}\PYG{+w}{ }\PYG{o}{@}\PYG{+w}{ }\PYG{n}{ThetaXOR}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} - - -\PYG{c+c1}{\PYGZsh{} The OR gate} -\PYG{n}{yOR} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{(} \PYG{p}{[} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{1} \PYG{p}{,}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{])} -\PYG{n}{ThetaOR} \PYG{o}{=} \PYG{n}{Xinv} \PYG{o}{@} \PYG{n}{X}\PYG{o}{.}\PYG{n}{T} \PYG{o}{@} \PYG{n}{yOR} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The values of theta for the OR gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{ThetaOR}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The linear regression prediction for the OR gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{X}\PYG{+w}{ }\PYG{o}{@}\PYG{+w}{ }\PYG{n}{ThetaOR}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} - - -\PYG{c+c1}{\PYGZsh{} The OR gate} -\PYG{n}{yAND} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{(} \PYG{p}{[} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{0} \PYG{p}{,}\PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{])} -\PYG{n}{ThetaAND} \PYG{o}{=} \PYG{n}{Xinv} \PYG{o}{@} \PYG{n}{X}\PYG{o}{.}\PYG{n}{T} \PYG{o}{@} \PYG{n}{yAND} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The values of theta for the AND gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{ThetaAND}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The linear regression prediction for the AND gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{X}\PYG{+w}{ }\PYG{o}{@}\PYG{+w}{ }\PYG{n}{ThetaAND}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} - -\PYG{c+c1}{\PYGZsh{} Now we change to logistic regression} - - -\PYG{c+c1}{\PYGZsh{} Logistic Regression} -\PYG{n}{logreg} \PYG{o}{=} \PYG{n}{LogisticRegression}\PYG{p}{()} -\PYG{n}{logreg}\PYG{o}{.}\PYG{n}{fit}\PYG{p}{(}\PYG{n}{X}\PYG{p}{,} \PYG{n}{yOR}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}Test set accuracy with Logistic Regression for OR gate: }\PYG{l+s+si}{\PYGZob{}:.2f\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{o}{.}\PYG{n}{format}\PYG{p}{(}\PYG{n}{logreg}\PYG{o}{.}\PYG{n}{score}\PYG{p}{(}\PYG{n}{X}\PYG{p}{,}\PYG{n}{yOR}\PYG{p}{)))} - -\PYG{n}{logreg}\PYG{o}{.}\PYG{n}{fit}\PYG{p}{(}\PYG{n}{X}\PYG{p}{,} \PYG{n}{yXOR}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}Test set accuracy with Logistic Regression for XOR gate: }\PYG{l+s+si}{\PYGZob{}:.2f\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{o}{.}\PYG{n}{format}\PYG{p}{(}\PYG{n}{logreg}\PYG{o}{.}\PYG{n}{score}\PYG{p}{(}\PYG{n}{X}\PYG{p}{,}\PYG{n}{yXOR}\PYG{p}{)))} - - -\PYG{n}{logreg}\PYG{o}{.}\PYG{n}{fit}\PYG{p}{(}\PYG{n}{X}\PYG{p}{,} \PYG{n}{yAND}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}Test set accuracy with Logistic Regression for AND gate: }\PYG{l+s+si}{\PYGZob{}:.2f\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{o}{.}\PYG{n}{format}\PYG{p}{(}\PYG{n}{logreg}\PYG{o}{.}\PYG{n}{score}\PYG{p}{(}\PYG{n}{X}\PYG{p}{,}\PYG{n}{yAND}\PYG{p}{)))} - -\end{Verbatim} diff --git a/doc/src/week41/_minted-week41/8FDA801D9EBD40558C744590672A037CBBBAD84E10F49A5F4278A7252110B6CA.pygtex b/doc/src/week41/_minted-week41/8FDA801D9EBD40558C744590672A037CBBBAD84E10F49A5F4278A7252110B6CA.pygtex deleted file mode 100644 index d913b9f53..000000000 --- a/doc/src/week41/_minted-week41/8FDA801D9EBD40558C744590672A037CBBBAD84E10F49A5F4278A7252110B6CA.pygtex +++ /dev/null @@ -1,11 +0,0 @@ -\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}] -\PYG{k+kn}{from} \PYG{n+nn}{\PYGZus{}\PYGZus{}future\PYGZus{}\PYGZus{}} \PYG{k+kn}{import} \PYG{n}{division} -\PYG{k+kn}{from} \PYG{n+nn}{sympy} \PYG{k+kn}{import} \PYG{o}{*} -\PYG{n}{x} \PYG{o}{=} \PYG{n}{symbols}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}x\PYGZsq{}}\PYG{p}{)} -\PYG{n}{expr} \PYG{o}{=} \PYG{n}{sqrt}\PYG{p}{(}\PYG{n}{x}\PYG{o}{*}\PYG{n}{x}\PYG{o}{+}\PYG{n}{exp}\PYG{p}{(}\PYG{n}{x}\PYG{o}{*}\PYG{n}{x}\PYG{p}{))} -\PYG{n}{simplify}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{)} -\PYG{n}{derivative} \PYG{o}{=} \PYG{n}{diff}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{,}\PYG{n}{x}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{python}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{))} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{python}\PYG{p}{(}\PYG{n}{derivative}\PYG{p}{))} - -\end{Verbatim} diff --git a/doc/src/week41/_minted-week41/91DA298044DB0DCD8186DE2877A3BBC1BBBAD84E10F49A5F4278A7252110B6CA.pygtex b/doc/src/week41/_minted-week41/91DA298044DB0DCD8186DE2877A3BBC1BBBAD84E10F49A5F4278A7252110B6CA.pygtex deleted file mode 100644 index 476d259fb..000000000 --- a/doc/src/week41/_minted-week41/91DA298044DB0DCD8186DE2877A3BBC1BBBAD84E10F49A5F4278A7252110B6CA.pygtex +++ /dev/null @@ -1,74 +0,0 @@ -\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}] -\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}The sigmoid function (or the logistic curve) is a} -\PYG{l+s+sd}{function that takes any real number, z, and outputs a number (0,1).} -\PYG{l+s+sd}{It is useful in neural networks for assigning weights on a relative scale.} -\PYG{l+s+sd}{The value z is the weighted sum of parameters involved in the learning algorithm.\PYGZdq{}\PYGZdq{}\PYGZdq{}} - -\PYG{k+kn}{import} \PYG{n+nn}{numpy} -\PYG{k+kn}{import} \PYG{n+nn}{matplotlib.pyplot} \PYG{k}{as} \PYG{n+nn}{plt} -\PYG{k+kn}{import} \PYG{n+nn}{math} \PYG{k}{as} \PYG{n+nn}{mt} - -\PYG{n}{z} \PYG{o}{=} \PYG{n}{numpy}\PYG{o}{.}\PYG{n}{arange}\PYG{p}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{5}\PYG{p}{,} \PYG{l+m+mi}{5}\PYG{p}{,} \PYG{l+m+mf}{.1}\PYG{p}{)} -\PYG{n}{sigma\PYGZus{}fn} \PYG{o}{=} \PYG{n}{numpy}\PYG{o}{.}\PYG{n}{vectorize}\PYG{p}{(}\PYG{k}{lambda} \PYG{n}{z}\PYG{p}{:} \PYG{l+m+mi}{1}\PYG{o}{/}\PYG{p}{(}\PYG{l+m+mi}{1}\PYG{o}{+}\PYG{n}{numpy}\PYG{o}{.}\PYG{n}{exp}\PYG{p}{(}\PYG{o}{\PYGZhy{}}\PYG{n}{z}\PYG{p}{)))} -\PYG{n}{sigma} \PYG{o}{=} \PYG{n}{sigma\PYGZus{}fn}\PYG{p}{(}\PYG{n}{z}\PYG{p}{)} - -\PYG{n}{fig} \PYG{o}{=} \PYG{n}{plt}\PYG{o}{.}\PYG{n}{figure}\PYG{p}{()} -\PYG{n}{ax} \PYG{o}{=} \PYG{n}{fig}\PYG{o}{.}\PYG{n}{add\PYGZus{}subplot}\PYG{p}{(}\PYG{l+m+mi}{111}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{plot}\PYG{p}{(}\PYG{n}{z}\PYG{p}{,} \PYG{n}{sigma}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}ylim}\PYG{p}{([}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{0.1}\PYG{p}{,} \PYG{l+m+mf}{1.1}\PYG{p}{])} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}xlim}\PYG{p}{([}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{5}\PYG{p}{,}\PYG{l+m+mi}{5}\PYG{p}{])} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{grid}\PYG{p}{(}\PYG{k+kc}{True}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}xlabel}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}z\PYGZsq{}}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}title}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}sigmoid function\PYGZsq{}}\PYG{p}{)} - -\PYG{n}{plt}\PYG{o}{.}\PYG{n}{show}\PYG{p}{()} - -\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}Step Function\PYGZdq{}\PYGZdq{}\PYGZdq{}} -\PYG{n}{z} \PYG{o}{=} \PYG{n}{numpy}\PYG{o}{.}\PYG{n}{arange}\PYG{p}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{5}\PYG{p}{,} \PYG{l+m+mi}{5}\PYG{p}{,} \PYG{l+m+mf}{.02}\PYG{p}{)} -\PYG{n}{step\PYGZus{}fn} \PYG{o}{=} \PYG{n}{numpy}\PYG{o}{.}\PYG{n}{vectorize}\PYG{p}{(}\PYG{k}{lambda} \PYG{n}{z}\PYG{p}{:} \PYG{l+m+mf}{1.0} \PYG{k}{if} \PYG{n}{z} \PYG{o}{\PYGZgt{}=} \PYG{l+m+mf}{0.0} \PYG{k}{else} \PYG{l+m+mf}{0.0}\PYG{p}{)} -\PYG{n}{step} \PYG{o}{=} \PYG{n}{step\PYGZus{}fn}\PYG{p}{(}\PYG{n}{z}\PYG{p}{)} - -\PYG{n}{fig} \PYG{o}{=} \PYG{n}{plt}\PYG{o}{.}\PYG{n}{figure}\PYG{p}{()} -\PYG{n}{ax} \PYG{o}{=} \PYG{n}{fig}\PYG{o}{.}\PYG{n}{add\PYGZus{}subplot}\PYG{p}{(}\PYG{l+m+mi}{111}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{plot}\PYG{p}{(}\PYG{n}{z}\PYG{p}{,} \PYG{n}{step}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}ylim}\PYG{p}{([}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{0.5}\PYG{p}{,} \PYG{l+m+mf}{1.5}\PYG{p}{])} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}xlim}\PYG{p}{([}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{5}\PYG{p}{,}\PYG{l+m+mi}{5}\PYG{p}{])} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{grid}\PYG{p}{(}\PYG{k+kc}{True}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}xlabel}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}z\PYGZsq{}}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}title}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}step function\PYGZsq{}}\PYG{p}{)} - -\PYG{n}{plt}\PYG{o}{.}\PYG{n}{show}\PYG{p}{()} - -\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}Sine Function\PYGZdq{}\PYGZdq{}\PYGZdq{}} -\PYG{n}{z} \PYG{o}{=} \PYG{n}{numpy}\PYG{o}{.}\PYG{n}{arange}\PYG{p}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{*}\PYG{n}{mt}\PYG{o}{.}\PYG{n}{pi}\PYG{p}{,} \PYG{l+m+mi}{2}\PYG{o}{*}\PYG{n}{mt}\PYG{o}{.}\PYG{n}{pi}\PYG{p}{,} \PYG{l+m+mf}{0.1}\PYG{p}{)} -\PYG{n}{t} \PYG{o}{=} \PYG{n}{numpy}\PYG{o}{.}\PYG{n}{sin}\PYG{p}{(}\PYG{n}{z}\PYG{p}{)} - -\PYG{n}{fig} \PYG{o}{=} \PYG{n}{plt}\PYG{o}{.}\PYG{n}{figure}\PYG{p}{()} -\PYG{n}{ax} \PYG{o}{=} \PYG{n}{fig}\PYG{o}{.}\PYG{n}{add\PYGZus{}subplot}\PYG{p}{(}\PYG{l+m+mi}{111}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{plot}\PYG{p}{(}\PYG{n}{z}\PYG{p}{,} \PYG{n}{t}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}ylim}\PYG{p}{([}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{1.0}\PYG{p}{,} \PYG{l+m+mf}{1.0}\PYG{p}{])} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}xlim}\PYG{p}{([}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{*}\PYG{n}{mt}\PYG{o}{.}\PYG{n}{pi}\PYG{p}{,}\PYG{l+m+mi}{2}\PYG{o}{*}\PYG{n}{mt}\PYG{o}{.}\PYG{n}{pi}\PYG{p}{])} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{grid}\PYG{p}{(}\PYG{k+kc}{True}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}xlabel}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}z\PYGZsq{}}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}title}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}sine function\PYGZsq{}}\PYG{p}{)} - -\PYG{n}{plt}\PYG{o}{.}\PYG{n}{show}\PYG{p}{()} - -\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}Plots a graph of the squashing function used by a rectified linear} -\PYG{l+s+sd}{unit\PYGZdq{}\PYGZdq{}\PYGZdq{}} -\PYG{n}{z} \PYG{o}{=} \PYG{n}{numpy}\PYG{o}{.}\PYG{n}{arange}\PYG{p}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{p}{,} \PYG{l+m+mi}{2}\PYG{p}{,} \PYG{l+m+mf}{.1}\PYG{p}{)} -\PYG{n}{zero} \PYG{o}{=} \PYG{n}{numpy}\PYG{o}{.}\PYG{n}{zeros}\PYG{p}{(}\PYG{n+nb}{len}\PYG{p}{(}\PYG{n}{z}\PYG{p}{))} -\PYG{n}{y} \PYG{o}{=} \PYG{n}{numpy}\PYG{o}{.}\PYG{n}{max}\PYG{p}{([}\PYG{n}{zero}\PYG{p}{,} \PYG{n}{z}\PYG{p}{],} \PYG{n}{axis}\PYG{o}{=}\PYG{l+m+mi}{0}\PYG{p}{)} - -\PYG{n}{fig} \PYG{o}{=} \PYG{n}{plt}\PYG{o}{.}\PYG{n}{figure}\PYG{p}{()} -\PYG{n}{ax} \PYG{o}{=} \PYG{n}{fig}\PYG{o}{.}\PYG{n}{add\PYGZus{}subplot}\PYG{p}{(}\PYG{l+m+mi}{111}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{plot}\PYG{p}{(}\PYG{n}{z}\PYG{p}{,} \PYG{n}{y}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}ylim}\PYG{p}{([}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{2.0}\PYG{p}{,} \PYG{l+m+mf}{2.0}\PYG{p}{])} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}xlim}\PYG{p}{([}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{2.0}\PYG{p}{,} \PYG{l+m+mf}{2.0}\PYG{p}{])} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{grid}\PYG{p}{(}\PYG{k+kc}{True}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}xlabel}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}z\PYGZsq{}}\PYG{p}{)} -\PYG{n}{ax}\PYG{o}{.}\PYG{n}{set\PYGZus{}title}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}Rectified linear unit\PYGZsq{}}\PYG{p}{)} - -\PYG{n}{plt}\PYG{o}{.}\PYG{n}{show}\PYG{p}{()} - -\end{Verbatim} diff --git a/doc/src/week41/_minted-week41/A94A396A1D27720ED5CDB1E3A9707FD7BBBAD84E10F49A5F4278A7252110B6CA.pygtex b/doc/src/week41/_minted-week41/A94A396A1D27720ED5CDB1E3A9707FD7BBBAD84E10F49A5F4278A7252110B6CA.pygtex deleted file mode 100644 index 7b771c08b..000000000 --- a/doc/src/week41/_minted-week41/A94A396A1D27720ED5CDB1E3A9707FD7BBBAD84E10F49A5F4278A7252110B6CA.pygtex +++ /dev/null @@ -1,33 +0,0 @@ -\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}] -\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}} -\PYG{l+s+sd}{Simple code that tests XOR, OR and AND gates with linear regression} -\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}} - -\PYG{k+kn}{import} \PYG{n+nn}{numpy} \PYG{k}{as} \PYG{n+nn}{np} -\PYG{c+c1}{\PYGZsh{} Design matrix} -\PYG{n}{X} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{([} \PYG{p}{[}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{],} \PYG{p}{[}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{],} \PYG{p}{[}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{],[}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{]],}\PYG{n}{dtype}\PYG{o}{=}\PYG{n}{np}\PYG{o}{.}\PYG{n}{float64}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The X.TX matrix:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{X}\PYG{o}{.}\PYG{n}{T}\PYG{+w}{ }\PYG{o}{@}\PYG{+w}{ }\PYG{n}{X}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} -\PYG{n}{Xinv} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{linalg}\PYG{o}{.}\PYG{n}{pinv}\PYG{p}{(}\PYG{n}{X}\PYG{o}{.}\PYG{n}{T} \PYG{o}{@} \PYG{n}{X}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The invers of X.TX matrix:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{Xinv}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} - -\PYG{c+c1}{\PYGZsh{} The XOR gate} -\PYG{n}{yXOR} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{(} \PYG{p}{[} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{1} \PYG{p}{,}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{0}\PYG{p}{])} -\PYG{n}{ThetaXOR} \PYG{o}{=} \PYG{n}{Xinv} \PYG{o}{@} \PYG{n}{X}\PYG{o}{.}\PYG{n}{T} \PYG{o}{@} \PYG{n}{yXOR} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The values of theta for the XOR gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{ThetaXOR}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The linear regression prediction for the XOR gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{X}\PYG{+w}{ }\PYG{o}{@}\PYG{+w}{ }\PYG{n}{ThetaXOR}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} - - -\PYG{c+c1}{\PYGZsh{} The OR gate} -\PYG{n}{yOR} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{(} \PYG{p}{[} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{1} \PYG{p}{,}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{])} -\PYG{n}{ThetaOR} \PYG{o}{=} \PYG{n}{Xinv} \PYG{o}{@} \PYG{n}{X}\PYG{o}{.}\PYG{n}{T} \PYG{o}{@} \PYG{n}{yOR} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The values of theta for the OR gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{ThetaOR}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The linear regression prediction for the OR gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{X}\PYG{+w}{ }\PYG{o}{@}\PYG{+w}{ }\PYG{n}{ThetaOR}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} - - -\PYG{c+c1}{\PYGZsh{} The OR gate} -\PYG{n}{yAND} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{(} \PYG{p}{[} \PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{0} \PYG{p}{,}\PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{])} -\PYG{n}{ThetaAND} \PYG{o}{=} \PYG{n}{Xinv} \PYG{o}{@} \PYG{n}{X}\PYG{o}{.}\PYG{n}{T} \PYG{o}{@} \PYG{n}{yAND} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The values of theta for the AND gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{ThetaAND}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}The linear regression prediction for the AND gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{X}\PYG{+w}{ }\PYG{o}{@}\PYG{+w}{ }\PYG{n}{ThetaAND}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} - -\end{Verbatim} diff --git a/doc/src/week41/_minted-week41/FAB7E87618A8A8AABAD77C666F19DDCDBBBAD84E10F49A5F4278A7252110B6CA.pygtex b/doc/src/week41/_minted-week41/FAB7E87618A8A8AABAD77C666F19DDCDBBBAD84E10F49A5F4278A7252110B6CA.pygtex deleted file mode 100644 index dad239c12..000000000 --- a/doc/src/week41/_minted-week41/FAB7E87618A8A8AABAD77C666F19DDCDBBBAD84E10F49A5F4278A7252110B6CA.pygtex +++ /dev/null @@ -1,13 +0,0 @@ -\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}] - -\PYG{c+c1}{\PYGZsh{} and now neural networks with Scikit\PYGZhy{}Learn and the XOR} - -\PYG{k+kn}{from} \PYG{n+nn}{sklearn.neural\PYGZus{}network} \PYG{k+kn}{import} \PYG{n}{MLPClassifier} -\PYG{k+kn}{from} \PYG{n+nn}{sklearn.datasets} \PYG{k+kn}{import} \PYG{n}{make\PYGZus{}classification} -\PYG{n}{X}\PYG{p}{,} \PYG{n}{yXOR} \PYG{o}{=} \PYG{n}{make\PYGZus{}classification}\PYG{p}{(}\PYG{n}{n\PYGZus{}samples}\PYG{o}{=}\PYG{l+m+mi}{100}\PYG{p}{,} \PYG{n}{random\PYGZus{}state}\PYG{o}{=}\PYG{l+m+mi}{1}\PYG{p}{)} -\PYG{n}{FFNN} \PYG{o}{=} \PYG{n}{MLPClassifier}\PYG{p}{(}\PYG{n}{random\PYGZus{}state}\PYG{o}{=}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{n}{max\PYGZus{}iter}\PYG{o}{=}\PYG{l+m+mi}{300}\PYG{p}{)}\PYG{o}{.}\PYG{n}{fit}\PYG{p}{(}\PYG{n}{X}\PYG{p}{,} \PYG{n}{yXOR}\PYG{p}{)} -\PYG{n}{FFNN}\PYG{o}{.}\PYG{n}{predict\PYGZus{}proba}\PYG{p}{(}\PYG{n}{X}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}Test set accuracy with Feed Forward Neural Network for XOR gate:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{FFNN}\PYG{o}{.}\PYG{n}{score}\PYG{p}{(}\PYG{n}{X}\PYG{p}{,}\PYG{+w}{ }\PYG{n}{yXOR}\PYG{p}{)}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} - - -\end{Verbatim} diff --git a/doc/src/week41/_minted-week41/FD9F88E66D9E5A715D98B8D276C06052BBBAD84E10F49A5F4278A7252110B6CA.pygtex b/doc/src/week41/_minted-week41/FD9F88E66D9E5A715D98B8D276C06052BBBAD84E10F49A5F4278A7252110B6CA.pygtex deleted file mode 100644 index d6b07fb6b..000000000 --- a/doc/src/week41/_minted-week41/FD9F88E66D9E5A715D98B8D276C06052BBBAD84E10F49A5F4278A7252110B6CA.pygtex +++ /dev/null @@ -1,67 +0,0 @@ -\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}] -\PYG{k+kn}{import} \PYG{n+nn}{numpy} \PYG{k}{as} \PYG{n+nn}{np} -\PYG{c+c1}{\PYGZsh{} We use the Sigmoid function as activation function} -\PYG{k}{def} \PYG{n+nf}{sigmoid}\PYG{p}{(}\PYG{n}{z}\PYG{p}{):} - \PYG{k}{return} \PYG{l+m+mf}{1.0}\PYG{o}{/}\PYG{p}{(}\PYG{l+m+mf}{1.0}\PYG{o}{+}\PYG{n}{np}\PYG{o}{.}\PYG{n}{exp}\PYG{p}{(}\PYG{o}{\PYGZhy{}}\PYG{n}{z}\PYG{p}{))} - -\PYG{k}{def} \PYG{n+nf}{forwardpropagation}\PYG{p}{(}\PYG{n}{x}\PYG{p}{):} - \PYG{c+c1}{\PYGZsh{} weighted sum of inputs to the hidden layer} - \PYG{n}{z\PYGZus{}1} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{x}\PYG{p}{,} \PYG{n}{w\PYGZus{}1}\PYG{p}{)} \PYG{o}{+} \PYG{n}{b\PYGZus{}1} - \PYG{c+c1}{\PYGZsh{} activation in the hidden layer} - \PYG{n}{a\PYGZus{}1} \PYG{o}{=} \PYG{n}{sigmoid}\PYG{p}{(}\PYG{n}{z\PYGZus{}1}\PYG{p}{)} - \PYG{c+c1}{\PYGZsh{} weighted sum of inputs to the output layer} - \PYG{n}{z\PYGZus{}2} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{a\PYGZus{}1}\PYG{p}{,} \PYG{n}{w\PYGZus{}2}\PYG{p}{)} \PYG{o}{+} \PYG{n}{b\PYGZus{}2} - \PYG{n}{a\PYGZus{}2} \PYG{o}{=} \PYG{n}{z\PYGZus{}2} - \PYG{k}{return} \PYG{n}{a\PYGZus{}1}\PYG{p}{,} \PYG{n}{a\PYGZus{}2} - -\PYG{k}{def} \PYG{n+nf}{backpropagation}\PYG{p}{(}\PYG{n}{x}\PYG{p}{,} \PYG{n}{y}\PYG{p}{):} - \PYG{n}{a\PYGZus{}1}\PYG{p}{,} \PYG{n}{a\PYGZus{}2} \PYG{o}{=} \PYG{n}{forwardpropagation}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)} - \PYG{c+c1}{\PYGZsh{} parameter delta for the output layer, note that a\PYGZus{}2=z\PYGZus{}2 and its derivative wrt z\PYGZus{}2 is just 1} - \PYG{n}{delta\PYGZus{}2} \PYG{o}{=} \PYG{n}{a\PYGZus{}2} \PYG{o}{\PYGZhy{}} \PYG{n}{y} - \PYG{n+nb}{print}\PYG{p}{(}\PYG{l+m+mf}{0.5}\PYG{o}{*}\PYG{p}{((}\PYG{n}{a\PYGZus{}2}\PYG{o}{\PYGZhy{}}\PYG{n}{y}\PYG{p}{)}\PYG{o}{**}\PYG{l+m+mi}{2}\PYG{p}{))} - \PYG{c+c1}{\PYGZsh{} delta for the hidden layer} - \PYG{n}{delta\PYGZus{}1} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{delta\PYGZus{}2}\PYG{p}{,} \PYG{n}{w\PYGZus{}2}\PYG{o}{.}\PYG{n}{T}\PYG{p}{)} \PYG{o}{*} \PYG{n}{a\PYGZus{}1} \PYG{o}{*} \PYG{p}{(}\PYG{l+m+mi}{1} \PYG{o}{\PYGZhy{}} \PYG{n}{a\PYGZus{}1}\PYG{p}{)} - \PYG{c+c1}{\PYGZsh{} gradients for the output layer} - \PYG{n}{output\PYGZus{}weights\PYGZus{}gradient} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{a\PYGZus{}1}\PYG{o}{.}\PYG{n}{T}\PYG{p}{,} \PYG{n}{delta\PYGZus{}2}\PYG{p}{)} - \PYG{n}{output\PYGZus{}bias\PYGZus{}gradient} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{sum}\PYG{p}{(}\PYG{n}{delta\PYGZus{}2}\PYG{p}{,} \PYG{n}{axis}\PYG{o}{=}\PYG{l+m+mi}{0}\PYG{p}{)} - \PYG{c+c1}{\PYGZsh{} gradient for the hidden layer} - \PYG{n}{hidden\PYGZus{}weights\PYGZus{}gradient} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{matmul}\PYG{p}{(}\PYG{n}{x}\PYG{o}{.}\PYG{n}{T}\PYG{p}{,} \PYG{n}{delta\PYGZus{}1}\PYG{p}{)} - \PYG{n}{hidden\PYGZus{}bias\PYGZus{}gradient} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{sum}\PYG{p}{(}\PYG{n}{delta\PYGZus{}1}\PYG{p}{,} \PYG{n}{axis}\PYG{o}{=}\PYG{l+m+mi}{0}\PYG{p}{)} - \PYG{k}{return} \PYG{n}{output\PYGZus{}weights\PYGZus{}gradient}\PYG{p}{,} \PYG{n}{output\PYGZus{}bias\PYGZus{}gradient}\PYG{p}{,} \PYG{n}{hidden\PYGZus{}weights\PYGZus{}gradient}\PYG{p}{,} \PYG{n}{hidden\PYGZus{}bias\PYGZus{}gradient} - - -\PYG{c+c1}{\PYGZsh{} ensure the same random numbers appear every time} -\PYG{n}{np}\PYG{o}{.}\PYG{n}{random}\PYG{o}{.}\PYG{n}{seed}\PYG{p}{(}\PYG{l+m+mi}{0}\PYG{p}{)} -\PYG{c+c1}{\PYGZsh{} Input variable} -\PYG{n}{x} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{array}\PYG{p}{([}\PYG{l+m+mf}{4.0}\PYG{p}{],}\PYG{n}{dtype}\PYG{o}{=}\PYG{n}{np}\PYG{o}{.}\PYG{n}{float64}\PYG{p}{)} -\PYG{c+c1}{\PYGZsh{} Target values} -\PYG{n}{y} \PYG{o}{=} \PYG{l+m+mi}{2}\PYG{o}{*}\PYG{n}{x}\PYG{o}{+}\PYG{l+m+mf}{1.0} - -\PYG{c+c1}{\PYGZsh{} Defining the neural network, only scalars here} -\PYG{n}{n\PYGZus{}inputs} \PYG{o}{=} \PYG{n}{x}\PYG{o}{.}\PYG{n}{shape} -\PYG{n}{n\PYGZus{}features} \PYG{o}{=} \PYG{l+m+mi}{1} -\PYG{n}{n\PYGZus{}hidden\PYGZus{}neurons} \PYG{o}{=} \PYG{l+m+mi}{1} -\PYG{n}{n\PYGZus{}outputs} \PYG{o}{=} \PYG{l+m+mi}{1} - -\PYG{c+c1}{\PYGZsh{} Initialize the network} -\PYG{c+c1}{\PYGZsh{} weights and bias in the hidden layer} -\PYG{n}{w\PYGZus{}1} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{random}\PYG{o}{.}\PYG{n}{randn}\PYG{p}{(}\PYG{n}{n\PYGZus{}features}\PYG{p}{,} \PYG{n}{n\PYGZus{}hidden\PYGZus{}neurons}\PYG{p}{)} -\PYG{n}{b\PYGZus{}1} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{zeros}\PYG{p}{(}\PYG{n}{n\PYGZus{}hidden\PYGZus{}neurons}\PYG{p}{)} \PYG{o}{+} \PYG{l+m+mf}{0.01} - -\PYG{c+c1}{\PYGZsh{} weights and bias in the output layer} -\PYG{n}{w\PYGZus{}2} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{random}\PYG{o}{.}\PYG{n}{randn}\PYG{p}{(}\PYG{n}{n\PYGZus{}hidden\PYGZus{}neurons}\PYG{p}{,} \PYG{n}{n\PYGZus{}outputs}\PYG{p}{)} -\PYG{n}{b\PYGZus{}2} \PYG{o}{=} \PYG{n}{np}\PYG{o}{.}\PYG{n}{zeros}\PYG{p}{(}\PYG{n}{n\PYGZus{}outputs}\PYG{p}{)} \PYG{o}{+} \PYG{l+m+mf}{0.01} - -\PYG{n}{eta} \PYG{o}{=} \PYG{l+m+mf}{0.1} -\PYG{k}{for} \PYG{n}{i} \PYG{o+ow}{in} \PYG{n+nb}{range}\PYG{p}{(}\PYG{l+m+mi}{50}\PYG{p}{):} - \PYG{c+c1}{\PYGZsh{} calculate gradients} - \PYG{n}{derivW2}\PYG{p}{,} \PYG{n}{derivB2}\PYG{p}{,} \PYG{n}{derivW1}\PYG{p}{,} \PYG{n}{derivB1} \PYG{o}{=} \PYG{n}{backpropagation}\PYG{p}{(}\PYG{n}{x}\PYG{p}{,} \PYG{n}{y}\PYG{p}{)} - \PYG{c+c1}{\PYGZsh{} update weights and biases} - \PYG{n}{w\PYGZus{}2} \PYG{o}{\PYGZhy{}=} \PYG{n}{eta} \PYG{o}{*} \PYG{n}{derivW2} - \PYG{n}{b\PYGZus{}2} \PYG{o}{\PYGZhy{}=} \PYG{n}{eta} \PYG{o}{*} \PYG{n}{derivB2} - \PYG{n}{w\PYGZus{}1} \PYG{o}{\PYGZhy{}=} \PYG{n}{eta} \PYG{o}{*} \PYG{n}{derivW1} - \PYG{n}{b\PYGZus{}1} \PYG{o}{\PYGZhy{}=} \PYG{n}{eta} \PYG{o}{*} \PYG{n}{derivB1} - - - -\end{Verbatim} diff --git a/doc/src/week41/_minted-week41/FDA896CDD8BFB6D38F791E78B364721CBBBAD84E10F49A5F4278A7252110B6CA.pygtex b/doc/src/week41/_minted-week41/FDA896CDD8BFB6D38F791E78B364721CBBBAD84E10F49A5F4278A7252110B6CA.pygtex deleted file mode 100644 index e311a8a9b..000000000 --- a/doc/src/week41/_minted-week41/FDA896CDD8BFB6D38F791E78B364721CBBBAD84E10F49A5F4278A7252110B6CA.pygtex +++ /dev/null @@ -1,11 +0,0 @@ -\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8\relax}] -\PYG{k+kn}{from} \PYG{n+nn}{\PYGZus{}\PYGZus{}future\PYGZus{}\PYGZus{}} \PYG{k+kn}{import} \PYG{n}{division} -\PYG{k+kn}{from} \PYG{n+nn}{sympy} \PYG{k+kn}{import} \PYG{o}{*} -\PYG{n}{x} \PYG{o}{=} \PYG{n}{symbols}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}x\PYGZsq{}}\PYG{p}{)} -\PYG{n}{expr} \PYG{o}{=} \PYG{n}{exp}\PYG{p}{(}\PYG{n}{x}\PYG{o}{*}\PYG{n}{x}\PYG{p}{)} -\PYG{n}{simplify}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{)} -\PYG{n}{derivative} \PYG{o}{=} \PYG{n}{diff}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{,}\PYG{n}{x}\PYG{p}{)} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{python}\PYG{p}{(}\PYG{n}{expr}\PYG{p}{))} -\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{python}\PYG{p}{(}\PYG{n}{derivative}\PYG{p}{))} - -\end{Verbatim} diff --git a/doc/src/week41/_minted-week41/default.pygstyle b/doc/src/week41/_minted-week41/default.pygstyle deleted file mode 100644 index 211763d1d..000000000 --- a/doc/src/week41/_minted-week41/default.pygstyle +++ /dev/null @@ -1,101 +0,0 @@ - -\makeatletter -\def\PYG@reset{\let\PYG@it=\relax \let\PYG@bf=\relax% - \let\PYG@ul=\relax \let\PYG@tc=\relax% - \let\PYG@bc=\relax \let\PYG@ff=\relax} -\def\PYG@tok#1{\csname PYG@tok@#1\endcsname} -\def\PYG@toks#1+{\ifx\relax#1\empty\else% - \PYG@tok{#1}\expandafter\PYG@toks\fi} -\def\PYG@do#1{\PYG@bc{\PYG@tc{\PYG@ul{% - \PYG@it{\PYG@bf{\PYG@ff{#1}}}}}}} -\def\PYG#1#2{\PYG@reset\PYG@toks#1+\relax+\PYG@do{#2}} - -\@namedef{PYG@tok@w}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.73,0.73}{##1}}} -\@namedef{PYG@tok@c}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}} -\@namedef{PYG@tok@cp}{\def\PYG@tc##1{\textcolor[rgb]{0.61,0.40,0.00}{##1}}} -\@namedef{PYG@tok@k}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@kp}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@kt}{\def\PYG@tc##1{\textcolor[rgb]{0.69,0.00,0.25}{##1}}} -\@namedef{PYG@tok@o}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} -\@namedef{PYG@tok@ow}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}} -\@namedef{PYG@tok@nb}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@nf}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}} -\@namedef{PYG@tok@nc}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}} -\@namedef{PYG@tok@nn}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}} -\@namedef{PYG@tok@ne}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.80,0.25,0.22}{##1}}} -\@namedef{PYG@tok@nv}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} -\@namedef{PYG@tok@no}{\def\PYG@tc##1{\textcolor[rgb]{0.53,0.00,0.00}{##1}}} -\@namedef{PYG@tok@nl}{\def\PYG@tc##1{\textcolor[rgb]{0.46,0.46,0.00}{##1}}} -\@namedef{PYG@tok@ni}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.44,0.44,0.44}{##1}}} -\@namedef{PYG@tok@na}{\def\PYG@tc##1{\textcolor[rgb]{0.41,0.47,0.13}{##1}}} -\@namedef{PYG@tok@nt}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@nd}{\def\PYG@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}} -\@namedef{PYG@tok@s}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} -\@namedef{PYG@tok@sd}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} -\@namedef{PYG@tok@si}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.64,0.35,0.47}{##1}}} -\@namedef{PYG@tok@se}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.67,0.36,0.12}{##1}}} -\@namedef{PYG@tok@sr}{\def\PYG@tc##1{\textcolor[rgb]{0.64,0.35,0.47}{##1}}} -\@namedef{PYG@tok@ss}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} -\@namedef{PYG@tok@sx}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@m}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} -\@namedef{PYG@tok@gh}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}} -\@namedef{PYG@tok@gu}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.50,0.00,0.50}{##1}}} -\@namedef{PYG@tok@gd}{\def\PYG@tc##1{\textcolor[rgb]{0.63,0.00,0.00}{##1}}} -\@namedef{PYG@tok@gi}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.52,0.00}{##1}}} -\@namedef{PYG@tok@gr}{\def\PYG@tc##1{\textcolor[rgb]{0.89,0.00,0.00}{##1}}} -\@namedef{PYG@tok@ge}{\let\PYG@it=\textit} -\@namedef{PYG@tok@gs}{\let\PYG@bf=\textbf} -\@namedef{PYG@tok@gp}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}} -\@namedef{PYG@tok@go}{\def\PYG@tc##1{\textcolor[rgb]{0.44,0.44,0.44}{##1}}} -\@namedef{PYG@tok@gt}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.27,0.87}{##1}}} -\@namedef{PYG@tok@err}{\def\PYG@bc##1{{\setlength{\fboxsep}{\string -\fboxrule}\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}} -\@namedef{PYG@tok@kc}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@kd}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@kn}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@kr}{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@bp}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} -\@namedef{PYG@tok@fm}{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}} -\@namedef{PYG@tok@vc}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} -\@namedef{PYG@tok@vg}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} -\@namedef{PYG@tok@vi}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} -\@namedef{PYG@tok@vm}{\def\PYG@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} -\@namedef{PYG@tok@sa}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} -\@namedef{PYG@tok@sb}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} -\@namedef{PYG@tok@sc}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} -\@namedef{PYG@tok@dl}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} -\@namedef{PYG@tok@s2}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} -\@namedef{PYG@tok@sh}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} -\@namedef{PYG@tok@s1}{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} -\@namedef{PYG@tok@mb}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} -\@namedef{PYG@tok@mf}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} -\@namedef{PYG@tok@mh}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} -\@namedef{PYG@tok@mi}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} -\@namedef{PYG@tok@il}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} -\@namedef{PYG@tok@mo}{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} -\@namedef{PYG@tok@ch}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}} -\@namedef{PYG@tok@cm}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}} -\@namedef{PYG@tok@cpf}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}} -\@namedef{PYG@tok@c1}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}} -\@namedef{PYG@tok@cs}{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.24,0.48,0.48}{##1}}} - -\def\PYGZbs{\char`\\} -\def\PYGZus{\char`\_} -\def\PYGZob{\char`\{} -\def\PYGZcb{\char`\}} -\def\PYGZca{\char`\^} -\def\PYGZam{\char`\&} -\def\PYGZlt{\char`\<} -\def\PYGZgt{\char`\>} -\def\PYGZsh{\char`\#} -\def\PYGZpc{\char`\%} -\def\PYGZdl{\char`\$} -\def\PYGZhy{\char`\-} -\def\PYGZsq{\char`\'} -\def\PYGZdq{\char`\"} -\def\PYGZti{\char`\~} -% for compatibility with earlier versions -\def\PYGZat{@} -\def\PYGZlb{[} -\def\PYGZrb{]} -\makeatother - diff --git a/doc/src/week41/ipynb-week41-src.tar.gz b/doc/src/week41/ipynb-week41-src.tar.gz deleted file mode 100644 index fd2fe62c3..000000000 Binary files a/doc/src/week41/ipynb-week41-src.tar.gz and /dev/null differ diff --git a/doc/src/week41/reveal.js/.gitignore b/doc/src/week41/reveal.js/.gitignore deleted file mode 100644 index a5df3133d..000000000 --- a/doc/src/week41/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/week41/reveal.js/.travis.yml b/doc/src/week41/reveal.js/.travis.yml deleted file mode 100644 index 165d9ae9f..000000000 --- a/doc/src/week41/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/week41/reveal.js/CONTRIBUTING.md b/doc/src/week41/reveal.js/CONTRIBUTING.md deleted file mode 100644 index c2091e88f..000000000 --- a/doc/src/week41/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/week41/reveal.js/Gruntfile.js b/doc/src/week41/reveal.js/Gruntfile.js deleted file mode 100644 index b257e8f32..000000000 --- a/doc/src/week41/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/week41/reveal.js/LICENSE b/doc/src/week41/reveal.js/LICENSE deleted file mode 100644 index 09623076f..000000000 --- a/doc/src/week41/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/week41/reveal.js/README.md b/doc/src/week41/reveal.js/README.md deleted file mode 100644 index 573b19597..000000000 --- a/doc/src/week41/reveal.js/README.md +++ /dev/null @@ -1,1052 +0,0 @@ -# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) - -A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). - -reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. - - -#### More reading: -- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. -- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. -- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! -- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. -- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. - -## Online Editor - -Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). - - -## Instructions - -### Markup - -Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: - -```html -
-
-
Single Horizontal Slide
-
-
Vertical Slide 1
-
Vertical Slide 2
-
-
-
-``` - -### Markdown - -It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` -
-``` - -#### External Markdown - -You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. - -When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). - -```html -
-
-``` - -#### Element Attributes - -Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. - -```html -
- -
-``` - -#### Slide Attributes - -Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. - -```html -
- -
-``` - - -### Configuration - -At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. - -```javascript -Reveal.initialize({ - - // Display controls in the bottom right corner - controls: true, - - // Display a presentation progress bar - progress: true, - - // Display the page number of the current slide - slideNumber: false, - - // Push each slide change to the browser history - history: false, - - // Enable keyboard shortcuts for navigation - keyboard: true, - - // Enable the slide overview mode - overview: true, - - // Vertical centering of slides - center: true, - - // Enables touch navigation on devices with touch input - touch: true, - - // Loop the presentation - loop: false, - - // Change the presentation direction to be RTL - rtl: false, - - // Turns fragments on and off globally - fragments: true, - - // Flags if the presentation is running in an embedded mode, - // i.e. contained within a limited portion of the screen - embedded: false, - - // Flags if we should show a help overlay when the questionmark - // key is pressed - help: true, - - // Number of milliseconds between automatically proceeding to the - // next slide, disabled when set to 0, this value can be overwritten - // by using a data-autoslide attribute on your slides - autoSlide: 0, - - // Stop auto-sliding after user input - autoSlideStoppable: true, - - // Enable slide navigation via mouse wheel - mouseWheel: false, - - // Hides the address bar on mobile devices - hideAddressBar: true, - - // Opens links in an iframe preview overlay - previewLinks: false, - - // Transition style - transition: 'default', // none/fade/slide/convex/concave/zoom - - // Transition speed - transitionSpeed: 'default', // default/fast/slow - - // Transition style for full page slide backgrounds - backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom - - // Number of slides away from the current that are visible - viewDistance: 3, - - // Parallax background image - parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - - // Amount to move parallax background (horizontal and vertical) on slide change - // Number, e.g. 100 - parallaxBackgroundHorizontal: '', - parallaxBackgroundVertical: '' - -}); -``` - - -The configuration can be updated after initialization using the ```configure``` method: - -```javascript -// Turn autoSlide off -Reveal.configure({ autoSlide: 0 }); - -// Start auto-sliding every 5s -Reveal.configure({ autoSlide: 5000 }); -``` - - -### Dependencies - -Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: - -```javascript -Reveal.initialize({ - dependencies: [ - // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ - { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, - - // Interpret Markdown in
elements - { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - - // Syntax highlight for elements - { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, - - // Zoom in and out with Alt+click - { src: 'plugin/zoom-js/zoom.js', async: true }, - - // Speaker notes - { src: 'plugin/notes/notes.js', async: true }, - - // Remote control your reveal.js presentation using a touch device - { src: 'plugin/remotes/remotes.js', async: true }, - - // MathJax - { src: 'plugin/math/math.js', async: true } - ] -}); -``` - -You can add your own extensions using the same syntax. The following properties are available for each dependency object: -- **src**: Path to the script to load -- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false -- **callback**: [optional] Function to execute when the script has loaded -- **condition**: [optional] Function which must return true for the script to be loaded - - -### Ready Event - -A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. - -```javascript -Reveal.addEventListener( 'ready', function( event ) { - // event.currentSlide, event.indexh, event.indexv -} ); -``` - - -### Presentation Size - -All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. - -See below for a list of configuration options related to sizing, including default values: - -```javascript -Reveal.initialize({ - - ... - - // The "normal" size of the presentation, aspect ratio will be preserved - // when the presentation is scaled to fit different resolutions. Can be - // specified using percentage units. - width: 960, - height: 700, - - // Factor of the display size that should remain empty around the content - margin: 0.1, - - // Bounds for smallest/largest possible scale to apply to content - minScale: 0.2, - maxScale: 1.5 - -}); -``` - - -### Auto-sliding - -Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: - -```javascript -// Slide every five seconds -Reveal.configure({ - autoSlide: 5000 -}); -``` -When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. - -You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: - -```html -
-

After 2 seconds the first fragment will be shown.

-

After 10 seconds the next fragment will be shown.

-

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

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

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

-
-
-

This slide will have a full-size background image.

-
-
-

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

-
-
-

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

-
-
-

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

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

This slide will override the presentation transition and zoom!

-
- -
-

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

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

grow

-

shrink

-

fade-out

-

visible only once

-

blue only once

-

highlight-red

-

highlight-green

-

highlight-blue

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

Appears last

-

Appears first

-

Appears second

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

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

 

 

 

- -
-
-

Week 41 Neural networks and constructing a neural network code

-
- - -
-Morten Hjorth-Jensen -
- -
-Department of Physics, University of Oslo -
-
-
-

Week 41

-
-
- - -
- - -

Plan for week 41, October 7-11

- - -

Material for the lecture on Monday October 7, 2024

-
    -
  1. Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
  2. -
  3. Building our own Feed-forward Neural Network - -
  4. -
-
-
- -
    -
  1. These lecture notes
  2. -
  3. Rashcka et al chapter 11
  4. -
  5. For neural networks we recommend Goodfellow et al chapter 6. -
      -
    1. Neural Networks demystified at https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs
    2. -
    -
  6. Building Neural Networks from scratch at https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex
  7. -
  8. Video on Neural Networks at https://www.youtube.com/watch?v=CqOfi41LfDw
  9. -
  10. Video on the back propagation algorithm at https://www.youtube.com/watch?v=Ilg3gGewQ5U
  11. -
-

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

-
-
- - - -

Material for the active learning sessions on Tuesday and Wednesday

-
    -
  • Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation
  • -
  • One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code
  • -
  • Discussion of project 2
  • -
  • Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent
  • -
- -

Lecture Monday October 7

- - -

Introduction to Neural networks

- -

Artificial neural networks are computational systems that can learn to -perform tasks by considering examples, generally without being -programmed with any task-specific rules. It is supposed to mimic a -biological system, wherein neurons interact by sending signals in the -form of mathematical functions between layers. All layers can contain -an arbitrary number of neurons, and each connection is represented by -a weight variable. -

- - -

Artificial neurons

- -

The field of artificial neural networks has a long history of -development, and is closely connected with the advancement of computer -science and computers in general. A model of artificial neurons was -first developed by McCulloch and Pitts in 1943 to study signal -processing in the brain and has later been refined by others. The -general idea is to mimic neural networks in the human brain, which is -composed of billions of neurons that communicate with each other by -sending electrical signals. Each neuron accumulates its incoming -signals, which must exceed an activation threshold to yield an -output. If the threshold is not overcome, the neuron remains inactive, -i.e. has zero output. -

- -

This behaviour has inspired a simple mathematical model for an artificial neuron.

- -$$ -\begin{equation} - y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u) -\label{artificialNeuron} -\end{equation} -$$ - -

Here, the output \( y \) of the neuron is the value of its activation function, which have as input -a weighted sum of signals \( x_i, \dots ,x_n \) received by \( n \) other neurons. -

- -

Conceptually, it is helpful to divide neural networks into four -categories: -

-
    -
  1. general purpose neural networks for supervised learning,
  2. -
  3. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),
  4. -
  5. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and
  6. -
  7. neural networks for unsupervised learning such as Deep Boltzmann Machines.
  8. -
-

In natural science, DNNs and CNNs have already found numerous -applications. In statistical physics, they have been applied to detect -phase transitions in 2D Ising and Potts models, lattice gauge -theories, and different phases of polymers, or solving the -Navier-Stokes equation in weather forecasting. Deep learning has also -found interesting applications in quantum physics. Various quantum -phase transitions can be detected and studied using DNNs and CNNs, -topological phases, and even non-equilibrium many-body -localization. Representing quantum states as DNNs quantum state -tomography are among some of the impressive achievements to reveal the -potential of DNNs to facilitate the study of quantum systems. -

- -

In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. -

- -

The applications are not limited to the natural sciences. There is a -plethora of applications in essentially all disciplines, from the -humanities to life science and medicine. -

- - -

Neural network types

- -

An artificial neural network (ANN), is a computational model that -consists of layers of connected neurons, or nodes or units. We will -refer to these interchangeably as units or nodes, and sometimes as -neurons. -

- -

It is supposed to mimic a biological nervous system by letting each -neuron interact with other neurons by sending signals in the form of -mathematical functions between layers. A wide variety of different -ANNs have been developed, but most of them consist of an input layer, -an output layer and eventual layers in-between, called hidden -layers. All layers can contain an arbitrary number of nodes, and each -connection between two nodes is associated with a weight variable. -

- -

Neural networks (also called neural nets) are neural-inspired -nonlinear models for supervised learning. As we will see, neural nets -can be viewed as natural, more powerful extensions of supervised -learning methods such as linear and logistic regression and soft-max -methods we discussed earlier. -

- - -

Feed-forward neural networks

- -

The feed-forward neural network (FFNN) was the first and simplest type -of ANNs that were devised. In this network, the information moves in -only one direction: forward through the layers. -

- -

Nodes are represented by circles, while the arrows display the -connections between the nodes, including the direction of information -flow. Additionally, each arrow corresponds to a weight variable -(figure to come). We observe that each node in a layer is connected -to all nodes in the subsequent layer, making this a so-called -fully-connected FFNN. -

- - -

Convolutional Neural Network

- -

A different variant of FFNNs are convolutional neural networks -(CNNs), which have a connectivity pattern inspired by the animal -visual cortex. Individual neurons in the visual cortex only respond to -stimuli from small sub-regions of the visual field, called a receptive -field. This makes the neurons well-suited to exploit the strong -spatially local correlation present in natural images. The response of -each neuron can be approximated mathematically as a convolution -operation. (figure to come) -

- -

Convolutional neural networks emulate the behaviour of neurons in the -visual cortex by enforcing a local connectivity pattern between -nodes of adjacent layers: Each node in a convolutional layer is -connected only to a subset of the nodes in the previous layer, in -contrast to the fully-connected FFNN. Often, CNNs consist of several -convolutional layers that learn local features of the input, with a -fully-connected layer at the end, which gathers all the local data and -produces the outputs. They have wide applications in image and video -recognition. -

- - -

Recurrent neural networks

- -

So far we have only mentioned ANNs where information flows in one -direction: forward. Recurrent neural networks on the other hand, -have connections between nodes that form directed cycles. This -creates a form of internal memory which are able to capture -information on what has been calculated before; the output is -dependent on the previous computations. Recurrent NNs make use of -sequential information by performing the same task for every element -in a sequence, where each element depends on previous elements. An -example of such information is sentences, making recurrent NNs -especially well-suited for handwriting and speech recognition. -

- - -

Other types of networks

- -

There are many other kinds of ANNs that have been developed. One type -that is specifically designed for interpolation in multidimensional -space is the radial basis function (RBF) network. RBFs are typically -made up of three layers: an input layer, a hidden layer with -non-linear radial symmetric activation functions and a linear output -layer (''linear'' here means that each node in the output layer has a -linear activation function). The layers are normally fully-connected -and there are no cycles, thus RBFs can be viewed as a type of -fully-connected FFNN. They are however usually treated as a separate -type of NN due the unusual activation functions. -

- - -

Multilayer perceptrons

- -

One uses often so-called fully-connected feed-forward neural networks -with three or more layers (an input layer, one or more hidden layers -and an output layer) consisting of neurons that have non-linear -activation functions. -

- -

Such networks are often called multilayer perceptrons (MLPs).

- - -

Why multilayer perceptrons?

- -

According to the Universal approximation theorem, a feed-forward -neural network with just a single hidden layer containing a finite -number of neurons can approximate a continuous multidimensional -function to arbitrary accuracy, assuming the activation function for -the hidden layer is a non-constant, bounded and -monotonically-increasing continuous function. -

- -

Note that the requirements on the activation function only applies to -the hidden layer, the output nodes are always assumed to be linear, so -as to not restrict the range of output values. -

- - -

Illustration of a single perceptron model and a multi-perceptron model

- -
-
-
-

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

-
-

-
- - -

Examples of XOR, OR and AND gates

- -

Let us first try to fit various gates using standard linear -regression. The gates we are thinking of are the classical XOR, OR and -AND gates, well-known elements in computer science. The tables here -show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a -specific target \( y_i \). -

- - - -
-
-
-
-
-
"""
-Simple code that tests XOR, OR and AND gates with linear regression
-"""
-
-import numpy as np
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX  matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX  matrix:{Xinv}")
-
-# The XOR gate 
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR  = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction  for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate 
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR  = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction  for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate 
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND  = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

What is happening here?

- - -

Does Logistic Regression do a better Job?

- - - -
-
-
-
-
-
"""
-Simple code that tests XOR and OR gates with linear regression
-and logistic regression
-"""
-
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LogisticRegression
-import numpy as np
-
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX  matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX  matrix:{Xinv}")
-
-# The XOR gate 
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR  = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction  for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate 
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR  = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction  for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate 
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND  = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
-
-# Now we change to logistic regression
-
-
-# Logistic Regression
-logreg = LogisticRegression()
-logreg.fit(X, yOR)
-print("Test set accuracy with Logistic Regression for OR gate: {:.2f}".format(logreg.score(X,yOR)))
-
-logreg.fit(X, yXOR)
-print("Test set accuracy with Logistic Regression for XOR gate: {:.2f}".format(logreg.score(X,yXOR)))
-
-
-logreg.fit(X, yAND)
-print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Not exactly impressive, but somewhat better.

- - -

Adding Neural Networks

- - - -
-
-
-
-
-
# and now neural networks with Scikit-Learn and the XOR
-
-from sklearn.neural_network import MLPClassifier
-from sklearn.datasets import make_classification
-X, yXOR = make_classification(n_samples=100, random_state=1)
-FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)
-FFNN.predict_proba(X)
-print(f"Test set accuracy with Feed Forward Neural Network  for XOR gate:{FFNN.score(X, yXOR)}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Mathematics of deep learning

- - - - - -

Reminder on books with hands-on material and codes

- - - - -

Reading recommendations

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

Mathematics of deep learning and neural networks

- -

Neural networks, in its so-called feed-forward form, where each -iterations contains a feed-forward stage and a back-propgagation -stage, consist of series of affine matrix-matrix and matrix-vector -multiplications. The unknown parameters (the so-called biases and -weights which deternine the architecture of a neural network), are -uptaded iteratively using the so-called back-propagation algorithm. -This algorithm corresponds to the so-called reverse mode of -automatic differentation. -

- - -

Basics of an NN

- -

A neural network consists of a series of hidden layers, in addition to -the input and output layers. Each layer \( l \) has a set of parameters -\( \boldsymbol{\Theta}^{(l)}=(\boldsymbol{W}^{(l)},\boldsymbol{b}^{(l)}) \) which are related to the -parameters in other layers through a series of affine transformations, -for a standard NN these are matrix-matrix and matrix-vector -multiplications. For all layers we will simply use a collective variable \( \boldsymbol{\Theta} \). -

- -

It consist of two basic steps:

-
    -
  1. a feed forward stage which takes a given input and produces a final output which is compared with the target values through our cost/loss function.
  2. -
  3. a back-propagation state where the unknown parameters \( \boldsymbol{\Theta} \) are updated through the optimization of the their gradients. The expressions for the gradients are obtained via the chain rule, starting from the derivative of the cost/function.
  4. -
-

These two steps make up one iteration. This iterative process is continued till we reach an eventual stopping criterion.

- - -

Overarching view of a neural network

- -

The architecture of a neural network defines our model. This model -aims at describing some function \( f(\boldsymbol{x} \) which represents -some final result (outputs or tagrget values) given a specific inpput -\( \boldsymbol{x} \). Note that here \( \boldsymbol{y} \) and \( \boldsymbol{x} \) are not limited to be -vectors. -

- -

The architecture consists of

-
    -
  1. An input and an output layer where the input layer is defined by the inputs \( \boldsymbol{x} \). The output layer produces the model ouput \( \boldsymbol{\tilde{y}} \) which is compared with the target value \( \boldsymbol{y} \)
  2. -
  3. A given number of hidden layers and neurons/nodes/units for each layer (this may vary)
  4. -
  5. A given activation function \( \sigma(\boldsymbol{z}) \) with arguments \( \boldsymbol{z} \) to be defined below. The activation functions may differ from layer to layer.
  6. -
  7. The last layer, normally called output layer has normally an activation function tailored to the specific problem
  8. -
  9. Finally we define a so-called cost or loss function which is used to gauge the quality of our model.
  10. -
- -

The optimization problem

- -

The cost function is a function of the unknown parameters -\( \boldsymbol{\Theta} \) where the latter is a container for all possible -parameters needed to define a neural network -

- -

If we are dealing with a regression task a typical cost/loss function -is the mean squared error -

-$$ -C(\boldsymbol{\Theta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)\right\}. -$$ - -

This function represents one of many possible ways to define -the so-called cost function. Note that here we have assumed a linear dependence in terms of the paramters \( \boldsymbol{\Theta} \). This is in general not the case. -

- - -

Parameters of neural networks

-

For neural networks the parameters -\( \boldsymbol{\Theta} \) are given by the so-called weights and biases (to be -defined below). -

- -

The weights are given by matrix elements \( w_{ij}^{(l)} \) where the -superscript indicates the layer number. The biases are typically given -by vector elements representing each single node of a given layer, -that is \( b_j^{(l)} \). -

- - -

Other ingredients of a neural network

- -

Having defined the architecture of a neural network, the optimization -of the cost function with respect to the parameters \( \boldsymbol{\Theta} \), -involves the calculations of gradients and their optimization. The -gradients represent the derivatives of a multidimensional object and -are often approximated by various gradient methods, including -

-
    -
  1. various quasi-Newton methods,
  2. -
  3. plain gradient descent (GD) with a constant learning rate \( \eta \),
  4. -
  5. GD with momentum and other approximations to the learning rates such as
  6. -
      -
    • Adapative gradient (ADAgrad)
    • -
    • Root mean-square propagation (RMSprop)
    • -
    • Adaptive gradient with momentum (ADAM) and many other
    • -
    -
  7. Stochastic gradient descent and various families of learning rate approximations
  8. -
- -

Other parameters

- -

In addition to the above, there are often additional hyperparamaters -which are included in the setup of a neural network. These will be -discussed below. -

- - -

Universal approximation theorem

- -

The universal approximation theorem plays a central role in deep -learning. Cybenko (1989) showed -the following: -

- -
-
- -

Let \( \sigma \) be any continuous sigmoidal function such that

-$$ -\sigma(z) = \left\{\begin{array}{cc} 1 & z\rightarrow \infty\\ 0 & z \rightarrow -\infty \end{array}\right. -$$ - -

Given a continuous and deterministic function \( F(\boldsymbol{x}) \) on the unit -cube in \( d \)-dimensions \( F\in [0,1]^d \), \( x\in [0,1]^d \) and a parameter -\( \epsilon >0 \), there is a one-layer (hidden) neural network -\( f(\boldsymbol{x};\boldsymbol{\Theta}) \) with \( \boldsymbol{\Theta}=(\boldsymbol{W},\boldsymbol{b}) \) and \( \boldsymbol{W}\in -\mathbb{R}^{m\times n} \) and \( \boldsymbol{b}\in \mathbb{R}^{n} \), for which -

-$$ -\vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert < \epsilon \hspace{0.1cm} \forall \boldsymbol{x}\in[0,1]^d. -$$ -
-
- - - -

Some parallels from real analysis

- -

For those of you familiar with for example the Stone-Weierstrass -theorem -for polynomial approximations or the convergence criterion for Fourier -series, there are similarities in the derivation of the proof for -neural networks. -

- - -

The approximation theorem in words

- -

Any continuous function \( y=F(\boldsymbol{x}) \) supported on the unit cube in -\( d \)-dimensions can be approximated by a one-layer sigmoidal network to -arbitrary accuracy. -

- -

Hornik (1991) extended the theorem by letting any non-constant, bounded activation function to be included using that the expectation value

-$$ -\mathbb{E}[\vert F(\boldsymbol{x})\vert^2] =\int_{\boldsymbol{x}\in D} \vert F(\boldsymbol{x})\vert^2p(\boldsymbol{x})d\boldsymbol{x} < \infty. -$$ - -

Then we have

-$$ -\mathbb{E}[\vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert^2] =\int_{\boldsymbol{x}\in D} \vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert^2p(\boldsymbol{x})d\boldsymbol{x} < \epsilon. -$$ - - - -

More on the general approximation theorem

- -

None of the proofs give any insight into the relation between the -number of of hidden layers and nodes and the approximation error -\( \epsilon \), nor the magnitudes of \( \boldsymbol{W} \) and \( \boldsymbol{b} \). -

- -

Neural networks (NNs) have what we may call a kind of universality no matter what function we want to compute.

- -
-
- -

It does not mean that an NN can be used to exactly compute any function. Rather, we get an approximation that is as good as we want.

-
-
- - - -

Class of functions we can approximate

- -
-
- -

The class of functions that can be approximated are the continuous ones. -If the function \( F(\boldsymbol{x}) \) is discontinuous, it won't in general be possible to approximate it. However, an NN may still give an approximation even if we fail in some points. -

-
-
- - - -

Setting up the equations for a neural network

- -

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

- -

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

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

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

- - -

Layout of a neural network with three hidden layers

- -

-
-

-
-

- - -

Definitions

- -

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

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

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

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

Inputs to the activation function

- -

With the activation values \( \boldsymbol{z}^l \) we can in turn define the -output of layer \( l \) as \( \boldsymbol{a}^l = f(\boldsymbol{z}^l) \) where \( f \) 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 \( f \) for all layers -and their nodes. It means we have -

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

Derivatives and the chain rule

- -

From the definition of the activation \( z_j^l \) we have

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

and

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

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

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

Derivative of the cost function

- -

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

- -

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

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

The derivative of this function with respect to the weights is

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

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

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

Simpler examples first, and automatic differentiation

- -

In order to understand the back propagation algorithm and its -derivation (an implementation of the chain rule), let us first digress -with some simple examples. These examples are also meant to motivate -the link with back propagation and automatic differentiation. -

- - -

Reminder on the chain rule and gradients

- -

If we have a multivariate function \( f(x,y) \) where \( x=x(t) \) and \( y=y(t) \) are functions of a variable \( t \), we have that the gradient of \( f \) with respect to \( t \) (without the explicit unit vector components)

-$$ -\frac{df}{dt} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial t} \end{bmatrix}=\frac{\partial f}{\partial x} \frac{\partial x}{\partial t} +\frac{\partial f}{\partial y} \frac{\partial y}{\partial t}. -$$ - - - -

Multivariable functions

- -

If we have a multivariate function \( f(x,y) \) where \( x=x(t,s) \) and \( y=y(t,s) \) are functions of the variables \( t \) and \( s \), we have that the partial derivatives

-$$ -\frac{\partial f}{\partial s}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial s}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial s}, -$$ - -

and

-$$ -\frac{\partial f}{\partial t}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial t}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial t}. -$$ - -

the gradient of \( f \) with respect to \( t \) and \( s \) (without the explicit unit vector components)

-$$ -\frac{df}{d(s,t)} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial s} &\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial s} & \frac{\partial y}{\partial t} \end{bmatrix}. -$$ - - - -

Automatic differentiation through examples

- -

A great introduction to automatic differentiation is given by Baydin et al., see https://arxiv.org/abs/1502.05767.

- -

Automatic differentiation is a represented by a repeated application -of the chain rule on well-known functions and allows for the -calculation of derivatives to numerical precision. It is not the same -as the calculation of symbolic derivatives via for example SymPy, nor -does it use approximative formulae based on Taylor-expansions of a -function around a given value. The latter are error prone due to -truncation errors and values of the step size \( \Delta \). -

- - -

Simple example

- -

Our first example is rather simple,

-$$ -f(x) =\exp{x^2}, -$$ - -

with derivative

-$$ -f'(x) =2x\exp{x^2}. -$$ - -

We can use SymPy to extract the pertinent lines of Python code through the following simple example

- - -
-
-
-
-
-
from __future__ import division
-from sympy import *
-x = symbols('x')
-expr = exp(x*x)
-simplify(expr)
-derivative = diff(expr,x)
-print(python(expr))
-print(python(derivative))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Smarter way of evaluating the above function

-

If we study this function, we note that we can reduce the number of operations by introducing an intermediate variable

-$$ -a = x^2, -$$ - -

leading to

-$$ -f(x) = f(a(x)) = b= \exp{a}. -$$ - -

We now assume that all operations can be counted in terms of equal -floating point operations. This means that in order to calculate -\( f(x) \) we need first to square \( x \) and then compute the exponential. We -have thus two floating point operations only. -

- - -

Reducing the number of operations

- -

With the introduction of a precalculated quantity \( a \) and thereby \( f(x) \) we have that the derivative can be written as

- -$$ -f'(x) = 2xb, -$$ - -

which reduces the number of operations from four in the orginal -expression to two. This means that if we need to compute \( f(x) \) and -its derivative (a common task in optimizations), we have reduced the -number of operations from six to four in total. -

- -

Note that the usage of a symbolic software like SymPy does not -include such simplifications and the calculations of the function and -the derivatives yield in general more floating point operations. -

- - -

Chain rule, forward and reverse modes

- -

In the above example we have introduced the variables \( a \) and \( b \), and our function is

-$$ -f(x) = f(a(x)) = b= \exp{a}, -$$ - -

with \( a=x^2 \). We can decompose the derivative of \( f \) with respect to \( x \) as

-$$ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}. -$$ - -

We note that since \( b=f(x) \) that

-$$ -\frac{df}{db}=1, -$$ - -

leading to

-$$ -\frac{df}{dx}=\frac{db}{da}\frac{da}{dx}=2x\exp{x^2}, -$$ - -

as before.

- - -

Forward and reverse modes

- -

We have that

-$$ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}, -$$ - -

which we can rewrite either as

-$$ -\frac{df}{dx}=\left[\frac{df}{db}\frac{db}{da}\right]\frac{da}{dx}, -$$ - -

or

-$$ -\frac{df}{dx}=\frac{df}{db}\left[\frac{db}{da}\frac{da}{dx}\right]. -$$ - -

The first expression is called reverse mode (or back propagation) -since we start by evaluating the derivatives at the end point and then -propagate backwards. This is the standard way of evaluating -derivatives (gradients) when optimizing the parameters of a neural -network. In the context of deep learning this is computationally -more efficient since the output of a neural network consists of either -one or some few other output variables. -

- -

The second equation defines the so-called forward mode.

- - -

More complicated function

- -

We increase our ambitions and introduce a slightly more complicated function

-$$ -f(x) =\sqrt{x^2+exp{x^2}}, -$$ - -

with derivative

-$$ -f'(x) =\frac{x(1+\exp{x^2})}{\sqrt{x^2+exp{x^2}}}. -$$ - -

The corresponding SymPy code reads

- - -
-
-
-
-
-
from __future__ import division
-from sympy import *
-x = symbols('x')
-expr = sqrt(x*x+exp(x*x))
-simplify(expr)
-derivative = diff(expr,x)
-print(python(expr))
-print(python(derivative))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Counting the number of floating point operations

- -

A simple count of operations shows that we need five operations for -the function itself and ten for the derivative. Fifteen operations in total if we wish to proceed with the above codes. -

- -

Can we reduce this to -say half the number of operations? -

- - -

Defining intermediate operations

- -

We can indeed reduce the number of operation to half of those listed in the brute force approach above. -We define the following quantities -

-$$ -a = x^2, -$$ - -

and

-$$ -b = \exp{x^2} = \exp{a}, -$$ - -

and

-$$ -c= a+b, -$$ - -

and

-$$ -d=f(x)=\sqrt{c}. -$$ - - - -

New expression for the derivative

- -

With these definitions we obtain the following partial derivatives

-$$ -\frac{\partial a}{\partial x} = 2x, -$$ - -

and

-$$ -\frac{\partial b}{\partial a} = \exp{a}, -$$ - -

and

-$$ -\frac{\partial c}{\partial a} = 1, -$$ - -

and

-$$ -\frac{\partial c}{\partial b} = 1, -$$ - -

and

-$$ -\frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -$$ - -

and finally

-$$ -\frac{\partial f}{\partial d} = 1. -$$ - - - -

Final derivatives

-

Our final derivatives are thus

-$$ -\frac{\partial f}{\partial c} = \frac{\partial f}{\partial d} \frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -$$ - -$$ -\frac{\partial f}{\partial b} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial b} = \frac{1}{2\sqrt{c}}, -$$ - -$$ -\frac{\partial f}{\partial a} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial a}+ -\frac{\partial f}{\partial b} \frac{\partial b}{\partial a} = \frac{1+\exp{a}}{2\sqrt{c}}, -$$ - -

and finally

-$$ -\frac{\partial f}{\partial x} = \frac{\partial f}{\partial a} \frac{\partial a}{\partial x} = \frac{x(1+\exp{a})}{\sqrt{c}}, -$$ - -

which is just

-$$ -\frac{\partial f}{\partial x} = \frac{x(1+b)}{d}, -$$ - -

and requires only three operations if we can reuse all intermediate variables.

- - -

In general not this simple

- -

In general, see the generalization below, unless we can obtain simple -analytical expressions which we can simplify further, the final -implementation of automatic differentiation involves repeated -calculations (and thereby operations) of derivatives of elementary -functions. -

- - -

Automatic differentiation

- -

We can make this example more formal. Automatic differentiation is a -formalization of the previous example (see graph). -

- -

We define \( \boldsymbol{x}\in x_1,\dots, x_l \) input variables to a given function \( f(\boldsymbol{x}) \) and \( x_{l+1},\dots, x_L \) intermediate variables.

- -

In the above example we have only one input variable, \( l=1 \) and four intermediate variables, that is

-$$ -\begin{bmatrix} x_1=x & x_2 = x^2=a & x_3 =\exp{a}= b & x_4=c=a+b & x_5 = \sqrt{c}=d \end{bmatrix}. -$$ - -

Furthemore, for \( i=l+1, \dots, L \) (here \( i=2,3,4,5 \) and \( f=x_L=d \)), we -define the elementary functions \( g_i(x_{Pa(x_i)}) \) where \( x_{Pa(x_i)} \) are the parent nodes of the variable \( x_i \). -

- -

In our case, we have for example for \( x_3=g_3(x_{Pa(x_i)})=\exp{a} \), that \( g_3=\exp{()} \) and \( x_{Pa(x_3)}=a \).

- - -

Chain rule

- -

We can now compute the gradients by back-propagating the derivatives using the chain rule. -We have defined -

-$$ -\frac{\partial f}{\partial x_L} = 1, -$$ - -

which allows us to find the derivatives of the various variables \( x_i \) as

-$$ -\frac{\partial f}{\partial x_i} = \sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial x_j}{\partial x_i}=\sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial g_j}{\partial x_i}. -$$ - -

Whenever we have a function which can be expressed as a computation -graph and the various functions can be expressed in terms of -elementary functions that are differentiable, then automatic -differentiation works. The functions may not need to be elementary -functions, they could also be computer programs, although not all -programs can be automatically differentiated. -

- - -

First network example, simple percepetron with one input

- -

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

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

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

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

Layout of a simple neural network with no hidden layer

- -

-
-

-
-

- - -

Optimizing the parameters

- -

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

- -

We need

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

Using the chain rule we find

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

and

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

which we later will just define as

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

Adding a hidden layer

- -

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

- -

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

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

and the cost function

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

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

- - -

Layout of a simple neural network with one hidden layer

- -

-
-

-
-

- - -

The derivatives

- -

The derivatives are now, using the chain rule again

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

Can you generalize this to more than one hidden layer?

- - -

Important observations

- -
-
- -

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

-
-
- - - -

The training

- -

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

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

and

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

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

- -

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

- -

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

- - -

Code example

- -

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

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

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

- - - - -

Exercise 1: Including more data

- -

Try to increase the amount of input and -target/output data. Try also to perform calculations for more values -of the learning rates. Feel free to add either hyperparameters with an -\( l_1 \) norm or an \( l_2 \) norm and discuss your results. -Discuss your results as functions of the amount of training data and various learning rates. -

- -

Challenge: Try to change the activation functions and replace the hard-coded analytical expressions with automatic derivation via either autograd or JAX.

- - - - -

Simple neural network and the back propagation equations

- -

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

- -

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

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

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

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

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

- -

-
-

-
-

- - -

The ouput layer

- -

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

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

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

-$$ -\boldsymbol{\Theta}=\left\{w_{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\}. -$$ - - - -

Compact expressions

- -

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

-$$ -\begin{bmatrix}z_0^{(1)} \\ z_1^{(1)} \end{bmatrix}=\begin{bmatrix}w_{00}^{(1)} & w_{01}^{(1)}\\ w_{10}^{(1)} &w_{11}^{(1)} \end{bmatrix}\begin{bmatrix}a_0^{(0)} \\ a_1^{(0)} \end{bmatrix}+\begin{bmatrix}b_0^{(1)} \\ b_1^{(1)} \end{bmatrix}, -$$ - -

with outputs

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

Output layer

- -

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

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

resulting in the output

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

Explicit derivatives

- -

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

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

with

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

and finally

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

Derivatives of the hidden layer

- -

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

-$$ -\frac{\partial C}{\partial w_{00}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\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)}}, -$$ - -

which, noting that

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

allows us to rewrite

-$$ -\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)}. -$$ - - - -

Final expression

-

Defining

-$$ -\delta_0^{(1)}=w_0^{(2)}\frac{\partial a_0^{(1)}}{\partial z_0^{(1)}}\delta^{(2)}, -$$ - -

we have

-$$ -\frac{\partial C}{\partial w_{00}^{(1)}}=\delta_0^{(1)}a_0^{(1)}. -$$ - -

Similarly, we obtain

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

Completing the list

- -

Similarly, we find

-$$ -\frac{\partial C}{\partial w_{10}^{(1)}}=\delta_1^{(1)}a_0^{(1)}, -$$ - -

and

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

where we have defined

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

Final expressions for the biases of the hidden layer

- -

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

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

and

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

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

- - -

Gradient expressions

- -

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

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

and

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

and

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

and

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

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

- - - - -

Exercise 2: Extended program

- -

We extend our simple code to a function which depends on two variable \( x_0 \) and \( x_1 \), that is

-$$ -y=f(x_0,x_1)=x_0^2+3x_0x_1+x_1^2+5. -$$ - -

We feed our network with \( n=100 \) entries \( x_0 \) and \( x_1 \). We have thus two features represented by these variable and an input matrix/design matrix \( \boldsymbol{X}\in \mathbf{R}^{n\times 2} \)

-$$ -\boldsymbol{X}=\begin{bmatrix} x_{00} & x_{01} \\ x_{00} & x_{01} \\ x_{10} & x_{11} \\ x_{20} & x_{21} \\ \dots & \dots \\ \dots & \dots \\ x_{n-20} & x_{n-21} \\ x_{n-10} & x_{n-11} \end{bmatrix}. -$$ - -

Write a code, based on the previous code examples, which takes as input these data and fit the above function. -You can extend your code to include automatic differentiation. -

- -

With these examples, we are now ready to embark upon the writing of more a general code for neural networks.

- - - - -

Getting serious, the back propagation equations for a neural network

- -

Now it is time to move away from one node in each layer only. Our inputs are also represented either by several inputs.

- -

We have thus

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

Defining

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

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

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

Analyzing the last results

- -

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

- - -

More considerations

- -

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

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

With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely

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

Derivatives in terms of \( z_j^L \)

- -

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

- -$$ -\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, -$$ - -

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

-$$ -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, -$$ - -

That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias.

- - -

Bringing it together

- -

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

- -$$ -\begin{equation} -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}, -\label{_auto1} -\end{equation} -$$ - -

and

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

and

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

Final back propagating equation

- -

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

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

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

- - -

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

- -

We obtain

-$$ -\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, -$$ - -

and recalling that

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

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

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

This is our final equation.

- -

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

- - -

Setting up the back propagation algorithm

- -

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.

- -

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

- -

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

- -

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

- - -

Setting up the back propagation algorithm, part 2

- -

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

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

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

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

Setting up the Back propagation algorithm, part 3

- -

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

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

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

- - -

Updating the gradients

- -

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

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

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

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

Activation functions

- -

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

- -
    -
  • Non-constant
  • -
  • Bounded
  • -
  • Monotonically-increasing
  • -
  • Continuous
  • -
- -

Activation functions, Logistic and Hyperbolic ones

- -

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

- -

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

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

and the hyperbolic tangent function

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

Relevance

- -

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

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

Fine-tuning neural network hyperparameters

- -

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

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

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

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

Hidden layers

- -

For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set you ca 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. -

- - -

Vanishing gradients

- -

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

- -

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

- - -

Exploding gradients

- -

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

- - -

Is the Logistic activation function (Sigmoid) our choice?

- -

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

- -

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

- - -

Logistic function as the root of problems

- -

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

- - -

The derivative of the Logistic funtion

- -

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

- -

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

- - -

Insights from the paper by Glorot and Bengio

- -

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

- - -

The RELU function family

- -

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

- -

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

- - -

ELU function

- -

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

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

Which activation function should we use?

- -

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

- -

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

- - -

More on activation functions, output layers

- -

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

- -

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

- -For the output layer: - -
    -
  • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
  • -
  • For regression tasks, you can simply use no activation function at all.
  • -
- -

Batch Normalization

- -

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

- -

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

- - -

Dropout

- -

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

- -

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

- - -

Gradient Clipping

- -

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

- -

This technique is called Gradient Clipping.

- -

In general however, Batch -Normalization is preferred. -

- - -

A top-down perspective on Neural networks

- -

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

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

More top-down perspectives

- -

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

- -

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

- - -

Limitations of supervised learning with deep networks

- -

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

- - -

Limitations of NNs

- -

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

- -
    -
  • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
  • -
  • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
  • -
- -

Homogeneous data

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

More limitations

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

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

- - -
- - - - -
- © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - diff --git a/doc/src/week41/week41-reveal.html b/doc/src/week41/week41-reveal.html deleted file mode 100644 index 34be85e14..000000000 --- a/doc/src/week41/week41-reveal.html +++ /dev/null @@ -1,2989 +0,0 @@ - - - - - - - - -Week 41 Neural networks and constructing a neural network code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - - - - - - - - - -
- -
-

Week 41 Neural networks and constructing a neural network code

-
- - -
-Morten Hjorth-Jensen -
- -
-Department of Physics, University of Oslo -
-
-
-

Week 41

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

Plan for week 41, October 7-11

-
- -
-

Material for the lecture on Monday October 7, 2024

-
    -

  1. Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
  2. -

  3. Building our own Feed-forward Neural Network - -
  4. -
-

-

-Readings and Videos: -

-

    -

  1. These lecture notes
  2. -

  3. Rashcka et al chapter 11
  4. -

  5. For neural networks we recommend Goodfellow et al chapter 6. -
      -

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

    -

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

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

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

-

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

-
-
- -
-

Material for the active learning sessions on Tuesday and Wednesday

-
    -

  • Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation
  • -

  • One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code
  • -

  • Discussion of project 2
  • -

  • Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent
  • -
-
- -
-

Lecture Monday October 7

-
- -
-

Introduction to Neural networks

- -

Artificial neural networks are computational systems that can learn to -perform tasks by considering examples, generally without being -programmed with any task-specific rules. It is supposed to mimic a -biological system, wherein neurons interact by sending signals in the -form of mathematical functions between layers. All layers can contain -an arbitrary number of neurons, and each connection is represented by -a weight variable. -

-
- -
-

Artificial neurons

- -

The field of artificial neural networks has a long history of -development, and is closely connected with the advancement of computer -science and computers in general. A model of artificial neurons was -first developed by McCulloch and Pitts in 1943 to study signal -processing in the brain and has later been refined by others. The -general idea is to mimic neural networks in the human brain, which is -composed of billions of neurons that communicate with each other by -sending electrical signals. Each neuron accumulates its incoming -signals, which must exceed an activation threshold to yield an -output. If the threshold is not overcome, the neuron remains inactive, -i.e. has zero output. -

- -

This behaviour has inspired a simple mathematical model for an artificial neuron.

- -

 
-$$ -\begin{equation} - y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u) -\tag{1} -\end{equation} -$$ -

 
- -

Here, the output \( y \) of the neuron is the value of its activation function, which have as input -a weighted sum of signals \( x_i, \dots ,x_n \) received by \( n \) other neurons. -

- -

Conceptually, it is helpful to divide neural networks into four -categories: -

-
    -

  1. general purpose neural networks for supervised learning,
  2. -

  3. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),
  4. -

  5. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and
  6. -

  7. neural networks for unsupervised learning such as Deep Boltzmann Machines.
  8. -
-

-

In natural science, DNNs and CNNs have already found numerous -applications. In statistical physics, they have been applied to detect -phase transitions in 2D Ising and Potts models, lattice gauge -theories, and different phases of polymers, or solving the -Navier-Stokes equation in weather forecasting. Deep learning has also -found interesting applications in quantum physics. Various quantum -phase transitions can be detected and studied using DNNs and CNNs, -topological phases, and even non-equilibrium many-body -localization. Representing quantum states as DNNs quantum state -tomography are among some of the impressive achievements to reveal the -potential of DNNs to facilitate the study of quantum systems. -

- -

In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. -

- -

The applications are not limited to the natural sciences. There is a -plethora of applications in essentially all disciplines, from the -humanities to life science and medicine. -

-
- -
-

Neural network types

- -

An artificial neural network (ANN), is a computational model that -consists of layers of connected neurons, or nodes or units. We will -refer to these interchangeably as units or nodes, and sometimes as -neurons. -

- -

It is supposed to mimic a biological nervous system by letting each -neuron interact with other neurons by sending signals in the form of -mathematical functions between layers. A wide variety of different -ANNs have been developed, but most of them consist of an input layer, -an output layer and eventual layers in-between, called hidden -layers. All layers can contain an arbitrary number of nodes, and each -connection between two nodes is associated with a weight variable. -

- -

Neural networks (also called neural nets) are neural-inspired -nonlinear models for supervised learning. As we will see, neural nets -can be viewed as natural, more powerful extensions of supervised -learning methods such as linear and logistic regression and soft-max -methods we discussed earlier. -

-
- -
-

Feed-forward neural networks

- -

The feed-forward neural network (FFNN) was the first and simplest type -of ANNs that were devised. In this network, the information moves in -only one direction: forward through the layers. -

- -

Nodes are represented by circles, while the arrows display the -connections between the nodes, including the direction of information -flow. Additionally, each arrow corresponds to a weight variable -(figure to come). We observe that each node in a layer is connected -to all nodes in the subsequent layer, making this a so-called -fully-connected FFNN. -

-
- -
-

Convolutional Neural Network

- -

A different variant of FFNNs are convolutional neural networks -(CNNs), which have a connectivity pattern inspired by the animal -visual cortex. Individual neurons in the visual cortex only respond to -stimuli from small sub-regions of the visual field, called a receptive -field. This makes the neurons well-suited to exploit the strong -spatially local correlation present in natural images. The response of -each neuron can be approximated mathematically as a convolution -operation. (figure to come) -

- -

Convolutional neural networks emulate the behaviour of neurons in the -visual cortex by enforcing a local connectivity pattern between -nodes of adjacent layers: Each node in a convolutional layer is -connected only to a subset of the nodes in the previous layer, in -contrast to the fully-connected FFNN. Often, CNNs consist of several -convolutional layers that learn local features of the input, with a -fully-connected layer at the end, which gathers all the local data and -produces the outputs. They have wide applications in image and video -recognition. -

-
- -
-

Recurrent neural networks

- -

So far we have only mentioned ANNs where information flows in one -direction: forward. Recurrent neural networks on the other hand, -have connections between nodes that form directed cycles. This -creates a form of internal memory which are able to capture -information on what has been calculated before; the output is -dependent on the previous computations. Recurrent NNs make use of -sequential information by performing the same task for every element -in a sequence, where each element depends on previous elements. An -example of such information is sentences, making recurrent NNs -especially well-suited for handwriting and speech recognition. -

-
- -
-

Other types of networks

- -

There are many other kinds of ANNs that have been developed. One type -that is specifically designed for interpolation in multidimensional -space is the radial basis function (RBF) network. RBFs are typically -made up of three layers: an input layer, a hidden layer with -non-linear radial symmetric activation functions and a linear output -layer (''linear'' here means that each node in the output layer has a -linear activation function). The layers are normally fully-connected -and there are no cycles, thus RBFs can be viewed as a type of -fully-connected FFNN. They are however usually treated as a separate -type of NN due the unusual activation functions. -

-
- -
-

Multilayer perceptrons

- -

One uses often so-called fully-connected feed-forward neural networks -with three or more layers (an input layer, one or more hidden layers -and an output layer) consisting of neurons that have non-linear -activation functions. -

- -

Such networks are often called multilayer perceptrons (MLPs).

-
- -
-

Why multilayer perceptrons?

- -

According to the Universal approximation theorem, a feed-forward -neural network with just a single hidden layer containing a finite -number of neurons can approximate a continuous multidimensional -function to arbitrary accuracy, assuming the activation function for -the hidden layer is a non-constant, bounded and -monotonically-increasing continuous function. -

- -

Note that the requirements on the activation function only applies to -the hidden layer, the output nodes are always assumed to be linear, so -as to not restrict the range of output values. -

-
- -
-

Illustration of a single perceptron model and a multi-perceptron model

- -
-
-
-

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

-
-

-
-
- -
-

Examples of XOR, OR and AND gates

- -

Let us first try to fit various gates using standard linear -regression. The gates we are thinking of are the classical XOR, OR and -AND gates, well-known elements in computer science. The tables here -show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a -specific target \( y_i \). -

- - - -
-
-
-
-
-
"""
-Simple code that tests XOR, OR and AND gates with linear regression
-"""
-
-import numpy as np
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX  matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX  matrix:{Xinv}")
-
-# The XOR gate 
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR  = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction  for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate 
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR  = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction  for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate 
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND  = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

What is happening here?

-
- -
-

Does Logistic Regression do a better Job?

- - - -
-
-
-
-
-
"""
-Simple code that tests XOR and OR gates with linear regression
-and logistic regression
-"""
-
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LogisticRegression
-import numpy as np
-
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX  matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX  matrix:{Xinv}")
-
-# The XOR gate 
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR  = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction  for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate 
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR  = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction  for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate 
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND  = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
-
-# Now we change to logistic regression
-
-
-# Logistic Regression
-logreg = LogisticRegression()
-logreg.fit(X, yOR)
-print("Test set accuracy with Logistic Regression for OR gate: {:.2f}".format(logreg.score(X,yOR)))
-
-logreg.fit(X, yXOR)
-print("Test set accuracy with Logistic Regression for XOR gate: {:.2f}".format(logreg.score(X,yXOR)))
-
-
-logreg.fit(X, yAND)
-print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Not exactly impressive, but somewhat better.

-
- -
-

Adding Neural Networks

- - - -
-
-
-
-
-
# and now neural networks with Scikit-Learn and the XOR
-
-from sklearn.neural_network import MLPClassifier
-from sklearn.datasets import make_classification
-X, yXOR = make_classification(n_samples=100, random_state=1)
-FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)
-FFNN.predict_proba(X)
-print(f"Test set accuracy with Feed Forward Neural Network  for XOR gate:{FFNN.score(X, yXOR)}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Mathematics of deep learning

- - -
- -
-

Reminder on books with hands-on material and codes

- -
- -
-

Reading recommendations

- -
    -

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

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

Mathematics of deep learning and neural networks

- -

Neural networks, in its so-called feed-forward form, where each -iterations contains a feed-forward stage and a back-propgagation -stage, consist of series of affine matrix-matrix and matrix-vector -multiplications. The unknown parameters (the so-called biases and -weights which deternine the architecture of a neural network), are -uptaded iteratively using the so-called back-propagation algorithm. -This algorithm corresponds to the so-called reverse mode of -automatic differentation. -

-
- -
-

Basics of an NN

- -

A neural network consists of a series of hidden layers, in addition to -the input and output layers. Each layer \( l \) has a set of parameters -\( \boldsymbol{\Theta}^{(l)}=(\boldsymbol{W}^{(l)},\boldsymbol{b}^{(l)}) \) which are related to the -parameters in other layers through a series of affine transformations, -for a standard NN these are matrix-matrix and matrix-vector -multiplications. For all layers we will simply use a collective variable \( \boldsymbol{\Theta} \). -

- -

It consist of two basic steps:

-
    -

  1. a feed forward stage which takes a given input and produces a final output which is compared with the target values through our cost/loss function.
  2. -

  3. a back-propagation state where the unknown parameters \( \boldsymbol{\Theta} \) are updated through the optimization of the their gradients. The expressions for the gradients are obtained via the chain rule, starting from the derivative of the cost/function.
  4. -
-

-

These two steps make up one iteration. This iterative process is continued till we reach an eventual stopping criterion.

-
- -
-

Overarching view of a neural network

- -

The architecture of a neural network defines our model. This model -aims at describing some function \( f(\boldsymbol{x} \) which represents -some final result (outputs or tagrget values) given a specific inpput -\( \boldsymbol{x} \). Note that here \( \boldsymbol{y} \) and \( \boldsymbol{x} \) are not limited to be -vectors. -

- -

The architecture consists of

-
    -

  1. An input and an output layer where the input layer is defined by the inputs \( \boldsymbol{x} \). The output layer produces the model ouput \( \boldsymbol{\tilde{y}} \) which is compared with the target value \( \boldsymbol{y} \)
  2. -

  3. A given number of hidden layers and neurons/nodes/units for each layer (this may vary)
  4. -

  5. A given activation function \( \sigma(\boldsymbol{z}) \) with arguments \( \boldsymbol{z} \) to be defined below. The activation functions may differ from layer to layer.
  6. -

  7. The last layer, normally called output layer has normally an activation function tailored to the specific problem
  8. -

  9. Finally we define a so-called cost or loss function which is used to gauge the quality of our model.
  10. -
-
- -
-

The optimization problem

- -

The cost function is a function of the unknown parameters -\( \boldsymbol{\Theta} \) where the latter is a container for all possible -parameters needed to define a neural network -

- -

If we are dealing with a regression task a typical cost/loss function -is the mean squared error -

-

 
-$$ -C(\boldsymbol{\Theta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)\right\}. -$$ -

 
- -

This function represents one of many possible ways to define -the so-called cost function. Note that here we have assumed a linear dependence in terms of the paramters \( \boldsymbol{\Theta} \). This is in general not the case. -

-
- -
-

Parameters of neural networks

-

For neural networks the parameters -\( \boldsymbol{\Theta} \) are given by the so-called weights and biases (to be -defined below). -

- -

The weights are given by matrix elements \( w_{ij}^{(l)} \) where the -superscript indicates the layer number. The biases are typically given -by vector elements representing each single node of a given layer, -that is \( b_j^{(l)} \). -

-
- -
-

Other ingredients of a neural network

- -

Having defined the architecture of a neural network, the optimization -of the cost function with respect to the parameters \( \boldsymbol{\Theta} \), -involves the calculations of gradients and their optimization. The -gradients represent the derivatives of a multidimensional object and -are often approximated by various gradient methods, including -

-
    -

  1. various quasi-Newton methods,
  2. -

  3. plain gradient descent (GD) with a constant learning rate \( \eta \),
  4. -

  5. GD with momentum and other approximations to the learning rates such as
  6. -
      - -

    • Adapative gradient (ADAgrad)
    • - -

    • Root mean-square propagation (RMSprop)
    • - -

    • Adaptive gradient with momentum (ADAM) and many other
    • -
    -

    -

  7. Stochastic gradient descent and various families of learning rate approximations
  8. -
-
- -
-

Other parameters

- -

In addition to the above, there are often additional hyperparamaters -which are included in the setup of a neural network. These will be -discussed below. -

-
- -
-

Universal approximation theorem

- -

The universal approximation theorem plays a central role in deep -learning. Cybenko (1989) showed -the following: -

- -
- -

-

Let \( \sigma \) be any continuous sigmoidal function such that

-

 
-$$ -\sigma(z) = \left\{\begin{array}{cc} 1 & z\rightarrow \infty\\ 0 & z \rightarrow -\infty \end{array}\right. -$$ -

 
- -

Given a continuous and deterministic function \( F(\boldsymbol{x}) \) on the unit -cube in \( d \)-dimensions \( F\in [0,1]^d \), \( x\in [0,1]^d \) and a parameter -\( \epsilon >0 \), there is a one-layer (hidden) neural network -\( f(\boldsymbol{x};\boldsymbol{\Theta}) \) with \( \boldsymbol{\Theta}=(\boldsymbol{W},\boldsymbol{b}) \) and \( \boldsymbol{W}\in -\mathbb{R}^{m\times n} \) and \( \boldsymbol{b}\in \mathbb{R}^{n} \), for which -

-

 
-$$ -\vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert < \epsilon \hspace{0.1cm} \forall \boldsymbol{x}\in[0,1]^d. -$$ -

 
-

-
- -
-

Some parallels from real analysis

- -

For those of you familiar with for example the Stone-Weierstrass -theorem -for polynomial approximations or the convergence criterion for Fourier -series, there are similarities in the derivation of the proof for -neural networks. -

-
- -
-

The approximation theorem in words

- -

Any continuous function \( y=F(\boldsymbol{x}) \) supported on the unit cube in -\( d \)-dimensions can be approximated by a one-layer sigmoidal network to -arbitrary accuracy. -

- -

Hornik (1991) extended the theorem by letting any non-constant, bounded activation function to be included using that the expectation value

-

 
-$$ -\mathbb{E}[\vert F(\boldsymbol{x})\vert^2] =\int_{\boldsymbol{x}\in D} \vert F(\boldsymbol{x})\vert^2p(\boldsymbol{x})d\boldsymbol{x} < \infty. -$$ -

 
- -

Then we have

-

 
-$$ -\mathbb{E}[\vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert^2] =\int_{\boldsymbol{x}\in D} \vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert^2p(\boldsymbol{x})d\boldsymbol{x} < \epsilon. -$$ -

 
-

- -
-

More on the general approximation theorem

- -

None of the proofs give any insight into the relation between the -number of of hidden layers and nodes and the approximation error -\( \epsilon \), nor the magnitudes of \( \boldsymbol{W} \) and \( \boldsymbol{b} \). -

- -

Neural networks (NNs) have what we may call a kind of universality no matter what function we want to compute.

- -
- -

-

It does not mean that an NN can be used to exactly compute any function. Rather, we get an approximation that is as good as we want.

-
-
- -
-

Class of functions we can approximate

- -
- -

-

The class of functions that can be approximated are the continuous ones. -If the function \( F(\boldsymbol{x}) \) is discontinuous, it won't in general be possible to approximate it. However, an NN may still give an approximation even if we fail in some points. -

-
-
- -
-

Setting up the equations for a neural network

- -

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

- -

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

- -

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

 
- -

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

-
- -
-

Layout of a neural network with three hidden layers

- -

-
-

-
-

-
- -
-

Definitions

- -

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

- -

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

 
- -

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

- -

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

 
-

- -
-

Inputs to the activation function

- -

With the activation values \( \boldsymbol{z}^l \) we can in turn define the -output of layer \( l \) as \( \boldsymbol{a}^l = f(\boldsymbol{z}^l) \) where \( f \) 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 \( f \) for all layers -and their nodes. It means we have -

- -

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

 
-

- -
-

Derivatives and the chain rule

- -

From the definition of the activation \( z_j^l \) we have

-

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

 
- -

and

-

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

 
- -

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

-

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

 
-

- -
-

Derivative of the cost function

- -

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

- -

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

-

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

 
- -

The derivative of this function with respect to the weights is

- -

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

 
- -

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

-

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

 
-

- -
-

Simpler examples first, and automatic differentiation

- -

In order to understand the back propagation algorithm and its -derivation (an implementation of the chain rule), let us first digress -with some simple examples. These examples are also meant to motivate -the link with back propagation and automatic differentiation. -

-
- -
-

Reminder on the chain rule and gradients

- -

If we have a multivariate function \( f(x,y) \) where \( x=x(t) \) and \( y=y(t) \) are functions of a variable \( t \), we have that the gradient of \( f \) with respect to \( t \) (without the explicit unit vector components)

-

 
-$$ -\frac{df}{dt} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial t} \end{bmatrix}=\frac{\partial f}{\partial x} \frac{\partial x}{\partial t} +\frac{\partial f}{\partial y} \frac{\partial y}{\partial t}. -$$ -

 
-

- -
-

Multivariable functions

- -

If we have a multivariate function \( f(x,y) \) where \( x=x(t,s) \) and \( y=y(t,s) \) are functions of the variables \( t \) and \( s \), we have that the partial derivatives

-

 
-$$ -\frac{\partial f}{\partial s}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial s}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial s}, -$$ -

 
- -

and

-

 
-$$ -\frac{\partial f}{\partial t}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial t}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial t}. -$$ -

 
- -

the gradient of \( f \) with respect to \( t \) and \( s \) (without the explicit unit vector components)

-

 
-$$ -\frac{df}{d(s,t)} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial s} &\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial s} & \frac{\partial y}{\partial t} \end{bmatrix}. -$$ -

 
-

- -
-

Automatic differentiation through examples

- -

A great introduction to automatic differentiation is given by Baydin et al., see https://arxiv.org/abs/1502.05767.

- -

Automatic differentiation is a represented by a repeated application -of the chain rule on well-known functions and allows for the -calculation of derivatives to numerical precision. It is not the same -as the calculation of symbolic derivatives via for example SymPy, nor -does it use approximative formulae based on Taylor-expansions of a -function around a given value. The latter are error prone due to -truncation errors and values of the step size \( \Delta \). -

-
- -
-

Simple example

- -

Our first example is rather simple,

-

 
-$$ -f(x) =\exp{x^2}, -$$ -

 
- -

with derivative

-

 
-$$ -f'(x) =2x\exp{x^2}. -$$ -

 
- -

We can use SymPy to extract the pertinent lines of Python code through the following simple example

- - -
-
-
-
-
-
from __future__ import division
-from sympy import *
-x = symbols('x')
-expr = exp(x*x)
-simplify(expr)
-derivative = diff(expr,x)
-print(python(expr))
-print(python(derivative))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Smarter way of evaluating the above function

-

If we study this function, we note that we can reduce the number of operations by introducing an intermediate variable

-

 
-$$ -a = x^2, -$$ -

 
- -

leading to

-

 
-$$ -f(x) = f(a(x)) = b= \exp{a}. -$$ -

 
- -

We now assume that all operations can be counted in terms of equal -floating point operations. This means that in order to calculate -\( f(x) \) we need first to square \( x \) and then compute the exponential. We -have thus two floating point operations only. -

-
- -
-

Reducing the number of operations

- -

With the introduction of a precalculated quantity \( a \) and thereby \( f(x) \) we have that the derivative can be written as

- -

 
-$$ -f'(x) = 2xb, -$$ -

 
- -

which reduces the number of operations from four in the orginal -expression to two. This means that if we need to compute \( f(x) \) and -its derivative (a common task in optimizations), we have reduced the -number of operations from six to four in total. -

- -

Note that the usage of a symbolic software like SymPy does not -include such simplifications and the calculations of the function and -the derivatives yield in general more floating point operations. -

-
- -
-

Chain rule, forward and reverse modes

- -

In the above example we have introduced the variables \( a \) and \( b \), and our function is

-

 
-$$ -f(x) = f(a(x)) = b= \exp{a}, -$$ -

 
- -

with \( a=x^2 \). We can decompose the derivative of \( f \) with respect to \( x \) as

-

 
-$$ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}. -$$ -

 
- -

We note that since \( b=f(x) \) that

-

 
-$$ -\frac{df}{db}=1, -$$ -

 
- -

leading to

-

 
-$$ -\frac{df}{dx}=\frac{db}{da}\frac{da}{dx}=2x\exp{x^2}, -$$ -

 
- -

as before.

-
- -
-

Forward and reverse modes

- -

We have that

-

 
-$$ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}, -$$ -

 
- -

which we can rewrite either as

-

 
-$$ -\frac{df}{dx}=\left[\frac{df}{db}\frac{db}{da}\right]\frac{da}{dx}, -$$ -

 
- -

or

-

 
-$$ -\frac{df}{dx}=\frac{df}{db}\left[\frac{db}{da}\frac{da}{dx}\right]. -$$ -

 
- -

The first expression is called reverse mode (or back propagation) -since we start by evaluating the derivatives at the end point and then -propagate backwards. This is the standard way of evaluating -derivatives (gradients) when optimizing the parameters of a neural -network. In the context of deep learning this is computationally -more efficient since the output of a neural network consists of either -one or some few other output variables. -

- -

The second equation defines the so-called forward mode.

-
- -
-

More complicated function

- -

We increase our ambitions and introduce a slightly more complicated function

-

 
-$$ -f(x) =\sqrt{x^2+exp{x^2}}, -$$ -

 
- -

with derivative

-

 
-$$ -f'(x) =\frac{x(1+\exp{x^2})}{\sqrt{x^2+exp{x^2}}}. -$$ -

 
- -

The corresponding SymPy code reads

- - -
-
-
-
-
-
from __future__ import division
-from sympy import *
-x = symbols('x')
-expr = sqrt(x*x+exp(x*x))
-simplify(expr)
-derivative = diff(expr,x)
-print(python(expr))
-print(python(derivative))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Counting the number of floating point operations

- -

A simple count of operations shows that we need five operations for -the function itself and ten for the derivative. Fifteen operations in total if we wish to proceed with the above codes. -

- -

Can we reduce this to -say half the number of operations? -

-
- -
-

Defining intermediate operations

- -

We can indeed reduce the number of operation to half of those listed in the brute force approach above. -We define the following quantities -

-

 
-$$ -a = x^2, -$$ -

 
- -

and

-

 
-$$ -b = \exp{x^2} = \exp{a}, -$$ -

 
- -

and

-

 
-$$ -c= a+b, -$$ -

 
- -

and

-

 
-$$ -d=f(x)=\sqrt{c}. -$$ -

 
-

- -
-

New expression for the derivative

- -

With these definitions we obtain the following partial derivatives

-

 
-$$ -\frac{\partial a}{\partial x} = 2x, -$$ -

 
- -

and

-

 
-$$ -\frac{\partial b}{\partial a} = \exp{a}, -$$ -

 
- -

and

-

 
-$$ -\frac{\partial c}{\partial a} = 1, -$$ -

 
- -

and

-

 
-$$ -\frac{\partial c}{\partial b} = 1, -$$ -

 
- -

and

-

 
-$$ -\frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -$$ -

 
- -

and finally

-

 
-$$ -\frac{\partial f}{\partial d} = 1. -$$ -

 
-

- -
-

Final derivatives

-

Our final derivatives are thus

-

 
-$$ -\frac{\partial f}{\partial c} = \frac{\partial f}{\partial d} \frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -$$ -

 
- -

 
-$$ -\frac{\partial f}{\partial b} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial b} = \frac{1}{2\sqrt{c}}, -$$ -

 
- -

 
-$$ -\frac{\partial f}{\partial a} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial a}+ -\frac{\partial f}{\partial b} \frac{\partial b}{\partial a} = \frac{1+\exp{a}}{2\sqrt{c}}, -$$ -

 
- -

and finally

-

 
-$$ -\frac{\partial f}{\partial x} = \frac{\partial f}{\partial a} \frac{\partial a}{\partial x} = \frac{x(1+\exp{a})}{\sqrt{c}}, -$$ -

 
- -

which is just

-

 
-$$ -\frac{\partial f}{\partial x} = \frac{x(1+b)}{d}, -$$ -

 
- -

and requires only three operations if we can reuse all intermediate variables.

-
- -
-

In general not this simple

- -

In general, see the generalization below, unless we can obtain simple -analytical expressions which we can simplify further, the final -implementation of automatic differentiation involves repeated -calculations (and thereby operations) of derivatives of elementary -functions. -

-
- -
-

Automatic differentiation

- -

We can make this example more formal. Automatic differentiation is a -formalization of the previous example (see graph). -

- -

We define \( \boldsymbol{x}\in x_1,\dots, x_l \) input variables to a given function \( f(\boldsymbol{x}) \) and \( x_{l+1},\dots, x_L \) intermediate variables.

- -

In the above example we have only one input variable, \( l=1 \) and four intermediate variables, that is

-

 
-$$ -\begin{bmatrix} x_1=x & x_2 = x^2=a & x_3 =\exp{a}= b & x_4=c=a+b & x_5 = \sqrt{c}=d \end{bmatrix}. -$$ -

 
- -

Furthemore, for \( i=l+1, \dots, L \) (here \( i=2,3,4,5 \) and \( f=x_L=d \)), we -define the elementary functions \( g_i(x_{Pa(x_i)}) \) where \( x_{Pa(x_i)} \) are the parent nodes of the variable \( x_i \). -

- -

In our case, we have for example for \( x_3=g_3(x_{Pa(x_i)})=\exp{a} \), that \( g_3=\exp{()} \) and \( x_{Pa(x_3)}=a \).

-
- -
-

Chain rule

- -

We can now compute the gradients by back-propagating the derivatives using the chain rule. -We have defined -

-

 
-$$ -\frac{\partial f}{\partial x_L} = 1, -$$ -

 
- -

which allows us to find the derivatives of the various variables \( x_i \) as

-

 
-$$ -\frac{\partial f}{\partial x_i} = \sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial x_j}{\partial x_i}=\sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial g_j}{\partial x_i}. -$$ -

 
- -

Whenever we have a function which can be expressed as a computation -graph and the various functions can be expressed in terms of -elementary functions that are differentiable, then automatic -differentiation works. The functions may not need to be elementary -functions, they could also be computer programs, although not all -programs can be automatically differentiated. -

-
- -
-

First network example, simple percepetron with one input

- -

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

- -

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

 
- -

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

- -

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

 
-

- -
-

Layout of a simple neural network with no hidden layer

- -

-
-

-
-

-
- -
-

Optimizing the parameters

- -

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

- -

We need

-

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

 
- -

Using the chain rule we find

-

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

 
- -

and

-

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

 
- -

which we later will just define as

-

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

 
-

- -
-

Adding a hidden layer

- -

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

- -

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

-

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

 
- -

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

 
- -

and the cost function

-

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

 
- -

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

-
- -
-

Layout of a simple neural network with one hidden layer

- -

-
-

-
-

-
- -
-

The derivatives

- -

The derivatives are now, using the chain rule again

- -

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

 
- -

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

 
- -

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

 
- -

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

 
- -

Can you generalize this to more than one hidden layer?

-
- -
-

Important observations

- -
- -

-

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

-
-
- -
-

The training

- -

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

- -

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

 
- -

and

-

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

 
- -

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

- -

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

- -

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

-
- -
-

Code example

- -

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

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

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

-
- -
- - -

Exercise 1: Including more data

- -

Try to increase the amount of input and -target/output data. Try also to perform calculations for more values -of the learning rates. Feel free to add either hyperparameters with an -\( l_1 \) norm or an \( l_2 \) norm and discuss your results. -Discuss your results as functions of the amount of training data and various learning rates. -

- -

Challenge: Try to change the activation functions and replace the hard-coded analytical expressions with automatic derivation via either autograd or JAX.

- - -
- -
-

Simple neural network and the back propagation equations

- -

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

- -

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

-

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

 
- -

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

-

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

 
-

- -
-

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

- -

-
-

-
-

-
- -
-

The ouput layer

- -

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

-

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

 
- -

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

-

 
-$$ -\boldsymbol{\Theta}=\left\{w_{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\}. -$$ -

 
-

- -
-

Compact expressions

- -

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

-

 
-$$ -\begin{bmatrix}z_0^{(1)} \\ z_1^{(1)} \end{bmatrix}=\begin{bmatrix}w_{00}^{(1)} & w_{01}^{(1)}\\ w_{10}^{(1)} &w_{11}^{(1)} \end{bmatrix}\begin{bmatrix}a_0^{(0)} \\ a_1^{(0)} \end{bmatrix}+\begin{bmatrix}b_0^{(1)} \\ b_1^{(1)} \end{bmatrix}, -$$ -

 
- -

with outputs

-

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

 
-

- -
-

Output layer

- -

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

-

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

 
- -

resulting in the output

-

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

 
-

- -
-

Explicit derivatives

- -

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

- -

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

 
- -

with

-

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

 
- -

and finally

-

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

 
-

- -
-

Derivatives of the hidden layer

- -

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

-

 
-$$ -\frac{\partial C}{\partial w_{00}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\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)}}, -$$ -

 
- -

which, noting that

-

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

 
- -

allows us to rewrite

-

 
-$$ -\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)}. -$$ -

 
-

- -
-

Final expression

-

Defining

-

 
-$$ -\delta_0^{(1)}=w_0^{(2)}\frac{\partial a_0^{(1)}}{\partial z_0^{(1)}}\delta^{(2)}, -$$ -

 
- -

we have

-

 
-$$ -\frac{\partial C}{\partial w_{00}^{(1)}}=\delta_0^{(1)}a_0^{(1)}. -$$ -

 
- -

Similarly, we obtain

-

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

 
-

- -
-

Completing the list

- -

Similarly, we find

-

 
-$$ -\frac{\partial C}{\partial w_{10}^{(1)}}=\delta_1^{(1)}a_0^{(1)}, -$$ -

 
- -

and

-

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

 
- -

where we have defined

-

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

 
-

- -
-

Final expressions for the biases of the hidden layer

- -

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

-

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

 
- -

and

-

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

 
- -

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

-
- -
-

Gradient expressions

- -

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

-

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

 
- -

and

-

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

 
- -

and

-

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

 
- -

and

-

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

 
- -

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

-
- -
- - -

Exercise 2: Extended program

- -

We extend our simple code to a function which depends on two variable \( x_0 \) and \( x_1 \), that is

-

 
-$$ -y=f(x_0,x_1)=x_0^2+3x_0x_1+x_1^2+5. -$$ -

 
- -

We feed our network with \( n=100 \) entries \( x_0 \) and \( x_1 \). We have thus two features represented by these variable and an input matrix/design matrix \( \boldsymbol{X}\in \mathbf{R}^{n\times 2} \)

-

 
-$$ -\boldsymbol{X}=\begin{bmatrix} x_{00} & x_{01} \\ x_{00} & x_{01} \\ x_{10} & x_{11} \\ x_{20} & x_{21} \\ \dots & \dots \\ \dots & \dots \\ x_{n-20} & x_{n-21} \\ x_{n-10} & x_{n-11} \end{bmatrix}. -$$ -

 
- -

Write a code, based on the previous code examples, which takes as input these data and fit the above function. -You can extend your code to include automatic differentiation. -

- -

With these examples, we are now ready to embark upon the writing of more a general code for neural networks.

- - -
- -
-

Getting serious, the back propagation equations for a neural network

- -

Now it is time to move away from one node in each layer only. Our inputs are also represented either by several inputs.

- -

We have thus

-

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

 
- -

Defining

-

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

 
- -

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

-

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

 
-

- -
-

Analyzing the last results

- -

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

-
- -
-

More considerations

- -

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

- -

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

 
- -

With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely

-

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

 
-

- -
-

Derivatives in terms of \( z_j^L \)

- -

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

- -

 
-$$ -\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, -$$ -

 
- -

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

-

 
-$$ -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, -$$ -

 
- -

That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias.

-
- -
-

Bringing it together

- -

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

- -

 
-$$ -\begin{equation} -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}, -\tag{2} -\end{equation} -$$ -

 
- -

and

-

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

 
- -

and

- -

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

 
-

- -
-

Final back propagating equation

- -

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

-

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

 
- -

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

-
- -
-

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

- -

We obtain

-

 
-$$ -\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, -$$ -

 
- -

and recalling that

-

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

 
- -

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

-

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

 
- -

This is our final equation.

- -

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

-
- -
-

Setting up the back propagation algorithm

- -

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.

- -

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

- -

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

- -

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

-
- -
-

Setting up the back propagation algorithm, part 2

- -

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

-

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

 
- -

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

-

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

 
-

- -
-

Setting up the Back propagation algorithm, part 3

- -

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

- -

 
-$$ -w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, -$$ -

 
- -

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

 
- -

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

-
- -
-

Updating the gradients

- -

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

-

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

 
- -

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

-

 
-$$ -w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, -$$ -

 
- -

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

 
-

- -
-

Activation functions

- -

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

- -
    - -

  • Non-constant
  • - -

  • Bounded
  • - -

  • Monotonically-increasing
  • - -

  • Continuous
  • -
-
- -
-

Activation functions, Logistic and Hyperbolic ones

- -

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

- -

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

- -

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

 
- -

and the hyperbolic tangent function

-

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

 
-

- -
-

Relevance

- -

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

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

Fine-tuning neural network hyperparameters

- -

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

- -
    -

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

-

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

- -
    -

  • You can use randomized search.
  • -

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

Hidden layers

- -

For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set you ca 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. -

-
- -
-

Vanishing gradients

- -

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

- -

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

-
- -
-

Exploding gradients

- -

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

-
- -
-

Is the Logistic activation function (Sigmoid) our choice?

- -

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

- -

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

-
- -
-

Logistic function as the root of problems

- -

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

-
- -
-

The derivative of the Logistic funtion

- -

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

- -

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

-
- -
-

Insights from the paper by Glorot and Bengio

- -

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

-
- -
-

The RELU function family

- -

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

- -

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

-
- -
-

ELU function

- -

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

- -

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

 
-

- -
-

Which activation function should we use?

- -

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

- -

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

-
- -
-

More on activation functions, output layers

- -

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

- -

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

- -For the output layer: - -
    -

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

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

Batch Normalization

- -

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

- -

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

-
- -
-

Dropout

- -

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

- -

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

-
- -
-

Gradient Clipping

- -

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

- -

This technique is called Gradient Clipping.

- -

In general however, Batch -Normalization is preferred. -

-
- -
-

A top-down perspective on Neural networks

- -

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

- -
    -

  1. Estimate optimal error rate
  2. -

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

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

More top-down perspectives

- -

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

- -

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

-
- -
-

Limitations of supervised learning with deep networks

- -

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

-
- -
-

Limitations of NNs

- -

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

- -
    -

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

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

Homogeneous data

- -
    -

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

More limitations

- -
    -

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

-

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

-
- - - -
-
- - - - - - - - - - - - - diff --git a/doc/src/week41/week41-solarized.html b/doc/src/week41/week41-solarized.html deleted file mode 100644 index c22ccca46..000000000 --- a/doc/src/week41/week41-solarized.html +++ /dev/null @@ -1,2750 +0,0 @@ - - - - - - - -Week 41 Neural networks and constructing a neural network code - - - - - - - - - - - - - - - - - - -
-

Week 41 Neural networks and constructing a neural network code

-
- - -
-Morten Hjorth-Jensen -
- -
-Department of Physics, University of Oslo -
-
-
-

Week 41

-
-
- -









-

Plan for week 41, October 7-11

- -









-

Material for the lecture on Monday October 7, 2024

-
    -
  1. Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
  2. -
  3. Building our own Feed-forward Neural Network - -
  4. -
-
-Readings and Videos: -

-

    -
  1. These lecture notes
  2. -
  3. Rashcka et al chapter 11
  4. -
  5. For neural networks we recommend Goodfellow et al chapter 6. -
      -
    1. Neural Networks demystified at https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs
    2. -
    -
  6. Building Neural Networks from scratch at https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex
  7. -
  8. Video on Neural Networks at https://www.youtube.com/watch?v=CqOfi41LfDw
  9. -
  10. Video on the back propagation algorithm at https://www.youtube.com/watch?v=Ilg3gGewQ5U
  11. -
-

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

-
- - -









-

Material for the active learning sessions on Tuesday and Wednesday

-
    -
  • Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation
  • -
  • One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code
  • -
  • Discussion of project 2
  • -
  • Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent
  • -
-









-

Lecture Monday October 7

- -









-

Introduction to Neural networks

- -

Artificial neural networks are computational systems that can learn to -perform tasks by considering examples, generally without being -programmed with any task-specific rules. It is supposed to mimic a -biological system, wherein neurons interact by sending signals in the -form of mathematical functions between layers. All layers can contain -an arbitrary number of neurons, and each connection is represented by -a weight variable. -

- -









-

Artificial neurons

- -

The field of artificial neural networks has a long history of -development, and is closely connected with the advancement of computer -science and computers in general. A model of artificial neurons was -first developed by McCulloch and Pitts in 1943 to study signal -processing in the brain and has later been refined by others. The -general idea is to mimic neural networks in the human brain, which is -composed of billions of neurons that communicate with each other by -sending electrical signals. Each neuron accumulates its incoming -signals, which must exceed an activation threshold to yield an -output. If the threshold is not overcome, the neuron remains inactive, -i.e. has zero output. -

- -

This behaviour has inspired a simple mathematical model for an artificial neuron.

- -$$ -\begin{equation} - y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u) -\label{artificialNeuron} -\end{equation} -$$ - -

Here, the output \( y \) of the neuron is the value of its activation function, which have as input -a weighted sum of signals \( x_i, \dots ,x_n \) received by \( n \) other neurons. -

- -

Conceptually, it is helpful to divide neural networks into four -categories: -

-
    -
  1. general purpose neural networks for supervised learning,
  2. -
  3. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),
  4. -
  5. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and
  6. -
  7. neural networks for unsupervised learning such as Deep Boltzmann Machines.
  8. -
-

In natural science, DNNs and CNNs have already found numerous -applications. In statistical physics, they have been applied to detect -phase transitions in 2D Ising and Potts models, lattice gauge -theories, and different phases of polymers, or solving the -Navier-Stokes equation in weather forecasting. Deep learning has also -found interesting applications in quantum physics. Various quantum -phase transitions can be detected and studied using DNNs and CNNs, -topological phases, and even non-equilibrium many-body -localization. Representing quantum states as DNNs quantum state -tomography are among some of the impressive achievements to reveal the -potential of DNNs to facilitate the study of quantum systems. -

- -

In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. -

- -

The applications are not limited to the natural sciences. There is a -plethora of applications in essentially all disciplines, from the -humanities to life science and medicine. -

- -









-

Neural network types

- -

An artificial neural network (ANN), is a computational model that -consists of layers of connected neurons, or nodes or units. We will -refer to these interchangeably as units or nodes, and sometimes as -neurons. -

- -

It is supposed to mimic a biological nervous system by letting each -neuron interact with other neurons by sending signals in the form of -mathematical functions between layers. A wide variety of different -ANNs have been developed, but most of them consist of an input layer, -an output layer and eventual layers in-between, called hidden -layers. All layers can contain an arbitrary number of nodes, and each -connection between two nodes is associated with a weight variable. -

- -

Neural networks (also called neural nets) are neural-inspired -nonlinear models for supervised learning. As we will see, neural nets -can be viewed as natural, more powerful extensions of supervised -learning methods such as linear and logistic regression and soft-max -methods we discussed earlier. -

- -









-

Feed-forward neural networks

- -

The feed-forward neural network (FFNN) was the first and simplest type -of ANNs that were devised. In this network, the information moves in -only one direction: forward through the layers. -

- -

Nodes are represented by circles, while the arrows display the -connections between the nodes, including the direction of information -flow. Additionally, each arrow corresponds to a weight variable -(figure to come). We observe that each node in a layer is connected -to all nodes in the subsequent layer, making this a so-called -fully-connected FFNN. -

- -









-

Convolutional Neural Network

- -

A different variant of FFNNs are convolutional neural networks -(CNNs), which have a connectivity pattern inspired by the animal -visual cortex. Individual neurons in the visual cortex only respond to -stimuli from small sub-regions of the visual field, called a receptive -field. This makes the neurons well-suited to exploit the strong -spatially local correlation present in natural images. The response of -each neuron can be approximated mathematically as a convolution -operation. (figure to come) -

- -

Convolutional neural networks emulate the behaviour of neurons in the -visual cortex by enforcing a local connectivity pattern between -nodes of adjacent layers: Each node in a convolutional layer is -connected only to a subset of the nodes in the previous layer, in -contrast to the fully-connected FFNN. Often, CNNs consist of several -convolutional layers that learn local features of the input, with a -fully-connected layer at the end, which gathers all the local data and -produces the outputs. They have wide applications in image and video -recognition. -

- -









-

Recurrent neural networks

- -

So far we have only mentioned ANNs where information flows in one -direction: forward. Recurrent neural networks on the other hand, -have connections between nodes that form directed cycles. This -creates a form of internal memory which are able to capture -information on what has been calculated before; the output is -dependent on the previous computations. Recurrent NNs make use of -sequential information by performing the same task for every element -in a sequence, where each element depends on previous elements. An -example of such information is sentences, making recurrent NNs -especially well-suited for handwriting and speech recognition. -

- -









-

Other types of networks

- -

There are many other kinds of ANNs that have been developed. One type -that is specifically designed for interpolation in multidimensional -space is the radial basis function (RBF) network. RBFs are typically -made up of three layers: an input layer, a hidden layer with -non-linear radial symmetric activation functions and a linear output -layer (''linear'' here means that each node in the output layer has a -linear activation function). The layers are normally fully-connected -and there are no cycles, thus RBFs can be viewed as a type of -fully-connected FFNN. They are however usually treated as a separate -type of NN due the unusual activation functions. -

- -









-

Multilayer perceptrons

- -

One uses often so-called fully-connected feed-forward neural networks -with three or more layers (an input layer, one or more hidden layers -and an output layer) consisting of neurons that have non-linear -activation functions. -

- -

Such networks are often called multilayer perceptrons (MLPs).

- -









-

Why multilayer perceptrons?

- -

According to the Universal approximation theorem, a feed-forward -neural network with just a single hidden layer containing a finite -number of neurons can approximate a continuous multidimensional -function to arbitrary accuracy, assuming the activation function for -the hidden layer is a non-constant, bounded and -monotonically-increasing continuous function. -

- -

Note that the requirements on the activation function only applies to -the hidden layer, the output nodes are always assumed to be linear, so -as to not restrict the range of output values. -

- -









-

Illustration of a single perceptron model and a multi-perceptron model

- -
-
-
-

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

-
-

-
- -









-

Examples of XOR, OR and AND gates

- -

Let us first try to fit various gates using standard linear -regression. The gates we are thinking of are the classical XOR, OR and -AND gates, well-known elements in computer science. The tables here -show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a -specific target \( y_i \). -

- - - -
-
-
-
-
-
"""
-Simple code that tests XOR, OR and AND gates with linear regression
-"""
-
-import numpy as np
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX  matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX  matrix:{Xinv}")
-
-# The XOR gate 
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR  = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction  for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate 
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR  = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction  for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate 
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND  = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

What is happening here?

- -









-

Does Logistic Regression do a better Job?

- - - -
-
-
-
-
-
"""
-Simple code that tests XOR and OR gates with linear regression
-and logistic regression
-"""
-
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LogisticRegression
-import numpy as np
-
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX  matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX  matrix:{Xinv}")
-
-# The XOR gate 
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR  = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction  for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate 
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR  = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction  for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate 
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND  = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
-
-# Now we change to logistic regression
-
-
-# Logistic Regression
-logreg = LogisticRegression()
-logreg.fit(X, yOR)
-print("Test set accuracy with Logistic Regression for OR gate: {:.2f}".format(logreg.score(X,yOR)))
-
-logreg.fit(X, yXOR)
-print("Test set accuracy with Logistic Regression for XOR gate: {:.2f}".format(logreg.score(X,yXOR)))
-
-
-logreg.fit(X, yAND)
-print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Not exactly impressive, but somewhat better.

- -









-

Adding Neural Networks

- - - -
-
-
-
-
-
# and now neural networks with Scikit-Learn and the XOR
-
-from sklearn.neural_network import MLPClassifier
-from sklearn.datasets import make_classification
-X, yXOR = make_classification(n_samples=100, random_state=1)
-FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)
-FFNN.predict_proba(X)
-print(f"Test set accuracy with Feed Forward Neural Network  for XOR gate:{FFNN.score(X, yXOR)}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Mathematics of deep learning

- - - - -









-

Reminder on books with hands-on material and codes

- - - -









-

Reading recommendations

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









-

Mathematics of deep learning and neural networks

- -

Neural networks, in its so-called feed-forward form, where each -iterations contains a feed-forward stage and a back-propgagation -stage, consist of series of affine matrix-matrix and matrix-vector -multiplications. The unknown parameters (the so-called biases and -weights which deternine the architecture of a neural network), are -uptaded iteratively using the so-called back-propagation algorithm. -This algorithm corresponds to the so-called reverse mode of -automatic differentation. -

- -









-

Basics of an NN

- -

A neural network consists of a series of hidden layers, in addition to -the input and output layers. Each layer \( l \) has a set of parameters -\( \boldsymbol{\Theta}^{(l)}=(\boldsymbol{W}^{(l)},\boldsymbol{b}^{(l)}) \) which are related to the -parameters in other layers through a series of affine transformations, -for a standard NN these are matrix-matrix and matrix-vector -multiplications. For all layers we will simply use a collective variable \( \boldsymbol{\Theta} \). -

- -

It consist of two basic steps:

-
    -
  1. a feed forward stage which takes a given input and produces a final output which is compared with the target values through our cost/loss function.
  2. -
  3. a back-propagation state where the unknown parameters \( \boldsymbol{\Theta} \) are updated through the optimization of the their gradients. The expressions for the gradients are obtained via the chain rule, starting from the derivative of the cost/function.
  4. -
-

These two steps make up one iteration. This iterative process is continued till we reach an eventual stopping criterion.

- -









-

Overarching view of a neural network

- -

The architecture of a neural network defines our model. This model -aims at describing some function \( f(\boldsymbol{x} \) which represents -some final result (outputs or tagrget values) given a specific inpput -\( \boldsymbol{x} \). Note that here \( \boldsymbol{y} \) and \( \boldsymbol{x} \) are not limited to be -vectors. -

- -

The architecture consists of

-
    -
  1. An input and an output layer where the input layer is defined by the inputs \( \boldsymbol{x} \). The output layer produces the model ouput \( \boldsymbol{\tilde{y}} \) which is compared with the target value \( \boldsymbol{y} \)
  2. -
  3. A given number of hidden layers and neurons/nodes/units for each layer (this may vary)
  4. -
  5. A given activation function \( \sigma(\boldsymbol{z}) \) with arguments \( \boldsymbol{z} \) to be defined below. The activation functions may differ from layer to layer.
  6. -
  7. The last layer, normally called output layer has normally an activation function tailored to the specific problem
  8. -
  9. Finally we define a so-called cost or loss function which is used to gauge the quality of our model.
  10. -
-









-

The optimization problem

- -

The cost function is a function of the unknown parameters -\( \boldsymbol{\Theta} \) where the latter is a container for all possible -parameters needed to define a neural network -

- -

If we are dealing with a regression task a typical cost/loss function -is the mean squared error -

-$$ -C(\boldsymbol{\Theta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)\right\}. -$$ - -

This function represents one of many possible ways to define -the so-called cost function. Note that here we have assumed a linear dependence in terms of the paramters \( \boldsymbol{\Theta} \). This is in general not the case. -

- -









-

Parameters of neural networks

-

For neural networks the parameters -\( \boldsymbol{\Theta} \) are given by the so-called weights and biases (to be -defined below). -

- -

The weights are given by matrix elements \( w_{ij}^{(l)} \) where the -superscript indicates the layer number. The biases are typically given -by vector elements representing each single node of a given layer, -that is \( b_j^{(l)} \). -

- -









-

Other ingredients of a neural network

- -

Having defined the architecture of a neural network, the optimization -of the cost function with respect to the parameters \( \boldsymbol{\Theta} \), -involves the calculations of gradients and their optimization. The -gradients represent the derivatives of a multidimensional object and -are often approximated by various gradient methods, including -

-
    -
  1. various quasi-Newton methods,
  2. -
  3. plain gradient descent (GD) with a constant learning rate \( \eta \),
  4. -
  5. GD with momentum and other approximations to the learning rates such as
  6. -
      -
    • Adapative gradient (ADAgrad)
    • -
    • Root mean-square propagation (RMSprop)
    • -
    • Adaptive gradient with momentum (ADAM) and many other
    • -
    -
  7. Stochastic gradient descent and various families of learning rate approximations
  8. -
-









-

Other parameters

- -

In addition to the above, there are often additional hyperparamaters -which are included in the setup of a neural network. These will be -discussed below. -

- -









-

Universal approximation theorem

- -

The universal approximation theorem plays a central role in deep -learning. Cybenko (1989) showed -the following: -

- -
- -

-

Let \( \sigma \) be any continuous sigmoidal function such that

-$$ -\sigma(z) = \left\{\begin{array}{cc} 1 & z\rightarrow \infty\\ 0 & z \rightarrow -\infty \end{array}\right. -$$ - -

Given a continuous and deterministic function \( F(\boldsymbol{x}) \) on the unit -cube in \( d \)-dimensions \( F\in [0,1]^d \), \( x\in [0,1]^d \) and a parameter -\( \epsilon >0 \), there is a one-layer (hidden) neural network -\( f(\boldsymbol{x};\boldsymbol{\Theta}) \) with \( \boldsymbol{\Theta}=(\boldsymbol{W},\boldsymbol{b}) \) and \( \boldsymbol{W}\in -\mathbb{R}^{m\times n} \) and \( \boldsymbol{b}\in \mathbb{R}^{n} \), for which -

-$$ -\vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert < \epsilon \hspace{0.1cm} \forall \boldsymbol{x}\in[0,1]^d. -$$ -
- - -









-

Some parallels from real analysis

- -

For those of you familiar with for example the Stone-Weierstrass -theorem -for polynomial approximations or the convergence criterion for Fourier -series, there are similarities in the derivation of the proof for -neural networks. -

- -









-

The approximation theorem in words

- -

Any continuous function \( y=F(\boldsymbol{x}) \) supported on the unit cube in -\( d \)-dimensions can be approximated by a one-layer sigmoidal network to -arbitrary accuracy. -

- -

Hornik (1991) extended the theorem by letting any non-constant, bounded activation function to be included using that the expectation value

-$$ -\mathbb{E}[\vert F(\boldsymbol{x})\vert^2] =\int_{\boldsymbol{x}\in D} \vert F(\boldsymbol{x})\vert^2p(\boldsymbol{x})d\boldsymbol{x} < \infty. -$$ - -

Then we have

-$$ -\mathbb{E}[\vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert^2] =\int_{\boldsymbol{x}\in D} \vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert^2p(\boldsymbol{x})d\boldsymbol{x} < \epsilon. -$$ - - -









-

More on the general approximation theorem

- -

None of the proofs give any insight into the relation between the -number of of hidden layers and nodes and the approximation error -\( \epsilon \), nor the magnitudes of \( \boldsymbol{W} \) and \( \boldsymbol{b} \). -

- -

Neural networks (NNs) have what we may call a kind of universality no matter what function we want to compute.

- -
- -

-

It does not mean that an NN can be used to exactly compute any function. Rather, we get an approximation that is as good as we want.

-
- - -









-

Class of functions we can approximate

- -
- -

-

The class of functions that can be approximated are the continuous ones. -If the function \( F(\boldsymbol{x}) \) is discontinuous, it won't in general be possible to approximate it. However, an NN may still give an approximation even if we fail in some points. -

-
- - -









-

Setting up the equations for a neural network

- -

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

- -

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

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

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

- -









-

Layout of a neural network with three hidden layers

- -

-
-

-
-

- -









-

Definitions

- -

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

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

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

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









-

Inputs to the activation function

- -

With the activation values \( \boldsymbol{z}^l \) we can in turn define the -output of layer \( l \) as \( \boldsymbol{a}^l = f(\boldsymbol{z}^l) \) where \( f \) 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 \( f \) for all layers -and their nodes. It means we have -

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









-

Derivatives and the chain rule

- -

From the definition of the activation \( z_j^l \) we have

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

and

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

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

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









-

Derivative of the cost function

- -

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

- -

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

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

The derivative of this function with respect to the weights is

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

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

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









-

Simpler examples first, and automatic differentiation

- -

In order to understand the back propagation algorithm and its -derivation (an implementation of the chain rule), let us first digress -with some simple examples. These examples are also meant to motivate -the link with back propagation and automatic differentiation. -

- -









-

Reminder on the chain rule and gradients

- -

If we have a multivariate function \( f(x,y) \) where \( x=x(t) \) and \( y=y(t) \) are functions of a variable \( t \), we have that the gradient of \( f \) with respect to \( t \) (without the explicit unit vector components)

-$$ -\frac{df}{dt} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial t} \end{bmatrix}=\frac{\partial f}{\partial x} \frac{\partial x}{\partial t} +\frac{\partial f}{\partial y} \frac{\partial y}{\partial t}. -$$ - - -









-

Multivariable functions

- -

If we have a multivariate function \( f(x,y) \) where \( x=x(t,s) \) and \( y=y(t,s) \) are functions of the variables \( t \) and \( s \), we have that the partial derivatives

-$$ -\frac{\partial f}{\partial s}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial s}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial s}, -$$ - -

and

-$$ -\frac{\partial f}{\partial t}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial t}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial t}. -$$ - -

the gradient of \( f \) with respect to \( t \) and \( s \) (without the explicit unit vector components)

-$$ -\frac{df}{d(s,t)} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial s} &\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial s} & \frac{\partial y}{\partial t} \end{bmatrix}. -$$ - - -









-

Automatic differentiation through examples

- -

A great introduction to automatic differentiation is given by Baydin et al., see https://arxiv.org/abs/1502.05767.

- -

Automatic differentiation is a represented by a repeated application -of the chain rule on well-known functions and allows for the -calculation of derivatives to numerical precision. It is not the same -as the calculation of symbolic derivatives via for example SymPy, nor -does it use approximative formulae based on Taylor-expansions of a -function around a given value. The latter are error prone due to -truncation errors and values of the step size \( \Delta \). -

- -









-

Simple example

- -

Our first example is rather simple,

-$$ -f(x) =\exp{x^2}, -$$ - -

with derivative

-$$ -f'(x) =2x\exp{x^2}. -$$ - -

We can use SymPy to extract the pertinent lines of Python code through the following simple example

- - -
-
-
-
-
-
from __future__ import division
-from sympy import *
-x = symbols('x')
-expr = exp(x*x)
-simplify(expr)
-derivative = diff(expr,x)
-print(python(expr))
-print(python(derivative))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Smarter way of evaluating the above function

-

If we study this function, we note that we can reduce the number of operations by introducing an intermediate variable

-$$ -a = x^2, -$$ - -

leading to

-$$ -f(x) = f(a(x)) = b= \exp{a}. -$$ - -

We now assume that all operations can be counted in terms of equal -floating point operations. This means that in order to calculate -\( f(x) \) we need first to square \( x \) and then compute the exponential. We -have thus two floating point operations only. -

- -









-

Reducing the number of operations

- -

With the introduction of a precalculated quantity \( a \) and thereby \( f(x) \) we have that the derivative can be written as

- -$$ -f'(x) = 2xb, -$$ - -

which reduces the number of operations from four in the orginal -expression to two. This means that if we need to compute \( f(x) \) and -its derivative (a common task in optimizations), we have reduced the -number of operations from six to four in total. -

- -

Note that the usage of a symbolic software like SymPy does not -include such simplifications and the calculations of the function and -the derivatives yield in general more floating point operations. -

- -









-

Chain rule, forward and reverse modes

- -

In the above example we have introduced the variables \( a \) and \( b \), and our function is

-$$ -f(x) = f(a(x)) = b= \exp{a}, -$$ - -

with \( a=x^2 \). We can decompose the derivative of \( f \) with respect to \( x \) as

-$$ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}. -$$ - -

We note that since \( b=f(x) \) that

-$$ -\frac{df}{db}=1, -$$ - -

leading to

-$$ -\frac{df}{dx}=\frac{db}{da}\frac{da}{dx}=2x\exp{x^2}, -$$ - -

as before.

- -









-

Forward and reverse modes

- -

We have that

-$$ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}, -$$ - -

which we can rewrite either as

-$$ -\frac{df}{dx}=\left[\frac{df}{db}\frac{db}{da}\right]\frac{da}{dx}, -$$ - -

or

-$$ -\frac{df}{dx}=\frac{df}{db}\left[\frac{db}{da}\frac{da}{dx}\right]. -$$ - -

The first expression is called reverse mode (or back propagation) -since we start by evaluating the derivatives at the end point and then -propagate backwards. This is the standard way of evaluating -derivatives (gradients) when optimizing the parameters of a neural -network. In the context of deep learning this is computationally -more efficient since the output of a neural network consists of either -one or some few other output variables. -

- -

The second equation defines the so-called forward mode.

- -









-

More complicated function

- -

We increase our ambitions and introduce a slightly more complicated function

-$$ -f(x) =\sqrt{x^2+exp{x^2}}, -$$ - -

with derivative

-$$ -f'(x) =\frac{x(1+\exp{x^2})}{\sqrt{x^2+exp{x^2}}}. -$$ - -

The corresponding SymPy code reads

- - -
-
-
-
-
-
from __future__ import division
-from sympy import *
-x = symbols('x')
-expr = sqrt(x*x+exp(x*x))
-simplify(expr)
-derivative = diff(expr,x)
-print(python(expr))
-print(python(derivative))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Counting the number of floating point operations

- -

A simple count of operations shows that we need five operations for -the function itself and ten for the derivative. Fifteen operations in total if we wish to proceed with the above codes. -

- -

Can we reduce this to -say half the number of operations? -

- -









-

Defining intermediate operations

- -

We can indeed reduce the number of operation to half of those listed in the brute force approach above. -We define the following quantities -

-$$ -a = x^2, -$$ - -

and

-$$ -b = \exp{x^2} = \exp{a}, -$$ - -

and

-$$ -c= a+b, -$$ - -

and

-$$ -d=f(x)=\sqrt{c}. -$$ - - -









-

New expression for the derivative

- -

With these definitions we obtain the following partial derivatives

-$$ -\frac{\partial a}{\partial x} = 2x, -$$ - -

and

-$$ -\frac{\partial b}{\partial a} = \exp{a}, -$$ - -

and

-$$ -\frac{\partial c}{\partial a} = 1, -$$ - -

and

-$$ -\frac{\partial c}{\partial b} = 1, -$$ - -

and

-$$ -\frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -$$ - -

and finally

-$$ -\frac{\partial f}{\partial d} = 1. -$$ - - -









-

Final derivatives

-

Our final derivatives are thus

-$$ -\frac{\partial f}{\partial c} = \frac{\partial f}{\partial d} \frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -$$ - -$$ -\frac{\partial f}{\partial b} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial b} = \frac{1}{2\sqrt{c}}, -$$ - -$$ -\frac{\partial f}{\partial a} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial a}+ -\frac{\partial f}{\partial b} \frac{\partial b}{\partial a} = \frac{1+\exp{a}}{2\sqrt{c}}, -$$ - -

and finally

-$$ -\frac{\partial f}{\partial x} = \frac{\partial f}{\partial a} \frac{\partial a}{\partial x} = \frac{x(1+\exp{a})}{\sqrt{c}}, -$$ - -

which is just

-$$ -\frac{\partial f}{\partial x} = \frac{x(1+b)}{d}, -$$ - -

and requires only three operations if we can reuse all intermediate variables.

- -









-

In general not this simple

- -

In general, see the generalization below, unless we can obtain simple -analytical expressions which we can simplify further, the final -implementation of automatic differentiation involves repeated -calculations (and thereby operations) of derivatives of elementary -functions. -

- -









-

Automatic differentiation

- -

We can make this example more formal. Automatic differentiation is a -formalization of the previous example (see graph). -

- -

We define \( \boldsymbol{x}\in x_1,\dots, x_l \) input variables to a given function \( f(\boldsymbol{x}) \) and \( x_{l+1},\dots, x_L \) intermediate variables.

- -

In the above example we have only one input variable, \( l=1 \) and four intermediate variables, that is

-$$ -\begin{bmatrix} x_1=x & x_2 = x^2=a & x_3 =\exp{a}= b & x_4=c=a+b & x_5 = \sqrt{c}=d \end{bmatrix}. -$$ - -

Furthemore, for \( i=l+1, \dots, L \) (here \( i=2,3,4,5 \) and \( f=x_L=d \)), we -define the elementary functions \( g_i(x_{Pa(x_i)}) \) where \( x_{Pa(x_i)} \) are the parent nodes of the variable \( x_i \). -

- -

In our case, we have for example for \( x_3=g_3(x_{Pa(x_i)})=\exp{a} \), that \( g_3=\exp{()} \) and \( x_{Pa(x_3)}=a \).

- -









-

Chain rule

- -

We can now compute the gradients by back-propagating the derivatives using the chain rule. -We have defined -

-$$ -\frac{\partial f}{\partial x_L} = 1, -$$ - -

which allows us to find the derivatives of the various variables \( x_i \) as

-$$ -\frac{\partial f}{\partial x_i} = \sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial x_j}{\partial x_i}=\sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial g_j}{\partial x_i}. -$$ - -

Whenever we have a function which can be expressed as a computation -graph and the various functions can be expressed in terms of -elementary functions that are differentiable, then automatic -differentiation works. The functions may not need to be elementary -functions, they could also be computer programs, although not all -programs can be automatically differentiated. -

- -









-

First network example, simple percepetron with one input

- -

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

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

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

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









-

Layout of a simple neural network with no hidden layer

- -

-
-

-
-

- -









-

Optimizing the parameters

- -

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

- -

We need

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

Using the chain rule we find

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

and

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

which we later will just define as

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









-

Adding a hidden layer

- -

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

- -

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

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

and the cost function

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

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

- -









-

Layout of a simple neural network with one hidden layer

- -

-
-

-
-

- -









-

The derivatives

- -

The derivatives are now, using the chain rule again

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

Can you generalize this to more than one hidden layer?

- -









-

Important observations

- -
- -

-

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

-
- - -









-

The training

- -

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

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

and

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

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

- -

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

- -

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

- -









-

Code example

- -

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

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

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

- -









- - -

Exercise 1: Including more data

- -

Try to increase the amount of input and -target/output data. Try also to perform calculations for more values -of the learning rates. Feel free to add either hyperparameters with an -\( l_1 \) norm or an \( l_2 \) norm and discuss your results. -Discuss your results as functions of the amount of training data and various learning rates. -

- -

Challenge: Try to change the activation functions and replace the hard-coded analytical expressions with automatic derivation via either autograd or JAX.

- - - -









-

Simple neural network and the back propagation equations

- -

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

- -

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

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

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

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









-

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

- -

-
-

-
-

- -









-

The ouput layer

- -

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

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

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

-$$ -\boldsymbol{\Theta}=\left\{w_{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\}. -$$ - - -









-

Compact expressions

- -

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

-$$ -\begin{bmatrix}z_0^{(1)} \\ z_1^{(1)} \end{bmatrix}=\begin{bmatrix}w_{00}^{(1)} & w_{01}^{(1)}\\ w_{10}^{(1)} &w_{11}^{(1)} \end{bmatrix}\begin{bmatrix}a_0^{(0)} \\ a_1^{(0)} \end{bmatrix}+\begin{bmatrix}b_0^{(1)} \\ b_1^{(1)} \end{bmatrix}, -$$ - -

with outputs

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









-

Output layer

- -

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

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

resulting in the output

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









-

Explicit derivatives

- -

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

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

with

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

and finally

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









-

Derivatives of the hidden layer

- -

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

-$$ -\frac{\partial C}{\partial w_{00}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\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)}}, -$$ - -

which, noting that

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

allows us to rewrite

-$$ -\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)}. -$$ - - -









-

Final expression

-

Defining

-$$ -\delta_0^{(1)}=w_0^{(2)}\frac{\partial a_0^{(1)}}{\partial z_0^{(1)}}\delta^{(2)}, -$$ - -

we have

-$$ -\frac{\partial C}{\partial w_{00}^{(1)}}=\delta_0^{(1)}a_0^{(1)}. -$$ - -

Similarly, we obtain

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









-

Completing the list

- -

Similarly, we find

-$$ -\frac{\partial C}{\partial w_{10}^{(1)}}=\delta_1^{(1)}a_0^{(1)}, -$$ - -

and

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

where we have defined

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









-

Final expressions for the biases of the hidden layer

- -

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

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

and

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

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

- -









-

Gradient expressions

- -

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

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

and

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

and

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

and

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

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

- -









- - -

Exercise 2: Extended program

- -

We extend our simple code to a function which depends on two variable \( x_0 \) and \( x_1 \), that is

-$$ -y=f(x_0,x_1)=x_0^2+3x_0x_1+x_1^2+5. -$$ - -

We feed our network with \( n=100 \) entries \( x_0 \) and \( x_1 \). We have thus two features represented by these variable and an input matrix/design matrix \( \boldsymbol{X}\in \mathbf{R}^{n\times 2} \)

-$$ -\boldsymbol{X}=\begin{bmatrix} x_{00} & x_{01} \\ x_{00} & x_{01} \\ x_{10} & x_{11} \\ x_{20} & x_{21} \\ \dots & \dots \\ \dots & \dots \\ x_{n-20} & x_{n-21} \\ x_{n-10} & x_{n-11} \end{bmatrix}. -$$ - -

Write a code, based on the previous code examples, which takes as input these data and fit the above function. -You can extend your code to include automatic differentiation. -

- -

With these examples, we are now ready to embark upon the writing of more a general code for neural networks.

- - - -









-

Getting serious, the back propagation equations for a neural network

- -

Now it is time to move away from one node in each layer only. Our inputs are also represented either by several inputs.

- -

We have thus

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

Defining

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

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

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









-

Analyzing the last results

- -

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

- -









-

More considerations

- -

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

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

With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely

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









-

Derivatives in terms of \( z_j^L \)

- -

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

- -$$ -\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, -$$ - -

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

-$$ -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, -$$ - -

That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias.

- -









-

Bringing it together

- -

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

- -$$ -\begin{equation} -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}, -\label{_auto1} -\end{equation} -$$ - -

and

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

and

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









-

Final back propagating equation

- -

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

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

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

- -









-

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

- -

We obtain

-$$ -\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, -$$ - -

and recalling that

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

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

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

This is our final equation.

- -

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

- -









-

Setting up the back propagation algorithm

- -

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.

- -

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

- -

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

- -

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

- -









-

Setting up the back propagation algorithm, part 2

- -

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

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

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

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









-

Setting up the Back propagation algorithm, part 3

- -

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

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

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

- -









-

Updating the gradients

- -

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

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

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

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









-

Activation functions

- -

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

- -
    -
  • Non-constant
  • -
  • Bounded
  • -
  • Monotonically-increasing
  • -
  • Continuous
  • -
-









-

Activation functions, Logistic and Hyperbolic ones

- -

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

- -

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

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

and the hyperbolic tangent function

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









-

Relevance

- -

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

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









-

Fine-tuning neural network hyperparameters

- -

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

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

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

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









-

Hidden layers

- -

For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set you ca 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. -

- - -

Vanishing gradients

- -

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

- -

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

- -









-

Exploding gradients

- -

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

- - -

Is the Logistic activation function (Sigmoid) our choice?

- -

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

- -

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

- -









-

Logistic function as the root of problems

- -

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

- -









-

The derivative of the Logistic funtion

- -

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

- -

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

- -









-

Insights from the paper by Glorot and Bengio

- -

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

- -









-

The RELU function family

- -

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

- -

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

- -









-

ELU function

- -

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

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









-

Which activation function should we use?

- -

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

- -

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

- -









-

More on activation functions, output layers

- -

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

- -

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

- -For the output layer: - -
    -
  • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
  • -
  • For regression tasks, you can simply use no activation function at all.
  • -
-









-

Batch Normalization

- -

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

- -

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

- -









-

Dropout

- -

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

- -

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

- -









-

Gradient Clipping

- -

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

- -

This technique is called Gradient Clipping.

- -

In general however, Batch -Normalization is preferred. -

- - -

A top-down perspective on Neural networks

- -

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

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









-

More top-down perspectives

- -

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

- -

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

- -









-

Limitations of supervised learning with deep networks

- -

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

- -









-

Limitations of NNs

- -

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

- -
    -
  • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
  • -
  • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
  • -
-









-

Homogeneous data

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









-

More limitations

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

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

- - -
- © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - diff --git a/doc/src/week41/week41.do.txt b/doc/src/week41/week41.do.txt index d5d7d1d54..8ced9671d 100644 --- a/doc/src/week41/week41.do.txt +++ b/doc/src/week41/week41.do.txt @@ -10,8 +10,8 @@ DATE: Week 41 ===== Material for the lecture on Monday October 7, 2024 ===== o Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model. o Building our own Feed-forward Neural Network -# * "Video of lecture notes":"https://youtu.be/5-RRTO9uDvI" -# * "Whiteboard notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf" + * Video of lecture notes at URL:"https://youtu.be/pMRUbf9E-gM" + * Whiteboard notes at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf" !bblock Readings and Videos: o These lecture notes o Rashcka et al chapter 11 diff --git a/doc/src/week41/week41.html b/doc/src/week41/week41.html deleted file mode 100644 index 36ac3704e..000000000 --- a/doc/src/week41/week41.html +++ /dev/null @@ -1,2827 +0,0 @@ - - - - - - - -Week 41 Neural networks and constructing a neural network code - - - - - - - - - - - - - - -
-

Week 41 Neural networks and constructing a neural network code

-
- - -
-Morten Hjorth-Jensen -
- -
-Department of Physics, University of Oslo -
-
-
-

Week 41

-
-
- -









-

Plan for week 41, October 7-11

- -









-

Material for the lecture on Monday October 7, 2024

-
    -
  1. Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.
  2. -
  3. Building our own Feed-forward Neural Network - -
  4. -
-
-Readings and Videos: -

-

    -
  1. These lecture notes
  2. -
  3. Rashcka et al chapter 11
  4. -
  5. For neural networks we recommend Goodfellow et al chapter 6. -
      -
    1. Neural Networks demystified at https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs
    2. -
    -
  6. Building Neural Networks from scratch at https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex
  7. -
  8. Video on Neural Networks at https://www.youtube.com/watch?v=CqOfi41LfDw
  9. -
  10. Video on the back propagation algorithm at https://www.youtube.com/watch?v=Ilg3gGewQ5U
  11. -
-

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

-
- - -









-

Material for the active learning sessions on Tuesday and Wednesday

-
    -
  • Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation
  • -
  • One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code
  • -
  • Discussion of project 2
  • -
  • Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent
  • -
-









-

Lecture Monday October 7

- -









-

Introduction to Neural networks

- -

Artificial neural networks are computational systems that can learn to -perform tasks by considering examples, generally without being -programmed with any task-specific rules. It is supposed to mimic a -biological system, wherein neurons interact by sending signals in the -form of mathematical functions between layers. All layers can contain -an arbitrary number of neurons, and each connection is represented by -a weight variable. -

- -









-

Artificial neurons

- -

The field of artificial neural networks has a long history of -development, and is closely connected with the advancement of computer -science and computers in general. A model of artificial neurons was -first developed by McCulloch and Pitts in 1943 to study signal -processing in the brain and has later been refined by others. The -general idea is to mimic neural networks in the human brain, which is -composed of billions of neurons that communicate with each other by -sending electrical signals. Each neuron accumulates its incoming -signals, which must exceed an activation threshold to yield an -output. If the threshold is not overcome, the neuron remains inactive, -i.e. has zero output. -

- -

This behaviour has inspired a simple mathematical model for an artificial neuron.

- -$$ -\begin{equation} - y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u) -\label{artificialNeuron} -\end{equation} -$$ - -

Here, the output \( y \) of the neuron is the value of its activation function, which have as input -a weighted sum of signals \( x_i, \dots ,x_n \) received by \( n \) other neurons. -

- -

Conceptually, it is helpful to divide neural networks into four -categories: -

-
    -
  1. general purpose neural networks for supervised learning,
  2. -
  3. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),
  4. -
  5. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and
  6. -
  7. neural networks for unsupervised learning such as Deep Boltzmann Machines.
  8. -
-

In natural science, DNNs and CNNs have already found numerous -applications. In statistical physics, they have been applied to detect -phase transitions in 2D Ising and Potts models, lattice gauge -theories, and different phases of polymers, or solving the -Navier-Stokes equation in weather forecasting. Deep learning has also -found interesting applications in quantum physics. Various quantum -phase transitions can be detected and studied using DNNs and CNNs, -topological phases, and even non-equilibrium many-body -localization. Representing quantum states as DNNs quantum state -tomography are among some of the impressive achievements to reveal the -potential of DNNs to facilitate the study of quantum systems. -

- -

In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. -

- -

The applications are not limited to the natural sciences. There is a -plethora of applications in essentially all disciplines, from the -humanities to life science and medicine. -

- -









-

Neural network types

- -

An artificial neural network (ANN), is a computational model that -consists of layers of connected neurons, or nodes or units. We will -refer to these interchangeably as units or nodes, and sometimes as -neurons. -

- -

It is supposed to mimic a biological nervous system by letting each -neuron interact with other neurons by sending signals in the form of -mathematical functions between layers. A wide variety of different -ANNs have been developed, but most of them consist of an input layer, -an output layer and eventual layers in-between, called hidden -layers. All layers can contain an arbitrary number of nodes, and each -connection between two nodes is associated with a weight variable. -

- -

Neural networks (also called neural nets) are neural-inspired -nonlinear models for supervised learning. As we will see, neural nets -can be viewed as natural, more powerful extensions of supervised -learning methods such as linear and logistic regression and soft-max -methods we discussed earlier. -

- -









-

Feed-forward neural networks

- -

The feed-forward neural network (FFNN) was the first and simplest type -of ANNs that were devised. In this network, the information moves in -only one direction: forward through the layers. -

- -

Nodes are represented by circles, while the arrows display the -connections between the nodes, including the direction of information -flow. Additionally, each arrow corresponds to a weight variable -(figure to come). We observe that each node in a layer is connected -to all nodes in the subsequent layer, making this a so-called -fully-connected FFNN. -

- -









-

Convolutional Neural Network

- -

A different variant of FFNNs are convolutional neural networks -(CNNs), which have a connectivity pattern inspired by the animal -visual cortex. Individual neurons in the visual cortex only respond to -stimuli from small sub-regions of the visual field, called a receptive -field. This makes the neurons well-suited to exploit the strong -spatially local correlation present in natural images. The response of -each neuron can be approximated mathematically as a convolution -operation. (figure to come) -

- -

Convolutional neural networks emulate the behaviour of neurons in the -visual cortex by enforcing a local connectivity pattern between -nodes of adjacent layers: Each node in a convolutional layer is -connected only to a subset of the nodes in the previous layer, in -contrast to the fully-connected FFNN. Often, CNNs consist of several -convolutional layers that learn local features of the input, with a -fully-connected layer at the end, which gathers all the local data and -produces the outputs. They have wide applications in image and video -recognition. -

- -









-

Recurrent neural networks

- -

So far we have only mentioned ANNs where information flows in one -direction: forward. Recurrent neural networks on the other hand, -have connections between nodes that form directed cycles. This -creates a form of internal memory which are able to capture -information on what has been calculated before; the output is -dependent on the previous computations. Recurrent NNs make use of -sequential information by performing the same task for every element -in a sequence, where each element depends on previous elements. An -example of such information is sentences, making recurrent NNs -especially well-suited for handwriting and speech recognition. -

- -









-

Other types of networks

- -

There are many other kinds of ANNs that have been developed. One type -that is specifically designed for interpolation in multidimensional -space is the radial basis function (RBF) network. RBFs are typically -made up of three layers: an input layer, a hidden layer with -non-linear radial symmetric activation functions and a linear output -layer (''linear'' here means that each node in the output layer has a -linear activation function). The layers are normally fully-connected -and there are no cycles, thus RBFs can be viewed as a type of -fully-connected FFNN. They are however usually treated as a separate -type of NN due the unusual activation functions. -

- -









-

Multilayer perceptrons

- -

One uses often so-called fully-connected feed-forward neural networks -with three or more layers (an input layer, one or more hidden layers -and an output layer) consisting of neurons that have non-linear -activation functions. -

- -

Such networks are often called multilayer perceptrons (MLPs).

- -









-

Why multilayer perceptrons?

- -

According to the Universal approximation theorem, a feed-forward -neural network with just a single hidden layer containing a finite -number of neurons can approximate a continuous multidimensional -function to arbitrary accuracy, assuming the activation function for -the hidden layer is a non-constant, bounded and -monotonically-increasing continuous function. -

- -

Note that the requirements on the activation function only applies to -the hidden layer, the output nodes are always assumed to be linear, so -as to not restrict the range of output values. -

- -









-

Illustration of a single perceptron model and a multi-perceptron model

- -
-
-
-

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

-
-

-
- -









-

Examples of XOR, OR and AND gates

- -

Let us first try to fit various gates using standard linear -regression. The gates we are thinking of are the classical XOR, OR and -AND gates, well-known elements in computer science. The tables here -show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a -specific target \( y_i \). -

- - - -
-
-
-
-
-
"""
-Simple code that tests XOR, OR and AND gates with linear regression
-"""
-
-import numpy as np
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX  matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX  matrix:{Xinv}")
-
-# The XOR gate 
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR  = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction  for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate 
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR  = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction  for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate 
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND  = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

What is happening here?

- -









-

Does Logistic Regression do a better Job?

- - - -
-
-
-
-
-
"""
-Simple code that tests XOR and OR gates with linear regression
-and logistic regression
-"""
-
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LogisticRegression
-import numpy as np
-
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX  matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX  matrix:{Xinv}")
-
-# The XOR gate 
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR  = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction  for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate 
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR  = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction  for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate 
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND  = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction  for the AND gate:{X @ ThetaAND}")
-
-# Now we change to logistic regression
-
-
-# Logistic Regression
-logreg = LogisticRegression()
-logreg.fit(X, yOR)
-print("Test set accuracy with Logistic Regression for OR gate: {:.2f}".format(logreg.score(X,yOR)))
-
-logreg.fit(X, yXOR)
-print("Test set accuracy with Logistic Regression for XOR gate: {:.2f}".format(logreg.score(X,yXOR)))
-
-
-logreg.fit(X, yAND)
-print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Not exactly impressive, but somewhat better.

- -









-

Adding Neural Networks

- - - -
-
-
-
-
-
# and now neural networks with Scikit-Learn and the XOR
-
-from sklearn.neural_network import MLPClassifier
-from sklearn.datasets import make_classification
-X, yXOR = make_classification(n_samples=100, random_state=1)
-FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)
-FFNN.predict_proba(X)
-print(f"Test set accuracy with Feed Forward Neural Network  for XOR gate:{FFNN.score(X, yXOR)}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Mathematics of deep learning

- - - - -









-

Reminder on books with hands-on material and codes

- - - -









-

Reading recommendations

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









-

Mathematics of deep learning and neural networks

- -

Neural networks, in its so-called feed-forward form, where each -iterations contains a feed-forward stage and a back-propgagation -stage, consist of series of affine matrix-matrix and matrix-vector -multiplications. The unknown parameters (the so-called biases and -weights which deternine the architecture of a neural network), are -uptaded iteratively using the so-called back-propagation algorithm. -This algorithm corresponds to the so-called reverse mode of -automatic differentation. -

- -









-

Basics of an NN

- -

A neural network consists of a series of hidden layers, in addition to -the input and output layers. Each layer \( l \) has a set of parameters -\( \boldsymbol{\Theta}^{(l)}=(\boldsymbol{W}^{(l)},\boldsymbol{b}^{(l)}) \) which are related to the -parameters in other layers through a series of affine transformations, -for a standard NN these are matrix-matrix and matrix-vector -multiplications. For all layers we will simply use a collective variable \( \boldsymbol{\Theta} \). -

- -

It consist of two basic steps:

-
    -
  1. a feed forward stage which takes a given input and produces a final output which is compared with the target values through our cost/loss function.
  2. -
  3. a back-propagation state where the unknown parameters \( \boldsymbol{\Theta} \) are updated through the optimization of the their gradients. The expressions for the gradients are obtained via the chain rule, starting from the derivative of the cost/function.
  4. -
-

These two steps make up one iteration. This iterative process is continued till we reach an eventual stopping criterion.

- -









-

Overarching view of a neural network

- -

The architecture of a neural network defines our model. This model -aims at describing some function \( f(\boldsymbol{x} \) which represents -some final result (outputs or tagrget values) given a specific inpput -\( \boldsymbol{x} \). Note that here \( \boldsymbol{y} \) and \( \boldsymbol{x} \) are not limited to be -vectors. -

- -

The architecture consists of

-
    -
  1. An input and an output layer where the input layer is defined by the inputs \( \boldsymbol{x} \). The output layer produces the model ouput \( \boldsymbol{\tilde{y}} \) which is compared with the target value \( \boldsymbol{y} \)
  2. -
  3. A given number of hidden layers and neurons/nodes/units for each layer (this may vary)
  4. -
  5. A given activation function \( \sigma(\boldsymbol{z}) \) with arguments \( \boldsymbol{z} \) to be defined below. The activation functions may differ from layer to layer.
  6. -
  7. The last layer, normally called output layer has normally an activation function tailored to the specific problem
  8. -
  9. Finally we define a so-called cost or loss function which is used to gauge the quality of our model.
  10. -
-









-

The optimization problem

- -

The cost function is a function of the unknown parameters -\( \boldsymbol{\Theta} \) where the latter is a container for all possible -parameters needed to define a neural network -

- -

If we are dealing with a regression task a typical cost/loss function -is the mean squared error -

-$$ -C(\boldsymbol{\Theta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)\right\}. -$$ - -

This function represents one of many possible ways to define -the so-called cost function. Note that here we have assumed a linear dependence in terms of the paramters \( \boldsymbol{\Theta} \). This is in general not the case. -

- -









-

Parameters of neural networks

-

For neural networks the parameters -\( \boldsymbol{\Theta} \) are given by the so-called weights and biases (to be -defined below). -

- -

The weights are given by matrix elements \( w_{ij}^{(l)} \) where the -superscript indicates the layer number. The biases are typically given -by vector elements representing each single node of a given layer, -that is \( b_j^{(l)} \). -

- -









-

Other ingredients of a neural network

- -

Having defined the architecture of a neural network, the optimization -of the cost function with respect to the parameters \( \boldsymbol{\Theta} \), -involves the calculations of gradients and their optimization. The -gradients represent the derivatives of a multidimensional object and -are often approximated by various gradient methods, including -

-
    -
  1. various quasi-Newton methods,
  2. -
  3. plain gradient descent (GD) with a constant learning rate \( \eta \),
  4. -
  5. GD with momentum and other approximations to the learning rates such as
  6. -
      -
    • Adapative gradient (ADAgrad)
    • -
    • Root mean-square propagation (RMSprop)
    • -
    • Adaptive gradient with momentum (ADAM) and many other
    • -
    -
  7. Stochastic gradient descent and various families of learning rate approximations
  8. -
-









-

Other parameters

- -

In addition to the above, there are often additional hyperparamaters -which are included in the setup of a neural network. These will be -discussed below. -

- -









-

Universal approximation theorem

- -

The universal approximation theorem plays a central role in deep -learning. Cybenko (1989) showed -the following: -

- -
- -

-

Let \( \sigma \) be any continuous sigmoidal function such that

-$$ -\sigma(z) = \left\{\begin{array}{cc} 1 & z\rightarrow \infty\\ 0 & z \rightarrow -\infty \end{array}\right. -$$ - -

Given a continuous and deterministic function \( F(\boldsymbol{x}) \) on the unit -cube in \( d \)-dimensions \( F\in [0,1]^d \), \( x\in [0,1]^d \) and a parameter -\( \epsilon >0 \), there is a one-layer (hidden) neural network -\( f(\boldsymbol{x};\boldsymbol{\Theta}) \) with \( \boldsymbol{\Theta}=(\boldsymbol{W},\boldsymbol{b}) \) and \( \boldsymbol{W}\in -\mathbb{R}^{m\times n} \) and \( \boldsymbol{b}\in \mathbb{R}^{n} \), for which -

-$$ -\vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert < \epsilon \hspace{0.1cm} \forall \boldsymbol{x}\in[0,1]^d. -$$ -
- - -









-

Some parallels from real analysis

- -

For those of you familiar with for example the Stone-Weierstrass -theorem -for polynomial approximations or the convergence criterion for Fourier -series, there are similarities in the derivation of the proof for -neural networks. -

- -









-

The approximation theorem in words

- -

Any continuous function \( y=F(\boldsymbol{x}) \) supported on the unit cube in -\( d \)-dimensions can be approximated by a one-layer sigmoidal network to -arbitrary accuracy. -

- -

Hornik (1991) extended the theorem by letting any non-constant, bounded activation function to be included using that the expectation value

-$$ -\mathbb{E}[\vert F(\boldsymbol{x})\vert^2] =\int_{\boldsymbol{x}\in D} \vert F(\boldsymbol{x})\vert^2p(\boldsymbol{x})d\boldsymbol{x} < \infty. -$$ - -

Then we have

-$$ -\mathbb{E}[\vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert^2] =\int_{\boldsymbol{x}\in D} \vert F(\boldsymbol{x})-f(\boldsymbol{x};\boldsymbol{\Theta})\vert^2p(\boldsymbol{x})d\boldsymbol{x} < \epsilon. -$$ - - -









-

More on the general approximation theorem

- -

None of the proofs give any insight into the relation between the -number of of hidden layers and nodes and the approximation error -\( \epsilon \), nor the magnitudes of \( \boldsymbol{W} \) and \( \boldsymbol{b} \). -

- -

Neural networks (NNs) have what we may call a kind of universality no matter what function we want to compute.

- -
- -

-

It does not mean that an NN can be used to exactly compute any function. Rather, we get an approximation that is as good as we want.

-
- - -









-

Class of functions we can approximate

- -
- -

-

The class of functions that can be approximated are the continuous ones. -If the function \( F(\boldsymbol{x}) \) is discontinuous, it won't in general be possible to approximate it. However, an NN may still give an approximation even if we fail in some points. -

-
- - -









-

Setting up the equations for a neural network

- -

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

- -

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

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

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

- -









-

Layout of a neural network with three hidden layers

- -

-
-

-
-

- -









-

Definitions

- -

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

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

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

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









-

Inputs to the activation function

- -

With the activation values \( \boldsymbol{z}^l \) we can in turn define the -output of layer \( l \) as \( \boldsymbol{a}^l = f(\boldsymbol{z}^l) \) where \( f \) 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 \( f \) for all layers -and their nodes. It means we have -

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









-

Derivatives and the chain rule

- -

From the definition of the activation \( z_j^l \) we have

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

and

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

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

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









-

Derivative of the cost function

- -

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

- -

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

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

The derivative of this function with respect to the weights is

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

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

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









-

Simpler examples first, and automatic differentiation

- -

In order to understand the back propagation algorithm and its -derivation (an implementation of the chain rule), let us first digress -with some simple examples. These examples are also meant to motivate -the link with back propagation and automatic differentiation. -

- -









-

Reminder on the chain rule and gradients

- -

If we have a multivariate function \( f(x,y) \) where \( x=x(t) \) and \( y=y(t) \) are functions of a variable \( t \), we have that the gradient of \( f \) with respect to \( t \) (without the explicit unit vector components)

-$$ -\frac{df}{dt} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial t} \end{bmatrix}=\frac{\partial f}{\partial x} \frac{\partial x}{\partial t} +\frac{\partial f}{\partial y} \frac{\partial y}{\partial t}. -$$ - - -









-

Multivariable functions

- -

If we have a multivariate function \( f(x,y) \) where \( x=x(t,s) \) and \( y=y(t,s) \) are functions of the variables \( t \) and \( s \), we have that the partial derivatives

-$$ -\frac{\partial f}{\partial s}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial s}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial s}, -$$ - -

and

-$$ -\frac{\partial f}{\partial t}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial t}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial t}. -$$ - -

the gradient of \( f \) with respect to \( t \) and \( s \) (without the explicit unit vector components)

-$$ -\frac{df}{d(s,t)} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial s} &\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial s} & \frac{\partial y}{\partial t} \end{bmatrix}. -$$ - - -









-

Automatic differentiation through examples

- -

A great introduction to automatic differentiation is given by Baydin et al., see https://arxiv.org/abs/1502.05767.

- -

Automatic differentiation is a represented by a repeated application -of the chain rule on well-known functions and allows for the -calculation of derivatives to numerical precision. It is not the same -as the calculation of symbolic derivatives via for example SymPy, nor -does it use approximative formulae based on Taylor-expansions of a -function around a given value. The latter are error prone due to -truncation errors and values of the step size \( \Delta \). -

- -









-

Simple example

- -

Our first example is rather simple,

-$$ -f(x) =\exp{x^2}, -$$ - -

with derivative

-$$ -f'(x) =2x\exp{x^2}. -$$ - -

We can use SymPy to extract the pertinent lines of Python code through the following simple example

- - -
-
-
-
-
-
from __future__ import division
-from sympy import *
-x = symbols('x')
-expr = exp(x*x)
-simplify(expr)
-derivative = diff(expr,x)
-print(python(expr))
-print(python(derivative))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Smarter way of evaluating the above function

-

If we study this function, we note that we can reduce the number of operations by introducing an intermediate variable

-$$ -a = x^2, -$$ - -

leading to

-$$ -f(x) = f(a(x)) = b= \exp{a}. -$$ - -

We now assume that all operations can be counted in terms of equal -floating point operations. This means that in order to calculate -\( f(x) \) we need first to square \( x \) and then compute the exponential. We -have thus two floating point operations only. -

- -









-

Reducing the number of operations

- -

With the introduction of a precalculated quantity \( a \) and thereby \( f(x) \) we have that the derivative can be written as

- -$$ -f'(x) = 2xb, -$$ - -

which reduces the number of operations from four in the orginal -expression to two. This means that if we need to compute \( f(x) \) and -its derivative (a common task in optimizations), we have reduced the -number of operations from six to four in total. -

- -

Note that the usage of a symbolic software like SymPy does not -include such simplifications and the calculations of the function and -the derivatives yield in general more floating point operations. -

- -









-

Chain rule, forward and reverse modes

- -

In the above example we have introduced the variables \( a \) and \( b \), and our function is

-$$ -f(x) = f(a(x)) = b= \exp{a}, -$$ - -

with \( a=x^2 \). We can decompose the derivative of \( f \) with respect to \( x \) as

-$$ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}. -$$ - -

We note that since \( b=f(x) \) that

-$$ -\frac{df}{db}=1, -$$ - -

leading to

-$$ -\frac{df}{dx}=\frac{db}{da}\frac{da}{dx}=2x\exp{x^2}, -$$ - -

as before.

- -









-

Forward and reverse modes

- -

We have that

-$$ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}, -$$ - -

which we can rewrite either as

-$$ -\frac{df}{dx}=\left[\frac{df}{db}\frac{db}{da}\right]\frac{da}{dx}, -$$ - -

or

-$$ -\frac{df}{dx}=\frac{df}{db}\left[\frac{db}{da}\frac{da}{dx}\right]. -$$ - -

The first expression is called reverse mode (or back propagation) -since we start by evaluating the derivatives at the end point and then -propagate backwards. This is the standard way of evaluating -derivatives (gradients) when optimizing the parameters of a neural -network. In the context of deep learning this is computationally -more efficient since the output of a neural network consists of either -one or some few other output variables. -

- -

The second equation defines the so-called forward mode.

- -









-

More complicated function

- -

We increase our ambitions and introduce a slightly more complicated function

-$$ -f(x) =\sqrt{x^2+exp{x^2}}, -$$ - -

with derivative

-$$ -f'(x) =\frac{x(1+\exp{x^2})}{\sqrt{x^2+exp{x^2}}}. -$$ - -

The corresponding SymPy code reads

- - -
-
-
-
-
-
from __future__ import division
-from sympy import *
-x = symbols('x')
-expr = sqrt(x*x+exp(x*x))
-simplify(expr)
-derivative = diff(expr,x)
-print(python(expr))
-print(python(derivative))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Counting the number of floating point operations

- -

A simple count of operations shows that we need five operations for -the function itself and ten for the derivative. Fifteen operations in total if we wish to proceed with the above codes. -

- -

Can we reduce this to -say half the number of operations? -

- -









-

Defining intermediate operations

- -

We can indeed reduce the number of operation to half of those listed in the brute force approach above. -We define the following quantities -

-$$ -a = x^2, -$$ - -

and

-$$ -b = \exp{x^2} = \exp{a}, -$$ - -

and

-$$ -c= a+b, -$$ - -

and

-$$ -d=f(x)=\sqrt{c}. -$$ - - -









-

New expression for the derivative

- -

With these definitions we obtain the following partial derivatives

-$$ -\frac{\partial a}{\partial x} = 2x, -$$ - -

and

-$$ -\frac{\partial b}{\partial a} = \exp{a}, -$$ - -

and

-$$ -\frac{\partial c}{\partial a} = 1, -$$ - -

and

-$$ -\frac{\partial c}{\partial b} = 1, -$$ - -

and

-$$ -\frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -$$ - -

and finally

-$$ -\frac{\partial f}{\partial d} = 1. -$$ - - -









-

Final derivatives

-

Our final derivatives are thus

-$$ -\frac{\partial f}{\partial c} = \frac{\partial f}{\partial d} \frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -$$ - -$$ -\frac{\partial f}{\partial b} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial b} = \frac{1}{2\sqrt{c}}, -$$ - -$$ -\frac{\partial f}{\partial a} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial a}+ -\frac{\partial f}{\partial b} \frac{\partial b}{\partial a} = \frac{1+\exp{a}}{2\sqrt{c}}, -$$ - -

and finally

-$$ -\frac{\partial f}{\partial x} = \frac{\partial f}{\partial a} \frac{\partial a}{\partial x} = \frac{x(1+\exp{a})}{\sqrt{c}}, -$$ - -

which is just

-$$ -\frac{\partial f}{\partial x} = \frac{x(1+b)}{d}, -$$ - -

and requires only three operations if we can reuse all intermediate variables.

- -









-

In general not this simple

- -

In general, see the generalization below, unless we can obtain simple -analytical expressions which we can simplify further, the final -implementation of automatic differentiation involves repeated -calculations (and thereby operations) of derivatives of elementary -functions. -

- -









-

Automatic differentiation

- -

We can make this example more formal. Automatic differentiation is a -formalization of the previous example (see graph). -

- -

We define \( \boldsymbol{x}\in x_1,\dots, x_l \) input variables to a given function \( f(\boldsymbol{x}) \) and \( x_{l+1},\dots, x_L \) intermediate variables.

- -

In the above example we have only one input variable, \( l=1 \) and four intermediate variables, that is

-$$ -\begin{bmatrix} x_1=x & x_2 = x^2=a & x_3 =\exp{a}= b & x_4=c=a+b & x_5 = \sqrt{c}=d \end{bmatrix}. -$$ - -

Furthemore, for \( i=l+1, \dots, L \) (here \( i=2,3,4,5 \) and \( f=x_L=d \)), we -define the elementary functions \( g_i(x_{Pa(x_i)}) \) where \( x_{Pa(x_i)} \) are the parent nodes of the variable \( x_i \). -

- -

In our case, we have for example for \( x_3=g_3(x_{Pa(x_i)})=\exp{a} \), that \( g_3=\exp{()} \) and \( x_{Pa(x_3)}=a \).

- -









-

Chain rule

- -

We can now compute the gradients by back-propagating the derivatives using the chain rule. -We have defined -

-$$ -\frac{\partial f}{\partial x_L} = 1, -$$ - -

which allows us to find the derivatives of the various variables \( x_i \) as

-$$ -\frac{\partial f}{\partial x_i} = \sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial x_j}{\partial x_i}=\sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial g_j}{\partial x_i}. -$$ - -

Whenever we have a function which can be expressed as a computation -graph and the various functions can be expressed in terms of -elementary functions that are differentiable, then automatic -differentiation works. The functions may not need to be elementary -functions, they could also be computer programs, although not all -programs can be automatically differentiated. -

- -









-

First network example, simple percepetron with one input

- -

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

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

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

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









-

Layout of a simple neural network with no hidden layer

- -

-
-

-
-

- -









-

Optimizing the parameters

- -

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

- -

We need

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

Using the chain rule we find

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

and

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

which we later will just define as

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









-

Adding a hidden layer

- -

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

- -

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

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

and the cost function

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

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

- -









-

Layout of a simple neural network with one hidden layer

- -

-
-

-
-

- -









-

The derivatives

- -

The derivatives are now, using the chain rule again

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

Can you generalize this to more than one hidden layer?

- -









-

Important observations

- -
- -

-

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

-
- - -









-

The training

- -

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

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

and

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

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

- -

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

- -

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

- -









-

Code example

- -

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

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

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

- -









- - -

Exercise 1: Including more data

- -

Try to increase the amount of input and -target/output data. Try also to perform calculations for more values -of the learning rates. Feel free to add either hyperparameters with an -\( l_1 \) norm or an \( l_2 \) norm and discuss your results. -Discuss your results as functions of the amount of training data and various learning rates. -

- -

Challenge: Try to change the activation functions and replace the hard-coded analytical expressions with automatic derivation via either autograd or JAX.

- - - -









-

Simple neural network and the back propagation equations

- -

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

- -

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

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

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

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









-

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

- -

-
-

-
-

- -









-

The ouput layer

- -

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

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

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

-$$ -\boldsymbol{\Theta}=\left\{w_{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\}. -$$ - - -









-

Compact expressions

- -

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

-$$ -\begin{bmatrix}z_0^{(1)} \\ z_1^{(1)} \end{bmatrix}=\begin{bmatrix}w_{00}^{(1)} & w_{01}^{(1)}\\ w_{10}^{(1)} &w_{11}^{(1)} \end{bmatrix}\begin{bmatrix}a_0^{(0)} \\ a_1^{(0)} \end{bmatrix}+\begin{bmatrix}b_0^{(1)} \\ b_1^{(1)} \end{bmatrix}, -$$ - -

with outputs

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









-

Output layer

- -

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

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

resulting in the output

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









-

Explicit derivatives

- -

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

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

with

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

and finally

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









-

Derivatives of the hidden layer

- -

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

-$$ -\frac{\partial C}{\partial w_{00}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\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)}}, -$$ - -

which, noting that

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

allows us to rewrite

-$$ -\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)}. -$$ - - -









-

Final expression

-

Defining

-$$ -\delta_0^{(1)}=w_0^{(2)}\frac{\partial a_0^{(1)}}{\partial z_0^{(1)}}\delta^{(2)}, -$$ - -

we have

-$$ -\frac{\partial C}{\partial w_{00}^{(1)}}=\delta_0^{(1)}a_0^{(1)}. -$$ - -

Similarly, we obtain

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









-

Completing the list

- -

Similarly, we find

-$$ -\frac{\partial C}{\partial w_{10}^{(1)}}=\delta_1^{(1)}a_0^{(1)}, -$$ - -

and

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

where we have defined

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









-

Final expressions for the biases of the hidden layer

- -

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

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

and

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

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

- -









-

Gradient expressions

- -

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

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

and

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

and

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

and

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

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

- -









- - -

Exercise 2: Extended program

- -

We extend our simple code to a function which depends on two variable \( x_0 \) and \( x_1 \), that is

-$$ -y=f(x_0,x_1)=x_0^2+3x_0x_1+x_1^2+5. -$$ - -

We feed our network with \( n=100 \) entries \( x_0 \) and \( x_1 \). We have thus two features represented by these variable and an input matrix/design matrix \( \boldsymbol{X}\in \mathbf{R}^{n\times 2} \)

-$$ -\boldsymbol{X}=\begin{bmatrix} x_{00} & x_{01} \\ x_{00} & x_{01} \\ x_{10} & x_{11} \\ x_{20} & x_{21} \\ \dots & \dots \\ \dots & \dots \\ x_{n-20} & x_{n-21} \\ x_{n-10} & x_{n-11} \end{bmatrix}. -$$ - -

Write a code, based on the previous code examples, which takes as input these data and fit the above function. -You can extend your code to include automatic differentiation. -

- -

With these examples, we are now ready to embark upon the writing of more a general code for neural networks.

- - - -









-

Getting serious, the back propagation equations for a neural network

- -

Now it is time to move away from one node in each layer only. Our inputs are also represented either by several inputs.

- -

We have thus

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

Defining

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

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

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









-

Analyzing the last results

- -

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

- -









-

More considerations

- -

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

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

With the definition of \( \delta_j^L \) we have a more compact definition of the derivative of the cost function in terms of the weights, namely

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









-

Derivatives in terms of \( z_j^L \)

- -

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

- -$$ -\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, -$$ - -

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

-$$ -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, -$$ - -

That is, the error \( \delta_j^L \) is exactly equal to the rate of change of the cost function as a function of the bias.

- -









-

Bringing it together

- -

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

- -$$ -\begin{equation} -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}, -\label{_auto1} -\end{equation} -$$ - -

and

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

and

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









-

Final back propagating equation

- -

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

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

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

- -









-

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

- -

We obtain

-$$ -\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, -$$ - -

and recalling that

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

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

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

This is our final equation.

- -

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

- -









-

Setting up the back propagation algorithm

- -

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.

- -

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

- -

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

- -

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

- -









-

Setting up the back propagation algorithm, part 2

- -

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

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

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

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









-

Setting up the Back propagation algorithm, part 3

- -

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

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

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

- -









-

Updating the gradients

- -

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

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

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

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









-

Activation functions

- -

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

- -
    -
  • Non-constant
  • -
  • Bounded
  • -
  • Monotonically-increasing
  • -
  • Continuous
  • -
-









-

Activation functions, Logistic and Hyperbolic ones

- -

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

- -

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

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

and the hyperbolic tangent function

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









-

Relevance

- -

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

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









-

Fine-tuning neural network hyperparameters

- -

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

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

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

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









-

Hidden layers

- -

For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set you ca 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. -

- - -

Vanishing gradients

- -

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

- -

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

- -









-

Exploding gradients

- -

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

- - -

Is the Logistic activation function (Sigmoid) our choice?

- -

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

- -

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

- -









-

Logistic function as the root of problems

- -

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

- -









-

The derivative of the Logistic funtion

- -

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

- -

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

- -









-

Insights from the paper by Glorot and Bengio

- -

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

- -









-

The RELU function family

- -

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

- -

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

- -









-

ELU function

- -

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

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









-

Which activation function should we use?

- -

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

- -

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

- -









-

More on activation functions, output layers

- -

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

- -

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

- -For the output layer: - -
    -
  • For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
  • -
  • For regression tasks, you can simply use no activation function at all.
  • -
-









-

Batch Normalization

- -

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

- -

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

- -









-

Dropout

- -

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

- -

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

- -









-

Gradient Clipping

- -

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

- -

This technique is called Gradient Clipping.

- -

In general however, Batch -Normalization is preferred. -

- - -

A top-down perspective on Neural networks

- -

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

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









-

More top-down perspectives

- -

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

- -

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

- -









-

Limitations of supervised learning with deep networks

- -

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

- -









-

Limitations of NNs

- -

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

- -
    -
  • Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
  • -
  • Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
  • -
-









-

Homogeneous data

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









-

More limitations

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

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

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

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

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "80e11a79", - "metadata": { - "editable": true - }, - "source": [ - "## Examples of XOR, OR and AND gates\n", - "\n", - "Let us first try to fit various gates using standard linear\n", - "regression. The gates we are thinking of are the classical XOR, OR and\n", - "AND gates, well-known elements in computer science. The tables here\n", - "show how we can set up the inputs $x_1$ and $x_2$ in order to yield a\n", - "specific target $y_i$." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "60cf9550", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\"\n", - "Simple code that tests XOR, OR and AND gates with linear regression\n", - "\"\"\"\n", - "\n", - "import numpy as np\n", - "# Design matrix\n", - "X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)\n", - "print(f\"The X.TX matrix:{X.T @ X}\")\n", - "Xinv = np.linalg.pinv(X.T @ X)\n", - "print(f\"The invers of X.TX matrix:{Xinv}\")\n", - "\n", - "# The XOR gate \n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "ThetaXOR = Xinv @ X.T @ yXOR\n", - "print(f\"The values of theta for the XOR gate:{ThetaXOR}\")\n", - "print(f\"The linear regression prediction for the XOR gate:{X @ ThetaXOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "ThetaOR = Xinv @ X.T @ yOR\n", - "print(f\"The values of theta for the OR gate:{ThetaOR}\")\n", - "print(f\"The linear regression prediction for the OR gate:{X @ ThetaOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "ThetaAND = Xinv @ X.T @ yAND\n", - "print(f\"The values of theta for the AND gate:{ThetaAND}\")\n", - "print(f\"The linear regression prediction for the AND gate:{X @ ThetaAND}\")" - ] - }, - { - "cell_type": "markdown", - "id": "72e221bf", - "metadata": { - "editable": true - }, - "source": [ - "What is happening here?" - ] - }, - { - "cell_type": "markdown", - "id": "67d0709a", - "metadata": { - "editable": true - }, - "source": [ - "## Does Logistic Regression do a better Job?" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "4afcb37f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "\"\"\"\n", - "Simple code that tests XOR and OR gates with linear regression\n", - "and logistic regression\n", - "\"\"\"\n", - "\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LogisticRegression\n", - "import numpy as np\n", - "\n", - "# Design matrix\n", - "X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)\n", - "print(f\"The X.TX matrix:{X.T @ X}\")\n", - "Xinv = np.linalg.pinv(X.T @ X)\n", - "print(f\"The invers of X.TX matrix:{Xinv}\")\n", - "\n", - "# The XOR gate \n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "ThetaXOR = Xinv @ X.T @ yXOR\n", - "print(f\"The values of theta for the XOR gate:{ThetaXOR}\")\n", - "print(f\"The linear regression prediction for the XOR gate:{X @ ThetaXOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "ThetaOR = Xinv @ X.T @ yOR\n", - "print(f\"The values of theta for the OR gate:{ThetaOR}\")\n", - "print(f\"The linear regression prediction for the OR gate:{X @ ThetaOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "ThetaAND = Xinv @ X.T @ yAND\n", - "print(f\"The values of theta for the AND gate:{ThetaAND}\")\n", - "print(f\"The linear regression prediction for the AND gate:{X @ ThetaAND}\")\n", - "\n", - "# Now we change to logistic regression\n", - "\n", - "\n", - "# Logistic Regression\n", - "logreg = LogisticRegression()\n", - "logreg.fit(X, yOR)\n", - "print(\"Test set accuracy with Logistic Regression for OR gate: {:.2f}\".format(logreg.score(X,yOR)))\n", - "\n", - "logreg.fit(X, yXOR)\n", - "print(\"Test set accuracy with Logistic Regression for XOR gate: {:.2f}\".format(logreg.score(X,yXOR)))\n", - "\n", - "\n", - "logreg.fit(X, yAND)\n", - "print(\"Test set accuracy with Logistic Regression for AND gate: {:.2f}\".format(logreg.score(X,yAND)))" - ] - }, - { - "cell_type": "markdown", - "id": "ac931e42", - "metadata": { - "editable": true - }, - "source": [ - "Not exactly impressive, but somewhat better." - ] - }, - { - "cell_type": "markdown", - "id": "e5455ad8", - "metadata": { - "editable": true - }, - "source": [ - "## Adding Neural Networks" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "cfbed3e7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "# and now neural networks with Scikit-Learn and the XOR\n", - "\n", - "from sklearn.neural_network import MLPClassifier\n", - "from sklearn.datasets import make_classification\n", - "X, yXOR = make_classification(n_samples=100, random_state=1)\n", - "FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)\n", - "FFNN.predict_proba(X)\n", - "print(f\"Test set accuracy with Feed Forward Neural Network for XOR gate:{FFNN.score(X, yXOR)}\")" - ] - }, - { - "cell_type": "markdown", - "id": "a619dfb2", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematics of deep learning\n", - "\n", - "**Two recent books online.**\n", - "\n", - "1. [The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen](https://arxiv.org/abs/2105.04026), published as [Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022](https://doi.org/10.1017/9781009025096.002)\n", - "\n", - "2. [Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger](https://doi.org/10.48550/arXiv.2310.20360)" - ] - }, - { - "cell_type": "markdown", - "id": "2cc88c73", - "metadata": { - "editable": true - }, - "source": [ - "## Reminder on books with hands-on material and codes\n", - "* [Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch](https://sebastianraschka.com/blog/2022/ml-pytorch-book.html)" - ] - }, - { - "cell_type": "markdown", - "id": "233d2972", - "metadata": { - "editable": true - }, - "source": [ - "## Reading recommendations\n", - "\n", - "1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from [GitHub](https://github.com/rasbt/machine-learning-book)\n", - "\n", - "2. Goodfellow et al, chapter 6 and 7 contain most of the neural network background." - ] - }, - { - "cell_type": "markdown", - "id": "27cc80b0", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematics of deep learning and neural networks\n", - "\n", - "Neural networks, in its so-called feed-forward form, where each\n", - "iterations contains a feed-forward stage and a back-propgagation\n", - "stage, consist of series of affine matrix-matrix and matrix-vector\n", - "multiplications. The unknown parameters (the so-called biases and\n", - "weights which deternine the architecture of a neural network), are\n", - "uptaded iteratively using the so-called back-propagation algorithm.\n", - "This algorithm corresponds to the so-called reverse mode of \n", - "automatic differentation." - ] - }, - { - "cell_type": "markdown", - "id": "ea3a3c02", - "metadata": { - "editable": true - }, - "source": [ - "## Basics of an NN\n", - "\n", - "A neural network consists of a series of hidden layers, in addition to\n", - "the input and output layers. Each layer $l$ has a set of parameters\n", - "$\\boldsymbol{\\Theta}^{(l)}=(\\boldsymbol{W}^{(l)},\\boldsymbol{b}^{(l)})$ which are related to the\n", - "parameters in other layers through a series of affine transformations,\n", - "for a standard NN these are matrix-matrix and matrix-vector\n", - "multiplications. For all layers we will simply use a collective variable $\\boldsymbol{\\Theta}$.\n", - "\n", - "It consist of two basic steps:\n", - "1. a feed forward stage which takes a given input and produces a final output which is compared with the target values through our cost/loss function.\n", - "\n", - "2. a back-propagation state where the unknown parameters $\\boldsymbol{\\Theta}$ are updated through the optimization of the their gradients. The expressions for the gradients are obtained via the chain rule, starting from the derivative of the cost/function.\n", - "\n", - "These two steps make up one iteration. This iterative process is continued till we reach an eventual stopping criterion." - ] - }, - { - "cell_type": "markdown", - "id": "502d4ad7", - "metadata": { - "editable": true - }, - "source": [ - "## Overarching view of a neural network\n", - "\n", - "The architecture of a neural network defines our model. This model\n", - "aims at describing some function $f(\\boldsymbol{x}$ which represents\n", - "some final result (outputs or tagrget values) given a specific inpput\n", - "$\\boldsymbol{x}$. Note that here $\\boldsymbol{y}$ and $\\boldsymbol{x}$ are not limited to be\n", - "vectors.\n", - "\n", - "The architecture consists of\n", - "1. An input and an output layer where the input layer is defined by the inputs $\\boldsymbol{x}$. The output layer produces the model ouput $\\boldsymbol{\\tilde{y}}$ which is compared with the target value $\\boldsymbol{y}$\n", - "\n", - "2. A given number of hidden layers and neurons/nodes/units for each layer (this may vary)\n", - "\n", - "3. A given activation function $\\sigma(\\boldsymbol{z})$ with arguments $\\boldsymbol{z}$ to be defined below. The activation functions may differ from layer to layer.\n", - "\n", - "4. The last layer, normally called **output** layer has normally an activation function tailored to the specific problem\n", - "\n", - "5. Finally we define a so-called cost or loss function which is used to gauge the quality of our model." - ] - }, - { - "cell_type": "markdown", - "id": "9182519a", - "metadata": { - "editable": true - }, - "source": [ - "## The optimization problem\n", - "\n", - "The cost function is a function of the unknown parameters\n", - "$\\boldsymbol{\\Theta}$ where the latter is a container for all possible\n", - "parameters needed to define a neural network\n", - "\n", - "If we are dealing with a regression task a typical cost/loss function\n", - "is the mean squared error" - ] - }, - { - "cell_type": "markdown", - "id": "15b78cfd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\Theta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\theta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\theta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "093b77f1", - "metadata": { - "editable": true - }, - "source": [ - "This function represents one of many possible ways to define\n", - "the so-called cost function. Note that here we have assumed a linear dependence in terms of the paramters $\\boldsymbol{\\Theta}$. This is in general not the case." - ] - }, - { - "cell_type": "markdown", - "id": "b6c8a224", - "metadata": { - "editable": true - }, - "source": [ - "## Parameters of neural networks\n", - "For neural networks the parameters\n", - "$\\boldsymbol{\\Theta}$ are given by the so-called weights and biases (to be\n", - "defined below).\n", - "\n", - "The weights are given by matrix elements $w_{ij}^{(l)}$ where the\n", - "superscript indicates the layer number. The biases are typically given\n", - "by vector elements representing each single node of a given layer,\n", - "that is $b_j^{(l)}$." - ] - }, - { - "cell_type": "markdown", - "id": "f30d7e81", - "metadata": { - "editable": true - }, - "source": [ - "## Other ingredients of a neural network\n", - "\n", - "Having defined the architecture of a neural network, the optimization\n", - "of the cost function with respect to the parameters $\\boldsymbol{\\Theta}$,\n", - "involves the calculations of gradients and their optimization. The\n", - "gradients represent the derivatives of a multidimensional object and\n", - "are often approximated by various gradient methods, including\n", - "1. various quasi-Newton methods,\n", - "\n", - "2. plain gradient descent (GD) with a constant learning rate $\\eta$,\n", - "\n", - "3. GD with momentum and other approximations to the learning rates such as\n", - "\n", - " * Adapative gradient (ADAgrad)\n", - "\n", - " * Root mean-square propagation (RMSprop)\n", - "\n", - " * Adaptive gradient with momentum (ADAM) and many other\n", - "\n", - "4. Stochastic gradient descent and various families of learning rate approximations" - ] - }, - { - "cell_type": "markdown", - "id": "5089007e", - "metadata": { - "editable": true - }, - "source": [ - "## Other parameters\n", - "\n", - "In addition to the above, there are often additional hyperparamaters\n", - "which are included in the setup of a neural network. These will be\n", - "discussed below." - ] - }, - { - "cell_type": "markdown", - "id": "3f9eedcb", - "metadata": { - "editable": true - }, - "source": [ - "## Universal approximation theorem\n", - "\n", - "The universal approximation theorem plays a central role in deep\n", - "learning. [Cybenko (1989)](https://link.springer.com/article/10.1007/BF02551274) showed\n", - "the following:\n", - "\n", - "Let $\\sigma$ be any continuous sigmoidal function such that" - ] - }, - { - "cell_type": "markdown", - "id": "ac052134", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma(z) = \\left\\{\\begin{array}{cc} 1 & z\\rightarrow \\infty\\\\ 0 & z \\rightarrow -\\infty \\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c0e639b1", - "metadata": { - "editable": true - }, - "source": [ - "Given a continuous and deterministic function $F(\\boldsymbol{x})$ on the unit\n", - "cube in $d$-dimensions $F\\in [0,1]^d$, $x\\in [0,1]^d$ and a parameter\n", - "$\\epsilon >0$, there is a one-layer (hidden) neural network\n", - "$f(\\boldsymbol{x};\\boldsymbol{\\Theta})$ with $\\boldsymbol{\\Theta}=(\\boldsymbol{W},\\boldsymbol{b})$ and $\\boldsymbol{W}\\in\n", - "\\mathbb{R}^{m\\times n}$ and $\\boldsymbol{b}\\in \\mathbb{R}^{n}$, for which" - ] - }, - { - "cell_type": "markdown", - "id": "6d2878d4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\vert F(\\boldsymbol{x})-f(\\boldsymbol{x};\\boldsymbol{\\Theta})\\vert < \\epsilon \\hspace{0.1cm} \\forall \\boldsymbol{x}\\in[0,1]^d.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dbb5133d", - "metadata": { - "editable": true - }, - "source": [ - "## Some parallels from real analysis\n", - "\n", - "For those of you familiar with for example the [Stone-Weierstrass\n", - "theorem](https://en.wikipedia.org/wiki/Stone%E2%80%93Weierstrass_theorem)\n", - "for polynomial approximations or the convergence criterion for Fourier\n", - "series, there are similarities in the derivation of the proof for\n", - "neural networks." - ] - }, - { - "cell_type": "markdown", - "id": "0da134a5", - "metadata": { - "editable": true - }, - "source": [ - "## The approximation theorem in words\n", - "\n", - "**Any continuous function $y=F(\\boldsymbol{x})$ supported on the unit cube in\n", - "$d$-dimensions can be approximated by a one-layer sigmoidal network to\n", - "arbitrary accuracy.**\n", - "\n", - "[Hornik (1991)](https://www.sciencedirect.com/science/article/abs/pii/089360809190009T) extended the theorem by letting any non-constant, bounded activation function to be included using that the expectation value" - ] - }, - { - "cell_type": "markdown", - "id": "5346e8a0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}[\\vert F(\\boldsymbol{x})\\vert^2] =\\int_{\\boldsymbol{x}\\in D} \\vert F(\\boldsymbol{x})\\vert^2p(\\boldsymbol{x})d\\boldsymbol{x} < \\infty.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "36737d10", - "metadata": { - "editable": true - }, - "source": [ - "Then we have" - ] - }, - { - "cell_type": "markdown", - "id": "d81b95ba", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}[\\vert F(\\boldsymbol{x})-f(\\boldsymbol{x};\\boldsymbol{\\Theta})\\vert^2] =\\int_{\\boldsymbol{x}\\in D} \\vert F(\\boldsymbol{x})-f(\\boldsymbol{x};\\boldsymbol{\\Theta})\\vert^2p(\\boldsymbol{x})d\\boldsymbol{x} < \\epsilon.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8432cac2", - "metadata": { - "editable": true - }, - "source": [ - "## More on the general approximation theorem\n", - "\n", - "None of the proofs give any insight into the relation between the\n", - "number of of hidden layers and nodes and the approximation error\n", - "$\\epsilon$, nor the magnitudes of $\\boldsymbol{W}$ and $\\boldsymbol{b}$.\n", - "\n", - "Neural networks (NNs) have what we may call a kind of universality no matter what function we want to compute.\n", - "\n", - "It does not mean that an NN can be used to exactly compute any function. Rather, we get an approximation that is as good as we want." - ] - }, - { - "cell_type": "markdown", - "id": "04d4d751", - "metadata": { - "editable": true - }, - "source": [ - "## Class of functions we can approximate\n", - "\n", - "The class of functions that can be approximated are the continuous ones.\n", - "If the function $F(\\boldsymbol{x})$ is discontinuous, it won't in general be possible to approximate it. However, an NN may still give an approximation even if we fail in some points." - ] - }, - { - "cell_type": "markdown", - "id": "df8f957e", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the equations for a neural network\n", - "\n", - "The questions we want to ask are how do changes in the biases and the\n", - "weights in our network change the cost function and how can we use the\n", - "final output to modify the weights and biases?\n", - "\n", - "To derive these equations let us start with a plain regression problem\n", - "and define our cost function as" - ] - }, - { - "cell_type": "markdown", - "id": "0fc51d93", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\cal C}(\\boldsymbol{\\Theta}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - \\tilde{y}_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fc372df4", - "metadata": { - "editable": true - }, - "source": [ - "where the $y_i$s are our $n$ targets (the values we want to\n", - "reproduce), while the outputs of the network after having propagated\n", - "all inputs $\\boldsymbol{x}$ are given by $\\boldsymbol{\\tilde{y}}_i$." - ] - }, - { - "cell_type": "markdown", - "id": "e1cbafd1", - "metadata": { - "editable": true - }, - "source": [ - "## Layout of a neural network with three hidden layers\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "aadba1e0", - "metadata": { - "editable": true - }, - "source": [ - "## Definitions\n", - "\n", - "With our definition of the targets $\\boldsymbol{y}$, the outputs of the\n", - "network $\\boldsymbol{\\tilde{y}}$ and the inputs $\\boldsymbol{x}$ we\n", - "define now the activation $z_j^l$ of node/neuron/unit $j$ of the\n", - "$l$-th layer as a function of the bias, the weights which add up from\n", - "the previous layer $l-1$ and the forward passes/outputs\n", - "$\\hat{a}^{l-1}$ from the previous layer as" - ] - }, - { - "cell_type": "markdown", - "id": "4f0a354f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_j^l = \\sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5b489754", - "metadata": { - "editable": true - }, - "source": [ - "where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$\n", - "represents the total number of nodes/neurons/units of layer $l-1$. The\n", - "figure in the whiteboard notes illustrates this equation. We can rewrite this in a more\n", - "compact form as the matrix-vector products we discussed earlier," - ] - }, - { - "cell_type": "markdown", - "id": "109a6626", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{z}^l = \\left(\\hat{W}^l\\right)^T\\hat{a}^{l-1}+\\hat{b}^l.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d075c31b", - "metadata": { - "editable": true - }, - "source": [ - "## Inputs to the activation function\n", - "\n", - "With the activation values $\\boldsymbol{z}^l$ we can in turn define the\n", - "output of layer $l$ as $\\boldsymbol{a}^l = f(\\boldsymbol{z}^l)$ where $f$ is our\n", - "activation function. In the examples here we will use the sigmoid\n", - "function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers\n", - "and their nodes. It means we have" - ] - }, - { - "cell_type": "markdown", - "id": "ea32a509", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "a_j^l = \\sigma(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8ac36725", - "metadata": { - "editable": true - }, - "source": [ - "## Derivatives and the chain rule\n", - "\n", - "From the definition of the activation $z_j^l$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "f3600e09", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3e537038", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "34b99ae7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e4faa2f2", - "metadata": { - "editable": true - }, - "source": [ - "With our definition of the activation function we have that (note that this function depends only on $z_j^l$)" - ] - }, - { - "cell_type": "markdown", - "id": "b4243031", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial a_j^l}{\\partial z_j^{l}} = a_j^l(1-a_j^l)=\\sigma(z_j^l)(1-\\sigma(z_j^l)).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b528c44c", - "metadata": { - "editable": true - }, - "source": [ - "## Derivative of the cost function\n", - "\n", - "With these definitions we can now compute the derivative of the cost function in terms of the weights.\n", - "\n", - "Let us specialize to the output layer $l=L$. Our cost function is" - ] - }, - { - "cell_type": "markdown", - "id": "602e81ab", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\cal C}(\\boldsymbol{\\Theta}^L) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - \\tilde{y}_i\\right)^2=\\frac{1}{2}\\sum_{i=1}^n\\left(a_i^L - y_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4ac5e382", - "metadata": { - "editable": true - }, - "source": [ - "The derivative of this function with respect to the weights is" - ] - }, - { - "cell_type": "markdown", - "id": "02edfab2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}(\\boldsymbol{\\Theta}^L)}{\\partial w_{jk}^L} = \\left(a_j^L - y_j\\right)\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "02fffe9d", - "metadata": { - "editable": true - }, - "source": [ - "The last partial derivative can easily be computed and reads (by applying the chain rule)" - ] - }, - { - "cell_type": "markdown", - "id": "f4d679cc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}} = \\frac{\\partial a_j^L}{\\partial z_{j}^{L}}\\frac{\\partial z_j^L}{\\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3638d432", - "metadata": { - "editable": true - }, - "source": [ - "## Simpler examples first, and automatic differentiation\n", - "\n", - "In order to understand the back propagation algorithm and its\n", - "derivation (an implementation of the chain rule), let us first digress\n", - "with some simple examples. These examples are also meant to motivate\n", - "the link with back propagation and [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation)." - ] - }, - { - "cell_type": "markdown", - "id": "d3039347", - "metadata": { - "editable": true - }, - "source": [ - "## Reminder on the chain rule and gradients\n", - "\n", - "If we have a multivariate function $f(x,y)$ where $x=x(t)$ and $y=y(t)$ are functions of a variable $t$, we have that the gradient of $f$ with respect to $t$ (without the explicit unit vector components)" - ] - }, - { - "cell_type": "markdown", - "id": "f48bfb76", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{df}{dt} = \\begin{bmatrix}\\frac{\\partial f}{\\partial x} & \\frac{\\partial f}{\\partial y} \\end{bmatrix} \\begin{bmatrix}\\frac{\\partial x}{\\partial t} \\\\ \\frac{\\partial y}{\\partial t} \\end{bmatrix}=\\frac{\\partial f}{\\partial x} \\frac{\\partial x}{\\partial t} +\\frac{\\partial f}{\\partial y} \\frac{\\partial y}{\\partial t}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "63176c54", - "metadata": { - "editable": true - }, - "source": [ - "## Multivariable functions\n", - "\n", - "If we have a multivariate function $f(x,y)$ where $x=x(t,s)$ and $y=y(t,s)$ are functions of the variables $t$ and $s$, we have that the partial derivatives" - ] - }, - { - "cell_type": "markdown", - "id": "f966f6f1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial s}=\\frac{\\partial f}{\\partial x}\\frac{\\partial x}{\\partial s}+\\frac{\\partial f}{\\partial y}\\frac{\\partial y}{\\partial s},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b0a5a64e", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "fedfd000", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial t}=\\frac{\\partial f}{\\partial x}\\frac{\\partial x}{\\partial t}+\\frac{\\partial f}{\\partial y}\\frac{\\partial y}{\\partial t}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "49281876", - "metadata": { - "editable": true - }, - "source": [ - "the gradient of $f$ with respect to $t$ and $s$ (without the explicit unit vector components)" - ] - }, - { - "cell_type": "markdown", - "id": "78dc9b72", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{df}{d(s,t)} = \\begin{bmatrix}\\frac{\\partial f}{\\partial x} & \\frac{\\partial f}{\\partial y} \\end{bmatrix} \\begin{bmatrix}\\frac{\\partial x}{\\partial s} &\\frac{\\partial x}{\\partial t} \\\\ \\frac{\\partial y}{\\partial s} & \\frac{\\partial y}{\\partial t} \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bf854510", - "metadata": { - "editable": true - }, - "source": [ - "## Automatic differentiation through examples\n", - "\n", - "A great introduction to automatic differentiation is given by Baydin et al., see .\n", - "\n", - "Automatic differentiation is a represented by a repeated application\n", - "of the chain rule on well-known functions and allows for the\n", - "calculation of derivatives to numerical precision. It is not the same\n", - "as the calculation of symbolic derivatives via for example SymPy, nor\n", - "does it use approximative formulae based on Taylor-expansions of a\n", - "function around a given value. The latter are error prone due to\n", - "truncation errors and values of the step size $\\Delta$." - ] - }, - { - "cell_type": "markdown", - "id": "35771431", - "metadata": { - "editable": true - }, - "source": [ - "## Simple example\n", - "\n", - "Our first example is rather simple," - ] - }, - { - "cell_type": "markdown", - "id": "6570ba80", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) =\\exp{x^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c30b4d72", - "metadata": { - "editable": true - }, - "source": [ - "with derivative" - ] - }, - { - "cell_type": "markdown", - "id": "183d5f0b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f'(x) =2x\\exp{x^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b2363c0a", - "metadata": { - "editable": true - }, - "source": [ - "We can use SymPy to extract the pertinent lines of Python code through the following simple example" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "0b51ea21", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from __future__ import division\n", - "from sympy import *\n", - "x = symbols('x')\n", - "expr = exp(x*x)\n", - "simplify(expr)\n", - "derivative = diff(expr,x)\n", - "print(python(expr))\n", - "print(python(derivative))" - ] - }, - { - "cell_type": "markdown", - "id": "07e24343", - "metadata": { - "editable": true - }, - "source": [ - "## Smarter way of evaluating the above function\n", - "If we study this function, we note that we can reduce the number of operations by introducing an intermediate variable" - ] - }, - { - "cell_type": "markdown", - "id": "1337dd0f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "a = x^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a7589947", - "metadata": { - "editable": true - }, - "source": [ - "leading to" - ] - }, - { - "cell_type": "markdown", - "id": "3586c972", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) = f(a(x)) = b= \\exp{a}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0ac52a19", - "metadata": { - "editable": true - }, - "source": [ - "We now assume that all operations can be counted in terms of equal\n", - "floating point operations. This means that in order to calculate\n", - "$f(x)$ we need first to square $x$ and then compute the exponential. We\n", - "have thus two floating point operations only." - ] - }, - { - "cell_type": "markdown", - "id": "18b67b7b", - "metadata": { - "editable": true - }, - "source": [ - "## Reducing the number of operations\n", - "\n", - "With the introduction of a precalculated quantity $a$ and thereby $f(x)$ we have that the derivative can be written as" - ] - }, - { - "cell_type": "markdown", - "id": "75f72d6b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f'(x) = 2xb,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ff72bef0", - "metadata": { - "editable": true - }, - "source": [ - "which reduces the number of operations from four in the orginal\n", - "expression to two. This means that if we need to compute $f(x)$ and\n", - "its derivative (a common task in optimizations), we have reduced the\n", - "number of operations from six to four in total.\n", - "\n", - "**Note** that the usage of a symbolic software like SymPy does not\n", - "include such simplifications and the calculations of the function and\n", - "the derivatives yield in general more floating point operations." - ] - }, - { - "cell_type": "markdown", - "id": "ef55737f", - "metadata": { - "editable": true - }, - "source": [ - "## Chain rule, forward and reverse modes\n", - "\n", - "In the above example we have introduced the variables $a$ and $b$, and our function is" - ] - }, - { - "cell_type": "markdown", - "id": "35ab7175", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) = f(a(x)) = b= \\exp{a},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "edc79b33", - "metadata": { - "editable": true - }, - "source": [ - "with $a=x^2$. We can decompose the derivative of $f$ with respect to $x$ as" - ] - }, - { - "cell_type": "markdown", - "id": "4dc12ed8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{df}{dx}=\\frac{df}{db}\\frac{db}{da}\\frac{da}{dx}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bc945b59", - "metadata": { - "editable": true - }, - "source": [ - "We note that since $b=f(x)$ that" - ] - }, - { - "cell_type": "markdown", - "id": "68eac5d0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{df}{db}=1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6ea49d77", - "metadata": { - "editable": true - }, - "source": [ - "leading to" - ] - }, - { - "cell_type": "markdown", - "id": "4a65d6fd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{df}{dx}=\\frac{db}{da}\\frac{da}{dx}=2x\\exp{x^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c66da8ef", - "metadata": { - "editable": true - }, - "source": [ - "as before." - ] - }, - { - "cell_type": "markdown", - "id": "b055e013", - "metadata": { - "editable": true - }, - "source": [ - "## Forward and reverse modes\n", - "\n", - "We have that" - ] - }, - { - "cell_type": "markdown", - "id": "006ef4f0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{df}{dx}=\\frac{df}{db}\\frac{db}{da}\\frac{da}{dx},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "99fd1e13", - "metadata": { - "editable": true - }, - "source": [ - "which we can rewrite either as" - ] - }, - { - "cell_type": "markdown", - "id": "d711ba8b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{df}{dx}=\\left[\\frac{df}{db}\\frac{db}{da}\\right]\\frac{da}{dx},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "394f38fd", - "metadata": { - "editable": true - }, - "source": [ - "or" - ] - }, - { - "cell_type": "markdown", - "id": "2f589cea", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{df}{dx}=\\frac{df}{db}\\left[\\frac{db}{da}\\frac{da}{dx}\\right].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "783c3588", - "metadata": { - "editable": true - }, - "source": [ - "The first expression is called reverse mode (or back propagation)\n", - "since we start by evaluating the derivatives at the end point and then\n", - "propagate backwards. This is the standard way of evaluating\n", - "derivatives (gradients) when optimizing the parameters of a neural\n", - "network. In the context of deep learning this is computationally\n", - "more efficient since the output of a neural network consists of either\n", - "one or some few other output variables.\n", - "\n", - "The second equation defines the so-called **forward mode**." - ] - }, - { - "cell_type": "markdown", - "id": "d1627f43", - "metadata": { - "editable": true - }, - "source": [ - "## More complicated function\n", - "\n", - "We increase our ambitions and introduce a slightly more complicated function" - ] - }, - { - "cell_type": "markdown", - "id": "53035043", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) =\\sqrt{x^2+exp{x^2}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f3293e4c", - "metadata": { - "editable": true - }, - "source": [ - "with derivative" - ] - }, - { - "cell_type": "markdown", - "id": "b6087529", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f'(x) =\\frac{x(1+\\exp{x^2})}{\\sqrt{x^2+exp{x^2}}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9a91562c", - "metadata": { - "editable": true - }, - "source": [ - "The corresponding SymPy code reads" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "49153549", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from __future__ import division\n", - "from sympy import *\n", - "x = symbols('x')\n", - "expr = sqrt(x*x+exp(x*x))\n", - "simplify(expr)\n", - "derivative = diff(expr,x)\n", - "print(python(expr))\n", - "print(python(derivative))" - ] - }, - { - "cell_type": "markdown", - "id": "3f8e08c9", - "metadata": { - "editable": true - }, - "source": [ - "## Counting the number of floating point operations\n", - "\n", - "A simple count of operations shows that we need five operations for\n", - "the function itself and ten for the derivative. Fifteen operations in total if we wish to proceed with the above codes.\n", - "\n", - "Can we reduce this to\n", - "say half the number of operations?" - ] - }, - { - "cell_type": "markdown", - "id": "9479dadf", - "metadata": { - "editable": true - }, - "source": [ - "## Defining intermediate operations\n", - "\n", - "We can indeed reduce the number of operation to half of those listed in the brute force approach above.\n", - "We define the following quantities" - ] - }, - { - "cell_type": "markdown", - "id": "9e5f867e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "a = x^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "21ee2a8a", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "e09cf187", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "b = \\exp{x^2} = \\exp{a},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c999c36b", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "8fbf66c6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "c= a+b,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dd11cc6a", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "69e9e950", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "d=f(x)=\\sqrt{c}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "970b6167", - "metadata": { - "editable": true - }, - "source": [ - "## New expression for the derivative\n", - "\n", - "With these definitions we obtain the following partial derivatives" - ] - }, - { - "cell_type": "markdown", - "id": "5655fa59", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial a}{\\partial x} = 2x,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1c8a1f68", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "edaf4340", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial b}{\\partial a} = \\exp{a},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f39563ef", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "c3fad1fe", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial c}{\\partial a} = 1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2f26318c", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "75e08a4f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial c}{\\partial b} = 1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2729f6dc", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "7ccfc31a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial d}{\\partial c} = \\frac{1}{2\\sqrt{c}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1e39402f", - "metadata": { - "editable": true - }, - "source": [ - "and finally" - ] - }, - { - "cell_type": "markdown", - "id": "a8313c23", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial d} = 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "64f5a96d", - "metadata": { - "editable": true - }, - "source": [ - "## Final derivatives\n", - "Our final derivatives are thus" - ] - }, - { - "cell_type": "markdown", - "id": "e087f8b8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial c} = \\frac{\\partial f}{\\partial d} \\frac{\\partial d}{\\partial c} = \\frac{1}{2\\sqrt{c}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ab9adb45", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial b} = \\frac{\\partial f}{\\partial c} \\frac{\\partial c}{\\partial b} = \\frac{1}{2\\sqrt{c}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e7125560", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial a} = \\frac{\\partial f}{\\partial c} \\frac{\\partial c}{\\partial a}+\n", - "\\frac{\\partial f}{\\partial b} \\frac{\\partial b}{\\partial a} = \\frac{1+\\exp{a}}{2\\sqrt{c}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6c4ad559", - "metadata": { - "editable": true - }, - "source": [ - "and finally" - ] - }, - { - "cell_type": "markdown", - "id": "b42e32a4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial x} = \\frac{\\partial f}{\\partial a} \\frac{\\partial a}{\\partial x} = \\frac{x(1+\\exp{a})}{\\sqrt{c}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "40de97ba", - "metadata": { - "editable": true - }, - "source": [ - "which is just" - ] - }, - { - "cell_type": "markdown", - "id": "22d0d252", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial x} = \\frac{x(1+b)}{d},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "be68a064", - "metadata": { - "editable": true - }, - "source": [ - "and requires only three operations if we can reuse all intermediate variables." - ] - }, - { - "cell_type": "markdown", - "id": "ed92fb3c", - "metadata": { - "editable": true - }, - "source": [ - "## In general not this simple\n", - "\n", - "In general, see the generalization below, unless we can obtain simple\n", - "analytical expressions which we can simplify further, the final\n", - "implementation of automatic differentiation involves repeated\n", - "calculations (and thereby operations) of derivatives of elementary\n", - "functions." - ] - }, - { - "cell_type": "markdown", - "id": "b565b39a", - "metadata": { - "editable": true - }, - "source": [ - "## Automatic differentiation\n", - "\n", - "We can make this example more formal. Automatic differentiation is a\n", - "formalization of the previous example (see graph).\n", - "\n", - "We define $\\boldsymbol{x}\\in x_1,\\dots, x_l$ input variables to a given function $f(\\boldsymbol{x})$ and $x_{l+1},\\dots, x_L$ intermediate variables.\n", - "\n", - "In the above example we have only one input variable, $l=1$ and four intermediate variables, that is" - ] - }, - { - "cell_type": "markdown", - "id": "587ae22d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{bmatrix} x_1=x & x_2 = x^2=a & x_3 =\\exp{a}= b & x_4=c=a+b & x_5 = \\sqrt{c}=d \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a54b74ca", - "metadata": { - "editable": true - }, - "source": [ - "Furthemore, for $i=l+1, \\dots, L$ (here $i=2,3,4,5$ and $f=x_L=d$), we\n", - "define the elementary functions $g_i(x_{Pa(x_i)})$ where $x_{Pa(x_i)}$ are the parent nodes of the variable $x_i$.\n", - "\n", - "In our case, we have for example for $x_3=g_3(x_{Pa(x_i)})=\\exp{a}$, that $g_3=\\exp{()}$ and $x_{Pa(x_3)}=a$." - ] - }, - { - "cell_type": "markdown", - "id": "bcfc076a", - "metadata": { - "editable": true - }, - "source": [ - "## Chain rule\n", - "\n", - "We can now compute the gradients by back-propagating the derivatives using the chain rule.\n", - "We have defined" - ] - }, - { - "cell_type": "markdown", - "id": "b4194098", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial x_L} = 1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "acc7030d", - "metadata": { - "editable": true - }, - "source": [ - "which allows us to find the derivatives of the various variables $x_i$ as" - ] - }, - { - "cell_type": "markdown", - "id": "02f92f41", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f}{\\partial x_i} = \\sum_{x_j:x_i\\in Pa(x_j)}\\frac{\\partial f}{\\partial x_j} \\frac{\\partial x_j}{\\partial x_i}=\\sum_{x_j:x_i\\in Pa(x_j)}\\frac{\\partial f}{\\partial x_j} \\frac{\\partial g_j}{\\partial x_i}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5541dfd1", - "metadata": { - "editable": true - }, - "source": [ - "Whenever we have a function which can be expressed as a computation\n", - "graph and the various functions can be expressed in terms of\n", - "elementary functions that are differentiable, then automatic\n", - "differentiation works. The functions may not need to be elementary\n", - "functions, they could also be computer programs, although not all\n", - "programs can be automatically differentiated." - ] - }, - { - "cell_type": "markdown", - "id": "f73cf263", - "metadata": { - "editable": true - }, - "source": [ - "## First network example, simple percepetron with one input\n", - "\n", - "As yet another example we define now a simple perceptron model with\n", - "all quantities given by scalars. We consider only one input variable\n", - "$x$ and one target value $y$. We define an activation function\n", - "$\\sigma_1$ which takes as input" - ] - }, - { - "cell_type": "markdown", - "id": "4b8722cb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_1 = w_1x+b_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a604334f", - "metadata": { - "editable": true - }, - "source": [ - "where $w_1$ is the weight and $b_1$ is the bias. These are the\n", - "parameters we want to optimize. The output is $a_1=\\sigma(z_1)$ (see\n", - "graph from whiteboard notes). This output is then fed into the\n", - "**cost/loss** function, which we here for the sake of simplicity just\n", - "define as the squared error" - ] - }, - { - "cell_type": "markdown", - "id": "0017f42e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(x;w_1,b_1)=\\frac{1}{2}(a_1-y)^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8c47d806", - "metadata": { - "editable": true - }, - "source": [ - "## Layout of a simple neural network with no hidden layer\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "df503def", - "metadata": { - "editable": true - }, - "source": [ - "## Optimizing the parameters\n", - "\n", - "In setting up the feed forward and back propagation parts of the\n", - "algorithm, we need now the derivative of the various variables we want\n", - "to train.\n", - "\n", - "We need" - ] - }, - { - "cell_type": "markdown", - "id": "bdc97982", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_1} \\hspace{0.1cm}\\mathrm{and}\\hspace{0.1cm}\\frac{\\partial C}{\\partial b_1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "42716985", - "metadata": { - "editable": true - }, - "source": [ - "Using the chain rule we find" - ] - }, - { - "cell_type": "markdown", - "id": "6df9aa60", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_1}=\\frac{\\partial C}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}\\frac{\\partial z_1}{\\partial w_1}=(a_1-y)\\sigma_1'x,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "30f9e077", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "77e9d494", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_1}=\\frac{\\partial C}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}\\frac{\\partial z_1}{\\partial b_1}=(a_1-y)\\sigma_1',\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1136c644", - "metadata": { - "editable": true - }, - "source": [ - "which we later will just define as" - ] - }, - { - "cell_type": "markdown", - "id": "b9f253ba", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}=\\delta_1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "14d41c44", - "metadata": { - "editable": true - }, - "source": [ - "## Adding a hidden layer\n", - "\n", - "We change our simple model to (see graph)\n", - "a network with just one hidden layer but with scalar variables only.\n", - "\n", - "Our output variable changes to $a_2$ and $a_1$ is now the output from the hidden node and $a_0=x$.\n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "id": "d7c607f5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_1 = w_1a_0+b_1 \\hspace{0.1cm} \\wedge a_1 = \\sigma_1(z_1),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "609e28e0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_2 = w_2a_1+b_2 \\hspace{0.1cm} \\wedge a_2 = \\sigma_2(z_2),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "494580d5", - "metadata": { - "editable": true - }, - "source": [ - "and the cost function" - ] - }, - { - "cell_type": "markdown", - "id": "03665a6f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(x;\\boldsymbol{\\Theta})=\\frac{1}{2}(a_2-y)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "911b5d2c", - "metadata": { - "editable": true - }, - "source": [ - "with $\\boldsymbol{\\Theta}=[w_1,w_2,b_1,b_2]$." - ] - }, - { - "cell_type": "markdown", - "id": "91e4f869", - "metadata": { - "editable": true - }, - "source": [ - "## Layout of a simple neural network with one hidden layer\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "43efdd27", - "metadata": { - "editable": true - }, - "source": [ - "## The derivatives\n", - "\n", - "The derivatives are now, using the chain rule again" - ] - }, - { - "cell_type": "markdown", - "id": "25d99018", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_2}=\\frac{\\partial C}{\\partial a_2}\\frac{\\partial a_2}{\\partial z_2}\\frac{\\partial z_2}{\\partial w_2}=(a_2-y)\\sigma_2'a_1=\\delta_2a_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6924f790", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_2}=\\frac{\\partial C}{\\partial a_2}\\frac{\\partial a_2}{\\partial z_2}\\frac{\\partial z_2}{\\partial b_2}=(a_2-y)\\sigma_2'=\\delta_2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f457fe37", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_1}=\\frac{\\partial C}{\\partial a_2}\\frac{\\partial a_2}{\\partial z_2}\\frac{\\partial z_2}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}\\frac{\\partial z_1}{\\partial w_1}=(a_2-y)\\sigma_2'a_1\\sigma_1'a_0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "81e40678", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_1}=\\frac{\\partial C}{\\partial a_2}\\frac{\\partial a_2}{\\partial z_2}\\frac{\\partial z_2}{\\partial a_1}\\frac{\\partial a_1}{\\partial z_1}\\frac{\\partial z_1}{\\partial b_1}=(a_2-y)\\sigma_2'\\sigma_1'=\\delta_1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c954b1f9", - "metadata": { - "editable": true - }, - "source": [ - "Can you generalize this to more than one hidden layer?" - ] - }, - { - "cell_type": "markdown", - "id": "87d10fa3", - "metadata": { - "editable": true - }, - "source": [ - "## Important observations\n", - "\n", - "From the above equations we see that the derivatives of the activation\n", - "functions play a central role. If they vanish, the training may\n", - "stop. This is called the vanishing gradient problem, see discussions below. If they become\n", - "large, the parameters $w_i$ and $b_i$ may simply go to infinity. This\n", - "is referenced as the exploding gradient problem." - ] - }, - { - "cell_type": "markdown", - "id": "c20ef010", - "metadata": { - "editable": true - }, - "source": [ - "## The training\n", - "\n", - "The training of the parameters is done through various gradient descent approximations with" - ] - }, - { - "cell_type": "markdown", - "id": "e9de19ea", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{i}\\leftarrow w_{i}- \\eta \\delta_i a_{i-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3487e8b8", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "7baa62bc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "b_i \\leftarrow b_i-\\eta \\delta_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a3c1590a", - "metadata": { - "editable": true - }, - "source": [ - "with $\\eta$ is the learning rate.\n", - "\n", - "One iteration consists of one feed forward step and one back-propagation step. Each back-propagation step does one update of the parameters $\\boldsymbol{\\Theta}$.\n", - "\n", - "For the first hidden layer $a_{i-1}=a_0=x$ for this simple model." - ] - }, - { - "cell_type": "markdown", - "id": "3c3dc625", - "metadata": { - "editable": true - }, - "source": [ - "## Code example\n", - "\n", - "The code here implements the above model with one hidden layer and\n", - "scalar variables for the same function we studied in the previous\n", - "example. The code is however set up so that we can add multiple\n", - "inputs $x$ and target values $y$. Note also that we have the\n", - "possibility of defining a feature matrix $\\boldsymbol{X}$ with more than just\n", - "one column for the input values. This will turn useful in our next example. We have also defined matrices and vectors for all of our operations although it is not necessary here." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "e9fb1fc9", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# We use the Sigmoid function as activation function\n", - "def sigmoid(z):\n", - " return 1.0/(1.0+np.exp(-z))\n", - "\n", - "def forwardpropagation(x):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_1 = np.matmul(x, w_1) + b_1\n", - " # activation in the hidden layer\n", - " a_1 = sigmoid(z_1)\n", - " # weighted sum of inputs to the output layer\n", - " z_2 = np.matmul(a_1, w_2) + b_2\n", - " a_2 = z_2\n", - " return a_1, a_2\n", - "\n", - "def backpropagation(x, y):\n", - " a_1, a_2 = forwardpropagation(x)\n", - " # parameter delta for the output layer, note that a_2=z_2 and its derivative wrt z_2 is just 1\n", - " delta_2 = a_2 - y\n", - " print(0.5*((a_2-y)**2))\n", - " # delta for the hidden layer\n", - " delta_1 = np.matmul(delta_2, w_2.T) * a_1 * (1 - a_1)\n", - " # gradients for the output layer\n", - " output_weights_gradient = np.matmul(a_1.T, delta_2)\n", - " output_bias_gradient = np.sum(delta_2, axis=0)\n", - " # gradient for the hidden layer\n", - " hidden_weights_gradient = np.matmul(x.T, delta_1)\n", - " hidden_bias_gradient = np.sum(delta_1, axis=0)\n", - " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "# Input variable\n", - "x = np.array([4.0],dtype=np.float64)\n", - "# Target values\n", - "y = 2*x+1.0 \n", - "\n", - "# Defining the neural network, only scalars here\n", - "n_inputs = x.shape\n", - "n_features = 1\n", - "n_hidden_neurons = 1\n", - "n_outputs = 1\n", - "\n", - "# Initialize the network\n", - "# weights and bias in the hidden layer\n", - "w_1 = np.random.randn(n_features, n_hidden_neurons)\n", - "b_1 = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "w_2 = np.random.randn(n_hidden_neurons, n_outputs)\n", - "b_2 = np.zeros(n_outputs) + 0.01\n", - "\n", - "eta = 0.1\n", - "for i in range(50):\n", - " # calculate gradients\n", - " derivW2, derivB2, derivW1, derivB1 = backpropagation(x, y)\n", - " # update weights and biases\n", - " w_2 -= eta * derivW2\n", - " b_2 -= eta * derivB2\n", - " w_1 -= eta * derivW1\n", - " b_1 -= eta * derivB1" - ] - }, - { - "cell_type": "markdown", - "id": "351debb8", - "metadata": { - "editable": true - }, - "source": [ - "We see that after some few iterations (the results do depend on the learning rate however), we get an error which is rather small." - ] - }, - { - "cell_type": "markdown", - "id": "c6579e36", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 1: Including more data\n", - "\n", - "Try to increase the amount of input and\n", - "target/output data. Try also to perform calculations for more values\n", - "of the learning rates. Feel free to add either hyperparameters with an\n", - "$l_1$ norm or an $l_2$ norm and discuss your results.\n", - "Discuss your results as functions of the amount of training data and various learning rates.\n", - "\n", - "**Challenge:** Try to change the activation functions and replace the hard-coded analytical expressions with automatic derivation via either **autograd** or **JAX**." - ] - }, - { - "cell_type": "markdown", - "id": "2c80a4b1", - "metadata": { - "editable": true - }, - "source": [ - "## Simple neural network and the back propagation equations\n", - "\n", - "Let us now try to increase our level of ambition and attempt at setting \n", - "up the equations for a neural network with two input nodes, one hidden\n", - "layer with two hidden nodes and one output layer with one output node/neuron only (see graph)..\n", - "\n", - "We need to define the following parameters and variables with the input layer (layer $(0)$) \n", - "where we label the nodes $x_0$ and $x_1$" - ] - }, - { - "cell_type": "markdown", - "id": "c834edc8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "x_0 = a_0^{(0)} \\wedge x_1 = a_1^{(0)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "79bd199b", - "metadata": { - "editable": true - }, - "source": [ - "The hidden layer (layer $(1)$) has nodes which yield the outputs $a_0^{(1)}$ and $a_1^{(1)}$) with weight $\\boldsymbol{w}$ and bias $\\boldsymbol{b}$ parameters" - ] - }, - { - "cell_type": "markdown", - "id": "0a856855", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{ij}^{(1)}=\\left\\{w_{00}^{(1)},w_{01}^{(1)},w_{10}^{(1)},w_{11}^{(1)}\\right\\} \\wedge b^{(1)}=\\left\\{b_0^{(1)},b_1^{(1)}\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "54280198", - "metadata": { - "editable": true - }, - "source": [ - "## Layout of a simple neural network with two input nodes, one hidden layer and one output node\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "b2cee09c", - "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" - ] - }, - { - "cell_type": "markdown", - "id": "710131c9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{i}^{(2)}=\\left\\{w_{0}^{(2)},w_{1}^{(2)}\\right\\} \\wedge b^{(2)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cd8b54e5", - "metadata": { - "editable": true - }, - "source": [ - "Our output is $\\tilde{y}=a^{(2)}$ and we define a generic cost function $C(a^{(2)},y;\\boldsymbol{\\Theta})$ where $y$ is the target value (a scalar here).\n", - "The parameters we need to optimize are given by" - ] - }, - { - "cell_type": "markdown", - "id": "8998ad11", - "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", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7d430cf7", - "metadata": { - "editable": true - }, - "source": [ - "## Compact expressions\n", - "\n", - "We can define the inputs to the activation functions for the various layers in terms of various matrix-vector multiplications and vector additions.\n", - "The inputs to the first hidden layer are" - ] - }, - { - "cell_type": "markdown", - "id": "9b5a6c95", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{bmatrix}z_0^{(1)} \\\\ z_1^{(1)} \\end{bmatrix}=\\begin{bmatrix}w_{00}^{(1)} & w_{01}^{(1)}\\\\ w_{10}^{(1)} &w_{11}^{(1)} \\end{bmatrix}\\begin{bmatrix}a_0^{(0)} \\\\ a_1^{(0)} \\end{bmatrix}+\\begin{bmatrix}b_0^{(1)} \\\\ b_1^{(1)} \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "31d044d8", - "metadata": { - "editable": true - }, - "source": [ - "with outputs" - ] - }, - { - "cell_type": "markdown", - "id": "f5125cb7", - "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", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0eed1fab", - "metadata": { - "editable": true - }, - "source": [ - "## Output layer\n", - "\n", - "For the final output layer we have the inputs to the final activation function" - ] - }, - { - "cell_type": "markdown", - "id": "9a9811d2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z^{(2)} = w_{0}^{(2)}a_0^{(1)} +w_{1}^{(2)}a_1^{(1)}+b^{(2)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "98bf5097", - "metadata": { - "editable": true - }, - "source": [ - "resulting in the output" - ] - }, - { - "cell_type": "markdown", - "id": "e749c895", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "a^{(2)}=\\sigma^{(2)}(z^{(2)}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ea6692ce", - "metadata": { - "editable": true - }, - "source": [ - "## Explicit derivatives\n", - "\n", - "In total we have nine parameters which we need to train. Using the\n", - "chain rule (or just the back-propagation algorithm) we can find all\n", - "derivatives. Since we will use automatic differentiation in reverse\n", - "mode, we start with the derivatives of the cost function with respect\n", - "to the parameters of the output layer, namely" - ] - }, - { - "cell_type": "markdown", - "id": "bf74eae4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{i}^{(2)}}=\\frac{\\partial C}{\\partial a^{(2)}}\\frac{\\partial a^{(2)}}{\\partial z^{(2)}}\\frac{\\partial z^{(2)}}{\\partial w_{i}^{(2)}}=\\delta^{(2)}a_i^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d590dc50", - "metadata": { - "editable": true - }, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "id": "eb0b8e3c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta^{(2)}=\\frac{\\partial C}{\\partial a^{(2)}}\\frac{\\partial a^{(2)}}{\\partial z^{(2)}}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7928cd11", - "metadata": { - "editable": true - }, - "source": [ - "and finally" - ] - }, - { - "cell_type": "markdown", - "id": "8fc852e0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b^{(2)}}=\\frac{\\partial C}{\\partial a^{(2)}}\\frac{\\partial a^{(2)}}{\\partial z^{(2)}}\\frac{\\partial z^{(2)}}{\\partial b^{(2)}}=\\delta^{(2)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "634713ba", - "metadata": { - "editable": true - }, - "source": [ - "## Derivatives of the hidden layer\n", - "\n", - "Using the chain rule we have the following expressions for say one of the weight parameters (it is easy to generalize to the other weight parameters)" - ] - }, - { - "cell_type": "markdown", - "id": "0f6ca3e6", - "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", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3b54e63f", - "metadata": { - "editable": true - }, - "source": [ - "which, noting that" - ] - }, - { - "cell_type": "markdown", - "id": "a69c61ff", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z^{(2)} =w_0^{(2)}a_0^{(1)}+w_1^{(2)}a_1^{(1)}+b^{(2)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a73b8fe2", - "metadata": { - "editable": true - }, - "source": [ - "allows us to rewrite" - ] - }, - { - "cell_type": "markdown", - "id": "093c845d", - "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", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dcd12209", - "metadata": { - "editable": true - }, - "source": [ - "## Final expression\n", - "Defining" - ] - }, - { - "cell_type": "markdown", - "id": "5d5e8985", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_0^{(1)}=w_0^{(2)}\\frac{\\partial a_0^{(1)}}{\\partial z_0^{(1)}}\\delta^{(2)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "506f74bf", - "metadata": { - "editable": true - }, - "source": [ - "we have" - ] - }, - { - "cell_type": "markdown", - "id": "b474afaa", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{00}^{(1)}}=\\delta_0^{(1)}a_0^{(1)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7d14d370", - "metadata": { - "editable": true - }, - "source": [ - "Similarly, we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "ca679e05", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{01}^{(1)}}=\\delta_0^{(1)}a_1^{(1)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "251a03fd", - "metadata": { - "editable": true - }, - "source": [ - "## Completing the list\n", - "\n", - "Similarly, we find" - ] - }, - { - "cell_type": "markdown", - "id": "b7575ec0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{10}^{(1)}}=\\delta_1^{(1)}a_0^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "02453de3", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "4e989854", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial w_{11}^{(1)}}=\\delta_1^{(1)}a_1^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "05a25565", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined" - ] - }, - { - "cell_type": "markdown", - "id": "d9e571d7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_1^{(1)}=w_1^{(2)}\\frac{\\partial a_1^{(1)}}{\\partial z_1^{(1)}}\\delta^{(2)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f96632e9", - "metadata": { - "editable": true - }, - "source": [ - "## Final expressions for the biases of the hidden layer\n", - "\n", - "For the sake of completeness, we list the derivatives of the biases, which are" - ] - }, - { - "cell_type": "markdown", - "id": "e15002e0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_{0}^{(1)}}=\\delta_0^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8c683755", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "da56a290", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial b_{1}^{(1)}}=\\delta_1^{(1)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e42a9d6c", - "metadata": { - "editable": true - }, - "source": [ - "As we will see below, these expressions can be generalized in a more compact form." - ] - }, - { - "cell_type": "markdown", - "id": "21dd6563", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient expressions\n", - "\n", - "For this specific model, with just one output node and two hidden\n", - "nodes, the gradient descent equations take the following form for output layer" - ] - }, - { - "cell_type": "markdown", - "id": "67fc0189", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{i}^{(2)}\\leftarrow w_{i}^{(2)}- \\eta \\delta^{(2)} a_{i}^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "daddd95e", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "5bf8af85", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "b^{(2)} \\leftarrow b^{(2)}-\\eta \\delta^{(2)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5a72ea0a", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "edd32da2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{ij}^{(1)}\\leftarrow w_{ij}^{(1)}- \\eta \\delta_{i}^{(1)} a_{j}^{(0)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "75c31af5", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "c037d92b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "b_{i}^{(1)} \\leftarrow b_{i}^{(1)}-\\eta \\delta_{i}^{(1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5937fd51", - "metadata": { - "editable": true - }, - "source": [ - "where $\\eta$ is the learning rate." - ] - }, - { - "cell_type": "markdown", - "id": "3f0f6cd3", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 2: Extended program\n", - "\n", - "We extend our simple code to a function which depends on two variable $x_0$ and $x_1$, that is" - ] - }, - { - "cell_type": "markdown", - "id": "057366c1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y=f(x_0,x_1)=x_0^2+3x_0x_1+x_1^2+5.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "293fa11b", - "metadata": { - "editable": true - }, - "source": [ - "We feed our network with $n=100$ entries $x_0$ and $x_1$. We have thus two features represented by these variable and an input matrix/design matrix $\\boldsymbol{X}\\in \\mathbf{R}^{n\\times 2}$" - ] - }, - { - "cell_type": "markdown", - "id": "d652c45d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} x_{00} & x_{01} \\\\ x_{00} & x_{01} \\\\ x_{10} & x_{11} \\\\ x_{20} & x_{21} \\\\ \\dots & \\dots \\\\ \\dots & \\dots \\\\ x_{n-20} & x_{n-21} \\\\ x_{n-10} & x_{n-11} \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8ca9d167", - "metadata": { - "editable": true - }, - "source": [ - "Write a code, based on the previous code examples, which takes as input these data and fit the above function.\n", - "You can extend your code to include automatic differentiation.\n", - "\n", - "With these examples, we are now ready to embark upon the writing of more a general code for neural networks." - ] - }, - { - "cell_type": "markdown", - "id": "8fed1e03", - "metadata": { - "editable": true - }, - "source": [ - "## Getting serious, the back propagation equations for a neural network\n", - "\n", - "Now it is time to move away from one node in each layer only. Our inputs are also represented either by several inputs.\n", - "\n", - "We have thus" - ] - }, - { - "cell_type": "markdown", - "id": "6394a2a5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}((\\boldsymbol{\\Theta}^L)}{\\partial w_{jk}^L} = \\left(a_j^L - y_j\\right)a_j^L(1-a_j^L)a_k^{L-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c2e22893", - "metadata": { - "editable": true - }, - "source": [ - "Defining" - ] - }, - { - "cell_type": "markdown", - "id": "5e054d69", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^L = a_j^L(1-a_j^L)\\left(a_j^L - y_j\\right) = \\sigma'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dd5f9a8d", - "metadata": { - "editable": true - }, - "source": [ - "and using the Hadamard product of two vectors we can write this as" - ] - }, - { - "cell_type": "markdown", - "id": "ff6e8f86", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\delta}^L = \\sigma'(\\hat{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\boldsymbol{a}^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6e186667", - "metadata": { - "editable": true - }, - "source": [ - "## Analyzing the last results\n", - "\n", - "This is an important expression. The second term on the right handside\n", - "measures how fast the cost function is changing as a function of the $j$th\n", - "output activation. If, for example, the cost function doesn't depend\n", - "much on a particular output node $j$, then $\\delta_j^L$ will be small,\n", - "which is what we would expect. The first term on the right, measures\n", - "how fast the activation function $f$ is changing at a given activation\n", - "value $z_j^L$." - ] - }, - { - "cell_type": "markdown", - "id": "0e0a514f", - "metadata": { - "editable": true - }, - "source": [ - "## More considerations\n", - "\n", - "Notice that everything in the above equations is easily computed. In\n", - "particular, we compute $z_j^L$ while computing the behaviour of the\n", - "network, and it is only a small additional overhead to compute\n", - "$\\sigma'(z^L_j)$. The exact form of the derivative with respect to the\n", - "output depends on the form of the cost function.\n", - "However, provided the cost function is known there should be little\n", - "trouble in calculating" - ] - }, - { - "cell_type": "markdown", - "id": "e8259ee9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3c817881", - "metadata": { - "editable": true - }, - "source": [ - "With the definition of $\\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely" - ] - }, - { - "cell_type": "markdown", - "id": "0f3e5b1c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4e14ef60", - "metadata": { - "editable": true - }, - "source": [ - "## Derivatives in terms of $z_j^L$\n", - "\n", - "It is also easy to see that our previous equation can be written as" - ] - }, - { - "cell_type": "markdown", - "id": "886fbebf", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^L =\\frac{\\partial {\\cal C}}{\\partial z_j^L}= \\frac{\\partial {\\cal C}}{\\partial a_j^L}\\frac{\\partial a_j^L}{\\partial z_j^L},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "16d62157", - "metadata": { - "editable": true - }, - "source": [ - "which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely" - ] - }, - { - "cell_type": "markdown", - "id": "4a81d6b5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L}\\frac{\\partial b_j^L}{\\partial z_j^L}=\\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0bcee50c", - "metadata": { - "editable": true - }, - "source": [ - "That is, the error $\\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias." - ] - }, - { - "cell_type": "markdown", - "id": "0ed7f7a0", - "metadata": { - "editable": true - }, - "source": [ - "## Bringing it together\n", - "\n", - "We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are" - ] - }, - { - "cell_type": "markdown", - "id": "a502b908", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1},\n", - "\\label{_auto1} \\tag{2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fa4de05b", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "cea42eaf", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\delta_j^L = \\sigma'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", - "\\label{_auto2} \\tag{3}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d04fa6e6", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "8716ad2e", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", - "\\label{_auto3} \\tag{4}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f64753b2", - "metadata": { - "editable": true - }, - "source": [ - "## Final back propagating equation\n", - "\n", - "We have that (replacing $L$ with a general layer $l$)" - ] - }, - { - "cell_type": "markdown", - "id": "4ad6d6d3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a8d42ee3", - "metadata": { - "editable": true - }, - "source": [ - "We want to express this in terms of the equations for layer $l+1$." - ] - }, - { - "cell_type": "markdown", - "id": "0628c4b8", - "metadata": { - "editable": true - }, - "source": [ - "## Using the chain rule and summing over all $k$ entries\n", - "\n", - "We obtain" - ] - }, - { - "cell_type": "markdown", - "id": "0868f3d3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^l =\\sum_k \\frac{\\partial {\\cal C}}{\\partial z_k^{l+1}}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}}=\\sum_k \\delta_k^{l+1}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "89190c24", - "metadata": { - "editable": true - }, - "source": [ - "and recalling that" - ] - }, - { - "cell_type": "markdown", - "id": "96af414a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_j^{l+1} = \\sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fe790abf", - "metadata": { - "editable": true - }, - "source": [ - "with $M_l$ being the number of nodes in layer $l$, we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "ece1f6fe", - "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": "9cafdde6", - "metadata": { - "editable": true - }, - "source": [ - "This is our final equation.\n", - "\n", - "We are now ready to set up the algorithm for back propagation and learning the weights and biases." - ] - }, - { - "cell_type": "markdown", - "id": "0766f482", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the back propagation algorithm\n", - "\n", - "The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", - "\n", - "**First**, we set up the input data $\\hat{x}$ and the activations\n", - "$\\hat{z}_1$ of the input layer and compute the activation function and\n", - "the pertinent outputs $\\hat{a}^1$.\n", - "\n", - "**Secondly**, we perform then the feed forward till we reach the output\n", - "layer and compute all $\\hat{z}_l$ of the input layer and compute the\n", - "activation function and the pertinent outputs $\\hat{a}^l$ for\n", - "$l=1,2,3,\\dots,L$.\n", - "\n", - "**Notation**: The first hidden layer has $l=1$ as label and the final output layer has $l=L$." - ] - }, - { - "cell_type": "markdown", - "id": "e29ae382", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the back propagation algorithm, part 2\n", - "\n", - "Thereafter we compute the ouput error $\\hat{\\delta}^L$ by computing all" - ] - }, - { - "cell_type": "markdown", - "id": "518b6578", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta_j^L = \\sigma'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4f804851", - "metadata": { - "editable": true - }, - "source": [ - "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,1$ as" - ] - }, - { - "cell_type": "markdown", - "id": "359aae81", - "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": "70123228", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the Back propagation algorithm, part 3\n", - "\n", - "Finally, we update the weights and the biases using gradient descent\n", - "for each $l=L-1,L-2,\\dots,1$ and update the weights and biases\n", - "according to the rules" - ] - }, - { - "cell_type": "markdown", - "id": "2df5a3de", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8081e4e4", - "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": "3c40603c", - "metadata": { - "editable": true - }, - "source": [ - "with $\\eta$ being the learning rate." - ] - }, - { - "cell_type": "markdown", - "id": "26de0b47", - "metadata": { - "editable": true - }, - "source": [ - "## Updating the gradients\n", - "\n", - "With the back propagate error for each $l=L-1,L-2,\\dots,1$ as" - ] - }, - { - "cell_type": "markdown", - "id": "a172a64a", - "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": "dfd6fc88", - "metadata": { - "editable": true - }, - "source": [ - "we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,1$ and update the weights and biases according to the rules" - ] - }, - { - "cell_type": "markdown", - "id": "a7df4398", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cfd24fc1", - "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": "869c3364", - "metadata": { - "editable": true - }, - "source": [ - "### Activation functions\n", - "\n", - "A property that characterizes a neural network, other than its\n", - "connectivity, is the choice of activation function(s). As described\n", - "in, the following restrictions are imposed on an activation function\n", - "for a FFNN to fulfill the universal approximation theorem\n", - "\n", - " * Non-constant\n", - "\n", - " * Bounded\n", - "\n", - " * Monotonically-increasing\n", - "\n", - " * Continuous" - ] - }, - { - "cell_type": "markdown", - "id": "91102a3c", - "metadata": { - "editable": true - }, - "source": [ - "### Activation functions, Logistic and Hyperbolic ones\n", - "\n", - "The second requirement excludes all linear functions. Furthermore, in\n", - "a MLP with only linear activation functions, each layer simply\n", - "performs a linear transformation of its inputs.\n", - "\n", - "Regardless of the number of layers, the output of the NN will be\n", - "nothing but a linear function of the inputs. Thus we need to introduce\n", - "some kind of non-linearity to the NN to be able to fit non-linear\n", - "functions Typical examples are the logistic *Sigmoid*" - ] - }, - { - "cell_type": "markdown", - "id": "9609f422", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) = \\frac{1}{1 + e^{-x}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cdd8d562", - "metadata": { - "editable": true - }, - "source": [ - "and the *hyperbolic tangent* function" - ] - }, - { - "cell_type": "markdown", - "id": "118a47f2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) = \\tanh(x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5d6387b5", - "metadata": { - "editable": true - }, - "source": [ - "### Relevance\n", - "\n", - "The *sigmoid* function are more biologically plausible because the\n", - "output of inactive neurons are zero. Such activation function are\n", - "called *one-sided*. However, it has been shown that the hyperbolic\n", - "tangent performs better than the sigmoid for training MLPs. has\n", - "become the most popular for *deep neural networks*" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "33449cca", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\"The sigmoid function (or the logistic curve) is a \n", - "function that takes any real number, z, and outputs a number (0,1).\n", - "It is useful in neural networks for assigning weights on a relative scale.\n", - "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n", - "\n", - "import numpy\n", - "import matplotlib.pyplot as plt\n", - "import math as mt\n", - "\n", - "z = numpy.arange(-5, 5, .1)\n", - "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n", - "sigma = sigma_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, sigma)\n", - "ax.set_ylim([-0.1, 1.1])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('sigmoid function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Step Function\"\"\"\n", - "z = numpy.arange(-5, 5, .02)\n", - "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n", - "step = step_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, step)\n", - "ax.set_ylim([-0.5, 1.5])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('step function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Sine Function\"\"\"\n", - "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n", - "t = numpy.sin(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, t)\n", - "ax.set_ylim([-1.0, 1.0])\n", - "ax.set_xlim([-2*mt.pi,2*mt.pi])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('sine function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Plots a graph of the squashing function used by a rectified linear\n", - "unit\"\"\"\n", - "z = numpy.arange(-2, 2, .1)\n", - "zero = numpy.zeros(len(z))\n", - "y = numpy.max([zero, z], axis=0)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, y)\n", - "ax.set_ylim([-2.0, 2.0])\n", - "ax.set_xlim([-2.0, 2.0])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('Rectified linear unit')\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "e8fafa8a", - "metadata": { - "editable": true - }, - "source": [ - "## Fine-tuning neural network hyperparameters\n", - "\n", - "The flexibility of neural networks is also one of their main\n", - "drawbacks: there are many hyperparameters to tweak. Not only can you\n", - "use any imaginable network topology (how neurons/nodes are\n", - "interconnected), but even in a simple FFNN you can change the number\n", - "of layers, the number of neurons per layer, the type of activation\n", - "function to use in each layer, the weight initialization logic, the\n", - "stochastic gradient optmized and much more. How do you know what\n", - "combination of hyperparameters is the best for your task?\n", - "\n", - "* You can use grid search with cross-validation to find the right hyperparameters.\n", - "\n", - "However,since there are many hyperparameters to tune, and since\n", - "training a neural network on a large dataset takes a lot of time, you\n", - "will only be able to explore a tiny part of the hyperparameter space.\n", - "\n", - "* You can use randomized search.\n", - "\n", - "* Or use tools like [Oscar](http://oscar.calldesk.ai/), which implements more complex algorithms to help you find a good set of hyperparameters quickly." - ] - }, - { - "cell_type": "markdown", - "id": "00965f5d", - "metadata": { - "editable": true - }, - "source": [ - "## Hidden layers\n", - "\n", - "For many problems you can start with just one or two hidden layers and\n", - "it will work just fine. For the MNIST data set you ca easily get a\n", - "high accuracy using just one hidden layer with a few hundred neurons.\n", - "You can reach for this data set above 98% accuracy using two hidden\n", - "layers with the same total amount of neurons, in roughly the same\n", - "amount of training time.\n", - "\n", - "For more complex problems, you can gradually ramp up the number of\n", - "hidden layers, until you start overfitting the training set. Very\n", - "complex tasks, such as large image classification or speech\n", - "recognition, typically require networks with dozens of layers and they\n", - "need a huge amount of training data. However, you will rarely have to\n", - "train such networks from scratch: it is much more common to reuse\n", - "parts of a pretrained state-of-the-art network that performs a similar\n", - "task." - ] - }, - { - "cell_type": "markdown", - "id": "d90316a8", - "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": "441fe8d9", - "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": "ae55ad1c", - "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": "96bbf798", - "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": "4b03e108", - "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": "2898691d", - "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": "4ac964f3", - "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": "c18a90e1", - "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": "eed9db84", - "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": "b375c182", - "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": "edb42800", - "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": "1a8fafc0", - "metadata": { - "editable": true - }, - "source": [ - "## Batch Normalization\n", - "\n", - "Batch Normalization aims to address the vanishing/exploding gradients\n", - "problems, and more generally the problem that the distribution of each\n", - "layer’s inputs changes during training, as the parameters of the\n", - "previous layers change.\n", - "\n", - "The technique consists of adding an operation in the model just before\n", - "the activation function of each layer, simply zero-centering and\n", - "normalizing the inputs, then scaling and shifting the result using two\n", - "new parameters per layer (one for scaling, the other for shifting). In\n", - "other words, this operation lets the model learn the optimal scale and\n", - "mean of the inputs for each layer. In order to zero-center and\n", - "normalize the inputs, the algorithm needs to estimate the inputs’ mean\n", - "and standard deviation. It does so by evaluating the mean and standard\n", - "deviation of the inputs over the current mini-batch, from this the\n", - "name batch normalization." - ] - }, - { - "cell_type": "markdown", - "id": "feef1d4d", - "metadata": { - "editable": true - }, - "source": [ - "## Dropout\n", - "\n", - "It is a fairly simple algorithm: at every training step, every neuron\n", - "(including the input neurons but excluding the output neurons) has a\n", - "probability $p$ of being temporarily dropped out, meaning it will be\n", - "entirely ignored during this training step, but it may be active\n", - "during the next step.\n", - "\n", - "The hyperparameter $p$ is called the dropout rate, and it is typically\n", - "set to 50%. After training, the neurons are not dropped anymore. It\n", - "is viewed as one of the most popular regularization techniques." - ] - }, - { - "cell_type": "markdown", - "id": "9428c225", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient Clipping\n", - "\n", - "A popular technique to lessen the exploding gradients problem is to\n", - "simply clip the gradients during backpropagation so that they never\n", - "exceed some threshold (this is mostly useful for recurrent neural\n", - "networks).\n", - "\n", - "This technique is called Gradient Clipping.\n", - "\n", - "In general however, Batch\n", - "Normalization is preferred." - ] - }, - { - "cell_type": "markdown", - "id": "504b21ae", - "metadata": { - "editable": true - }, - "source": [ - "## A top-down perspective on Neural networks\n", - "\n", - "The first thing we would like to do is divide the data into two or\n", - "three parts. A training set, a validation or dev (development) set,\n", - "and a test set. The test set is the data on which we want to make\n", - "predictions. The dev set is a subset of the training data we use to\n", - "check how well we are doing out-of-sample, after training the model on\n", - "the training dataset. We use the validation error as a proxy for the\n", - "test error in order to make tweaks to our model. It is crucial that we\n", - "do not use any of the test data to train the algorithm. This is a\n", - "cardinal sin in ML. Then:\n", - "\n", - "1. Estimate optimal error rate\n", - "\n", - "2. Minimize underfitting (bias) on training data set.\n", - "\n", - "3. Make sure you are not overfitting." - ] - }, - { - "cell_type": "markdown", - "id": "c51837a9", - "metadata": { - "editable": true - }, - "source": [ - "## More top-down perspectives\n", - "\n", - "If the validation and test sets are drawn from the same distributions,\n", - "then a good performance on the validation set should lead to similarly\n", - "good performance on the test set. \n", - "\n", - "However, sometimes\n", - "the training data and test data differ in subtle ways because, for\n", - "example, they are collected using slightly different methods, or\n", - "because it is cheaper to collect data in one way versus another. In\n", - "this case, there can be a mismatch between the training and test\n", - "data. This can lead to the neural network overfitting these small\n", - "differences between the test and training sets, and a poor performance\n", - "on the test set despite having a good performance on the validation\n", - "set. To rectify this, Andrew Ng suggests making two validation or dev\n", - "sets, one constructed from the training data and one constructed from\n", - "the test data. The difference between the performance of the algorithm\n", - "on these two validation sets quantifies the train-test mismatch. This\n", - "can serve as another important diagnostic when using DNNs for\n", - "supervised learning." - ] - }, - { - "cell_type": "markdown", - "id": "a7357657", - "metadata": { - "editable": true - }, - "source": [ - "## Limitations of supervised learning with deep networks\n", - "\n", - "Like all statistical methods, supervised learning using neural\n", - "networks has important limitations. This is especially important when\n", - "one seeks to apply these methods, especially to physics problems. Like\n", - "all tools, DNNs are not a universal solution. Often, the same or\n", - "better performance on a task can be achieved by using a few\n", - "hand-engineered features (or even a collection of random\n", - "features)." - ] - }, - { - "cell_type": "markdown", - "id": "e92c8a84", - "metadata": { - "editable": true - }, - "source": [ - "## Limitations of NNs\n", - "\n", - "Here we list some of the important limitations of supervised neural network based models. \n", - "\n", - "* **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).\n", - "\n", - "* **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs." - ] - }, - { - "cell_type": "markdown", - "id": "793aee7d", - "metadata": { - "editable": true - }, - "source": [ - "## Homogeneous data\n", - "\n", - "* **Homogeneous data.** Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types." - ] - }, - { - "cell_type": "markdown", - "id": "739960d6", - "metadata": { - "editable": true - }, - "source": [ - "## More limitations\n", - "\n", - "* **Many problems are not about prediction.** In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.\n", - "\n", - "Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/src/week41/week41.p.tex b/doc/src/week41/week41.p.tex deleted file mode 100644 index ef8e6139e..000000000 --- a/doc/src/week41/week41.p.tex +++ /dev/null @@ -1,2612 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/doconce/doconce/) -%% doconce format latex week41.do.txt --latex_title_layout=beamer --latex_table_format=footnotesize --no_mako -%% -% #ifdef PTEX2TEX_EXPLANATION -%% -%% The file follows the ptex2tex extended LaTeX format, see -%% ptex2tex: https://code.google.com/p/ptex2tex/ -%% -%% Run -%% ptex2tex myfile -%% or -%% doconce ptex2tex myfile -%% -%% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex. -%% (The ptex2tex program: https://code.google.com/p/ptex2tex) -%% Many preprocess options can be added to ptex2tex or doconce ptex2tex -%% -%% ptex2tex -DMINTED myfile -%% doconce ptex2tex myfile envir=minted -%% -%% ptex2tex will typeset code environments according to a global or local -%% .ptex2tex.cfg configure file. doconce ptex2tex will typeset code -%% according to options on the command line (just type doconce ptex2tex to -%% see examples). If doconce ptex2tex has envir=minted, it enables the -%% minted style without needing -DMINTED. -% #endif - -% #define PREAMBLE - -% #ifdef PREAMBLE -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{ptex2tex} -% #ifdef MINTED -\usepackage{minted} -\usemintedstyle{default} -% #endif - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% Tricks for having figures close to where they are defined: -% 1. define less restrictive rules for where to put figures -\setcounter{topnumber}{2} -\setcounter{bottomnumber}{2} -\setcounter{totalnumber}{4} -\renewcommand{\topfraction}{0.95} -\renewcommand{\bottomfraction}{0.95} -\renewcommand{\textfraction}{0} -\renewcommand{\floatpagefraction}{0.75} -% floatpagefraction must always be less than topfraction! -% 2. ensure all figures are flushed before next section -\usepackage[section]{placeins} -% 3. enable begin{figure}[H] (often leads to ugly pagebreaks) -%\usepackage{float}\restylefloat{figure} - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -\usepackage[framemethod=TikZ]{mdframed} - -% --- begin definitions of admonition environments --- - -% Admonition style "mdfbox" is an oval colored box based on mdframed -% "notice" admon -\colorlet{mdfbox_notice_background}{gray!5} -\newmdenv[ - skipabove=15pt, - skipbelow=15pt, - outerlinewidth=0, - backgroundcolor=mdfbox_notice_background, - linecolor=black, - linewidth=2pt, % frame thickness - frametitlebackgroundcolor=mdfbox_notice_background, - frametitlerule=true, - frametitlefont=\normalfont\bfseries, - shadow=false, % frame shadow? - shadowsize=11pt, - leftmargin=0, - rightmargin=0, - roundcorner=5, - needspace=0pt, -]{notice_mdfboxmdframed} - -\newenvironment{notice_mdfboxadmon}[1][]{ -\begin{notice_mdfboxmdframed}[frametitle=#1] -} -{ -\end{notice_mdfboxmdframed} -} - -% Admonition style "mdfbox" is an oval colored box based on mdframed -% "summary" admon -\colorlet{mdfbox_summary_background}{gray!5} -\newmdenv[ - skipabove=15pt, - skipbelow=15pt, - outerlinewidth=0, - backgroundcolor=mdfbox_summary_background, - linecolor=black, - linewidth=2pt, % frame thickness - frametitlebackgroundcolor=mdfbox_summary_background, - frametitlerule=true, - frametitlefont=\normalfont\bfseries, - shadow=false, % frame shadow? - shadowsize=11pt, - leftmargin=0, - rightmargin=0, - roundcorner=5, - needspace=0pt, -]{summary_mdfboxmdframed} - -\newenvironment{summary_mdfboxadmon}[1][]{ -\begin{summary_mdfboxmdframed}[frametitle=#1] -} -{ -\end{summary_mdfboxmdframed} -} - -% Admonition style "mdfbox" is an oval colored box based on mdframed -% "warning" admon -\colorlet{mdfbox_warning_background}{gray!5} -\newmdenv[ - skipabove=15pt, - skipbelow=15pt, - outerlinewidth=0, - backgroundcolor=mdfbox_warning_background, - linecolor=black, - linewidth=2pt, % frame thickness - frametitlebackgroundcolor=mdfbox_warning_background, - frametitlerule=true, - frametitlefont=\normalfont\bfseries, - shadow=false, % frame shadow? - shadowsize=11pt, - leftmargin=0, - rightmargin=0, - roundcorner=5, - needspace=0pt, -]{warning_mdfboxmdframed} - -\newenvironment{warning_mdfboxadmon}[1][]{ -\begin{warning_mdfboxmdframed}[frametitle=#1] -} -{ -\end{warning_mdfboxmdframed} -} - -% Admonition style "mdfbox" is an oval colored box based on mdframed -% "question" admon -\colorlet{mdfbox_question_background}{gray!5} -\newmdenv[ - skipabove=15pt, - skipbelow=15pt, - outerlinewidth=0, - backgroundcolor=mdfbox_question_background, - linecolor=black, - linewidth=2pt, % frame thickness - frametitlebackgroundcolor=mdfbox_question_background, - frametitlerule=true, - frametitlefont=\normalfont\bfseries, - shadow=false, % frame shadow? - shadowsize=11pt, - leftmargin=0, - rightmargin=0, - roundcorner=5, - needspace=0pt, -]{question_mdfboxmdframed} - -\newenvironment{question_mdfboxadmon}[1][]{ -\begin{question_mdfboxmdframed}[frametitle=#1] -} -{ -\end{question_mdfboxmdframed} -} - -% Admonition style "mdfbox" is an oval colored box based on mdframed -% "block" admon -\colorlet{mdfbox_block_background}{gray!5} -\newmdenv[ - skipabove=15pt, - skipbelow=15pt, - outerlinewidth=0, - backgroundcolor=mdfbox_block_background, - linecolor=black, - linewidth=2pt, % frame thickness - frametitlebackgroundcolor=mdfbox_block_background, - frametitlerule=true, - frametitlefont=\normalfont\bfseries, - shadow=false, % frame shadow? - shadowsize=11pt, - leftmargin=0, - rightmargin=0, - roundcorner=5, - needspace=0pt, -]{block_mdfboxmdframed} - -\newenvironment{block_mdfboxadmon}[1][]{ -\begin{block_mdfboxmdframed}[frametitle=#1] -} -{ -\end{block_mdfboxmdframed} -} - -% --- end of definitions of admonition environments --- - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -\newenvironment{doconceexercise}{}{} -\newcounter{doconceexercisecounter} - - -% ------ header in subexercises ------ -%\newcommand{\subex}[1]{\paragraph{#1}} -%\newcommand{\subex}[1]{\par\vspace{1.7mm}\noindent{\bf #1}\ \ } -\makeatletter -% 1.5ex is the spacing above the header, 0.5em the spacing after subex title -\newcommand\subex{\@startsection{paragraph}{4}{\z@}% - {1.5ex\@plus1ex \@minus.2ex}% - {-0.5em}% - {\normalfont\normalsize\bfseries}} -\makeatother - - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE -% #endif - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\title{Week 41 Neural networks and constructing a neural network code} - -% ----------------- author(s) ------------------------- - -\author{Morten Hjorth-Jensen\inst{1}} -\institute{Department of Physics, University of Oslo\inst{1}} -% ----------------- end author(s) ------------------------- - -\date{Week 41 -% -% -} - -% !split -\subsection{Plan for week 41, October 7-11} - -% !split -\subsection{Material for the lecture on Monday October 7, 2024} -\begin{enumerate} -\item Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model. - -\item Building our own Feed-forward Neural Network -% * \href{{https://youtu.be/5-RRTO9uDvI}}{Video of lecture notes} -% * \href{{https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf}}{Whiteboard notes} -\end{enumerate} - -\noindent -\begin{block}{Readings and Videos: } -\begin{enumerate} -\item These lecture notes - -\item Rashcka et al chapter 11 - -\item For neural networks we recommend Goodfellow et al chapter 6. -\begin{enumerate} - - \item Neural Networks demystified at \href{{https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs}}{\nolinkurl{https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs}} - -\end{enumerate} - -\noindent -\item Building Neural Networks from scratch at \href{{https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex}}{\nolinkurl{https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex}} - -\item Video on Neural Networks at \href{{https://www.youtube.com/watch?v=CqOfi41LfDw}}{\nolinkurl{https://www.youtube.com/watch?v=CqOfi41LfDw}} - -\item Video on the back propagation algorithm at \href{{https://www.youtube.com/watch?v=Ilg3gGewQ5U}}{\nolinkurl{https://www.youtube.com/watch?v=Ilg3gGewQ5U}} -\end{enumerate} - -\noindent -We also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at \href{{http://neuralnetworksanddeeplearning.com/chap4.html}}{\nolinkurl{http://neuralnetworksanddeeplearning.com/chap4.html}}. -\end{block} - -% !split -\subsection{Material for the active learning sessions on Tuesday and Wednesday} -\begin{itemize} -\item Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation - -\item One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code - -\item Discussion of project 2 - -\item Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent -\end{itemize} - -\noindent -% !split -\subsection{Lecture Monday October 7} - -% !split -\subsection{Introduction to Neural networks} - -Artificial neural networks are computational systems that can learn to -perform tasks by considering examples, generally without being -programmed with any task-specific rules. It is supposed to mimic a -biological system, wherein neurons interact by sending signals in the -form of mathematical functions between layers. All layers can contain -an arbitrary number of neurons, and each connection is represented by -a weight variable. - -% !split -\subsection{Artificial neurons} - -The field of artificial neural networks has a long history of -development, and is closely connected with the advancement of computer -science and computers in general. A model of artificial neurons was -first developed by McCulloch and Pitts in 1943 to study signal -processing in the brain and has later been refined by others. The -general idea is to mimic neural networks in the human brain, which is -composed of billions of neurons that communicate with each other by -sending electrical signals. Each neuron accumulates its incoming -signals, which must exceed an activation threshold to yield an -output. If the threshold is not overcome, the neuron remains inactive, -i.e.~has zero output. - -This behaviour has inspired a simple mathematical model for an artificial neuron. - -\begin{equation} - y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u) - \label{artificialNeuron} -\end{equation} -Here, the output $y$ of the neuron is the value of its activation function, which have as input -a weighted sum of signals $x_i, \dots ,x_n$ received by $n$ other neurons. - -Conceptually, it is helpful to divide neural networks into four -categories: -\begin{enumerate} -\item general purpose neural networks for supervised learning, - -\item neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs), - -\item neural networks for sequential data such as Recurrent Neural Networks (RNNs), and - -\item neural networks for unsupervised learning such as Deep Boltzmann Machines. -\end{enumerate} - -\noindent -In natural science, DNNs and CNNs have already found numerous -applications. In statistical physics, they have been applied to detect -phase transitions in 2D Ising and Potts models, lattice gauge -theories, and different phases of polymers, or solving the -Navier-Stokes equation in weather forecasting. Deep learning has also -found interesting applications in quantum physics. Various quantum -phase transitions can be detected and studied using DNNs and CNNs, -topological phases, and even non-equilibrium many-body -localization. Representing quantum states as DNNs quantum state -tomography are among some of the impressive achievements to reveal the -potential of DNNs to facilitate the study of quantum systems. - -In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. - -The applications are not limited to the natural sciences. There is a -plethora of applications in essentially all disciplines, from the -humanities to life science and medicine. - -% !split -\subsection{Neural network types} - -An artificial neural network (ANN), is a computational model that -consists of layers of connected neurons, or nodes or units. We will -refer to these interchangeably as units or nodes, and sometimes as -neurons. - -It is supposed to mimic a biological nervous system by letting each -neuron interact with other neurons by sending signals in the form of -mathematical functions between layers. A wide variety of different -ANNs have been developed, but most of them consist of an input layer, -an output layer and eventual layers in-between, called \emph{hidden -layers}. All layers can contain an arbitrary number of nodes, and each -connection between two nodes is associated with a weight variable. - -Neural networks (also called neural nets) are neural-inspired -nonlinear models for supervised learning. As we will see, neural nets -can be viewed as natural, more powerful extensions of supervised -learning methods such as linear and logistic regression and soft-max -methods we discussed earlier. - -% !split -\subsection{Feed-forward neural networks} - -The feed-forward neural network (FFNN) was the first and simplest type -of ANNs that were devised. In this network, the information moves in -only one direction: forward through the layers. - -Nodes are represented by circles, while the arrows display the -connections between the nodes, including the direction of information -flow. Additionally, each arrow corresponds to a weight variable -(figure to come). We observe that each node in a layer is connected -to \emph{all} nodes in the subsequent layer, making this a so-called -\emph{fully-connected} FFNN. - -% !split -\subsection{Convolutional Neural Network} - -A different variant of FFNNs are \emph{convolutional neural networks} -(CNNs), which have a connectivity pattern inspired by the animal -visual cortex. Individual neurons in the visual cortex only respond to -stimuli from small sub-regions of the visual field, called a receptive -field. This makes the neurons well-suited to exploit the strong -spatially local correlation present in natural images. The response of -each neuron can be approximated mathematically as a convolution -operation. (figure to come) - -Convolutional neural networks emulate the behaviour of neurons in the -visual cortex by enforcing a \emph{local} connectivity pattern between -nodes of adjacent layers: Each node in a convolutional layer is -connected only to a subset of the nodes in the previous layer, in -contrast to the fully-connected FFNN. Often, CNNs consist of several -convolutional layers that learn local features of the input, with a -fully-connected layer at the end, which gathers all the local data and -produces the outputs. They have wide applications in image and video -recognition. - -% !split -\subsection{Recurrent neural networks} - -So far we have only mentioned ANNs where information flows in one -direction: forward. \emph{Recurrent neural networks} on the other hand, -have connections between nodes that form directed \emph{cycles}. This -creates a form of internal memory which are able to capture -information on what has been calculated before; the output is -dependent on the previous computations. Recurrent NNs make use of -sequential information by performing the same task for every element -in a sequence, where each element depends on previous elements. An -example of such information is sentences, making recurrent NNs -especially well-suited for handwriting and speech recognition. - -% !split -\subsection{Other types of networks} - -There are many other kinds of ANNs that have been developed. One type -that is specifically designed for interpolation in multidimensional -space is the radial basis function (RBF) network. RBFs are typically -made up of three layers: an input layer, a hidden layer with -non-linear radial symmetric activation functions and a linear output -layer (''linear'' here means that each node in the output layer has a -linear activation function). The layers are normally fully-connected -and there are no cycles, thus RBFs can be viewed as a type of -fully-connected FFNN. They are however usually treated as a separate -type of NN due the unusual activation functions. - -% !split -\subsection{Multilayer perceptrons} - -One uses often so-called fully-connected feed-forward neural networks -with three or more layers (an input layer, one or more hidden layers -and an output layer) consisting of neurons that have non-linear -activation functions. - -Such networks are often called \emph{multilayer perceptrons} (MLPs). - -% !split -\subsection{Why multilayer perceptrons?} - -According to the \emph{Universal approximation theorem}, a feed-forward -neural network with just a single hidden layer containing a finite -number of neurons can approximate a continuous multidimensional -function to arbitrary accuracy, assuming the activation function for -the hidden layer is a \textbf{non-constant, bounded and -monotonically-increasing continuous function}. - -Note that the requirements on the activation function only applies to -the hidden layer, the output nodes are always assumed to be linear, so -as to not restrict the range of output values. - -% !split -\subsection{Illustration of a single perceptron model and a multi-perceptron model} - -\begin{figure}[!ht] % - \centerline{\includegraphics[width=0.8\linewidth]{figures/nns.png}} - \caption{ - In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer. - } -\end{figure} -%\clearpage % flush figures - -% !split -\subsection{Examples of XOR, OR and AND gates} - -Let us first try to fit various gates using standard linear -regression. The gates we are thinking of are the classical XOR, OR and -AND gates, well-known elements in computer science. The tables here -show how we can set up the inputs $x_1$ and $x_2$ in order to yield a -specific target $y_i$. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\bpycod -""" -Simple code that tests XOR, OR and AND gates with linear regression -""" - -import numpy as np -# Design matrix -X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64) -print(f"The X.TX matrix:{X.T @ X}") -Xinv = np.linalg.pinv(X.T @ X) -print(f"The invers of X.TX matrix:{Xinv}") - -# The XOR gate -yXOR = np.array( [ 0, 1 ,1, 0]) -ThetaXOR = Xinv @ X.T @ yXOR -print(f"The values of theta for the XOR gate:{ThetaXOR}") -print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}") - - -# The OR gate -yOR = np.array( [ 0, 1 ,1, 1]) -ThetaOR = Xinv @ X.T @ yOR -print(f"The values of theta for the OR gate:{ThetaOR}") -print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}") - - -# The OR gate -yAND = np.array( [ 0, 0 ,0, 1]) -ThetaAND = Xinv @ X.T @ yAND -print(f"The values of theta for the AND gate:{ThetaAND}") -print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}") - -\epycod - - -What is happening here? - -% !split -\subsection{Does Logistic Regression do a better Job?} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\bpycod -""" -Simple code that tests XOR and OR gates with linear regression -and logistic regression -""" - -import matplotlib.pyplot as plt -from sklearn.linear_model import LogisticRegression -import numpy as np - -# Design matrix -X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64) -print(f"The X.TX matrix:{X.T @ X}") -Xinv = np.linalg.pinv(X.T @ X) -print(f"The invers of X.TX matrix:{Xinv}") - -# The XOR gate -yXOR = np.array( [ 0, 1 ,1, 0]) -ThetaXOR = Xinv @ X.T @ yXOR -print(f"The values of theta for the XOR gate:{ThetaXOR}") -print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}") - - -# The OR gate -yOR = np.array( [ 0, 1 ,1, 1]) -ThetaOR = Xinv @ X.T @ yOR -print(f"The values of theta for the OR gate:{ThetaOR}") -print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}") - - -# The OR gate -yAND = np.array( [ 0, 0 ,0, 1]) -ThetaAND = Xinv @ X.T @ yAND -print(f"The values of theta for the AND gate:{ThetaAND}") -print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}") - -# Now we change to logistic regression - - -# Logistic Regression -logreg = LogisticRegression() -logreg.fit(X, yOR) -print("Test set accuracy with Logistic Regression for OR gate: {:.2f}".format(logreg.score(X,yOR))) - -logreg.fit(X, yXOR) -print("Test set accuracy with Logistic Regression for XOR gate: {:.2f}".format(logreg.score(X,yXOR))) - - -logreg.fit(X, yAND) -print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND))) - -\epycod - - -Not exactly impressive, but somewhat better. - -% !split -\subsection{Adding Neural Networks} - - - - - - - - - - - - -\bpycod - -# and now neural networks with Scikit-Learn and the XOR - -from sklearn.neural_network import MLPClassifier -from sklearn.datasets import make_classification -X, yXOR = make_classification(n_samples=100, random_state=1) -FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR) -FFNN.predict_proba(X) -print(f"Test set accuracy with Feed Forward Neural Network for XOR gate:{FFNN.score(X, yXOR)}") - - -\epycod - - -% !split -\subsection{Mathematics of deep learning} - -\begin{block}{Two recent books online } -\begin{enumerate} -\item \href{{https://arxiv.org/abs/2105.04026}}{The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen}, published as \href{{https://doi.org/10.1017/9781009025096.002}}{Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022} - -\item \href{{https://doi.org/10.48550/arXiv.2310.20360}}{Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger} -\end{enumerate} - -\noindent -\end{block} - -% !split -\subsection{Reminder on books with hands-on material and codes} -\begin{block}{} -\begin{itemize} -\item \href{{https://sebastianraschka.com/blog/2022/ml-pytorch-book.html}}{Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch} -\end{itemize} - -\noindent -\end{block} - -% !split -\subsection{Reading recommendations} - -\begin{enumerate} -\item Rashkca et al., chapter 11, jupyter-notebook sent separately, from \href{{https://github.com/rasbt/machine-learning-book}}{GitHub} - -\item Goodfellow et al, chapter 6 and 7 contain most of the neural network background. -\end{enumerate} - -\noindent -% !split -\subsection{Mathematics of deep learning and neural networks} - -Neural networks, in its so-called feed-forward form, where each -iterations contains a feed-forward stage and a back-propgagation -stage, consist of series of affine matrix-matrix and matrix-vector -multiplications. The unknown parameters (the so-called biases and -weights which deternine the architecture of a neural network), are -uptaded iteratively using the so-called back-propagation algorithm. -This algorithm corresponds to the so-called reverse mode of -automatic differentation. - -% !split -\subsection{Basics of an NN} - -A neural network consists of a series of hidden layers, in addition to -the input and output layers. Each layer $l$ has a set of parameters -$\bm{\Theta}^{(l)}=(\bm{W}^{(l)},\bm{b}^{(l)})$ which are related to the -parameters in other layers through a series of affine transformations, -for a standard NN these are matrix-matrix and matrix-vector -multiplications. For all layers we will simply use a collective variable $\bm{\Theta}$. - -It consist of two basic steps: -\begin{enumerate} -\item a feed forward stage which takes a given input and produces a final output which is compared with the target values through our cost/loss function. - -\item a back-propagation state where the unknown parameters $\bm{\Theta}$ are updated through the optimization of the their gradients. The expressions for the gradients are obtained via the chain rule, starting from the derivative of the cost/function. -\end{enumerate} - -\noindent -These two steps make up one iteration. This iterative process is continued till we reach an eventual stopping criterion. - -% !split -\subsection{Overarching view of a neural network} - -The architecture of a neural network defines our model. This model -aims at describing some function $f(\bm{x}$ which represents -some final result (outputs or tagrget values) given a specific inpput -$\bm{x}$. Note that here $\bm{y}$ and $\bm{x}$ are not limited to be -vectors. - -The architecture consists of -\begin{enumerate} -\item An input and an output layer where the input layer is defined by the inputs $\bm{x}$. The output layer produces the model ouput $\bm{\tilde{y}}$ which is compared with the target value $\bm{y}$ - -\item A given number of hidden layers and neurons/nodes/units for each layer (this may vary) - -\item A given activation function $\sigma(\bm{z})$ with arguments $\bm{z}$ to be defined below. The activation functions may differ from layer to layer. - -\item The last layer, normally called \textbf{output} layer has normally an activation function tailored to the specific problem - -\item Finally we define a so-called cost or loss function which is used to gauge the quality of our model. -\end{enumerate} - -\noindent -% !split -\subsection{The optimization problem} - -The cost function is a function of the unknown parameters -$\bm{\Theta}$ where the latter is a container for all possible -parameters needed to define a neural network - -If we are dealing with a regression task a typical cost/loss function -is the mean squared error -\[ -C(\bm{\Theta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\theta}\right)^T\left(\bm{y}-\bm{X}\bm{\theta}\right)\right\}. -\] -This function represents one of many possible ways to define -the so-called cost function. Note that here we have assumed a linear dependence in terms of the paramters $\bm{\Theta}$. This is in general not the case. - -% !split -\subsection{Parameters of neural networks} -For neural networks the parameters -$\bm{\Theta}$ are given by the so-called weights and biases (to be -defined below). - -The weights are given by matrix elements $w_{ij}^{(l)}$ where the -superscript indicates the layer number. The biases are typically given -by vector elements representing each single node of a given layer, -that is $b_j^{(l)}$. - -% !split -\subsection{Other ingredients of a neural network} - -Having defined the architecture of a neural network, the optimization -of the cost function with respect to the parameters $\bm{\Theta}$, -involves the calculations of gradients and their optimization. The -gradients represent the derivatives of a multidimensional object and -are often approximated by various gradient methods, including -\begin{enumerate} -\item various quasi-Newton methods, - -\item plain gradient descent (GD) with a constant learning rate $\eta$, - -\item GD with momentum and other approximations to the learning rates such as -\begin{itemize} - - \item Adapative gradient (ADAgrad) - - \item Root mean-square propagation (RMSprop) - - \item Adaptive gradient with momentum (ADAM) and many other - -\end{itemize} - -\noindent -\item Stochastic gradient descent and various families of learning rate approximations -\end{enumerate} - -\noindent -% !split -\subsection{Other parameters} - -In addition to the above, there are often additional hyperparamaters -which are included in the setup of a neural network. These will be -discussed below. - -% !split -\subsection{Universal approximation theorem} - -The universal approximation theorem plays a central role in deep -learning. \href{{https://link.springer.com/article/10.1007/BF02551274}}{Cybenko (1989)} showed -the following: - -\begin{block}{} -Let $\sigma$ be any continuous sigmoidal function such that -\[ -\sigma(z) = \left\{\begin{array}{cc} 1 & z\rightarrow \infty\\ 0 & z \rightarrow -\infty \end{array}\right. -\] -Given a continuous and deterministic function $F(\bm{x})$ on the unit -cube in $d$-dimensions $F\in [0,1]^d$, $x\in [0,1]^d$ and a parameter -$\epsilon >0$, there is a one-layer (hidden) neural network -$f(\bm{x};\bm{\Theta})$ with $\bm{\Theta}=(\bm{W},\bm{b})$ and $\bm{W}\in -\mathbb{R}^{m\times n}$ and $\bm{b}\in \mathbb{R}^{n}$, for which -\[ -\vert F(\bm{x})-f(\bm{x};\bm{\Theta})\vert < \epsilon \hspace{0.1cm} \forall \bm{x}\in[0,1]^d. -\] - -\end{block} - -% !split -\subsection{Some parallels from real analysis} - -For those of you familiar with for example the \href{{https://en.wikipedia.org/wiki/Stone%E2%80%93Weierstrass_theorem}}{Stone-Weierstrass -theorem} -for polynomial approximations or the convergence criterion for Fourier -series, there are similarities in the derivation of the proof for -neural networks. - -% !split -\subsection{The approximation theorem in words} - -\textbf{Any continuous function $y=F(\bm{x})$ supported on the unit cube in -$d$-dimensions can be approximated by a one-layer sigmoidal network to -arbitrary accuracy.} - -\href{{https://www.sciencedirect.com/science/article/abs/pii/089360809190009T}}{Hornik (1991)} extended the theorem by letting any non-constant, bounded activation function to be included using that the expectation value -\[ -\mathbb{E}[\vert F(\bm{x})\vert^2] =\int_{\bm{x}\in D} \vert F(\bm{x})\vert^2p(\bm{x})d\bm{x} < \infty. -\] -Then we have -\[ -\mathbb{E}[\vert F(\bm{x})-f(\bm{x};\bm{\Theta})\vert^2] =\int_{\bm{x}\in D} \vert F(\bm{x})-f(\bm{x};\bm{\Theta})\vert^2p(\bm{x})d\bm{x} < \epsilon. -\] - -% !split -\subsection{More on the general approximation theorem} - -None of the proofs give any insight into the relation between the -number of of hidden layers and nodes and the approximation error -$\epsilon$, nor the magnitudes of $\bm{W}$ and $\bm{b}$. - -Neural networks (NNs) have what we may call a kind of universality no matter what function we want to compute. - -\begin{block}{} -It does not mean that an NN can be used to exactly compute any function. Rather, we get an approximation that is as good as we want. -\end{block} - -% !split -\subsection{Class of functions we can approximate} - -\begin{block}{} -The class of functions that can be approximated are the continuous ones. -If the function $F(\bm{x})$ is discontinuous, it won't in general be possible to approximate it. However, an NN may still give an approximation even if we fail in some points. -\end{block} - -% !split -\subsection{Setting up the equations for a neural network} - -The questions we want to ask are how do changes in the biases and the -weights in our network change the cost function and how can we use the -final output to modify the weights and biases? - -To derive these equations let us start with a plain regression problem -and define our cost function as - -\[ -{\cal C}(\bm{\Theta}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2, -\] - -where the $y_i$s are our $n$ targets (the values we want to -reproduce), while the outputs of the network after having propagated -all inputs $\bm{x}$ are given by $\bm{\tilde{y}}_i$. - -% !split -\subsection{Layout of a neural network with three hidden layers} - -\vspace{6mm} - -% inline figure -\centerline{\includegraphics[width=1.0\linewidth]{figures/nn1.pdf}} - -\vspace{6mm} - -% !split -\subsection{Definitions} - -With our definition of the targets $\bm{y}$, the outputs of the -network $\bm{\tilde{y}}$ and the inputs $\bm{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 -$\hat{a}^{l-1}$ from the previous layer as - -\[ -z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, -\] - -where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$ -represents the total number of nodes/neurons/units of layer $l-1$. The -figure in the whiteboard notes illustrates this equation. We can rewrite this in a more -compact form as the matrix-vector products we discussed earlier, - -\[ -\hat{z}^l = \left(\hat{W}^l\right)^T\hat{a}^{l-1}+\hat{b}^l. -\] - -% !split -\subsection{Inputs to the activation function} - -With the activation values $\bm{z}^l$ we can in turn define the -output of layer $l$ as $\bm{a}^l = f(\bm{z}^l)$ where $f$ 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 $f$ for all layers -and their nodes. It means we have - -\[ -a_j^l = \sigma(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. -\] - -% !split -\subsection{Derivatives and the chain rule} - -From the definition of the activation $z_j^l$ we have -\[ -\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, -\] -and -\[ -\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. -\] - -With our definition of the activation function we have that (note that this function depends only on $z_j^l$) -\[ -\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=\sigma(z_j^l)(1-\sigma(z_j^l)). -\] - -% !split -\subsection{Derivative of the cost function} - -With these definitions we can now compute the derivative of the cost function in terms of the weights. - -Let us specialize to the output layer $l=L$. Our cost function is -\[ -{\cal C}(\bm{\Theta}^L) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - y_i\right)^2, -\] -The derivative of this function with respect to the weights is - -\[ -\frac{\partial{\cal C}(\bm{\Theta}^L)}{\partial w_{jk}^L} = \left(a_j^L - y_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}}, -\] -The last partial derivative can easily be computed and reads (by applying the chain rule) -\[ -\frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1}. -\] - -% !split -\subsection{Simpler examples first, and automatic differentiation} - -In order to understand the back propagation algorithm and its -derivation (an implementation of the chain rule), let us first digress -with some simple examples. These examples are also meant to motivate -the link with back propagation and \href{{https://en.wikipedia.org/wiki/Automatic_differentiation}}{automatic differentiation}. - -% !split -\subsection{Reminder on the chain rule and gradients} - -If we have a multivariate function $f(x,y)$ where $x=x(t)$ and $y=y(t)$ are functions of a variable $t$, we have that the gradient of $f$ with respect to $t$ (without the explicit unit vector components) -\[ -\frac{df}{dt} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial t} \end{bmatrix}=\frac{\partial f}{\partial x} \frac{\partial x}{\partial t} +\frac{\partial f}{\partial y} \frac{\partial y}{\partial t}. -\] - -% !split -\subsection{Multivariable functions} - -If we have a multivariate function $f(x,y)$ where $x=x(t,s)$ and $y=y(t,s)$ are functions of the variables $t$ and $s$, we have that the partial derivatives -\[ -\frac{\partial f}{\partial s}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial s}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial s}, -\] -and -\[ -\frac{\partial f}{\partial t}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial t}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial t}. -\] - -the gradient of $f$ with respect to $t$ and $s$ (without the explicit unit vector components) -\[ -\frac{df}{d(s,t)} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial s} &\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial s} & \frac{\partial y}{\partial t} \end{bmatrix}. -\] - -% !split -\subsection{Automatic differentiation through examples} - -A great introduction to automatic differentiation is given by Baydin et al., see \href{{https://arxiv.org/abs/1502.05767}}{\nolinkurl{https://arxiv.org/abs/1502.05767}}. - -Automatic differentiation is a represented by a repeated application -of the chain rule on well-known functions and allows for the -calculation of derivatives to numerical precision. It is not the same -as the calculation of symbolic derivatives via for example SymPy, nor -does it use approximative formulae based on Taylor-expansions of a -function around a given value. The latter are error prone due to -truncation errors and values of the step size $\Delta$. - -% !split -\subsection{Simple example} - -Our first example is rather simple, -\[ -f(x) =\exp{x^2}, -\] -with derivative -\[ -f'(x) =2x\exp{x^2}. -\] -We can use SymPy to extract the pertinent lines of Python code through the following simple example - - - - - - - - - -\bpycod -from __future__ import division -from sympy import * -x = symbols('x') -expr = exp(x*x) -simplify(expr) -derivative = diff(expr,x) -print(python(expr)) -print(python(derivative)) - -\epycod - - -% !split -\subsection{Smarter way of evaluating the above function} -If we study this function, we note that we can reduce the number of operations by introducing an intermediate variable -\[ -a = x^2, -\] -leading to -\[ -f(x) = f(a(x)) = b= \exp{a}. -\] - -We now assume that all operations can be counted in terms of equal -floating point operations. This means that in order to calculate -$f(x)$ we need first to square $x$ and then compute the exponential. We -have thus two floating point operations only. - -% !split -\subsection{Reducing the number of operations} - -With the introduction of a precalculated quantity $a$ and thereby $f(x)$ we have that the derivative can be written as - -\[ -f'(x) = 2xb, -\] - -which reduces the number of operations from four in the orginal -expression to two. This means that if we need to compute $f(x)$ and -its derivative (a common task in optimizations), we have reduced the -number of operations from six to four in total. - -\textbf{Note} that the usage of a symbolic software like SymPy does not -include such simplifications and the calculations of the function and -the derivatives yield in general more floating point operations. - -% !split -\subsection{Chain rule, forward and reverse modes} - -In the above example we have introduced the variables $a$ and $b$, and our function is -\[ -f(x) = f(a(x)) = b= \exp{a}, -\] -with $a=x^2$. We can decompose the derivative of $f$ with respect to $x$ as -\[ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}. -\] - -We note that since $b=f(x)$ that -\[ -\frac{df}{db}=1, -\] -leading to -\[ -\frac{df}{dx}=\frac{db}{da}\frac{da}{dx}=2x\exp{x^2}, -\] -as before. - -% !split -\subsection{Forward and reverse modes} - -We have that -\[ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}, -\] -which we can rewrite either as -\[ -\frac{df}{dx}=\left[\frac{df}{db}\frac{db}{da}\right]\frac{da}{dx}, -\] -or -\[ -\frac{df}{dx}=\frac{df}{db}\left[\frac{db}{da}\frac{da}{dx}\right]. -\] - -The first expression is called reverse mode (or back propagation) -since we start by evaluating the derivatives at the end point and then -propagate backwards. This is the standard way of evaluating -derivatives (gradients) when optimizing the parameters of a neural -network. In the context of deep learning this is computationally -more efficient since the output of a neural network consists of either -one or some few other output variables. - -The second equation defines the so-called \textbf{forward mode}. - -% !split -\subsection{More complicated function} - -We increase our ambitions and introduce a slightly more complicated function -\[ -f(x) =\sqrt{x^2+exp{x^2}}, -\] -with derivative -\[ -f'(x) =\frac{x(1+\exp{x^2})}{\sqrt{x^2+exp{x^2}}}. -\] -The corresponding SymPy code reads - - - - - - - - - -\bpycod -from __future__ import division -from sympy import * -x = symbols('x') -expr = sqrt(x*x+exp(x*x)) -simplify(expr) -derivative = diff(expr,x) -print(python(expr)) -print(python(derivative)) - -\epycod - - -% !split -\subsection{Counting the number of floating point operations} - -A simple count of operations shows that we need five operations for -the function itself and ten for the derivative. Fifteen operations in total if we wish to proceed with the above codes. - -Can we reduce this to -say half the number of operations? - -% !split -\subsection{Defining intermediate operations} - -We can indeed reduce the number of operation to half of those listed in the brute force approach above. -We define the following quantities -\[ -a = x^2, -\] -and -\[ -b = \exp{x^2} = \exp{a}, -\] -and -\[ -c= a+b, -\] -and -\[ -d=f(x)=\sqrt{c}. -\] - -% !split -\subsection{New expression for the derivative} - -With these definitions we obtain the following partial derivatives -\[ -\frac{\partial a}{\partial x} = 2x, -\] -and -\[ -\frac{\partial b}{\partial a} = \exp{a}, -\] -and -\[ -\frac{\partial c}{\partial a} = 1, -\] -and -\[ -\frac{\partial c}{\partial b} = 1, -\] -and -\[ -\frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -\] -and finally -\[ -\frac{\partial f}{\partial d} = 1. -\] - -% !split -\subsection{Final derivatives} -Our final derivatives are thus -\[ -\frac{\partial f}{\partial c} = \frac{\partial f}{\partial d} \frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -\] -\[ -\frac{\partial f}{\partial b} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial b} = \frac{1}{2\sqrt{c}}, -\] -\[ -\frac{\partial f}{\partial a} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial a}+ -\frac{\partial f}{\partial b} \frac{\partial b}{\partial a} = \frac{1+\exp{a}}{2\sqrt{c}}, -\] -and finally -\[ -\frac{\partial f}{\partial x} = \frac{\partial f}{\partial a} \frac{\partial a}{\partial x} = \frac{x(1+\exp{a})}{\sqrt{c}}, -\] -which is just -\[ -\frac{\partial f}{\partial x} = \frac{x(1+b)}{d}, -\] -and requires only three operations if we can reuse all intermediate variables. - -% !split -\subsection{In general not this simple} - -In general, see the generalization below, unless we can obtain simple -analytical expressions which we can simplify further, the final -implementation of automatic differentiation involves repeated -calculations (and thereby operations) of derivatives of elementary -functions. - -% !split -\subsection{Automatic differentiation} - -We can make this example more formal. Automatic differentiation is a -formalization of the previous example (see graph). - -We define $\bm{x}\in x_1,\dots, x_l$ input variables to a given function $f(\bm{x})$ and $x_{l+1},\dots, x_L$ intermediate variables. - -In the above example we have only one input variable, $l=1$ and four intermediate variables, that is -\[ -\begin{bmatrix} x_1=x & x_2 = x^2=a & x_3 =\exp{a}= b & x_4=c=a+b & x_5 = \sqrt{c}=d \end{bmatrix}. -\] - -Furthemore, for $i=l+1, \dots, L$ (here $i=2,3,4,5$ and $f=x_L=d$), we -define the elementary functions $g_i(x_{Pa(x_i)})$ where $x_{Pa(x_i)}$ are the parent nodes of the variable $x_i$. - -In our case, we have for example for $x_3=g_3(x_{Pa(x_i)})=\exp{a}$, that $g_3=\exp{()}$ and $x_{Pa(x_3)}=a$. - -% !split -\subsection{Chain rule} - -We can now compute the gradients by back-propagating the derivatives using the chain rule. -We have defined -\[ -\frac{\partial f}{\partial x_L} = 1, -\] -which allows us to find the derivatives of the various variables $x_i$ as -\[ -\frac{\partial f}{\partial x_i} = \sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial x_j}{\partial x_i}=\sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial g_j}{\partial x_i}. -\] - -Whenever we have a function which can be expressed as a computation -graph and the various functions can be expressed in terms of -elementary functions that are differentiable, then automatic -differentiation works. The functions may not need to be elementary -functions, they could also be computer programs, although not all -programs can be automatically differentiated. - -% !split -\subsection{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 -\textbf{cost/loss} function, which we here for the sake of simplicity just -define as the squared error - -\[ -C(x;w_1,b_1)=\frac{1}{2}(a_1-y)^2. -\] - -% !split -\subsection{Layout of a simple neural network with no hidden layer} - -\vspace{6mm} - -% inline figure -\centerline{\includegraphics[width=1.0\linewidth]{figures/simplenn1.png}} - -\vspace{6mm} - -% !split -\subsection{Optimizing the parameters} - -In setting up the feed forward and back propagation parts of the -algorithm, we need now the derivative of the various variables we want -to train. - -We need -\[ -\frac{\partial C}{\partial w_1} \hspace{0.1cm}\mathrm{and}\hspace{0.1cm}\frac{\partial C}{\partial b_1}. -\] - -Using the chain rule we find -\[ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_1-y)\sigma_1'x, -\] -and -\[ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_1-y)\sigma_1', -\] -which we later will just define as -\[ -\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}=\delta_1. -\] - -% !split -\subsection{Adding a hidden layer} - -We change our simple model to (see graph) -a network with just one hidden layer but with scalar variables only. - -Our output variable changes to $a_2$ and $a_1$ is now the output from the hidden node and $a_0=x$. -We have then -\[ -z_1 = w_1a_0+b_1 \hspace{0.1cm} \wedge a_1 = \sigma_1(z_1), -\] -\[ -z_2 = w_2a_1+b_2 \hspace{0.1cm} \wedge a_2 = \sigma_2(z_2), -\] -and the cost function -\[ -C(x;\bm{\Theta})=\frac{1}{2}(a_2-y)^2, -\] -with $\bm{\Theta}=[w_1,w_2,b_1,b_2]$. - -% !split -\subsection{Layout of a simple neural network with one hidden layer} - -\vspace{6mm} - -% inline figure -\centerline{\includegraphics[width=1.0\linewidth]{figures/simplenn2.png}} - -\vspace{6mm} - -% !split -\subsection{The derivatives} - -The derivatives are now, using the chain rule again - -\[ -\frac{\partial C}{\partial w_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial w_2}=(a_2-y)\sigma_2'a_1=\delta_2a_1, -\] -\[ -\frac{\partial C}{\partial b_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial b_2}=(a_2-y)\sigma_2'=\delta_2, -\] -\[ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_2-y)\sigma_2'a_1\sigma_1'a_0, -\] -\[ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_2-y)\sigma_2'\sigma_1'=\delta_1. -\] - -Can you generalize this to more than one hidden layer? - -% !split -\subsection{Important observations} - -\begin{block}{} -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. -\end{block} - -% !split -\subsection{The training} - -The training of the parameters is done through various gradient descent approximations with - -\[ -w_{i}\leftarrow w_{i}- \eta \delta_i a_{i-1}, -\] -and -\[ -b_i \leftarrow b_i-\eta \delta_i, -\] -with $\eta$ is the learning rate. - -One iteration consists of one feed forward step and one back-propagation step. Each back-propagation step does one update of the parameters $\bm{\Theta}$. - -For the first hidden layer $a_{i-1}=a_0=x$ for this simple model. - -% !split -\subsection{Code example} - -The code here implements the above model with one hidden layer and -scalar variables for the same function we studied in the previous -example. The code is however set up so that we can add multiple -inputs $x$ and target values $y$. Note also that we have the -possibility of defining a feature matrix $\bm{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. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\bpycod -import numpy as np -# We use the Sigmoid function as activation function -def sigmoid(z): - return 1.0/(1.0+np.exp(-z)) - -def forwardpropagation(x): - # weighted sum of inputs to the hidden layer - z_1 = np.matmul(x, w_1) + b_1 - # activation in the hidden layer - a_1 = sigmoid(z_1) - # weighted sum of inputs to the output layer - z_2 = np.matmul(a_1, w_2) + b_2 - a_2 = z_2 - return a_1, a_2 - -def backpropagation(x, y): - a_1, a_2 = forwardpropagation(x) - # parameter delta for the output layer, note that a_2=z_2 and its derivative wrt z_2 is just 1 - delta_2 = a_2 - y - print(0.5*((a_2-y)**2)) - # delta for the hidden layer - delta_1 = np.matmul(delta_2, w_2.T) * a_1 * (1 - a_1) - # gradients for the output layer - output_weights_gradient = np.matmul(a_1.T, delta_2) - output_bias_gradient = np.sum(delta_2, axis=0) - # gradient for the hidden layer - hidden_weights_gradient = np.matmul(x.T, delta_1) - hidden_bias_gradient = np.sum(delta_1, axis=0) - return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient - - -# ensure the same random numbers appear every time -np.random.seed(0) -# Input variable -x = np.array([4.0],dtype=np.float64) -# Target values -y = 2*x+1.0 - -# Defining the neural network, only scalars here -n_inputs = x.shape -n_features = 1 -n_hidden_neurons = 1 -n_outputs = 1 - -# Initialize the network -# weights and bias in the hidden layer -w_1 = np.random.randn(n_features, n_hidden_neurons) -b_1 = np.zeros(n_hidden_neurons) + 0.01 - -# weights and bias in the output layer -w_2 = np.random.randn(n_hidden_neurons, n_outputs) -b_2 = np.zeros(n_outputs) + 0.01 - -eta = 0.1 -for i in range(50): - # calculate gradients - derivW2, derivB2, derivW1, derivB1 = backpropagation(x, y) - # update weights and biases - w_2 -= eta * derivW2 - b_2 -= eta * derivB2 - w_1 -= eta * derivW1 - b_1 -= eta * derivB1 - - - -\epycod - - -We see that after some few iterations (the results do depend on the learning rate however), we get an error which is rather small. - -% !split - -% --- begin exercise --- -\begin{doconceexercise} -\refstepcounter{doconceexercisecounter} - -\exercisesection{Exercise \thedoconceexercisecounter: Including more data} - - -Try to increase the amount of input and -target/output data. Try also to perform calculations for more values -of the learning rates. Feel free to add either hyperparameters with an -$l_1$ norm or an $l_2$ norm and discuss your results. -Discuss your results as functions of the amount of training data and various learning rates. - -\textbf{Challenge:} Try to change the activation functions and replace the hard-coded analytical expressions with automatic derivation via either \textbf{autograd} or \textbf{JAX}. - -\end{doconceexercise} -% --- end exercise --- - -% !split -\subsection{Simple neural network and the back propagation equations} - -Let us now try to increase our level of ambition and attempt at setting -up the equations for a neural network with two input nodes, one hidden -layer with two hidden nodes and one output layer with one output node/neuron only (see graph).. - -We need to define the following parameters and variables with the input layer (layer $(0)$) -where we label the nodes $x_0$ and $x_1$ -\[ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. -\] - -The hidden layer (layer $(1)$) has nodes which yield the outputs $a_0^{(1)}$ and $a_1^{(1)}$) with weight $\bm{w}$ and bias $\bm{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\}. -\] - -% !split -\subsection{Layout of a simple neural network with two input nodes, one hidden layer and one output node} - -\vspace{6mm} - -% inline figure -\centerline{\includegraphics[width=1.0\linewidth]{figures/simplenn3.png}} - -\vspace{6mm} - -% !split -\subsection{The ouput layer} - -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 -\[ -w_{i}^{(2)}=\left\{w_{0}^{(2)},w_{1}^{(2)}\right\} \wedge b^{(2)}. -\] - -Our output is $\tilde{y}=a^{(2)}$ and we define a generic cost function $C(a^{(2)},y;\bm{\Theta})$ where $y$ is the target value (a scalar here). -The parameters we need to optimize are given by -\[ -\bm{\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\}. -\] - -% !split -\subsection{Compact expressions} - -We can define the inputs to the activation functions for the various layers in terms of various matrix-vector multiplications and vector additions. -The inputs to the first hidden layer are -\[ -\begin{bmatrix}z_0^{(1)} \\ z_1^{(1)} \end{bmatrix}=\begin{bmatrix}w_{00}^{(1)} & w_{01}^{(1)}\\ w_{10}^{(1)} &w_{11}^{(1)} \end{bmatrix}\begin{bmatrix}a_0^{(0)} \\ a_1^{(0)} \end{bmatrix}+\begin{bmatrix}b_0^{(1)} \\ b_1^{(1)} \end{bmatrix}, -\] -with outputs -\[ -\begin{bmatrix}a_0^{(1)} \\ a_1^{(1)} \end{bmatrix}=\begin{bmatrix}\sigma^{(1)}(z_0^{(1)}) \\ \sigma^{(1)}(z_1^{(1)}) \end{bmatrix}. -\] - -% !split -\subsection{Output layer} - -For the final output layer we have the inputs to the final activation function -\[ -z^{(2)} = w_{0}^{(2)}a_0^{(1)} +w_{1}^{(2)}a_1^{(1)}+b^{(2)}, -\] -resulting in the output -\[ -a^{(2)}=\sigma^{(2)}(z^{(2)}). -\] - -% !split -\subsection{Explicit derivatives} - -In total we have nine parameters which we need to train. Using the -chain rule (or just the back-propagation algorithm) we can find all -derivatives. Since we will use automatic differentiation in reverse -mode, we start with the derivatives of the cost function with respect -to the parameters of the output layer, namely - -\[ -\frac{\partial C}{\partial w_{i}^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial w_{i}^{(2)}}=\delta^{(2)}a_i^{(1)}, -\] -with -\[ -\delta^{(2)}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\] -and finally -\[ -\frac{\partial C}{\partial b^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial b^{(2)}}=\delta^{(2)}. -\] - -% !split -\subsection{Derivatives of the hidden layer} - -Using the chain rule we have the following expressions for say one of the weight parameters (it is easy to generalize to the other weight parameters) -\[ -\frac{\partial C}{\partial w_{00}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\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)}}, -\] -which, noting that -\[ -z^{(2)} =w_0^{(2)}a_0^{(1)}+w_1^{(2)}a_1^{(1)}+b^{(2)}, -\] -allows us to rewrite -\[ -\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)}. -\] - -% !split -\subsection{Final expression} -Defining -\[ -\delta_0^{(1)}=w_0^{(2)}\frac{\partial a_0^{(1)}}{\partial z_0^{(1)}}\delta^{(2)}, -\] -we have -\[ -\frac{\partial C}{\partial w_{00}^{(1)}}=\delta_0^{(1)}a_0^{(1)}. -\] -Similarly, we obtain -\[ -\frac{\partial C}{\partial w_{01}^{(1)}}=\delta_0^{(1)}a_1^{(1)}. -\] - -% !split -\subsection{Completing the list} - -Similarly, we find -\[ -\frac{\partial C}{\partial w_{10}^{(1)}}=\delta_1^{(1)}a_0^{(1)}, -\] -and -\[ -\frac{\partial C}{\partial w_{11}^{(1)}}=\delta_1^{(1)}a_1^{(1)}, -\] -where we have defined -\[ -\delta_1^{(1)}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}\delta^{(2)}. -\] - -% !split -\subsection{Final expressions for the biases of the hidden layer} - -For the sake of completeness, we list the derivatives of the biases, which are -\[ -\frac{\partial C}{\partial b_{0}^{(1)}}=\delta_0^{(1)}, -\] -and -\[ -\frac{\partial C}{\partial b_{1}^{(1)}}=\delta_1^{(1)}. -\] -As we will see below, these expressions can be generalized in a more compact form. - -% !split -\subsection{Gradient expressions} - -For this specific model, with just one output node and two hidden -nodes, the gradient descent equations take the following form for output layer -\[ -w_{i}^{(2)}\leftarrow w_{i}^{(2)}- \eta \delta^{(2)} a_{i}^{(1)}, -\] -and -\[ -b^{(2)} \leftarrow b^{(2)}-\eta \delta^{(2)}, -\] -and -\[ -w_{ij}^{(1)}\leftarrow w_{ij}^{(1)}- \eta \delta_{i}^{(1)} a_{j}^{(0)}, -\] -and -\[ -b_{i}^{(1)} \leftarrow b_{i}^{(1)}-\eta \delta_{i}^{(1)}, -\] -where $\eta$ is the learning rate. - -% !split - -% --- begin exercise --- -\begin{doconceexercise} -\refstepcounter{doconceexercisecounter} - -\exercisesection{Exercise \thedoconceexercisecounter: Extended program} - - -We extend our simple code to a function which depends on two variable $x_0$ and $x_1$, that is -\[ -y=f(x_0,x_1)=x_0^2+3x_0x_1+x_1^2+5. -\] -We feed our network with $n=100$ entries $x_0$ and $x_1$. We have thus two features represented by these variable and an input matrix/design matrix $\bm{X}\in \mathbf{R}^{n\times 2}$ -\[ -\bm{X}=\begin{bmatrix} x_{00} & x_{01} \\ x_{00} & x_{01} \\ x_{10} & x_{11} \\ x_{20} & x_{21} \\ \dots & \dots \\ \dots & \dots \\ x_{n-20} & x_{n-21} \\ x_{n-10} & x_{n-11} \end{bmatrix}. -\] -Write a code, based on the previous code examples, which takes as input these data and fit the above function. -You can extend your code to include automatic differentiation. - -With these examples, we are now ready to embark upon the writing of more a general code for neural networks. - -\end{doconceexercise} -% --- end exercise --- - -% !split -\subsection{Getting serious, the back propagation equations for a neural network} - -Now it is time to move away from one node in each layer only. Our inputs are also represented either by several inputs. - -We have thus -\[ -\frac{\partial{\cal C}((\bm{\Theta}^L)}{\partial w_{jk}^L} = \left(a_j^L - y_j\right)a_j^L(1-a_j^L)a_k^{L-1}, -\] - -Defining -\[ -\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - y_j\right) = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\] -and using the Hadamard product of two vectors we can write this as -\[ -\bm{\delta}^L = \sigma'(\hat{z}^L)\circ\frac{\partial {\cal C}}{\partial (\bm{a}^L)}. -\] - -% !split -\subsection{Analyzing the last results} - -This is an important expression. The second term on the right handside -measures how fast the cost function is changing as a function of the $j$th -output activation. If, for example, the cost function doesn't depend -much on a particular output node $j$, then $\delta_j^L$ will be small, -which is what we would expect. The first term on the right, measures -how fast the activation function $f$ is changing at a given activation -value $z_j^L$. - -% !split -\subsection{More considerations} - -Notice that everything in the above equations is easily computed. In -particular, we compute $z_j^L$ while computing the behaviour of the -network, and it is only a small additional overhead to compute -$\sigma'(z^L_j)$. The exact form of the derivative with respect to the -output depends on the form of the cost function. -However, provided the cost function is known there should be little -trouble in calculating - -\[ -\frac{\partial {\cal C}}{\partial (a_j^L)} -\] - -With the definition of $\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely -\[ -\frac{\partial{\cal C}}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}. -\] - -% !split -\subsection{Derivatives in terms of $z_j^L$} - -It is also easy to see that our previous equation can be written as - -\[ -\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, -\] -which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely -\[ -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, -\] -That is, the error $\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias. - -% !split -\subsection{Bringing it together} - -We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are - -\begin{equation} -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}, -\end{equation} -and -\begin{equation} -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\end{equation} -and - -\begin{equation} -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}, -\end{equation} - -% !split -\subsection{Final back propagating equation} - -We have that (replacing $L$ with a general layer $l$) -\[ -\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. -\] -We want to express this in terms of the equations for layer $l+1$. - -% !split -\subsection{Using the chain rule and summing over all $k$ entries} - -We obtain -\[ -\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, -\] -and recalling that -\[ -z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, -\] -with $M_l$ being the number of nodes in layer $l$, we obtain -\[ -\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -\] -This is our final equation. - -We are now ready to set up the algorithm for back propagation and learning the weights and biases. - -% !split -\subsection{Setting up the back propagation algorithm} - -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. - -\textbf{First}, we set up the input data $\hat{x}$ and the activations -$\hat{z}_1$ of the input layer and compute the activation function and -the pertinent outputs $\hat{a}^1$. - -\textbf{Secondly}, we perform then the feed forward till we reach the output -layer and compute all $\hat{z}_l$ of the input layer and compute the -activation function and the pertinent outputs $\hat{a}^l$ for -$l=1,2,3,\dots,L$. - -\textbf{Notation}: The first hidden layer has $l=1$ as label and the final output layer has $l=L$. - -% !split -\subsection{Setting up the back propagation algorithm, part 2} - -Thereafter we compute the ouput error $\hat{\delta}^L$ by computing all -\[ -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. -\] - -Then we compute the back propagate error for each $l=L-1,L-2,\dots,1$ as -\[ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). -\] - -% !split -\subsection{Setting up the Back propagation algorithm, part 3} - -Finally, we update the weights and the biases using gradient descent -for each $l=L-1,L-2,\dots,1$ and update the weights and biases -according to the rules - -\[ -w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, -\] - -\[ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -\] -with $\eta$ being the learning rate. - -% !split -\subsection{Updating the gradients} - -With the back propagate error for each $l=L-1,L-2,\dots,1$ as -\[ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}sigma'(z_j^l), -\] -we update the weights and the biases using gradient descent for each $l=L-1,L-2,\dots,1$ and update the weights and biases according to the rules -\[ -w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, -\] - -\[ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -\] - -% !split -\paragraph{Activation functions.} -A property that characterizes a neural network, other than its -connectivity, is the choice of activation function(s). As described -in, the following restrictions are imposed on an activation function -for a FFNN to fulfill the universal approximation theorem - -\begin{itemize} - \item Non-constant - - \item Bounded - - \item Monotonically-increasing - - \item Continuous -\end{itemize} - -\noindent -% !split -\paragraph{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 \emph{Sigmoid} - -\[ - f(x) = \frac{1}{1 + e^{-x}}, -\] -and the \emph{hyperbolic tangent} function -\[ - f(x) = \tanh(x) -\] - -% !split -\paragraph{Relevance.} -The \emph{sigmoid} function are more biologically plausible because the -output of inactive neurons are zero. Such activation function are -called \emph{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 \emph{deep neural networks} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\bpycod -"""The sigmoid function (or the logistic curve) is a -function that takes any real number, z, and outputs a number (0,1). -It is useful in neural networks for assigning weights on a relative scale. -The value z is the weighted sum of parameters involved in the learning algorithm.""" - -import numpy -import matplotlib.pyplot as plt -import math as mt - -z = numpy.arange(-5, 5, .1) -sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z))) -sigma = sigma_fn(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, sigma) -ax.set_ylim([-0.1, 1.1]) -ax.set_xlim([-5,5]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('sigmoid function') - -plt.show() - -"""Step Function""" -z = numpy.arange(-5, 5, .02) -step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0) -step = step_fn(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, step) -ax.set_ylim([-0.5, 1.5]) -ax.set_xlim([-5,5]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('step function') - -plt.show() - -"""Sine Function""" -z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1) -t = numpy.sin(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, t) -ax.set_ylim([-1.0, 1.0]) -ax.set_xlim([-2*mt.pi,2*mt.pi]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('sine function') - -plt.show() - -"""Plots a graph of the squashing function used by a rectified linear -unit""" -z = numpy.arange(-2, 2, .1) -zero = numpy.zeros(len(z)) -y = numpy.max([zero, z], axis=0) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, y) -ax.set_ylim([-2.0, 2.0]) -ax.set_xlim([-2.0, 2.0]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('Rectified linear unit') - -plt.show() - -\epycod - - -% !split -\subsection{Fine-tuning neural network hyperparameters} - -The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are -interconnected), but even in a simple FFNN you can change the number -of layers, the number of neurons per layer, the type of activation -function to use in each layer, the weight initialization logic, the -stochastic gradient optmized and much more. How do you know what -combination of hyperparameters is the best for your task? - -\begin{itemize} -\item You can use grid search with cross-validation to find the right hyperparameters. -\end{itemize} - -\noindent -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. - -\begin{itemize} -\item You can use randomized search. - -\item Or use tools like \href{{http://oscar.calldesk.ai/}}{Oscar}, which implements more complex algorithms to help you find a good set of hyperparameters quickly. -\end{itemize} - -\noindent -% !split -\subsection{Hidden layers} - -For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set you ca 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. - -% !split -\subsection{Vanishing gradients} - -The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. - -Unfortunately for us, the gradients often get smaller and smaller as -the algorithm progresses down to the first hidden layers. As a result, -the GD update leaves the lower layer connection weights virtually -unchanged, and training never converges to a good solution. This is -known in the literature as \textbf{the vanishing gradients problem}. - -% !split -\subsection{Exploding gradients} - -In other cases, the opposite can happen, namely the the gradients can -grow bigger and bigger. The result is that many of the layers get -large updates of the weights the algorithm diverges. This is the -\textbf{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 - -% !split -\subsection{Is the Logistic activation function (Sigmoid) our choice?} - -Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. - -A paper titled \href{{http://proceedings.mlr.press/v9/glorot10a.html}}{Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio} found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. - -% !split -\subsection{Logistic function as the root of problems} - -They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). - -% !split -\subsection{The derivative of the Logistic funtion} - -Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. - -In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. - -% !split -\subsection{Insights from the paper by Glorot and Bengio} - -One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). - -% !split -\subsection{The RELU function family} - -The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. - -In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. - -% !split -\subsection{ELU function} - -To solve this problem, nowadays practitioners use a variant of the -ReLU function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function - -\[ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -\] - -% !split -\subsection{Which activation function should we use?} - -In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than $\tanh$ which in turn performs better -than the logistic function. - -If runtime performance is an issue, then you may opt for the leaky -ReLU function over the ELU function If you don’t want to tweak yet -another hyperparameter, you may just use the default $\alpha$ of -$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and -computing power, you can use cross-validation or bootstrap to evaluate -other activation functions. - -% !split -\subsection{More on activation functions, output layers} - -In most cases you can use the ReLU activation function in the hidden -layers (or one of its variants). - -It is a bit faster to compute than other activation functions, and the -gradient descent optimization does in general not get stuck. - -\textbf{For the output layer:} - -\begin{itemize} -\item For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive). - -\item For regression tasks, you can simply use no activation function at all. -\end{itemize} - -\noindent -% !split -\subsection{Batch Normalization} - -Batch Normalization aims to address the vanishing/exploding gradients -problems, and more generally the problem that the distribution of each -layer’s inputs changes during training, as the parameters of the -previous layers change. - -The technique consists of adding an operation in the model just before -the activation function of each layer, simply zero-centering and -normalizing the inputs, then scaling and shifting the result using two -new parameters per layer (one for scaling, the other for shifting). In -other words, this operation lets the model learn the optimal scale and -mean of the inputs for each layer. In order to zero-center and -normalize the inputs, the algorithm needs to estimate the inputs’ mean -and standard deviation. It does so by evaluating the mean and standard -deviation of the inputs over the current mini-batch, from this the -name batch normalization. - -% !split -\subsection{Dropout} - -It is a fairly simple algorithm: at every training step, every neuron -(including the input neurons but excluding the output neurons) has a -probability $p$ of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active -during the next step. - -The hyperparameter $p$ is called the dropout rate, and it is typically -set to 50\%. After training, the neurons are not dropped anymore. It -is viewed as one of the most popular regularization techniques. - -% !split -\subsection{Gradient Clipping} - -A popular technique to lessen the exploding gradients problem is to -simply clip the gradients during backpropagation so that they never -exceed some threshold (this is mostly useful for recurrent neural -networks). - -This technique is called Gradient Clipping. - -In general however, Batch -Normalization is preferred. - -% !split -\subsection{A top-down perspective on Neural networks} - -The first thing we would like to do is divide the data into two or -three parts. A training set, a validation or dev (development) set, -and a test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: - -\begin{enumerate} -\item Estimate optimal error rate - -\item Minimize underfitting (bias) on training data set. - -\item Make sure you are not overfitting. -\end{enumerate} - -\noindent -% !split -\subsection{More top-down perspectives} - -If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. - -However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. - -% !split -\subsection{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). - -% !split -\subsection{Limitations of NNs} - -Here we list some of the important limitations of supervised neural network based models. - -\begin{itemize} -\item \textbf{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). - -\item \textbf{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. -\end{itemize} - -\noindent -% !split -\subsection{Homogeneous data} - -\begin{itemize} -\item \textbf{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. -\end{itemize} - -\noindent -% !split -\subsection{More limitations} - -\begin{itemize} -\item \textbf{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 \emph{wrong} model. The model might or might not be useful for understanding the underlying science. -\end{itemize} - -\noindent -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. - - -% ------------------- end of main content --------------- - -% #ifdef PREAMBLE -\end{document} -% #endif - diff --git a/doc/src/week41/week41.pdf b/doc/src/week41/week41.pdf deleted file mode 100644 index 59b557bf3..000000000 Binary files a/doc/src/week41/week41.pdf and /dev/null differ diff --git a/doc/src/week41/week41.tex b/doc/src/week41/week41.tex deleted file mode 100644 index 67914f75e..000000000 --- a/doc/src/week41/week41.tex +++ /dev/null @@ -1,2494 +0,0 @@ - -% LaTeX Beamer file automatically generated from DocOnce -% https://github.com/doconce/doconce - -%-------------------- begin beamer-specific preamble ---------------------- - -\documentclass{beamer} - -\usetheme{red_plain} -\usecolortheme{default} - -% turn off the almost invisible, yet disturbing, navigation symbols: -\setbeamertemplate{navigation symbols}{} - -% Examples on customization: -%\usecolortheme[named=RawSienna]{structure} -%\usetheme[height=7mm]{Rochester} -%\setbeamerfont{frametitle}{family=\rmfamily,shape=\itshape} -%\setbeamertemplate{items}[ball] -%\setbeamertemplate{blocks}[rounded][shadow=true] -%\useoutertheme{infolines} -% -%\usefonttheme{} -%\useinntertheme{} -% -%\setbeameroption{show notes} -%\setbeameroption{show notes on second screen=right} - -% fine for B/W printing: -%\usecolortheme{seahorse} - -\usepackage{pgf} -\usepackage{graphicx} -\usepackage{epsfig} -\usepackage{relsize} - -\usepackage{fancybox} % make sure fancybox is loaded before fancyvrb - -\usepackage{fancyvrb} -\usepackage{minted} % requires pygments and latex -shell-escape filename -%\usepackage{anslistings} -%\usepackage{listingsutf8} - -\usepackage{amsmath,amssymb,bm} -%\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\usepackage[utf8]{inputenc} -\usepackage{colortbl} -\usepackage[english]{babel} -\usepackage{tikz} -\usepackage{framed} -% Use some nice templates -\beamertemplatetransparentcovereddynamic - -% --- begin table of contents based on sections --- -% Delete this, if you do not want the table of contents to pop up at -% the beginning of each section: -% (Only section headings can enter the table of contents in Beamer -% slides generated from DocOnce source, while subsections are used -% for the title in ordinary slides.) -\AtBeginSection[] -{ - \begin{frame}[plain] - \frametitle{} - %\frametitle{Outline} - \tableofcontents[currentsection] - \end{frame} -} -% --- end table of contents based on sections --- - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: - -%\beamerdefaultoverlayspecification{<+->} - -\newcommand{\shortinlinecomment}[3]{\note{\textbf{#1}: #2}} -\newcommand{\longinlinecomment}[3]{\shortinlinecomment{#1}{#2}{#3}} - -\definecolor{linkcolor}{rgb}{0,0,0.4} -\hypersetup{ - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 - } -\setlength{\parskip}{0pt} % {1em} - -\newenvironment{doconceexercise}{}{} -\newcounter{doconceexercisecounter} -\newenvironment{doconce:movie}{}{} -\newcounter{doconce:movie:counter} - -\newcommand{\subex}[1]{\noindent\textbf{#1}} % for subexercises: a), b), etc - -\logo{{\tiny \copyright\ 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - -%-------------------- end beamer-specific preamble ---------------------- - -% Add user's preamble - - - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\title{Week 41 Neural networks and constructing a neural network code} - -% ----------------- author(s) ------------------------- - -\author{Morten Hjorth-Jensen\inst{1}} -\institute{Department of Physics, University of Oslo\inst{1}} -% ----------------- end author(s) ------------------------- - -\date{Week 41 -% -\ \\ -{\tiny \copyright\ 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license} -} - -\begin{frame}[plain,fragile] -\titlepage -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Material for the lecture on Monday October 7, 2024} - -\begin{enumerate} -\item Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model. - -\item Building our own Feed-forward Neural Network -% * \href{{https://youtu.be/5-RRTO9uDvI}}{Video of lecture notes} -% * \href{{https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOctober7.pdf}}{Whiteboard notes} -\end{enumerate} - -\noindent -\begin{block}{Readings and Videos: } -\begin{enumerate} -\item These lecture notes - -\item Rashcka et al chapter 11 - -\item For neural networks we recommend Goodfellow et al chapter 6. -\begin{enumerate} - - \item Neural Networks demystified at \href{{https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs}}{\nolinkurl{https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs}} - -\end{enumerate} - -\noindent -\item Building Neural Networks from scratch at \href{{https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex}}{\nolinkurl{https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex}} - -\item Video on Neural Networks at \href{{https://www.youtube.com/watch?v=CqOfi41LfDw}}{\nolinkurl{https://www.youtube.com/watch?v=CqOfi41LfDw}} - -\item Video on the back propagation algorithm at \href{{https://www.youtube.com/watch?v=Ilg3gGewQ5U}}{\nolinkurl{https://www.youtube.com/watch?v=Ilg3gGewQ5U}} -\end{enumerate} - -\noindent -We also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at \href{{http://neuralnetworksanddeeplearning.com/chap4.html}}{\nolinkurl{http://neuralnetworksanddeeplearning.com/chap4.html}}. -\end{block} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Material for the active learning sessions on Tuesday and Wednesday} - -\begin{itemize} -\item Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation - -\item One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code - -\item Discussion of project 2 - -\item Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent -\end{itemize} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Introduction to Neural networks} - -Artificial neural networks are computational systems that can learn to -perform tasks by considering examples, generally without being -programmed with any task-specific rules. It is supposed to mimic a -biological system, wherein neurons interact by sending signals in the -form of mathematical functions between layers. All layers can contain -an arbitrary number of neurons, and each connection is represented by -a weight variable. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Artificial neurons} - -The field of artificial neural networks has a long history of -development, and is closely connected with the advancement of computer -science and computers in general. A model of artificial neurons was -first developed by McCulloch and Pitts in 1943 to study signal -processing in the brain and has later been refined by others. The -general idea is to mimic neural networks in the human brain, which is -composed of billions of neurons that communicate with each other by -sending electrical signals. Each neuron accumulates its incoming -signals, which must exceed an activation threshold to yield an -output. If the threshold is not overcome, the neuron remains inactive, -i.e.~has zero output. - -This behaviour has inspired a simple mathematical model for an artificial neuron. - -\begin{equation} - y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u) - \label{artificialNeuron} -\end{equation} -Here, the output $y$ of the neuron is the value of its activation function, which have as input -a weighted sum of signals $x_i, \dots ,x_n$ received by $n$ other neurons. - -Conceptually, it is helpful to divide neural networks into four -categories: -\begin{enumerate} -\item general purpose neural networks for supervised learning, - -\item neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs), - -\item neural networks for sequential data such as Recurrent Neural Networks (RNNs), and - -\item neural networks for unsupervised learning such as Deep Boltzmann Machines. -\end{enumerate} - -\noindent -In natural science, DNNs and CNNs have already found numerous -applications. In statistical physics, they have been applied to detect -phase transitions in 2D Ising and Potts models, lattice gauge -theories, and different phases of polymers, or solving the -Navier-Stokes equation in weather forecasting. Deep learning has also -found interesting applications in quantum physics. Various quantum -phase transitions can be detected and studied using DNNs and CNNs, -topological phases, and even non-equilibrium many-body -localization. Representing quantum states as DNNs quantum state -tomography are among some of the impressive achievements to reveal the -potential of DNNs to facilitate the study of quantum systems. - -In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. - -The applications are not limited to the natural sciences. There is a -plethora of applications in essentially all disciplines, from the -humanities to life science and medicine. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Neural network types} - -An artificial neural network (ANN), is a computational model that -consists of layers of connected neurons, or nodes or units. We will -refer to these interchangeably as units or nodes, and sometimes as -neurons. - -It is supposed to mimic a biological nervous system by letting each -neuron interact with other neurons by sending signals in the form of -mathematical functions between layers. A wide variety of different -ANNs have been developed, but most of them consist of an input layer, -an output layer and eventual layers in-between, called \emph{hidden -layers}. All layers can contain an arbitrary number of nodes, and each -connection between two nodes is associated with a weight variable. - -Neural networks (also called neural nets) are neural-inspired -nonlinear models for supervised learning. As we will see, neural nets -can be viewed as natural, more powerful extensions of supervised -learning methods such as linear and logistic regression and soft-max -methods we discussed earlier. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Feed-forward neural networks} - -The feed-forward neural network (FFNN) was the first and simplest type -of ANNs that were devised. In this network, the information moves in -only one direction: forward through the layers. - -Nodes are represented by circles, while the arrows display the -connections between the nodes, including the direction of information -flow. Additionally, each arrow corresponds to a weight variable -(figure to come). We observe that each node in a layer is connected -to \emph{all} nodes in the subsequent layer, making this a so-called -\emph{fully-connected} FFNN. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Convolutional Neural Network} - -A different variant of FFNNs are \emph{convolutional neural networks} -(CNNs), which have a connectivity pattern inspired by the animal -visual cortex. Individual neurons in the visual cortex only respond to -stimuli from small sub-regions of the visual field, called a receptive -field. This makes the neurons well-suited to exploit the strong -spatially local correlation present in natural images. The response of -each neuron can be approximated mathematically as a convolution -operation. (figure to come) - -Convolutional neural networks emulate the behaviour of neurons in the -visual cortex by enforcing a \emph{local} connectivity pattern between -nodes of adjacent layers: Each node in a convolutional layer is -connected only to a subset of the nodes in the previous layer, in -contrast to the fully-connected FFNN. Often, CNNs consist of several -convolutional layers that learn local features of the input, with a -fully-connected layer at the end, which gathers all the local data and -produces the outputs. They have wide applications in image and video -recognition. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Recurrent neural networks} - -So far we have only mentioned ANNs where information flows in one -direction: forward. \emph{Recurrent neural networks} on the other hand, -have connections between nodes that form directed \emph{cycles}. This -creates a form of internal memory which are able to capture -information on what has been calculated before; the output is -dependent on the previous computations. Recurrent NNs make use of -sequential information by performing the same task for every element -in a sequence, where each element depends on previous elements. An -example of such information is sentences, making recurrent NNs -especially well-suited for handwriting and speech recognition. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Other types of networks} - -There are many other kinds of ANNs that have been developed. One type -that is specifically designed for interpolation in multidimensional -space is the radial basis function (RBF) network. RBFs are typically -made up of three layers: an input layer, a hidden layer with -non-linear radial symmetric activation functions and a linear output -layer (''linear'' here means that each node in the output layer has a -linear activation function). The layers are normally fully-connected -and there are no cycles, thus RBFs can be viewed as a type of -fully-connected FFNN. They are however usually treated as a separate -type of NN due the unusual activation functions. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Multilayer perceptrons} - -One uses often so-called fully-connected feed-forward neural networks -with three or more layers (an input layer, one or more hidden layers -and an output layer) consisting of neurons that have non-linear -activation functions. - -Such networks are often called \emph{multilayer perceptrons} (MLPs). -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Why multilayer perceptrons?} - -According to the \emph{Universal approximation theorem}, a feed-forward -neural network with just a single hidden layer containing a finite -number of neurons can approximate a continuous multidimensional -function to arbitrary accuracy, assuming the activation function for -the hidden layer is a \textbf{non-constant, bounded and -monotonically-increasing continuous function}. - -Note that the requirements on the activation function only applies to -the hidden layer, the output nodes are always assumed to be linear, so -as to not restrict the range of output values. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Illustration of a single perceptron model and a multi-perceptron model} - -\begin{figure}[!ht] % - \centerline{\includegraphics[width=0.8\linewidth]{figures/nns.png}} - \caption{ - In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer. - } -\end{figure} -%\clearpage % flush figures -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Examples of XOR, OR and AND gates} - -Let us first try to fit various gates using standard linear -regression. The gates we are thinking of are the classical XOR, OR and -AND gates, well-known elements in computer science. The tables here -show how we can set up the inputs $x_1$ and $x_2$ in order to yield a -specific target $y_i$. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=2mm]{python} -""" -Simple code that tests XOR, OR and AND gates with linear regression -""" - -import numpy as np -# Design matrix -X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64) -print(f"The X.TX matrix:{X.T @ X}") -Xinv = np.linalg.pinv(X.T @ X) -print(f"The invers of X.TX matrix:{Xinv}") - -# The XOR gate -yXOR = np.array( [ 0, 1 ,1, 0]) -ThetaXOR = Xinv @ X.T @ yXOR -print(f"The values of theta for the XOR gate:{ThetaXOR}") -print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}") - - -# The OR gate -yOR = np.array( [ 0, 1 ,1, 1]) -ThetaOR = Xinv @ X.T @ yOR -print(f"The values of theta for the OR gate:{ThetaOR}") -print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}") - - -# The OR gate -yAND = np.array( [ 0, 0 ,0, 1]) -ThetaAND = Xinv @ X.T @ yAND -print(f"The values of theta for the AND gate:{ThetaAND}") -print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}") - -\end{minted} - - -What is happening here? -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Does Logistic Regression do a better Job?} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=2mm]{python} -""" -Simple code that tests XOR and OR gates with linear regression -and logistic regression -""" - -import matplotlib.pyplot as plt -from sklearn.linear_model import LogisticRegression -import numpy as np - -# Design matrix -X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64) -print(f"The X.TX matrix:{X.T @ X}") -Xinv = np.linalg.pinv(X.T @ X) -print(f"The invers of X.TX matrix:{Xinv}") - -# The XOR gate -yXOR = np.array( [ 0, 1 ,1, 0]) -ThetaXOR = Xinv @ X.T @ yXOR -print(f"The values of theta for the XOR gate:{ThetaXOR}") -print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}") - - -# The OR gate -yOR = np.array( [ 0, 1 ,1, 1]) -ThetaOR = Xinv @ X.T @ yOR -print(f"The values of theta for the OR gate:{ThetaOR}") -print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}") - - -# The OR gate -yAND = np.array( [ 0, 0 ,0, 1]) -ThetaAND = Xinv @ X.T @ yAND -print(f"The values of theta for the AND gate:{ThetaAND}") -print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}") - -# Now we change to logistic regression - - -# Logistic Regression -logreg = LogisticRegression() -logreg.fit(X, yOR) -print("Test set accuracy with Logistic Regression for OR gate: {:.2f}".format(logreg.score(X,yOR))) - -logreg.fit(X, yXOR) -print("Test set accuracy with Logistic Regression for XOR gate: {:.2f}".format(logreg.score(X,yXOR))) - - -logreg.fit(X, yAND) -print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND))) - -\end{minted} - - -Not exactly impressive, but somewhat better. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Adding Neural Networks} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=2mm]{python} - -# and now neural networks with Scikit-Learn and the XOR - -from sklearn.neural_network import MLPClassifier -from sklearn.datasets import make_classification -X, yXOR = make_classification(n_samples=100, random_state=1) -FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR) -FFNN.predict_proba(X) -print(f"Test set accuracy with Feed Forward Neural Network for XOR gate:{FFNN.score(X, yXOR)}") - - -\end{minted} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Mathematics of deep learning} - -\begin{block}{Two recent books online } -\begin{enumerate} -\item \href{{https://arxiv.org/abs/2105.04026}}{The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen}, published as \href{{https://doi.org/10.1017/9781009025096.002}}{Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022} - -\item \href{{https://doi.org/10.48550/arXiv.2310.20360}}{Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger} -\end{enumerate} - -\noindent -\end{block} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Reminder on books with hands-on material and codes} - -\begin{block}{} -\begin{itemize} -\item \href{{https://sebastianraschka.com/blog/2022/ml-pytorch-book.html}}{Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch} -\end{itemize} - -\noindent -\end{block} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Reading recommendations} - -\begin{enumerate} -\item Rashkca et al., chapter 11, jupyter-notebook sent separately, from \href{{https://github.com/rasbt/machine-learning-book}}{GitHub} - -\item Goodfellow et al, chapter 6 and 7 contain most of the neural network background. -\end{enumerate} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Mathematics of deep learning and neural networks} - -Neural networks, in its so-called feed-forward form, where each -iterations contains a feed-forward stage and a back-propgagation -stage, consist of series of affine matrix-matrix and matrix-vector -multiplications. The unknown parameters (the so-called biases and -weights which deternine the architecture of a neural network), are -uptaded iteratively using the so-called back-propagation algorithm. -This algorithm corresponds to the so-called reverse mode of -automatic differentation. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Basics of an NN} - -A neural network consists of a series of hidden layers, in addition to -the input and output layers. Each layer $l$ has a set of parameters -$\bm{\Theta}^{(l)}=(\bm{W}^{(l)},\bm{b}^{(l)})$ which are related to the -parameters in other layers through a series of affine transformations, -for a standard NN these are matrix-matrix and matrix-vector -multiplications. For all layers we will simply use a collective variable $\bm{\Theta}$. - -It consist of two basic steps: -\begin{enumerate} -\item a feed forward stage which takes a given input and produces a final output which is compared with the target values through our cost/loss function. - -\item a back-propagation state where the unknown parameters $\bm{\Theta}$ are updated through the optimization of the their gradients. The expressions for the gradients are obtained via the chain rule, starting from the derivative of the cost/function. -\end{enumerate} - -\noindent -These two steps make up one iteration. This iterative process is continued till we reach an eventual stopping criterion. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Overarching view of a neural network} - -The architecture of a neural network defines our model. This model -aims at describing some function $f(\bm{x}$ which represents -some final result (outputs or tagrget values) given a specific inpput -$\bm{x}$. Note that here $\bm{y}$ and $\bm{x}$ are not limited to be -vectors. - -The architecture consists of -\begin{enumerate} -\item An input and an output layer where the input layer is defined by the inputs $\bm{x}$. The output layer produces the model ouput $\bm{\tilde{y}}$ which is compared with the target value $\bm{y}$ - -\item A given number of hidden layers and neurons/nodes/units for each layer (this may vary) - -\item A given activation function $\sigma(\bm{z})$ with arguments $\bm{z}$ to be defined below. The activation functions may differ from layer to layer. - -\item The last layer, normally called \textbf{output} layer has normally an activation function tailored to the specific problem - -\item Finally we define a so-called cost or loss function which is used to gauge the quality of our model. -\end{enumerate} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{The optimization problem} - -The cost function is a function of the unknown parameters -$\bm{\Theta}$ where the latter is a container for all possible -parameters needed to define a neural network - -If we are dealing with a regression task a typical cost/loss function -is the mean squared error -\[ -C(\bm{\Theta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\theta}\right)^T\left(\bm{y}-\bm{X}\bm{\theta}\right)\right\}. -\] -This function represents one of many possible ways to define -the so-called cost function. Note that here we have assumed a linear dependence in terms of the paramters $\bm{\Theta}$. This is in general not the case. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Parameters of neural networks} - -For neural networks the parameters -$\bm{\Theta}$ are given by the so-called weights and biases (to be -defined below). - -The weights are given by matrix elements $w_{ij}^{(l)}$ where the -superscript indicates the layer number. The biases are typically given -by vector elements representing each single node of a given layer, -that is $b_j^{(l)}$. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Other ingredients of a neural network} - -Having defined the architecture of a neural network, the optimization -of the cost function with respect to the parameters $\bm{\Theta}$, -involves the calculations of gradients and their optimization. The -gradients represent the derivatives of a multidimensional object and -are often approximated by various gradient methods, including -\begin{enumerate} -\item various quasi-Newton methods, - -\item plain gradient descent (GD) with a constant learning rate $\eta$, - -\item GD with momentum and other approximations to the learning rates such as -\begin{itemize} - - \item Adapative gradient (ADAgrad) - - \item Root mean-square propagation (RMSprop) - - \item Adaptive gradient with momentum (ADAM) and many other - -\end{itemize} - -\noindent -\item Stochastic gradient descent and various families of learning rate approximations -\end{enumerate} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Other parameters} - -In addition to the above, there are often additional hyperparamaters -which are included in the setup of a neural network. These will be -discussed below. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Universal approximation theorem} - -The universal approximation theorem plays a central role in deep -learning. \href{{https://link.springer.com/article/10.1007/BF02551274}}{Cybenko (1989)} showed -the following: - -\begin{block}{} -Let $\sigma$ be any continuous sigmoidal function such that -\[ -\sigma(z) = \left\{\begin{array}{cc} 1 & z\rightarrow \infty\\ 0 & z \rightarrow -\infty \end{array}\right. -\] -Given a continuous and deterministic function $F(\bm{x})$ on the unit -cube in $d$-dimensions $F\in [0,1]^d$, $x\in [0,1]^d$ and a parameter -$\epsilon >0$, there is a one-layer (hidden) neural network -$f(\bm{x};\bm{\Theta})$ with $\bm{\Theta}=(\bm{W},\bm{b})$ and $\bm{W}\in -\mathbb{R}^{m\times n}$ and $\bm{b}\in \mathbb{R}^{n}$, for which -\[ -\vert F(\bm{x})-f(\bm{x};\bm{\Theta})\vert < \epsilon \hspace{0.1cm} \forall \bm{x}\in[0,1]^d. -\] - -\end{block} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Some parallels from real analysis} - -For those of you familiar with for example the \href{{https://en.wikipedia.org/wiki/Stone%E2%80%93Weierstrass_theorem}}{Stone-Weierstrass -theorem} -for polynomial approximations or the convergence criterion for Fourier -series, there are similarities in the derivation of the proof for -neural networks. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{The approximation theorem in words} - -\textbf{Any continuous function $y=F(\bm{x})$ supported on the unit cube in -$d$-dimensions can be approximated by a one-layer sigmoidal network to -arbitrary accuracy.} - -\href{{https://www.sciencedirect.com/science/article/abs/pii/089360809190009T}}{Hornik (1991)} extended the theorem by letting any non-constant, bounded activation function to be included using that the expectation value -\[ -\mathbb{E}[\vert F(\bm{x})\vert^2] =\int_{\bm{x}\in D} \vert F(\bm{x})\vert^2p(\bm{x})d\bm{x} < \infty. -\] -Then we have -\[ -\mathbb{E}[\vert F(\bm{x})-f(\bm{x};\bm{\Theta})\vert^2] =\int_{\bm{x}\in D} \vert F(\bm{x})-f(\bm{x};\bm{\Theta})\vert^2p(\bm{x})d\bm{x} < \epsilon. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{More on the general approximation theorem} - -None of the proofs give any insight into the relation between the -number of of hidden layers and nodes and the approximation error -$\epsilon$, nor the magnitudes of $\bm{W}$ and $\bm{b}$. - -Neural networks (NNs) have what we may call a kind of universality no matter what function we want to compute. - -\begin{block}{} -It does not mean that an NN can be used to exactly compute any function. Rather, we get an approximation that is as good as we want. -\end{block} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Class of functions we can approximate} - -\begin{block}{} -The class of functions that can be approximated are the continuous ones. -If the function $F(\bm{x})$ is discontinuous, it won't in general be possible to approximate it. However, an NN may still give an approximation even if we fail in some points. -\end{block} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Setting up the equations for a neural network} - -The questions we want to ask are how do changes in the biases and the -weights in our network change the cost function and how can we use the -final output to modify the weights and biases? - -To derive these equations let us start with a plain regression problem -and define our cost function as - -\[ -{\cal C}(\bm{\Theta}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2, -\] - -where the $y_i$s are our $n$ targets (the values we want to -reproduce), while the outputs of the network after having propagated -all inputs $\bm{x}$ are given by $\bm{\tilde{y}}_i$. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Layout of a neural network with three hidden layers} - -\vspace{6mm} - -% inline figure -\centerline{\includegraphics[width=1.0\linewidth]{figures/nn1.pdf}} - -\vspace{6mm} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Definitions} - -With our definition of the targets $\bm{y}$, the outputs of the -network $\bm{\tilde{y}}$ and the inputs $\bm{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 -$\hat{a}^{l-1}$ from the previous layer as - -\[ -z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, -\] - -where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$ -represents the total number of nodes/neurons/units of layer $l-1$. The -figure in the whiteboard notes illustrates this equation. We can rewrite this in a more -compact form as the matrix-vector products we discussed earlier, - -\[ -\hat{z}^l = \left(\hat{W}^l\right)^T\hat{a}^{l-1}+\hat{b}^l. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Inputs to the activation function} - -With the activation values $\bm{z}^l$ we can in turn define the -output of layer $l$ as $\bm{a}^l = f(\bm{z}^l)$ where $f$ 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 $f$ for all layers -and their nodes. It means we have - -\[ -a_j^l = \sigma(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Derivatives and the chain rule} - -From the definition of the activation $z_j^l$ we have -\[ -\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, -\] -and -\[ -\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. -\] - -With our definition of the activation function we have that (note that this function depends only on $z_j^l$) -\[ -\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=\sigma(z_j^l)(1-\sigma(z_j^l)). -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Derivative of the cost function} - -With these definitions we can now compute the derivative of the cost function in terms of the weights. - -Let us specialize to the output layer $l=L$. Our cost function is -\[ -{\cal C}(\bm{\Theta}^L) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - y_i\right)^2, -\] -The derivative of this function with respect to the weights is - -\[ -\frac{\partial{\cal C}(\bm{\Theta}^L)}{\partial w_{jk}^L} = \left(a_j^L - y_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}}, -\] -The last partial derivative can easily be computed and reads (by applying the chain rule) -\[ -\frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Simpler examples first, and automatic differentiation} - -In order to understand the back propagation algorithm and its -derivation (an implementation of the chain rule), let us first digress -with some simple examples. These examples are also meant to motivate -the link with back propagation and \href{{https://en.wikipedia.org/wiki/Automatic_differentiation}}{automatic differentiation}. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Reminder on the chain rule and gradients} - -If we have a multivariate function $f(x,y)$ where $x=x(t)$ and $y=y(t)$ are functions of a variable $t$, we have that the gradient of $f$ with respect to $t$ (without the explicit unit vector components) -\[ -\frac{df}{dt} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial t} \end{bmatrix}=\frac{\partial f}{\partial x} \frac{\partial x}{\partial t} +\frac{\partial f}{\partial y} \frac{\partial y}{\partial t}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Multivariable functions} - -If we have a multivariate function $f(x,y)$ where $x=x(t,s)$ and $y=y(t,s)$ are functions of the variables $t$ and $s$, we have that the partial derivatives -\[ -\frac{\partial f}{\partial s}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial s}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial s}, -\] -and -\[ -\frac{\partial f}{\partial t}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial t}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial t}. -\] - -the gradient of $f$ with respect to $t$ and $s$ (without the explicit unit vector components) -\[ -\frac{df}{d(s,t)} = \begin{bmatrix}\frac{\partial f}{\partial x} & \frac{\partial f}{\partial y} \end{bmatrix} \begin{bmatrix}\frac{\partial x}{\partial s} &\frac{\partial x}{\partial t} \\ \frac{\partial y}{\partial s} & \frac{\partial y}{\partial t} \end{bmatrix}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Automatic differentiation through examples} - -A great introduction to automatic differentiation is given by Baydin et al., see \href{{https://arxiv.org/abs/1502.05767}}{\nolinkurl{https://arxiv.org/abs/1502.05767}}. - -Automatic differentiation is a represented by a repeated application -of the chain rule on well-known functions and allows for the -calculation of derivatives to numerical precision. It is not the same -as the calculation of symbolic derivatives via for example SymPy, nor -does it use approximative formulae based on Taylor-expansions of a -function around a given value. The latter are error prone due to -truncation errors and values of the step size $\Delta$. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Simple example} - -Our first example is rather simple, -\[ -f(x) =\exp{x^2}, -\] -with derivative -\[ -f'(x) =2x\exp{x^2}. -\] -We can use SymPy to extract the pertinent lines of Python code through the following simple example - - - - - - - - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=2mm]{python} -from __future__ import division -from sympy import * -x = symbols('x') -expr = exp(x*x) -simplify(expr) -derivative = diff(expr,x) -print(python(expr)) -print(python(derivative)) - -\end{minted} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Smarter way of evaluating the above function} - -If we study this function, we note that we can reduce the number of operations by introducing an intermediate variable -\[ -a = x^2, -\] -leading to -\[ -f(x) = f(a(x)) = b= \exp{a}. -\] - -We now assume that all operations can be counted in terms of equal -floating point operations. This means that in order to calculate -$f(x)$ we need first to square $x$ and then compute the exponential. We -have thus two floating point operations only. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Reducing the number of operations} - -With the introduction of a precalculated quantity $a$ and thereby $f(x)$ we have that the derivative can be written as - -\[ -f'(x) = 2xb, -\] - -which reduces the number of operations from four in the orginal -expression to two. This means that if we need to compute $f(x)$ and -its derivative (a common task in optimizations), we have reduced the -number of operations from six to four in total. - -\textbf{Note} that the usage of a symbolic software like SymPy does not -include such simplifications and the calculations of the function and -the derivatives yield in general more floating point operations. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Chain rule, forward and reverse modes} - -In the above example we have introduced the variables $a$ and $b$, and our function is -\[ -f(x) = f(a(x)) = b= \exp{a}, -\] -with $a=x^2$. We can decompose the derivative of $f$ with respect to $x$ as -\[ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}. -\] - -We note that since $b=f(x)$ that -\[ -\frac{df}{db}=1, -\] -leading to -\[ -\frac{df}{dx}=\frac{db}{da}\frac{da}{dx}=2x\exp{x^2}, -\] -as before. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Forward and reverse modes} - -We have that -\[ -\frac{df}{dx}=\frac{df}{db}\frac{db}{da}\frac{da}{dx}, -\] -which we can rewrite either as -\[ -\frac{df}{dx}=\left[\frac{df}{db}\frac{db}{da}\right]\frac{da}{dx}, -\] -or -\[ -\frac{df}{dx}=\frac{df}{db}\left[\frac{db}{da}\frac{da}{dx}\right]. -\] - -The first expression is called reverse mode (or back propagation) -since we start by evaluating the derivatives at the end point and then -propagate backwards. This is the standard way of evaluating -derivatives (gradients) when optimizing the parameters of a neural -network. In the context of deep learning this is computationally -more efficient since the output of a neural network consists of either -one or some few other output variables. - -The second equation defines the so-called \textbf{forward mode}. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{More complicated function} - -We increase our ambitions and introduce a slightly more complicated function -\[ -f(x) =\sqrt{x^2+exp{x^2}}, -\] -with derivative -\[ -f'(x) =\frac{x(1+\exp{x^2})}{\sqrt{x^2+exp{x^2}}}. -\] -The corresponding SymPy code reads - - - - - - - - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=2mm]{python} -from __future__ import division -from sympy import * -x = symbols('x') -expr = sqrt(x*x+exp(x*x)) -simplify(expr) -derivative = diff(expr,x) -print(python(expr)) -print(python(derivative)) - -\end{minted} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Counting the number of floating point operations} - -A simple count of operations shows that we need five operations for -the function itself and ten for the derivative. Fifteen operations in total if we wish to proceed with the above codes. - -Can we reduce this to -say half the number of operations? -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Defining intermediate operations} - -We can indeed reduce the number of operation to half of those listed in the brute force approach above. -We define the following quantities -\[ -a = x^2, -\] -and -\[ -b = \exp{x^2} = \exp{a}, -\] -and -\[ -c= a+b, -\] -and -\[ -d=f(x)=\sqrt{c}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{New expression for the derivative} - -With these definitions we obtain the following partial derivatives -\[ -\frac{\partial a}{\partial x} = 2x, -\] -and -\[ -\frac{\partial b}{\partial a} = \exp{a}, -\] -and -\[ -\frac{\partial c}{\partial a} = 1, -\] -and -\[ -\frac{\partial c}{\partial b} = 1, -\] -and -\[ -\frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -\] -and finally -\[ -\frac{\partial f}{\partial d} = 1. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Final derivatives} - -Our final derivatives are thus -\[ -\frac{\partial f}{\partial c} = \frac{\partial f}{\partial d} \frac{\partial d}{\partial c} = \frac{1}{2\sqrt{c}}, -\] -\[ -\frac{\partial f}{\partial b} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial b} = \frac{1}{2\sqrt{c}}, -\] -\[ -\frac{\partial f}{\partial a} = \frac{\partial f}{\partial c} \frac{\partial c}{\partial a}+ -\frac{\partial f}{\partial b} \frac{\partial b}{\partial a} = \frac{1+\exp{a}}{2\sqrt{c}}, -\] -and finally -\[ -\frac{\partial f}{\partial x} = \frac{\partial f}{\partial a} \frac{\partial a}{\partial x} = \frac{x(1+\exp{a})}{\sqrt{c}}, -\] -which is just -\[ -\frac{\partial f}{\partial x} = \frac{x(1+b)}{d}, -\] -and requires only three operations if we can reuse all intermediate variables. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{In general not this simple} - -In general, see the generalization below, unless we can obtain simple -analytical expressions which we can simplify further, the final -implementation of automatic differentiation involves repeated -calculations (and thereby operations) of derivatives of elementary -functions. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Automatic differentiation} - -We can make this example more formal. Automatic differentiation is a -formalization of the previous example (see graph). - -We define $\bm{x}\in x_1,\dots, x_l$ input variables to a given function $f(\bm{x})$ and $x_{l+1},\dots, x_L$ intermediate variables. - -In the above example we have only one input variable, $l=1$ and four intermediate variables, that is -\[ -\begin{bmatrix} x_1=x & x_2 = x^2=a & x_3 =\exp{a}= b & x_4=c=a+b & x_5 = \sqrt{c}=d \end{bmatrix}. -\] - -Furthemore, for $i=l+1, \dots, L$ (here $i=2,3,4,5$ and $f=x_L=d$), we -define the elementary functions $g_i(x_{Pa(x_i)})$ where $x_{Pa(x_i)}$ are the parent nodes of the variable $x_i$. - -In our case, we have for example for $x_3=g_3(x_{Pa(x_i)})=\exp{a}$, that $g_3=\exp{()}$ and $x_{Pa(x_3)}=a$. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Chain rule} - -We can now compute the gradients by back-propagating the derivatives using the chain rule. -We have defined -\[ -\frac{\partial f}{\partial x_L} = 1, -\] -which allows us to find the derivatives of the various variables $x_i$ as -\[ -\frac{\partial f}{\partial x_i} = \sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial x_j}{\partial x_i}=\sum_{x_j:x_i\in Pa(x_j)}\frac{\partial f}{\partial x_j} \frac{\partial g_j}{\partial x_i}. -\] - -Whenever we have a function which can be expressed as a computation -graph and the various functions can be expressed in terms of -elementary functions that are differentiable, then automatic -differentiation works. The functions may not need to be elementary -functions, they could also be computer programs, although not all -programs can be automatically differentiated. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{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 -\textbf{cost/loss} function, which we here for the sake of simplicity just -define as the squared error - -\[ -C(x;w_1,b_1)=\frac{1}{2}(a_1-y)^2. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Layout of a simple neural network with no hidden layer} - -\vspace{6mm} - -% inline figure -\centerline{\includegraphics[width=1.0\linewidth]{figures/simplenn1.png}} - -\vspace{6mm} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Optimizing the parameters} - -In setting up the feed forward and back propagation parts of the -algorithm, we need now the derivative of the various variables we want -to train. - -We need -\[ -\frac{\partial C}{\partial w_1} \hspace{0.1cm}\mathrm{and}\hspace{0.1cm}\frac{\partial C}{\partial b_1}. -\] - -Using the chain rule we find -\[ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_1-y)\sigma_1'x, -\] -and -\[ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_1-y)\sigma_1', -\] -which we later will just define as -\[ -\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}=\delta_1. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Adding a hidden layer} - -We change our simple model to (see graph) -a network with just one hidden layer but with scalar variables only. - -Our output variable changes to $a_2$ and $a_1$ is now the output from the hidden node and $a_0=x$. -We have then -\[ -z_1 = w_1a_0+b_1 \hspace{0.1cm} \wedge a_1 = \sigma_1(z_1), -\] -\[ -z_2 = w_2a_1+b_2 \hspace{0.1cm} \wedge a_2 = \sigma_2(z_2), -\] -and the cost function -\[ -C(x;\bm{\Theta})=\frac{1}{2}(a_2-y)^2, -\] -with $\bm{\Theta}=[w_1,w_2,b_1,b_2]$. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Layout of a simple neural network with one hidden layer} - -\vspace{6mm} - -% inline figure -\centerline{\includegraphics[width=1.0\linewidth]{figures/simplenn2.png}} - -\vspace{6mm} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{The derivatives} - -The derivatives are now, using the chain rule again - -\[ -\frac{\partial C}{\partial w_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial w_2}=(a_2-y)\sigma_2'a_1=\delta_2a_1, -\] -\[ -\frac{\partial C}{\partial b_2}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial b_2}=(a_2-y)\sigma_2'=\delta_2, -\] -\[ -\frac{\partial C}{\partial w_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial w_1}=(a_2-y)\sigma_2'a_1\sigma_1'a_0, -\] -\[ -\frac{\partial C}{\partial b_1}=\frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_2}\frac{\partial z_2}{\partial a_1}\frac{\partial a_1}{\partial z_1}\frac{\partial z_1}{\partial b_1}=(a_2-y)\sigma_2'\sigma_1'=\delta_1. -\] - -Can you generalize this to more than one hidden layer? -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Important observations} - -\begin{block}{} -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. -\end{block} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{The training} - -The training of the parameters is done through various gradient descent approximations with - -\[ -w_{i}\leftarrow w_{i}- \eta \delta_i a_{i-1}, -\] -and -\[ -b_i \leftarrow b_i-\eta \delta_i, -\] -with $\eta$ is the learning rate. - -One iteration consists of one feed forward step and one back-propagation step. Each back-propagation step does one update of the parameters $\bm{\Theta}$. - -For the first hidden layer $a_{i-1}=a_0=x$ for this simple model. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Code example} - -The code here implements the above model with one hidden layer and -scalar variables for the same function we studied in the previous -example. The code is however set up so that we can add multiple -inputs $x$ and target values $y$. Note also that we have the -possibility of defining a feature matrix $\bm{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. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=2mm]{python} -import numpy as np -# We use the Sigmoid function as activation function -def sigmoid(z): - return 1.0/(1.0+np.exp(-z)) - -def forwardpropagation(x): - # weighted sum of inputs to the hidden layer - z_1 = np.matmul(x, w_1) + b_1 - # activation in the hidden layer - a_1 = sigmoid(z_1) - # weighted sum of inputs to the output layer - z_2 = np.matmul(a_1, w_2) + b_2 - a_2 = z_2 - return a_1, a_2 - -def backpropagation(x, y): - a_1, a_2 = forwardpropagation(x) - # parameter delta for the output layer, note that a_2=z_2 and its derivative wrt z_2 is just 1 - delta_2 = a_2 - y - print(0.5*((a_2-y)**2)) - # delta for the hidden layer - delta_1 = np.matmul(delta_2, w_2.T) * a_1 * (1 - a_1) - # gradients for the output layer - output_weights_gradient = np.matmul(a_1.T, delta_2) - output_bias_gradient = np.sum(delta_2, axis=0) - # gradient for the hidden layer - hidden_weights_gradient = np.matmul(x.T, delta_1) - hidden_bias_gradient = np.sum(delta_1, axis=0) - return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient - - -# ensure the same random numbers appear every time -np.random.seed(0) -# Input variable -x = np.array([4.0],dtype=np.float64) -# Target values -y = 2*x+1.0 - -# Defining the neural network, only scalars here -n_inputs = x.shape -n_features = 1 -n_hidden_neurons = 1 -n_outputs = 1 - -# Initialize the network -# weights and bias in the hidden layer -w_1 = np.random.randn(n_features, n_hidden_neurons) -b_1 = np.zeros(n_hidden_neurons) + 0.01 - -# weights and bias in the output layer -w_2 = np.random.randn(n_hidden_neurons, n_outputs) -b_2 = np.zeros(n_outputs) + 0.01 - -eta = 0.1 -for i in range(50): - # calculate gradients - derivW2, derivB2, derivW1, derivB1 = backpropagation(x, y) - # update weights and biases - w_2 -= eta * derivW2 - b_2 -= eta * derivB2 - w_1 -= eta * derivW1 - b_1 -= eta * derivB1 - - - -\end{minted} - - -We see that after some few iterations (the results do depend on the learning rate however), we get an error which is rather small. -\end{frame} - -\begin{frame}[plain,fragile] -% No title on this slide - -% --- begin exercise --- -\begin{doconceexercise} -\refstepcounter{doconceexercisecounter} - -\exercisesection{Exercise \thedoconceexercisecounter: Including more data} - - -Try to increase the amount of input and -target/output data. Try also to perform calculations for more values -of the learning rates. Feel free to add either hyperparameters with an -$l_1$ norm or an $l_2$ norm and discuss your results. -Discuss your results as functions of the amount of training data and various learning rates. - -\textbf{Challenge:} Try to change the activation functions and replace the hard-coded analytical expressions with automatic derivation via either \textbf{autograd} or \textbf{JAX}. - -\end{doconceexercise} -% --- end exercise --- -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Simple neural network and the back propagation equations} - -Let us now try to increase our level of ambition and attempt at setting -up the equations for a neural network with two input nodes, one hidden -layer with two hidden nodes and one output layer with one output node/neuron only (see graph).. - -We need to define the following parameters and variables with the input layer (layer $(0)$) -where we label the nodes $x_0$ and $x_1$ -\[ -x_0 = a_0^{(0)} \wedge x_1 = a_1^{(0)}. -\] - -The hidden layer (layer $(1)$) has nodes which yield the outputs $a_0^{(1)}$ and $a_1^{(1)}$) with weight $\bm{w}$ and bias $\bm{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\}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Layout of a simple neural network with two input nodes, one hidden layer and one output node} - -\vspace{6mm} - -% inline figure -\centerline{\includegraphics[width=1.0\linewidth]{figures/simplenn3.png}} - -\vspace{6mm} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{The ouput layer} - -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 -\[ -w_{i}^{(2)}=\left\{w_{0}^{(2)},w_{1}^{(2)}\right\} \wedge b^{(2)}. -\] - -Our output is $\tilde{y}=a^{(2)}$ and we define a generic cost function $C(a^{(2)},y;\bm{\Theta})$ where $y$ is the target value (a scalar here). -The parameters we need to optimize are given by -\[ -\bm{\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\}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Compact expressions} - -We can define the inputs to the activation functions for the various layers in terms of various matrix-vector multiplications and vector additions. -The inputs to the first hidden layer are -\[ -\begin{bmatrix}z_0^{(1)} \\ z_1^{(1)} \end{bmatrix}=\begin{bmatrix}w_{00}^{(1)} & w_{01}^{(1)}\\ w_{10}^{(1)} &w_{11}^{(1)} \end{bmatrix}\begin{bmatrix}a_0^{(0)} \\ a_1^{(0)} \end{bmatrix}+\begin{bmatrix}b_0^{(1)} \\ b_1^{(1)} \end{bmatrix}, -\] -with outputs -\[ -\begin{bmatrix}a_0^{(1)} \\ a_1^{(1)} \end{bmatrix}=\begin{bmatrix}\sigma^{(1)}(z_0^{(1)}) \\ \sigma^{(1)}(z_1^{(1)}) \end{bmatrix}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Output layer} - -For the final output layer we have the inputs to the final activation function -\[ -z^{(2)} = w_{0}^{(2)}a_0^{(1)} +w_{1}^{(2)}a_1^{(1)}+b^{(2)}, -\] -resulting in the output -\[ -a^{(2)}=\sigma^{(2)}(z^{(2)}). -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Explicit derivatives} - -In total we have nine parameters which we need to train. Using the -chain rule (or just the back-propagation algorithm) we can find all -derivatives. Since we will use automatic differentiation in reverse -mode, we start with the derivatives of the cost function with respect -to the parameters of the output layer, namely - -\[ -\frac{\partial C}{\partial w_{i}^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial w_{i}^{(2)}}=\delta^{(2)}a_i^{(1)}, -\] -with -\[ -\delta^{(2)}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\] -and finally -\[ -\frac{\partial C}{\partial b^{(2)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}\frac{\partial z^{(2)}}{\partial b^{(2)}}=\delta^{(2)}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Derivatives of the hidden layer} - -Using the chain rule we have the following expressions for say one of the weight parameters (it is easy to generalize to the other weight parameters) -\[ -\frac{\partial C}{\partial w_{00}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}} -\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)}}, -\] -which, noting that -\[ -z^{(2)} =w_0^{(2)}a_0^{(1)}+w_1^{(2)}a_1^{(1)}+b^{(2)}, -\] -allows us to rewrite -\[ -\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)}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Final expression} - -Defining -\[ -\delta_0^{(1)}=w_0^{(2)}\frac{\partial a_0^{(1)}}{\partial z_0^{(1)}}\delta^{(2)}, -\] -we have -\[ -\frac{\partial C}{\partial w_{00}^{(1)}}=\delta_0^{(1)}a_0^{(1)}. -\] -Similarly, we obtain -\[ -\frac{\partial C}{\partial w_{01}^{(1)}}=\delta_0^{(1)}a_1^{(1)}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Completing the list} - -Similarly, we find -\[ -\frac{\partial C}{\partial w_{10}^{(1)}}=\delta_1^{(1)}a_0^{(1)}, -\] -and -\[ -\frac{\partial C}{\partial w_{11}^{(1)}}=\delta_1^{(1)}a_1^{(1)}, -\] -where we have defined -\[ -\delta_1^{(1)}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}\delta^{(2)}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Final expressions for the biases of the hidden layer} - -For the sake of completeness, we list the derivatives of the biases, which are -\[ -\frac{\partial C}{\partial b_{0}^{(1)}}=\delta_0^{(1)}, -\] -and -\[ -\frac{\partial C}{\partial b_{1}^{(1)}}=\delta_1^{(1)}. -\] -As we will see below, these expressions can be generalized in a more compact form. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Gradient expressions} - -For this specific model, with just one output node and two hidden -nodes, the gradient descent equations take the following form for output layer -\[ -w_{i}^{(2)}\leftarrow w_{i}^{(2)}- \eta \delta^{(2)} a_{i}^{(1)}, -\] -and -\[ -b^{(2)} \leftarrow b^{(2)}-\eta \delta^{(2)}, -\] -and -\[ -w_{ij}^{(1)}\leftarrow w_{ij}^{(1)}- \eta \delta_{i}^{(1)} a_{j}^{(0)}, -\] -and -\[ -b_{i}^{(1)} \leftarrow b_{i}^{(1)}-\eta \delta_{i}^{(1)}, -\] -where $\eta$ is the learning rate. -\end{frame} - -\begin{frame}[plain,fragile] -% No title on this slide - -% --- begin exercise --- -\begin{doconceexercise} -\refstepcounter{doconceexercisecounter} - -\exercisesection{Exercise \thedoconceexercisecounter: Extended program} - - -We extend our simple code to a function which depends on two variable $x_0$ and $x_1$, that is -\[ -y=f(x_0,x_1)=x_0^2+3x_0x_1+x_1^2+5. -\] -We feed our network with $n=100$ entries $x_0$ and $x_1$. We have thus two features represented by these variable and an input matrix/design matrix $\bm{X}\in \mathbf{R}^{n\times 2}$ -\[ -\bm{X}=\begin{bmatrix} x_{00} & x_{01} \\ x_{00} & x_{01} \\ x_{10} & x_{11} \\ x_{20} & x_{21} \\ \dots & \dots \\ \dots & \dots \\ x_{n-20} & x_{n-21} \\ x_{n-10} & x_{n-11} \end{bmatrix}. -\] -Write a code, based on the previous code examples, which takes as input these data and fit the above function. -You can extend your code to include automatic differentiation. - -With these examples, we are now ready to embark upon the writing of more a general code for neural networks. - -\end{doconceexercise} -% --- end exercise --- -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Getting serious, the back propagation equations for a neural network} - -Now it is time to move away from one node in each layer only. Our inputs are also represented either by several inputs. - -We have thus -\[ -\frac{\partial{\cal C}((\bm{\Theta}^L)}{\partial w_{jk}^L} = \left(a_j^L - y_j\right)a_j^L(1-a_j^L)a_k^{L-1}, -\] - -Defining -\[ -\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - y_j\right) = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\] -and using the Hadamard product of two vectors we can write this as -\[ -\bm{\delta}^L = \sigma'(\hat{z}^L)\circ\frac{\partial {\cal C}}{\partial (\bm{a}^L)}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Analyzing the last results} - -This is an important expression. The second term on the right handside -measures how fast the cost function is changing as a function of the $j$th -output activation. If, for example, the cost function doesn't depend -much on a particular output node $j$, then $\delta_j^L$ will be small, -which is what we would expect. The first term on the right, measures -how fast the activation function $f$ is changing at a given activation -value $z_j^L$. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{More considerations} - -Notice that everything in the above equations is easily computed. In -particular, we compute $z_j^L$ while computing the behaviour of the -network, and it is only a small additional overhead to compute -$\sigma'(z^L_j)$. The exact form of the derivative with respect to the -output depends on the form of the cost function. -However, provided the cost function is known there should be little -trouble in calculating - -\[ -\frac{\partial {\cal C}}{\partial (a_j^L)} -\] - -With the definition of $\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely -\[ -\frac{\partial{\cal C}}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Derivatives in terms of $z_j^L$} - -It is also easy to see that our previous equation can be written as - -\[ -\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, -\] -which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely -\[ -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, -\] -That is, the error $\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Bringing it together} - -We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are - -\begin{equation} -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}, -\end{equation} -and -\begin{equation} -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\end{equation} -and - -\begin{equation} -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}, -\end{equation} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Final back propagating equation} - -We have that (replacing $L$ with a general layer $l$) -\[ -\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. -\] -We want to express this in terms of the equations for layer $l+1$. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Using the chain rule and summing over all $k$ entries} - -We obtain -\[ -\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, -\] -and recalling that -\[ -z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1}, -\] -with $M_l$ being the number of nodes in layer $l$, we obtain -\[ -\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), -\] -This is our final equation. - -We are now ready to set up the algorithm for back propagation and learning the weights and biases. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Setting up the back propagation algorithm} - -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. - -\textbf{First}, we set up the input data $\hat{x}$ and the activations -$\hat{z}_1$ of the input layer and compute the activation function and -the pertinent outputs $\hat{a}^1$. - -\textbf{Secondly}, we perform then the feed forward till we reach the output -layer and compute all $\hat{z}_l$ of the input layer and compute the -activation function and the pertinent outputs $\hat{a}^l$ for -$l=1,2,3,\dots,L$. - -\textbf{Notation}: The first hidden layer has $l=1$ as label and the final output layer has $l=L$. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Setting up the back propagation algorithm, part 2} - -Thereafter we compute the ouput error $\hat{\delta}^L$ by computing all -\[ -\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. -\] - -Then we compute the back propagate error for each $l=L-1,L-2,\dots,1$ as -\[ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Setting up the Back propagation algorithm, part 3} - -Finally, we update the weights and the biases using gradient descent -for each $l=L-1,L-2,\dots,1$ and update the weights and biases -according to the rules - -\[ -w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, -\] - -\[ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -\] -with $\eta$ being the learning rate. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Updating the gradients} - -With the back propagate error for each $l=L-1,L-2,\dots,1$ as -\[ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}sigma'(z_j^l), -\] -we update the weights and the biases using gradient descent for each $l=L-1,L-2,\dots,1$ and update the weights and biases according to the rules -\[ -w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, -\] - -\[ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -\] -\end{frame} - -\begin{frame}[plain,fragile] -% No title on this slide - -\noindent\textbf{Activation functions.} -A property that characterizes a neural network, other than its -connectivity, is the choice of activation function(s). As described -in, the following restrictions are imposed on an activation function -for a FFNN to fulfill the universal approximation theorem - -\begin{itemize} - \item Non-constant - - \item Bounded - - \item Monotonically-increasing - - \item Continuous -\end{itemize} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -% No title on this slide - -\noindent\textbf{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 \emph{Sigmoid} - -\[ - f(x) = \frac{1}{1 + e^{-x}}, -\] -and the \emph{hyperbolic tangent} function -\[ - f(x) = \tanh(x) -\] -\end{frame} - -\begin{frame}[plain,fragile] -% No title on this slide - -\noindent\textbf{Relevance.} -The \emph{sigmoid} function are more biologically plausible because the -output of inactive neurons are zero. Such activation function are -called \emph{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 \emph{deep neural networks} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=2mm]{python} -"""The sigmoid function (or the logistic curve) is a -function that takes any real number, z, and outputs a number (0,1). -It is useful in neural networks for assigning weights on a relative scale. -The value z is the weighted sum of parameters involved in the learning algorithm.""" - -import numpy -import matplotlib.pyplot as plt -import math as mt - -z = numpy.arange(-5, 5, .1) -sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z))) -sigma = sigma_fn(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, sigma) -ax.set_ylim([-0.1, 1.1]) -ax.set_xlim([-5,5]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('sigmoid function') - -plt.show() - -"""Step Function""" -z = numpy.arange(-5, 5, .02) -step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0) -step = step_fn(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, step) -ax.set_ylim([-0.5, 1.5]) -ax.set_xlim([-5,5]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('step function') - -plt.show() - -"""Sine Function""" -z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1) -t = numpy.sin(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, t) -ax.set_ylim([-1.0, 1.0]) -ax.set_xlim([-2*mt.pi,2*mt.pi]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('sine function') - -plt.show() - -"""Plots a graph of the squashing function used by a rectified linear -unit""" -z = numpy.arange(-2, 2, .1) -zero = numpy.zeros(len(z)) -y = numpy.max([zero, z], axis=0) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, y) -ax.set_ylim([-2.0, 2.0]) -ax.set_xlim([-2.0, 2.0]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('Rectified linear unit') - -plt.show() - -\end{minted} -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Fine-tuning neural network hyperparameters} - -The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are -interconnected), but even in a simple FFNN you can change the number -of layers, the number of neurons per layer, the type of activation -function to use in each layer, the weight initialization logic, the -stochastic gradient optmized and much more. How do you know what -combination of hyperparameters is the best for your task? - -\begin{itemize} -\item You can use grid search with cross-validation to find the right hyperparameters. -\end{itemize} - -\noindent -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. - -\begin{itemize} -\item You can use randomized search. - -\item Or use tools like \href{{http://oscar.calldesk.ai/}}{Oscar}, which implements more complex algorithms to help you find a good set of hyperparameters quickly. -\end{itemize} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Hidden layers} - -For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set you ca 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. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Vanishing gradients} - -The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. - -Unfortunately for us, the gradients often get smaller and smaller as -the algorithm progresses down to the first hidden layers. As a result, -the GD update leaves the lower layer connection weights virtually -unchanged, and training never converges to a good solution. This is -known in the literature as \textbf{the vanishing gradients problem}. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Exploding gradients} - -In other cases, the opposite can happen, namely the the gradients can -grow bigger and bigger. The result is that many of the layers get -large updates of the weights the algorithm diverges. This is the -\textbf{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 -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Is the Logistic activation function (Sigmoid) our choice?} - -Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. - -A paper titled \href{{http://proceedings.mlr.press/v9/glorot10a.html}}{Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio} found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Logistic function as the root of problems} - -They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{The derivative of the Logistic funtion} - -Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. - -In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Insights from the paper by Glorot and Bengio} - -One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{The RELU function family} - -The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. - -In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{ELU function} - -To solve this problem, nowadays practitioners use a variant of the -ReLU function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function - -\[ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -\] -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Which activation function should we use?} - -In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than $\tanh$ which in turn performs better -than the logistic function. - -If runtime performance is an issue, then you may opt for the leaky -ReLU function over the ELU function If you don’t want to tweak yet -another hyperparameter, you may just use the default $\alpha$ of -$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and -computing power, you can use cross-validation or bootstrap to evaluate -other activation functions. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{More on activation functions, output layers} - -In most cases you can use the ReLU activation function in the hidden -layers (or one of its variants). - -It is a bit faster to compute than other activation functions, and the -gradient descent optimization does in general not get stuck. - -\textbf{For the output layer:} - -\begin{itemize} -\item For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive). - -\item For regression tasks, you can simply use no activation function at all. -\end{itemize} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Batch Normalization} - -Batch Normalization aims to address the vanishing/exploding gradients -problems, and more generally the problem that the distribution of each -layer’s inputs changes during training, as the parameters of the -previous layers change. - -The technique consists of adding an operation in the model just before -the activation function of each layer, simply zero-centering and -normalizing the inputs, then scaling and shifting the result using two -new parameters per layer (one for scaling, the other for shifting). In -other words, this operation lets the model learn the optimal scale and -mean of the inputs for each layer. In order to zero-center and -normalize the inputs, the algorithm needs to estimate the inputs’ mean -and standard deviation. It does so by evaluating the mean and standard -deviation of the inputs over the current mini-batch, from this the -name batch normalization. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Dropout} - -It is a fairly simple algorithm: at every training step, every neuron -(including the input neurons but excluding the output neurons) has a -probability $p$ of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active -during the next step. - -The hyperparameter $p$ is called the dropout rate, and it is typically -set to 50\%. After training, the neurons are not dropped anymore. It -is viewed as one of the most popular regularization techniques. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Gradient Clipping} - -A popular technique to lessen the exploding gradients problem is to -simply clip the gradients during backpropagation so that they never -exceed some threshold (this is mostly useful for recurrent neural -networks). - -This technique is called Gradient Clipping. - -In general however, Batch -Normalization is preferred. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{A top-down perspective on Neural networks} - -The first thing we would like to do is divide the data into two or -three parts. A training set, a validation or dev (development) set, -and a test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: - -\begin{enumerate} -\item Estimate optimal error rate - -\item Minimize underfitting (bias) on training data set. - -\item Make sure you are not overfitting. -\end{enumerate} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{More top-down perspectives} - -If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. - -However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{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). -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Limitations of NNs} - -Here we list some of the important limitations of supervised neural network based models. - -\begin{itemize} -\item \textbf{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). - -\item \textbf{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. -\end{itemize} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{Homogeneous data} - -\begin{itemize} -\item \textbf{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. -\end{itemize} - -\noindent -\end{frame} - -\begin{frame}[plain,fragile] -\frametitle{More limitations} - -\begin{itemize} -\item \textbf{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 \emph{wrong} model. The model might or might not be useful for understanding the underlying science. -\end{itemize} - -\noindent -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. -\end{frame} - -\end{document}