Files
FYS-STK4155/doc/LectureNotes/_build/html/week42.html
T
Morten Hjorth-Jensen ec650f521d update of p2
2025-10-14 07:01:07 +02:00

4059 lines
219 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en" data-content_root="./" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Week 42 Constructing a Neural Network code with examples &#8212; Applied Data Analysis and Machine Learning</title>
<script data-cfasync="false">
document.documentElement.dataset.mode = localStorage.getItem("mode") || "";
document.documentElement.dataset.theme = localStorage.getItem("theme") || "";
</script>
<!-- Loaded before other Sphinx assets -->
<link href="_static/styles/theme.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="_static/styles/bootstrap.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="_static/styles/pydata-sphinx-theme.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="_static/vendor/fontawesome/6.5.2/css/all.min.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.5.2/webfonts/fa-solid-900.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.5.2/webfonts/fa-brands-400.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.5.2/webfonts/fa-regular-400.woff2" />
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=fa44fd50" />
<link rel="stylesheet" type="text/css" href="_static/styles/sphinx-book-theme.css?v=eba8b062" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css?v=13237357" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.8ecb98da25f57f5357bf6f572d296f466b2cfe2517ffebfabe82451661e28f02.css?v=6644e6bb" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css?v=4fa983c6" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-design.min.css?v=95c83b7e" />
<!-- Pre-loaded scripts that we'll load fully later -->
<link rel="preload" as="script" href="_static/scripts/bootstrap.js?digest=dfe6caa3a7d634c4db9b" />
<link rel="preload" as="script" href="_static/scripts/pydata-sphinx-theme.js?digest=dfe6caa3a7d634c4db9b" />
<script src="_static/vendor/fontawesome/6.5.2/js/all.min.js?digest=dfe6caa3a7d634c4db9b"></script>
<script src="_static/documentation_options.js?v=9eb32ce0"></script>
<script src="_static/doctools.js?v=9a2dae69"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/clipboard.min.js?v=a7894cd8"></script>
<script src="_static/copybutton.js?v=f281be69"></script>
<script src="_static/scripts/sphinx-book-theme.js?v=887ef09a"></script>
<script>let toggleHintShow = 'Click to show';</script>
<script>let toggleHintHide = 'Click to hide';</script>
<script>let toggleOpenOnPrint = 'true';</script>
<script src="_static/togglebutton.js?v=4a39c7ea"></script>
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown';</script>
<script src="_static/design-tabs.js?v=f930bc37"></script>
<script>const THEBE_JS_URL = "https://unpkg.com/thebe@0.8.2/lib/index.js"; const thebe_selector = ".thebe,.cell"; const thebe_selector_input = "pre"; const thebe_selector_output = ".output, .cell_output"</script>
<script async="async" src="_static/sphinx-thebe.js?v=c100c467"></script>
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown';</script>
<script>const THEBE_JS_URL = "https://unpkg.com/thebe@0.8.2/lib/index.js"; const thebe_selector = ".thebe,.cell"; const thebe_selector_input = "pre"; const thebe_selector_output = ".output, .cell_output"</script>
<script>window.MathJax = {"options": {"processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>DOCUMENTATION_OPTIONS.pagename = 'week42';</script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Exercises week 42" href="exercisesweek42.html" />
<link rel="prev" title="Exercises week 41" href="exercisesweek41.html" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="docsearch:language" content="en"/>
</head>
<body data-bs-spy="scroll" data-bs-target=".bd-toc-nav" data-offset="180" data-bs-root-margin="0px 0px -60%" data-default-mode="">
<div id="pst-skip-link" class="skip-link d-print-none"><a href="#main-content">Skip to main content</a></div>
<div id="pst-scroll-pixel-helper"></div>
<button type="button" class="btn rounded-pill" id="pst-back-to-top">
<i class="fa-solid fa-arrow-up"></i>Back to top</button>
<input type="checkbox"
class="sidebar-toggle"
id="pst-primary-sidebar-checkbox"/>
<label class="overlay overlay-primary" for="pst-primary-sidebar-checkbox"></label>
<input type="checkbox"
class="sidebar-toggle"
id="pst-secondary-sidebar-checkbox"/>
<label class="overlay overlay-secondary" for="pst-secondary-sidebar-checkbox"></label>
<div class="search-button__wrapper">
<div class="search-button__overlay"></div>
<div class="search-button__search-container">
<form class="bd-search d-flex align-items-center"
action="search.html"
method="get">
<i class="fa-solid fa-magnifying-glass"></i>
<input type="search"
class="form-control"
name="q"
id="search-input"
placeholder="Search this book..."
aria-label="Search this book..."
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"/>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd>K</kbd></span>
</form></div>
</div>
<div class="pst-async-banner-revealer d-none">
<aside id="bd-header-version-warning" class="d-none d-print-none" aria-label="Version warning"></aside>
</div>
<header class="bd-header navbar navbar-expand-lg bd-navbar d-print-none">
</header>
<div class="bd-container">
<div class="bd-container__inner bd-page-width">
<div class="bd-sidebar-primary bd-sidebar">
<div class="sidebar-header-items sidebar-primary__section">
</div>
<div class="sidebar-primary-items__start sidebar-primary__section">
<div class="sidebar-primary-item">
<a class="navbar-brand logo" href="intro.html">
<img src="_static/logo.png" class="logo__image only-light" alt="Applied Data Analysis and Machine Learning - Home"/>
<script>document.write(`<img src="_static/logo.png" class="logo__image only-dark" alt="Applied Data Analysis and Machine Learning - Home"/>`);</script>
</a></div>
<div class="sidebar-primary-item">
<script>
document.write(`
<button class="btn search-button-field search-button__button" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass"></i>
<span class="search-button__default-text">Search</span>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd class="kbd-shortcut__modifier">K</kbd></span>
</button>
`);
</script></div>
<div class="sidebar-primary-item"><nav class="bd-links bd-docs-nav" aria-label="Main">
<div class="bd-toc-item navbar-nav active">
<ul class="nav bd-sidenav bd-sidenav__home-link">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">About the course</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="schedule.html">Course setting</a></li>
<li class="toctree-l1"><a class="reference internal" href="teachers.html">Teachers and Grading</a></li>
<li class="toctree-l1"><a class="reference internal" href="textbooks.html">Textbooks</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Review of Statistics with Resampling Techniques and Linear Algebra</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="statistics.html">1. Elements of Probability Theory and Statistical Data Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="linalg.html">2. Linear Algebra, Handling of Arrays and more Python Features</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">From Regression to Support Vector Machines</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter1.html">3. Linear Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter2.html">4. Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter3.html">5. Resampling Methods</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter4.html">6. Logistic Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapteroptimization.html">7. Optimization, the central part of any Machine Learning algortithm</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter5.html">8. Support Vector Machines, overarching aims</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Decision Trees, Ensemble Methods and Boosting</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter6.html">9. Decision trees, overarching aims</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter7.html">10. Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Dimensionality Reduction</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter8.html">11. Basic ideas of the Principal Component Analysis (PCA)</a></li>
<li class="toctree-l1"><a class="reference internal" href="clustering.html">12. Clustering and Unsupervised Learning</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Deep Learning Methods</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter9.html">13. Neural networks</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter10.html">14. Building a Feed Forward Neural Network</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter11.html">15. Solving Differential Equations with Deep Learning</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter12.html">16. Convolutional Neural Networks</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter13.html">17. Recurrent neural networks: Overarching view</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Weekly material, notes and exercises</span></p>
<ul class="current nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="exercisesweek34.html">Exercises week 34</a></li>
<li class="toctree-l1"><a class="reference internal" href="week34.html">Week 34: Introduction to the course, Logistics and Practicalities</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek35.html">Exercises week 35</a></li>
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 37</a></li>
<li class="toctree-l1"><a class="reference internal" href="week37.html">Week 37: Gradient descent methods</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek38.html">Exercises week 38</a></li>
<li class="toctree-l1"><a class="reference internal" href="week38.html">Week 38: Statistical analysis, bias-variance tradeoff and resampling methods</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek39.html">Exercises week 39</a></li>
<li class="toctree-l1"><a class="reference internal" href="week39.html">Week 39: Resampling methods and logistic regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="week40.html">Week 40: Gradient descent methods (continued) and start Neural networks</a></li>
<li class="toctree-l1"><a class="reference internal" href="week41.html">Week 41 Neural networks and constructing a neural network code</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek41.html">Exercises week 41</a></li>
<li class="toctree-l1 current active"><a class="current reference internal" href="#">Week 42 Constructing a Neural Network code with examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek42.html">Exercises week 42</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Projects</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="project1.html">Project 1 on Machine Learning, deadline October 6 (midnight), 2025</a></li>
<li class="toctree-l1"><a class="reference internal" href="project2.html">Project 2 on Machine Learning, deadline November 10 (Midnight)</a></li>
</ul>
</div>
</nav></div>
</div>
<div class="sidebar-primary-items__end sidebar-primary__section">
</div>
<div id="rtd-footer-container"></div>
</div>
<main id="main-content" class="bd-main" role="main">
<div class="sbt-scroll-pixel-helper"></div>
<div class="bd-content">
<div class="bd-article-container">
<div class="bd-header-article d-print-none">
<div class="header-article-items header-article__inner">
<div class="header-article-items__start">
<div class="header-article-item"><button class="sidebar-toggle primary-toggle btn btn-sm" title="Toggle primary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-bars"></span>
</button></div>
</div>
<div class="header-article-items__end">
<div class="header-article-item">
<div class="article-header-buttons">
<div class="dropdown dropdown-download-buttons">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Download this page">
<i class="fas fa-download"></i>
</button>
<ul class="dropdown-menu">
<li><a href="_sources/week42.ipynb" target="_blank"
class="btn btn-sm btn-download-source-button dropdown-item"
title="Download source file"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file"></i>
</span>
<span class="btn__text-container">.ipynb</span>
</a>
</li>
<li>
<button onclick="window.print()"
class="btn btn-sm btn-download-pdf-button dropdown-item"
title="Print to PDF"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file-pdf"></i>
</span>
<span class="btn__text-container">.pdf</span>
</button>
</li>
</ul>
</div>
<button onclick="toggleFullScreen()"
class="btn btn-sm btn-fullscreen-button"
title="Fullscreen mode"
data-bs-placement="bottom" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-expand"></i>
</span>
</button>
<script>
document.write(`
<button class="btn btn-sm nav-link pst-navbar-icon theme-switch-button" title="light/dark" aria-label="light/dark" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="theme-switch fa-solid fa-sun fa-lg" data-mode="light"></i>
<i class="theme-switch fa-solid fa-moon fa-lg" data-mode="dark"></i>
<i class="theme-switch fa-solid fa-circle-half-stroke fa-lg" data-mode="auto"></i>
</button>
`);
</script>
<script>
document.write(`
<button class="btn btn-sm pst-navbar-icon search-button search-button__button" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass fa-lg"></i>
</button>
`);
</script>
<button class="sidebar-toggle secondary-toggle btn btn-sm" title="Toggle secondary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-list"></span>
</button>
</div></div>
</div>
</div>
</div>
<div id="jb-print-docs-body" class="onlyprint">
<h1>Week 42 Constructing a Neural Network code with examples</h1>
<!-- Table of contents -->
<div id="print-main-content">
<div id="jb-print-toc">
<div>
<h2> Contents </h2>
</div>
<nav aria-label="Page">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#lecture-october-13-2025">Lecture October 13, 2025</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#readings-and-videos">Readings and videos</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#material-for-the-lab-sessions-on-tuesday-and-wednesday">Material for the lab sessions on Tuesday and Wednesday</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#lecture-material-writing-a-code-which-implements-a-feed-forward-neural-network">Lecture material: Writing a code which implements a feed-forward neural network</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#mathematics-of-deep-learning">Mathematics of deep learning</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#reminder-on-books-with-hands-on-material-and-codes">Reminder on books with hands-on material and codes</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#reading-recommendations">Reading recommendations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#reminder-from-last-week-first-network-example-simple-percepetron-with-one-input">Reminder from last week: First network example, simple percepetron with one input</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-a-simple-neural-network-with-no-hidden-layer">Layout of a simple neural network with no hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#optimizing-the-parameters">Optimizing the parameters</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#adding-a-hidden-layer">Adding a hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-a-simple-neural-network-with-one-hidden-layer">Layout of a simple neural network with one hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-derivatives">The derivatives</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#important-observations">Important observations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-training">The training</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#code-example">Code example</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#simple-neural-network-and-the-back-propagation-equations">Simple neural network and the back propagation equations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-a-simple-neural-network-with-two-input-nodes-one-hidden-layer-with-two-hidden-noeds-and-one-output-node">Layout of a simple neural network with two input nodes, one hidden layer with two hidden noeds and one output node</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-ouput-layer">The ouput layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#compact-expressions">Compact expressions</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#output-layer">Output layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#explicit-derivatives">Explicit derivatives</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#derivatives-of-the-hidden-layer">Derivatives of the hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#final-expression">Final expression</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#completing-the-list">Completing the list</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#final-expressions-for-the-biases-of-the-hidden-layer">Final expressions for the biases of the hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#gradient-expressions">Gradient expressions</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-equations-for-a-neural-network">Setting up the equations for a neural network</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-a-neural-network-with-three-hidden-layers-last-layer-l-l-4-first-layer-l-0">Layout of a neural network with three hidden layers (last layer = <span class="math notranslate nohighlight">\(l=L=4\)</span>, first layer <span class="math notranslate nohighlight">\(l=0\)</span>)</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#definitions">Definitions</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#inputs-to-the-activation-function">Inputs to the activation function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-input-to-first-hidden-layer-l-1-from-input-layer-l-0">Layout of input to first hidden layer <span class="math notranslate nohighlight">\(l=1\)</span> from input layer <span class="math notranslate nohighlight">\(l=0\)</span></a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#derivatives-and-the-chain-rule">Derivatives and the chain rule</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#derivative-of-the-cost-function">Derivative of the cost function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-back-propagation-equations-for-a-neural-network">The back propagation equations for a neural network</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#analyzing-the-last-results">Analyzing the last results</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-considerations">More considerations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#derivatives-in-terms-of-z-j-l">Derivatives in terms of <span class="math notranslate nohighlight">\(z_j^L\)</span></a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#bringing-it-together">Bringing it together</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#final-back-propagating-equation">Final back propagating equation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#using-the-chain-rule-and-summing-over-all-k-entries">Using the chain rule and summing over all <span class="math notranslate nohighlight">\(k\)</span> entries</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-back-propagation-algorithm-and-algorithm-for-a-feed-forward-nn-initalizations">Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-back-propagation-algorithm-part-1">Setting up the back propagation algorithm, part 1</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-back-propagation-algorithm-part-2">Setting up the back propagation algorithm, part 2</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-back-propagation-algorithm-part-3">Setting up the Back propagation algorithm, part 3</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#updating-the-gradients">Updating the gradients</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#activation-functions">Activation functions</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#activation-functions-logistic-and-hyperbolic-ones">Activation functions, Logistic and Hyperbolic ones</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#relevance">Relevance</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#vanishing-gradients">Vanishing gradients</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#exploding-gradients">Exploding gradients</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#is-the-logistic-activation-function-sigmoid-our-choice">Is the Logistic activation function (Sigmoid) our choice?</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#logistic-function-as-the-root-of-problems">Logistic function as the root of problems</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-derivative-of-the-logistic-funtion">The derivative of the Logistic funtion</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#insights-from-the-paper-by-glorot-and-bengio">Insights from the paper by Glorot and Bengio</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-relu-function-family">The RELU function family</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#elu-function">ELU function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#which-activation-function-should-we-use">Which activation function should we use?</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-on-activation-functions-output-layers">More on activation functions, output layers</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#fine-tuning-neural-network-hyperparameters">Fine-tuning neural network hyperparameters</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#hidden-layers">Hidden layers</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#batch-normalization">Batch Normalization</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#dropout">Dropout</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#gradient-clipping">Gradient Clipping</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#a-top-down-perspective-on-neural-networks">A top-down perspective on Neural networks</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-top-down-perspectives">More top-down perspectives</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#limitations-of-supervised-learning-with-deep-networks">Limitations of supervised learning with deep networks</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#limitations-of-nns">Limitations of NNs</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#homogeneous-data">Homogeneous data</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-limitations">More limitations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-a-multi-layer-perceptron-model-for-classification">Setting up a Multi-layer perceptron model for classification</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#defining-the-cost-function">Defining the cost function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#example-binary-classification-problem">Example: binary classification problem</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-softmax-function">The Softmax function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#developing-a-code-for-doing-neural-networks-with-back-propagation">Developing a code for doing neural networks with back propagation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#collect-and-pre-process-data">Collect and pre-process data</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#train-and-test-datasets">Train and test datasets</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#define-model-and-architecture">Define model and architecture</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layers">Layers</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#weights-and-biases">Weights and biases</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#feed-forward-pass">Feed-forward pass</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#matrix-multiplications">Matrix multiplications</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#choose-cost-function-and-optimizer">Choose cost function and optimizer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#optimizing-the-cost-function">Optimizing the cost function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#regularization">Regularization</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#matrix-multiplication">Matrix multiplication</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#improving-performance">Improving performance</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#full-object-oriented-implementation">Full object-oriented implementation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#evaluate-model-performance-on-test-data">Evaluate model performance on test data</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#adjust-hyperparameters">Adjust hyperparameters</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#visualization">Visualization</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#scikit-learn-implementation">scikit-learn implementation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#id1">Visualization</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#building-neural-networks-in-tensorflow-and-keras">Building neural networks in Tensorflow and Keras</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#tensorflow">Tensorflow</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#using-keras">Using Keras</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#id2">Collect and pre-process data</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#building-a-neural-network-code">Building a neural network code</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#learning-rate-methods">Learning rate methods</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#usage-of-the-above-learning-rate-schedulers">Usage of the above learning rate schedulers</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#cost-functions">Cost functions</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#id3">Activation functions</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#the-neural-network">The Neural Network</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#multiclass-classification">Multiclass classification</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#testing-the-xor-gate-and-other-gates">Testing the XOR gate and other gates</a></li>
</ul>
</nav>
</div>
</div>
</div>
<div id="searchbox"></div>
<article class="bd-article">
<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
doconce format html week42.do.txt --no_mako -->
<!-- dom:TITLE: Week 42 Constructing a Neural Network code with examples --><section class="tex2jax_ignore mathjax_ignore" id="week-42-constructing-a-neural-network-code-with-examples">
<h1>Week 42 Constructing a Neural Network code with examples<a class="headerlink" href="#week-42-constructing-a-neural-network-code-with-examples" title="Link to this heading">#</a></h1>
<p><strong>Morten Hjorth-Jensen</strong>, Department of Physics, University of Oslo, Norway</p>
<p>Date: <strong>October 13-17, 2025</strong></p>
<section id="lecture-october-13-2025">
<h2>Lecture October 13, 2025<a class="headerlink" href="#lecture-october-13-2025" title="Link to this heading">#</a></h2>
<ol class="arabic simple">
<li><p>Building our own Feed-forward Neural Network and discussion of project 2</p></li>
<li><p>Project 2 is available at <a class="github reference external" href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/2025/Project2/ipynb/Project2.ipynb">CompPhysics/MachineLearning</a></p></li>
</ol>
</section>
<section id="readings-and-videos">
<h2>Readings and videos<a class="headerlink" href="#readings-and-videos" title="Link to this heading">#</a></h2>
<ol class="arabic simple">
<li><p>These lecture notes</p></li>
<li><p>Video of lecture at <a class="reference external" href="https://youtu.be/eqyNrEYRXnY">https://youtu.be/eqyNrEYRXnY</a></p></li>
<li><p>Whiteboard notes at <a class="github reference external" href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2025/FYSSTKweek42.pdf">CompPhysics/MachineLearning</a></p></li>
<li><p>For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. For the optimization part, see chapter 8.</p></li>
<li><p>Neural Networks demystified at <a class="reference external" href="https://www.youtube.com/watch?v=bxe2T-V8XRs&amp;amp;list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&amp;amp;ab_channel=WelchLabs">https://www.youtube.com/watch?v=bxe2T-V8XRs&amp;list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&amp;ab_channel=WelchLabs</a></p></li>
<li><p>Building Neural Networks from scratch at <a class="reference external" href="https://www.youtube.com/watch?v=Wo5dMEP_BbI&amp;amp;list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&amp;amp;ab_channel=sentdex">https://www.youtube.com/watch?v=Wo5dMEP_BbI&amp;list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&amp;ab_channel=sentdex</a></p></li>
<li><p>Video on Neural Networks at <a class="reference external" href="https://www.youtube.com/watch?v=CqOfi41LfDw">https://www.youtube.com/watch?v=CqOfi41LfDw</a></p></li>
<li><p>Video on the back propagation algorithm at <a class="reference external" href="https://www.youtube.com/watch?v=Ilg3gGewQ5U">https://www.youtube.com/watch?v=Ilg3gGewQ5U</a></p></li>
</ol>
<p>I also recommend Michael Nielsens intuitive approach to the neural networks and the universal approximation theorem, see the slides at <a class="reference external" href="http://neuralnetworksanddeeplearning.com/chap4.html">http://neuralnetworksanddeeplearning.com/chap4.html</a>.</p>
</section>
<section id="material-for-the-lab-sessions-on-tuesday-and-wednesday">
<h2>Material for the lab sessions on Tuesday and Wednesday<a class="headerlink" href="#material-for-the-lab-sessions-on-tuesday-and-wednesday" title="Link to this heading">#</a></h2>
<ol class="arabic simple">
<li><p>Exercises on writing a code for neural networks, back propagation part, see exercises for week 42 at <a class="reference external" href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html">https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html</a></p></li>
<li><p>Discussion of project 2</p></li>
</ol>
</section>
<section id="lecture-material-writing-a-code-which-implements-a-feed-forward-neural-network">
<h2>Lecture material: Writing a code which implements a feed-forward neural network<a class="headerlink" href="#lecture-material-writing-a-code-which-implements-a-feed-forward-neural-network" title="Link to this heading">#</a></h2>
<p>Last week we discussed the basics of neural networks and deep learning
and the basics of automatic differentiation. We looked also at
examples on how compute the parameters of a simple network with scalar
inputs and ouputs and no or just one hidden layers.</p>
<p>We ended our discussions with the derivation of the equations for a
neural network with one hidden layers and two input variables and two
hidden nodes but only one output node. We did almost finish the derivation of the back propagation algorithm.</p>
</section>
<section id="mathematics-of-deep-learning">
<h2>Mathematics of deep learning<a class="headerlink" href="#mathematics-of-deep-learning" title="Link to this heading">#</a></h2>
<p><strong>Two recent books online.</strong></p>
<ol class="arabic simple">
<li><p><a class="reference external" href="https://arxiv.org/abs/2105.04026">The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen</a>, published as <a class="reference external" href="https://doi.org/10.1017/9781009025096.002">Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022</a></p></li>
<li><p><a class="reference external" 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</a></p></li>
</ol>
</section>
<section id="reminder-on-books-with-hands-on-material-and-codes">
<h2>Reminder on books with hands-on material and codes<a class="headerlink" href="#reminder-on-books-with-hands-on-material-and-codes" title="Link to this heading">#</a></h2>
<ul class="simple">
<li><p><a class="reference external" href="https://sebastianraschka.com/blog/2022/ml-pytorch-book.html">Sebastian Rashcka et al, Machine learning with Sickit-Learn and PyTorch</a></p></li>
</ul>
</section>
<section id="reading-recommendations">
<h2>Reading recommendations<a class="headerlink" href="#reading-recommendations" title="Link to this heading">#</a></h2>
<ol class="arabic simple">
<li><p>Rashkca et al., chapter 11, jupyter-notebook sent separately, from <a class="reference external" href="https://github.com/rasbt/machine-learning-book">GitHub</a></p></li>
<li><p>Goodfellow et al, chapter 6 and 7 contain most of the neural network background.</p></li>
</ol>
</section>
<section id="reminder-from-last-week-first-network-example-simple-percepetron-with-one-input">
<h2>Reminder from last week: First network example, simple percepetron with one input<a class="headerlink" href="#reminder-from-last-week-first-network-example-simple-percepetron-with-one-input" title="Link to this heading">#</a></h2>
<p>As yet another example we define now a simple perceptron model with
all quantities given by scalars. We consider only one input variable
<span class="math notranslate nohighlight">\(x\)</span> and one target value <span class="math notranslate nohighlight">\(y\)</span>. We define an activation function
<span class="math notranslate nohighlight">\(\sigma_1\)</span> which takes as input</p>
<div class="math notranslate nohighlight">
\[
z_1 = w_1x+b_1,
\]</div>
<p>where <span class="math notranslate nohighlight">\(w_1\)</span> is the weight and <span class="math notranslate nohighlight">\(b_1\)</span> is the bias. These are the
parameters we want to optimize. The output is <span class="math notranslate nohighlight">\(a_1=\sigma(z_1)\)</span> (see
graph from whiteboard notes). This output is then fed into the
<strong>cost/loss</strong> function, which we here for the sake of simplicity just
define as the squared error</p>
<div class="math notranslate nohighlight">
\[
C(x;w_1,b_1)=\frac{1}{2}(a_1-y)^2.
\]</div>
</section>
<section id="layout-of-a-simple-neural-network-with-no-hidden-layer">
<h2>Layout of a simple neural network with no hidden layer<a class="headerlink" href="#layout-of-a-simple-neural-network-with-no-hidden-layer" title="Link to this heading">#</a></h2>
<!-- dom:FIGURE: [figures/simplenn1.png, width=900 frac=1.0] -->
<!-- begin figure -->
<p><img src="figures/simplenn1.png" width="900"><p style="font-size: 0.9em"><i>Figure 1: </i></p></p>
<!-- end figure --></section>
<section id="optimizing-the-parameters">
<h2>Optimizing the parameters<a class="headerlink" href="#optimizing-the-parameters" title="Link to this heading">#</a></h2>
<p>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.</p>
<p>We need</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial C}{\partial w_1} \hspace{0.1cm}\mathrm{and}\hspace{0.1cm}\frac{\partial C}{\partial b_1}.
\]</div>
<p>Using the chain rule we find</p>
<div class="math notranslate nohighlight">
\[
\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,
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
\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',
\]</div>
<p>which we later will just define as</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1}=\delta_1.
\]</div>
</section>
<section id="adding-a-hidden-layer">
<h2>Adding a hidden layer<a class="headerlink" href="#adding-a-hidden-layer" title="Link to this heading">#</a></h2>
<p>We change our simple model to (see graph)
a network with just one hidden layer but with scalar variables only.</p>
<p>Our output variable changes to <span class="math notranslate nohighlight">\(a_2\)</span> and <span class="math notranslate nohighlight">\(a_1\)</span> is now the output from the hidden node and <span class="math notranslate nohighlight">\(a_0=x\)</span>.
We have then</p>
<div class="math notranslate nohighlight">
\[
z_1 = w_1a_0+b_1 \hspace{0.1cm} \wedge a_1 = \sigma_1(z_1),
\]</div>
<div class="math notranslate nohighlight">
\[
z_2 = w_2a_1+b_2 \hspace{0.1cm} \wedge a_2 = \sigma_2(z_2),
\]</div>
<p>and the cost function</p>
<div class="math notranslate nohighlight">
\[
C(x;\boldsymbol{\Theta})=\frac{1}{2}(a_2-y)^2,
\]</div>
<p>with <span class="math notranslate nohighlight">\(\boldsymbol{\Theta}=[w_1,w_2,b_1,b_2]\)</span>.</p>
</section>
<section id="layout-of-a-simple-neural-network-with-one-hidden-layer">
<h2>Layout of a simple neural network with one hidden layer<a class="headerlink" href="#layout-of-a-simple-neural-network-with-one-hidden-layer" title="Link to this heading">#</a></h2>
<!-- dom:FIGURE: [figures/simplenn2.png, width=900 frac=1.0] -->
<!-- begin figure -->
<p><img src="figures/simplenn2.png" width="900"><p style="font-size: 0.9em"><i>Figure 1: </i></p></p>
<!-- end figure --></section>
<section id="the-derivatives">
<h2>The derivatives<a class="headerlink" href="#the-derivatives" title="Link to this heading">#</a></h2>
<p>The derivatives are now, using the chain rule again</p>
<div class="math notranslate nohighlight">
\[
\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,
\]</div>
<div class="math notranslate nohighlight">
\[
\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,
\]</div>
<div class="math notranslate nohighlight">
\[
\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,
\]</div>
<div class="math notranslate nohighlight">
\[
\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.
\]</div>
<p>Can you generalize this to more than one hidden layer?</p>
</section>
<section id="important-observations">
<h2>Important observations<a class="headerlink" href="#important-observations" title="Link to this heading">#</a></h2>
<p>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 <span class="math notranslate nohighlight">\(w_i\)</span> and <span class="math notranslate nohighlight">\(b_i\)</span> may simply go to infinity. This
is referenced as the exploding gradient problem.</p>
</section>
<section id="the-training">
<h2>The training<a class="headerlink" href="#the-training" title="Link to this heading">#</a></h2>
<p>The training of the parameters is done through various gradient descent approximations with</p>
<div class="math notranslate nohighlight">
\[
w_{i}\leftarrow w_{i}- \eta \delta_i a_{i-1},
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
b_i \leftarrow b_i-\eta \delta_i,
\]</div>
<p>with <span class="math notranslate nohighlight">\(\eta\)</span> is the learning rate.</p>
<p>One iteration consists of one feed forward step and one back-propagation step. Each back-propagation step does one update of the parameters <span class="math notranslate nohighlight">\(\boldsymbol{\Theta}\)</span>.</p>
<p>For the first hidden layer <span class="math notranslate nohighlight">\(a_{i-1}=a_0=x\)</span> for this simple model.</p>
</section>
<section id="code-example">
<h2>Code example<a class="headerlink" href="#code-example" title="Link to this heading">#</a></h2>
<p>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 <span class="math notranslate nohighlight">\(x\)</span> and target values <span class="math notranslate nohighlight">\(y\)</span>. Note also that we have the
possibility of defining a feature matrix <span class="math notranslate nohighlight">\(\boldsymbol{X}\)</span> 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.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>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
</pre></div>
</div>
</div>
</div>
<p>We see that after some few iterations (the results do depend on the learning rate however), we get an error which is rather small.</p>
</section>
<section id="simple-neural-network-and-the-back-propagation-equations">
<h2>Simple neural network and the back propagation equations<a class="headerlink" href="#simple-neural-network-and-the-back-propagation-equations" title="Link to this heading">#</a></h2>
<p>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)..</p>
<p>We need to define the following parameters and variables with the input layer (layer <span class="math notranslate nohighlight">\((0)\)</span>)
where we label the nodes <span class="math notranslate nohighlight">\(x_1\)</span> and <span class="math notranslate nohighlight">\(x_2\)</span></p>
<div class="math notranslate nohighlight">
\[
x_1 = a_1^{(0)} \wedge x_2 = a_2^{(0)}.
\]</div>
<p>The hidden layer (layer <span class="math notranslate nohighlight">\((1)\)</span>) has nodes which yield the outputs <span class="math notranslate nohighlight">\(a_1^{(1)}\)</span> and <span class="math notranslate nohighlight">\(a_2^{(1)}\)</span>) with weight <span class="math notranslate nohighlight">\(\boldsymbol{w}\)</span> and bias <span class="math notranslate nohighlight">\(\boldsymbol{b}\)</span> parameters</p>
<div class="math notranslate nohighlight">
\[
w_{ij}^{(1)}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)}\right\} \wedge b^{(1)}=\left\{b_1^{(1)},b_2^{(1)}\right\}.
\]</div>
</section>
<section id="layout-of-a-simple-neural-network-with-two-input-nodes-one-hidden-layer-with-two-hidden-noeds-and-one-output-node">
<h2>Layout of a simple neural network with two input nodes, one hidden layer with two hidden noeds and one output node<a class="headerlink" href="#layout-of-a-simple-neural-network-with-two-input-nodes-one-hidden-layer-with-two-hidden-noeds-and-one-output-node" title="Link to this heading">#</a></h2>
<!-- dom:FIGURE: [figures/simplenn3.png, width=900 frac=1.0] -->
<!-- begin figure -->
<p><img src="figures/simplenn3.png" width="900"><p style="font-size: 0.9em"><i>Figure 1: </i></p></p>
<!-- end figure --></section>
<section id="the-ouput-layer">
<h2>The ouput layer<a class="headerlink" href="#the-ouput-layer" title="Link to this heading">#</a></h2>
<p>We have the ouput layer given by layer label <span class="math notranslate nohighlight">\((2)\)</span> with output <span class="math notranslate nohighlight">\(a^{(2)}\)</span> and weights and biases to be determined given by the variables</p>
<div class="math notranslate nohighlight">
\[
w_{i}^{(2)}=\left\{w_{1}^{(2)},w_{2}^{(2)}\right\} \wedge b^{(2)}.
\]</div>
<p>Our output is <span class="math notranslate nohighlight">\(\tilde{y}=a^{(2)}\)</span> and we define a generic cost function <span class="math notranslate nohighlight">\(C(a^{(2)},y;\boldsymbol{\Theta})\)</span> where <span class="math notranslate nohighlight">\(y\)</span> is the target value (a scalar here).
The parameters we need to optimize are given by</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{\Theta}=\left\{w_{11}^{(1)},w_{12}^{(1)},w_{21}^{(1)},w_{22}^{(1)},w_{1}^{(2)},w_{2}^{(2)},b_1^{(1)},b_2^{(1)},b^{(2)}\right\}.
\]</div>
</section>
<section id="compact-expressions">
<h2>Compact expressions<a class="headerlink" href="#compact-expressions" title="Link to this heading">#</a></h2>
<p>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</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{bmatrix}z_1^{(1)} \\ z_2^{(1)} \end{bmatrix}=\left(\begin{bmatrix}w_{11}^{(1)} &amp; w_{12}^{(1)}\\ w_{21}^{(1)} &amp;w_{22}^{(1)} \end{bmatrix}\right)^{T}\begin{bmatrix}a_1^{(0)} \\ a_2^{(0)} \end{bmatrix}+\begin{bmatrix}b_1^{(1)} \\ b_2^{(1)} \end{bmatrix},
\end{split}\]</div>
<p>with outputs</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{bmatrix}a_1^{(1)} \\ a_2^{(1)} \end{bmatrix}=\begin{bmatrix}\sigma^{(1)}(z_1^{(1)}) \\ \sigma^{(1)}(z_2^{(1)}) \end{bmatrix}.
\end{split}\]</div>
</section>
<section id="output-layer">
<h2>Output layer<a class="headerlink" href="#output-layer" title="Link to this heading">#</a></h2>
<p>For the final output layer we have the inputs to the final activation function</p>
<div class="math notranslate nohighlight">
\[
z^{(2)} = w_{1}^{(2)}a_1^{(1)} +w_{2}^{(2)}a_2^{(1)}+b^{(2)},
\]</div>
<p>resulting in the output</p>
<div class="math notranslate nohighlight">
\[
a^{(2)}=\sigma^{(2)}(z^{(2)}).
\]</div>
</section>
<section id="explicit-derivatives">
<h2>Explicit derivatives<a class="headerlink" href="#explicit-derivatives" title="Link to this heading">#</a></h2>
<p>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</p>
<div class="math notranslate nohighlight">
\[
\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)},
\]</div>
<p>with</p>
<div class="math notranslate nohighlight">
\[
\delta^{(2)}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}
\]</div>
<p>and finally</p>
<div class="math notranslate nohighlight">
\[
\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)}.
\]</div>
</section>
<section id="derivatives-of-the-hidden-layer">
<h2>Derivatives of the hidden layer<a class="headerlink" href="#derivatives-of-the-hidden-layer" title="Link to this heading">#</a></h2>
<p>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)</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial C}{\partial w_{11}^{(1)}}=\frac{\partial C}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial z^{(2)}}
\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}= \delta^{(2)}\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}},
\]</div>
<p>which, noting that</p>
<div class="math notranslate nohighlight">
\[
z^{(2)} =w_1^{(2)}a_1^{(1)}+w_2^{(2)}a_2^{(1)}+b^{(2)},
\]</div>
<p>allows us to rewrite</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial z^{(2)}}{\partial z_1^{(1)}}\frac{\partial z_1^{(1)}}{\partial w_{11}^{(1)}}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}a_1^{(1)}.
\]</div>
</section>
<section id="final-expression">
<h2>Final expression<a class="headerlink" href="#final-expression" title="Link to this heading">#</a></h2>
<p>Defining</p>
<div class="math notranslate nohighlight">
\[
\delta_1^{(1)}=w_1^{(2)}\frac{\partial a_1^{(1)}}{\partial z_1^{(1)}}\delta^{(2)},
\]</div>
<p>we have</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial C}{\partial w_{11}^{(1)}}=\delta_1^{(1)}a_1^{(1)}.
\]</div>
<p>Similarly, we obtain</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial C}{\partial w_{12}^{(1)}}=\delta_1^{(1)}a_2^{(1)}.
\]</div>
</section>
<section id="completing-the-list">
<h2>Completing the list<a class="headerlink" href="#completing-the-list" title="Link to this heading">#</a></h2>
<p>Similarly, we find</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial C}{\partial w_{21}^{(1)}}=\delta_2^{(1)}a_1^{(1)},
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial C}{\partial w_{22}^{(1)}}=\delta_2^{(1)}a_2^{(1)},
\]</div>
<p>where we have defined</p>
<div class="math notranslate nohighlight">
\[
\delta_2^{(1)}=w_2^{(2)}\frac{\partial a_2^{(1)}}{\partial z_2^{(1)}}\delta^{(2)}.
\]</div>
</section>
<section id="final-expressions-for-the-biases-of-the-hidden-layer">
<h2>Final expressions for the biases of the hidden layer<a class="headerlink" href="#final-expressions-for-the-biases-of-the-hidden-layer" title="Link to this heading">#</a></h2>
<p>For the sake of completeness, we list the derivatives of the biases, which are</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial C}{\partial b_{1}^{(1)}}=\delta_1^{(1)},
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial C}{\partial b_{2}^{(1)}}=\delta_2^{(1)}.
\]</div>
<p>As we will see below, these expressions can be generalized in a more compact form.</p>
</section>
<section id="gradient-expressions">
<h2>Gradient expressions<a class="headerlink" href="#gradient-expressions" title="Link to this heading">#</a></h2>
<p>For this specific model, with just one output node and two hidden
nodes, the gradient descent equations take the following form for output layer</p>
<div class="math notranslate nohighlight">
\[
w_{i}^{(2)}\leftarrow w_{i}^{(2)}- \eta \delta^{(2)} a_{i}^{(1)},
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
b^{(2)} \leftarrow b^{(2)}-\eta \delta^{(2)},
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
w_{ij}^{(1)}\leftarrow w_{ij}^{(1)}- \eta \delta_{i}^{(1)} a_{j}^{(0)},
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
b_{i}^{(1)} \leftarrow b_{i}^{(1)}-\eta \delta_{i}^{(1)},
\]</div>
<p>where <span class="math notranslate nohighlight">\(\eta\)</span> is the learning rate.</p>
</section>
<section id="setting-up-the-equations-for-a-neural-network">
<h2>Setting up the equations for a neural network<a class="headerlink" href="#setting-up-the-equations-for-a-neural-network" title="Link to this heading">#</a></h2>
<p>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?</p>
<p>To derive these equations let us start with a plain regression problem
and define our cost function as</p>
<div class="math notranslate nohighlight">
\[
{\cal C}(\boldsymbol{\Theta}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - \tilde{y}_i\right)^2,
\]</div>
<p>where the <span class="math notranslate nohighlight">\(y_i\)</span>s are our <span class="math notranslate nohighlight">\(n\)</span> targets (the values we want to
reproduce), while the outputs of the network after having propagated
all inputs <span class="math notranslate nohighlight">\(\boldsymbol{x}\)</span> are given by <span class="math notranslate nohighlight">\(\boldsymbol{\tilde{y}}_i\)</span>.</p>
</section>
<section id="layout-of-a-neural-network-with-three-hidden-layers-last-layer-l-l-4-first-layer-l-0">
<h2>Layout of a neural network with three hidden layers (last layer = <span class="math notranslate nohighlight">\(l=L=4\)</span>, first layer <span class="math notranslate nohighlight">\(l=0\)</span>)<a class="headerlink" href="#layout-of-a-neural-network-with-three-hidden-layers-last-layer-l-l-4-first-layer-l-0" title="Link to this heading">#</a></h2>
<!-- dom:FIGURE: [figures/nn2.png, width=900 frac=1.0] -->
<!-- begin figure -->
<p><img src="figures/nn2.png" width="900"><p style="font-size: 0.9em"><i>Figure 1: </i></p></p>
<!-- end figure --></section>
<section id="definitions">
<h2>Definitions<a class="headerlink" href="#definitions" title="Link to this heading">#</a></h2>
<p>With our definition of the targets <span class="math notranslate nohighlight">\(\boldsymbol{y}\)</span>, the outputs of the
network <span class="math notranslate nohighlight">\(\boldsymbol{\tilde{y}}\)</span> and the inputs <span class="math notranslate nohighlight">\(\boldsymbol{x}\)</span> we
define now the activation <span class="math notranslate nohighlight">\(z_j^l\)</span> of node/neuron/unit <span class="math notranslate nohighlight">\(j\)</span> of the
<span class="math notranslate nohighlight">\(l\)</span>-th layer as a function of the bias, the weights which add up from
the previous layer <span class="math notranslate nohighlight">\(l-1\)</span> and the forward passes/outputs
<span class="math notranslate nohighlight">\(\boldsymbol{a}^{l-1}\)</span> from the previous layer as</p>
<div class="math notranslate nohighlight">
\[
z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,
\]</div>
<p>where <span class="math notranslate nohighlight">\(b_k^l\)</span> are the biases from layer <span class="math notranslate nohighlight">\(l\)</span>. Here <span class="math notranslate nohighlight">\(M_{l-1}\)</span>
represents the total number of nodes/neurons/units of layer <span class="math notranslate nohighlight">\(l-1\)</span>. 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,</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{z}^l = \left(\boldsymbol{W}^l\right)^T\boldsymbol{a}^{l-1}+\boldsymbol{b}^l.
\]</div>
</section>
<section id="inputs-to-the-activation-function">
<h2>Inputs to the activation function<a class="headerlink" href="#inputs-to-the-activation-function" title="Link to this heading">#</a></h2>
<p>With the activation values <span class="math notranslate nohighlight">\(\boldsymbol{z}^l\)</span> we can in turn define the
output of layer <span class="math notranslate nohighlight">\(l\)</span> as <span class="math notranslate nohighlight">\(\boldsymbol{a}^l = \sigma(\boldsymbol{z}^l)\)</span> where <span class="math notranslate nohighlight">\(\sigma\)</span> 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 <span class="math notranslate nohighlight">\(\sigma\)</span> for all layers
and their nodes. It means we have</p>
<div class="math notranslate nohighlight">
\[
a_j^l = \sigma(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}.
\]</div>
</section>
<section id="layout-of-input-to-first-hidden-layer-l-1-from-input-layer-l-0">
<h2>Layout of input to first hidden layer <span class="math notranslate nohighlight">\(l=1\)</span> from input layer <span class="math notranslate nohighlight">\(l=0\)</span><a class="headerlink" href="#layout-of-input-to-first-hidden-layer-l-1-from-input-layer-l-0" title="Link to this heading">#</a></h2>
<!-- dom:FIGURE: [figures/structure.png, width=900 frac=1.0] -->
<!-- begin figure -->
<p><img src="figures/structure.png" width="900"><p style="font-size: 0.9em"><i>Figure 1: </i></p></p>
<!-- end figure --></section>
<section id="derivatives-and-the-chain-rule">
<h2>Derivatives and the chain rule<a class="headerlink" href="#derivatives-and-the-chain-rule" title="Link to this heading">#</a></h2>
<p>From the definition of the input variable to the activation function, that is <span class="math notranslate nohighlight">\(z_j^l\)</span> we have</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1},
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l.
\]</div>
<p>With our definition of the activation function we have that (note that this function depends only on <span class="math notranslate nohighlight">\(z_j^l\)</span>)</p>
<div class="math notranslate nohighlight">
\[
\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)).
\]</div>
</section>
<section id="derivative-of-the-cost-function">
<h2>Derivative of the cost function<a class="headerlink" href="#derivative-of-the-cost-function" title="Link to this heading">#</a></h2>
<p>With these definitions we can now compute the derivative of the cost function in terms of the weights.</p>
<p>Let us specialize to the output layer <span class="math notranslate nohighlight">\(l=L\)</span>. Our cost function is</p>
<div class="math notranslate nohighlight">
\[
{\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,
\]</div>
<p>The derivative of this function with respect to the weights is</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial{\cal C}(\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)\frac{\partial a_j^L}{\partial w_{ij}^{L}},
\]</div>
<p>The last partial derivative can easily be computed and reads (by applying the chain rule)</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial a_j^L}{\partial w_{ij}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{ij}^{L}}=a_j^L(1-a_j^L)a_i^{L-1}.
\]</div>
</section>
<section id="the-back-propagation-equations-for-a-neural-network">
<h2>The back propagation equations for a neural network<a class="headerlink" href="#the-back-propagation-equations-for-a-neural-network" title="Link to this heading">#</a></h2>
<p>We have thus</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial{\cal C}((\boldsymbol{\Theta}^L)}{\partial w_{ij}^L} = \left(a_j^L - y_j\right)a_j^L(1-a_j^L)a_i^{L-1},
\]</div>
<p>Defining</p>
<div class="math notranslate nohighlight">
\[
\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)},
\]</div>
<p>and using the Hadamard product of two vectors we can write this as</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{\delta}^L = \sigma'(\boldsymbol{z}^L)\circ\frac{\partial {\cal C}}{\partial (\boldsymbol{a}^L)}.
\]</div>
</section>
<section id="analyzing-the-last-results">
<h2>Analyzing the last results<a class="headerlink" href="#analyzing-the-last-results" title="Link to this heading">#</a></h2>
<p>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 <span class="math notranslate nohighlight">\(j\)</span>th
output activation. If, for example, the cost function doesnt depend
much on a particular output node <span class="math notranslate nohighlight">\(j\)</span>, then <span class="math notranslate nohighlight">\(\delta_j^L\)</span> will be small,
which is what we would expect. The first term on the right, measures
how fast the activation function <span class="math notranslate nohighlight">\(f\)</span> is changing at a given activation
value <span class="math notranslate nohighlight">\(z_j^L\)</span>.</p>
</section>
<section id="more-considerations">
<h2>More considerations<a class="headerlink" href="#more-considerations" title="Link to this heading">#</a></h2>
<p>Notice that everything in the above equations is easily computed. In
particular, we compute <span class="math notranslate nohighlight">\(z_j^L\)</span> while computing the behaviour of the
network, and it is only a small additional overhead to compute
<span class="math notranslate nohighlight">\(\sigma'(z^L_j)\)</span>. 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</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial {\cal C}}{\partial (a_j^L)}
\]</div>
<p>With the definition of <span class="math notranslate nohighlight">\(\delta_j^L\)</span> we have a more compact definition of the derivative of the cost function in terms of the weights, namely</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial{\cal C}}{\partial w_{ij}^L} = \delta_j^La_i^{L-1}.
\]</div>
</section>
<section id="derivatives-in-terms-of-z-j-l">
<h2>Derivatives in terms of <span class="math notranslate nohighlight">\(z_j^L\)</span><a class="headerlink" href="#derivatives-in-terms-of-z-j-l" title="Link to this heading">#</a></h2>
<p>It is also easy to see that our previous equation can be written as</p>
<div class="math notranslate nohighlight">
\[
\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},
\]</div>
<p>which can also be interpreted as the partial derivative of the cost function with respect to the biases <span class="math notranslate nohighlight">\(b_j^L\)</span>, namely</p>
<div class="math notranslate nohighlight">
\[
\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},
\]</div>
<p>That is, the error <span class="math notranslate nohighlight">\(\delta_j^L\)</span> is exactly equal to the rate of change of the cost function as a function of the bias.</p>
</section>
<section id="bringing-it-together">
<h2>Bringing it together<a class="headerlink" href="#bringing-it-together" title="Link to this heading">#</a></h2>
<p>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</p>
<!-- Equation labels as ordinary links -->
<div id="_auto1"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}
\frac{\partial{\cal C}(\boldsymbol{W^L})}{\partial w_{ij}^L} = \delta_j^La_i^{L-1},
\label{_auto1} \tag{1}
\end{equation}
\]</div>
<p>and</p>
<!-- Equation labels as ordinary links -->
<div id="_auto2"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}
\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)},
\label{_auto2} \tag{2}
\end{equation}
\]</div>
<p>and</p>
<!-- Equation labels as ordinary links -->
<div id="_auto3"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}
\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L},
\label{_auto3} \tag{3}
\end{equation}
\]</div>
</section>
<section id="final-back-propagating-equation">
<h2>Final back propagating equation<a class="headerlink" href="#final-back-propagating-equation" title="Link to this heading">#</a></h2>
<p>We have that (replacing <span class="math notranslate nohighlight">\(L\)</span> with a general layer <span class="math notranslate nohighlight">\(l\)</span>)</p>
<div class="math notranslate nohighlight">
\[
\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}.
\]</div>
<p>We want to express this in terms of the equations for layer <span class="math notranslate nohighlight">\(l+1\)</span>.</p>
</section>
<section id="using-the-chain-rule-and-summing-over-all-k-entries">
<h2>Using the chain rule and summing over all <span class="math notranslate nohighlight">\(k\)</span> entries<a class="headerlink" href="#using-the-chain-rule-and-summing-over-all-k-entries" title="Link to this heading">#</a></h2>
<p>We obtain</p>
<div class="math notranslate nohighlight">
\[
\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}},
\]</div>
<p>and recalling that</p>
<div class="math notranslate nohighlight">
\[
z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},
\]</div>
<p>with <span class="math notranslate nohighlight">\(M_l\)</span> being the number of nodes in layer <span class="math notranslate nohighlight">\(l\)</span>, we obtain</p>
<div class="math notranslate nohighlight">
\[
\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l),
\]</div>
<p>This is our final equation.</p>
<p>We are now ready to set up the algorithm for back propagation and learning the weights and biases.</p>
</section>
<section id="setting-up-the-back-propagation-algorithm-and-algorithm-for-a-feed-forward-nn-initalizations">
<h2>Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations<a class="headerlink" href="#setting-up-the-back-propagation-algorithm-and-algorithm-for-a-feed-forward-nn-initalizations" title="Link to this heading">#</a></h2>
<p><strong>The architecture (our model).</strong></p>
<ol class="arabic simple">
<li><p>Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)</p></li>
<li><p>Define the number of hidden layers and hidden nodes</p></li>
<li><p>Define activation functions for hidden layers and output layers</p></li>
<li><p>Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates</p></li>
<li><p>Define cost function and possible regularization terms with hyperparameters</p></li>
<li><p>Initialize weights and biases</p></li>
<li><p>Fix number of iterations for the feed forward part and back propagation part</p></li>
</ol>
</section>
<section id="setting-up-the-back-propagation-algorithm-part-1">
<h2>Setting up the back propagation algorithm, part 1<a class="headerlink" href="#setting-up-the-back-propagation-algorithm-part-1" title="Link to this heading">#</a></h2>
<p>The four equations provide us with a way of computing the gradients of the cost function. Let us write this out in the form of an algorithm.</p>
<p><strong>First</strong>, we set up the input data <span class="math notranslate nohighlight">\(\boldsymbol{x}\)</span> and the activations
<span class="math notranslate nohighlight">\(\boldsymbol{z}_1\)</span> of the input layer and compute the activation function and
the pertinent outputs <span class="math notranslate nohighlight">\(\boldsymbol{a}^1\)</span>.</p>
<p><strong>Secondly</strong>, we perform then the feed forward till we reach the output
layer and compute all <span class="math notranslate nohighlight">\(\boldsymbol{z}_l\)</span> of the input layer and compute the
activation function and the pertinent outputs <span class="math notranslate nohighlight">\(\boldsymbol{a}^l\)</span> for
<span class="math notranslate nohighlight">\(l=1,2,3,\dots,L\)</span>.</p>
<p><strong>Notation</strong>: The first hidden layer has <span class="math notranslate nohighlight">\(l=1\)</span> as label and the final output layer has <span class="math notranslate nohighlight">\(l=L\)</span>.</p>
</section>
<section id="setting-up-the-back-propagation-algorithm-part-2">
<h2>Setting up the back propagation algorithm, part 2<a class="headerlink" href="#setting-up-the-back-propagation-algorithm-part-2" title="Link to this heading">#</a></h2>
<p>Thereafter we compute the ouput error <span class="math notranslate nohighlight">\(\boldsymbol{\delta}^L\)</span> by computing all</p>
<div class="math notranslate nohighlight">
\[
\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}.
\]</div>
<p>Then we compute the back propagate error for each <span class="math notranslate nohighlight">\(l=L-1,L-2,\dots,1\)</span> as</p>
<div class="math notranslate nohighlight">
\[
\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l).
\]</div>
</section>
<section id="setting-up-the-back-propagation-algorithm-part-3">
<h2>Setting up the Back propagation algorithm, part 3<a class="headerlink" href="#setting-up-the-back-propagation-algorithm-part-3" title="Link to this heading">#</a></h2>
<p>Finally, we update the weights and the biases using gradient descent
for each <span class="math notranslate nohighlight">\(l=L-1,L-2,\dots,1\)</span> (the first hidden layer) and update the weights and biases
according to the rules</p>
<div class="math notranslate nohighlight">
\[
w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1},
\]</div>
<div class="math notranslate nohighlight">
\[
b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l,
\]</div>
<p>with <span class="math notranslate nohighlight">\(\eta\)</span> being the learning rate.</p>
</section>
<section id="updating-the-gradients">
<h2>Updating the gradients<a class="headerlink" href="#updating-the-gradients" title="Link to this heading">#</a></h2>
<p>With the back propagate error for each <span class="math notranslate nohighlight">\(l=L-1,L-2,\dots,1\)</span> as</p>
<div class="math notranslate nohighlight">
\[
\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l),
\]</div>
<p>we update the weights and the biases using gradient descent for each <span class="math notranslate nohighlight">\(l=L-1,L-2,\dots,1\)</span> and update the weights and biases according to the rules</p>
<div class="math notranslate nohighlight">
\[
w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1},
\]</div>
<div class="math notranslate nohighlight">
\[
b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l,
\]</div>
</section>
<section id="activation-functions">
<h2>Activation functions<a class="headerlink" href="#activation-functions" title="Link to this heading">#</a></h2>
<p>A property that characterizes a neural network, other than its
connectivity, is the choice of activation function(s). The following
restrictions are imposed on an activation function for an FFNN to
fulfill the universal approximation theorem</p>
<ul class="simple">
<li><p>Non-constant</p></li>
<li><p>Bounded</p></li>
<li><p>Monotonically-increasing</p></li>
<li><p>Continuous</p></li>
</ul>
<section id="activation-functions-logistic-and-hyperbolic-ones">
<h3>Activation functions, Logistic and Hyperbolic ones<a class="headerlink" href="#activation-functions-logistic-and-hyperbolic-ones" title="Link to this heading">#</a></h3>
<p>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.</p>
<p>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 <em>Sigmoid</em></p>
<div class="math notranslate nohighlight">
\[
\sigma(x) = \frac{1}{1 + e^{-x}},
\]</div>
<p>and the <em>hyperbolic tangent</em> function</p>
<div class="math notranslate nohighlight">
\[
\sigma(x) = \tanh(x)
\]</div>
</section>
</section>
<section id="relevance">
<h2>Relevance<a class="headerlink" href="#relevance" title="Link to this heading">#</a></h2>
<p>The <em>sigmoid</em> function are more biologically plausible because the
output of inactive neurons are zero. Such activation function are
called <em>one-sided</em>. However, it has been shown that the hyperbolic
tangent performs better than the sigmoid for training MLPs. has
become the most popular for <em>deep neural networks</em></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>%matplotlib inline
&quot;&quot;&quot;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.&quot;&quot;&quot;
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(&#39;z&#39;)
ax.set_title(&#39;sigmoid function&#39;)
plt.show()
&quot;&quot;&quot;Step Function&quot;&quot;&quot;
z = numpy.arange(-5, 5, .02)
step_fn = numpy.vectorize(lambda z: 1.0 if z &gt;= 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(&#39;z&#39;)
ax.set_title(&#39;step function&#39;)
plt.show()
&quot;&quot;&quot;Sine Function&quot;&quot;&quot;
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(&#39;z&#39;)
ax.set_title(&#39;sine function&#39;)
plt.show()
&quot;&quot;&quot;Plots a graph of the squashing function used by a rectified linear
unit&quot;&quot;&quot;
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(&#39;z&#39;)
ax.set_title(&#39;Rectified linear unit&#39;)
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="vanishing-gradients">
<h2>Vanishing gradients<a class="headerlink" href="#vanishing-gradients" title="Link to this heading">#</a></h2>
<p>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.</p>
<p>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 <strong>the vanishing gradients problem</strong>.</p>
</section>
<section id="exploding-gradients">
<h2>Exploding gradients<a class="headerlink" href="#exploding-gradients" title="Link to this heading">#</a></h2>
<p>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
<strong>exploding gradients problem</strong>, 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</p>
</section>
<section id="is-the-logistic-activation-function-sigmoid-our-choice">
<h2>Is the Logistic activation function (Sigmoid) our choice?<a class="headerlink" href="#is-the-logistic-activation-function-sigmoid-our-choice" title="Link to this heading">#</a></h2>
<p>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.</p>
<p>A paper titled <a class="reference external" href="http://proceedings.mlr.press/v9/glorot10a.html">Understanding the Difficulty of Training Deep
Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio</a> 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.</p>
</section>
<section id="logistic-function-as-the-root-of-problems">
<h2>Logistic function as the root of problems<a class="headerlink" href="#logistic-function-as-the-root-of-problems" title="Link to this heading">#</a></h2>
<p>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).</p>
</section>
<section id="the-derivative-of-the-logistic-funtion">
<h2>The derivative of the Logistic funtion<a class="headerlink" href="#the-derivative-of-the-logistic-funtion" title="Link to this heading">#</a></h2>
<p>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.</p>
<p>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 dont 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.</p>
</section>
<section id="insights-from-the-paper-by-glorot-and-bengio">
<h2>Insights from the paper by Glorot and Bengio<a class="headerlink" href="#insights-from-the-paper-by-glorot-and-bengio" title="Link to this heading">#</a></h2>
<p>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).</p>
</section>
<section id="the-relu-function-family">
<h2>The RELU function family<a class="headerlink" href="#the-relu-function-family" title="Link to this heading">#</a></h2>
<p>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.</p>
<p>In some cases, you may find that half of your networks neurons are
dead, especially if you used a large learning rate. During training,
if a neurons weights get updated such that the weighted sum of the
neurons 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.</p>
</section>
<section id="elu-function">
<h2>ELU function<a class="headerlink" href="#elu-function" title="Link to this heading">#</a></h2>
<p>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</p>
<div class="math notranslate nohighlight">
\[\begin{split}
ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) &amp; z &lt; 0,\\ z &amp; z \ge 0.\end{array}\right.
\end{split}\]</div>
</section>
<section id="which-activation-function-should-we-use">
<h2>Which activation function should we use?<a class="headerlink" href="#which-activation-function-should-we-use" title="Link to this heading">#</a></h2>
<p>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 <span class="math notranslate nohighlight">\(\tanh\)</span> which in turn performs better
than the logistic function.</p>
<p>If runtime performance is an issue, then you may opt for the leaky
ReLU function over the ELU function If you dont want to tweak yet
another hyperparameter, you may just use the default <span class="math notranslate nohighlight">\(\alpha\)</span> of
<span class="math notranslate nohighlight">\(0.01\)</span> for the leaky ReLU, and <span class="math notranslate nohighlight">\(1\)</span> for ELU. If you have spare time and
computing power, you can use cross-validation or bootstrap to evaluate
other activation functions.</p>
</section>
<section id="more-on-activation-functions-output-layers">
<h2>More on activation functions, output layers<a class="headerlink" href="#more-on-activation-functions-output-layers" title="Link to this heading">#</a></h2>
<p>In most cases you can use the ReLU activation function in the hidden
layers (or one of its variants).</p>
<p>It is a bit faster to compute than other activation functions, and the
gradient descent optimization does in general not get stuck.</p>
<p><strong>For the output layer:</strong></p>
<ul class="simple">
<li><p>For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).</p></li>
<li><p>For regression tasks, you can simply use no activation function at all.</p></li>
</ul>
</section>
<section id="fine-tuning-neural-network-hyperparameters">
<h2>Fine-tuning neural network hyperparameters<a class="headerlink" href="#fine-tuning-neural-network-hyperparameters" title="Link to this heading">#</a></h2>
<p>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?</p>
<ul class="simple">
<li><p>You can use grid search with cross-validation to find the right hyperparameters.</p></li>
</ul>
<p>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.</p>
<ul class="simple">
<li><p>You can use randomized search.</p></li>
<li><p>Or use tools like <a class="reference external" href="http://oscar.calldesk.ai/">Oscar</a>, which implements more complex algorithms to help you find a good set of hyperparameters quickly.</p></li>
</ul>
</section>
<section id="hidden-layers">
<h2>Hidden layers<a class="headerlink" href="#hidden-layers" title="Link to this heading">#</a></h2>
<p>For many problems you can start with just one or two hidden layers and
it will work just fine. For the MNIST data set discussed below you can easily get a
high accuracy using just one hidden layer with a few hundred neurons.
You can reach for this data set above 98% accuracy using two hidden
layers with the same total amount of neurons, in roughly the same
amount of training time.</p>
<p>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.</p>
</section>
<section id="batch-normalization">
<h2>Batch Normalization<a class="headerlink" href="#batch-normalization" title="Link to this heading">#</a></h2>
<p>Batch Normalization aims to address the vanishing/exploding gradients
problems, and more generally the problem that the distribution of each
layers inputs changes during training, as the parameters of the
previous layers change.</p>
<p>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.</p>
</section>
<section id="dropout">
<h2>Dropout<a class="headerlink" href="#dropout" title="Link to this heading">#</a></h2>
<p>It is a fairly simple algorithm: at every training step, every neuron
(including the input neurons but excluding the output neurons) has a
probability <span class="math notranslate nohighlight">\(p\)</span> of being temporarily dropped out, meaning it will be
entirely ignored during this training step, but it may be active
during the next step.</p>
<p>The hyperparameter <span class="math notranslate nohighlight">\(p\)</span> 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.</p>
</section>
<section id="gradient-clipping">
<h2>Gradient Clipping<a class="headerlink" href="#gradient-clipping" title="Link to this heading">#</a></h2>
<p>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).</p>
<p>This technique is called Gradient Clipping.</p>
<p>In general however, Batch
Normalization is preferred.</p>
</section>
<section id="a-top-down-perspective-on-neural-networks">
<h2>A top-down perspective on Neural networks<a class="headerlink" href="#a-top-down-perspective-on-neural-networks" title="Link to this heading">#</a></h2>
<p>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:</p>
<ol class="arabic simple">
<li><p>Estimate optimal error rate</p></li>
<li><p>Minimize underfitting (bias) on training data set.</p></li>
<li><p>Make sure you are not overfitting.</p></li>
</ol>
</section>
<section id="more-top-down-perspectives">
<h2>More top-down perspectives<a class="headerlink" href="#more-top-down-perspectives" title="Link to this heading">#</a></h2>
<p>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.</p>
<p>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.</p>
</section>
<section id="limitations-of-supervised-learning-with-deep-networks">
<h2>Limitations of supervised learning with deep networks<a class="headerlink" href="#limitations-of-supervised-learning-with-deep-networks" title="Link to this heading">#</a></h2>
<p>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).</p>
</section>
<section id="limitations-of-nns">
<h2>Limitations of NNs<a class="headerlink" href="#limitations-of-nns" title="Link to this heading">#</a></h2>
<p>Here we list some of the important limitations of supervised neural network based models.</p>
<ul class="simple">
<li><p><strong>Need labeled data</strong>. 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).</p></li>
<li><p><strong>Supervised neural networks are extremely data intensive.</strong> 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.</p></li>
</ul>
</section>
<section id="homogeneous-data">
<h2>Homogeneous data<a class="headerlink" href="#homogeneous-data" title="Link to this heading">#</a></h2>
<ul class="simple">
<li><p><strong>Homogeneous data.</strong> 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.</p></li>
</ul>
</section>
<section id="more-limitations">
<h2>More limitations<a class="headerlink" href="#more-limitations" title="Link to this heading">#</a></h2>
<ul class="simple">
<li><p><strong>Many problems are not about prediction.</strong> 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 <em>wrong</em> model. The model might or might not be useful for understanding the underlying science.</p></li>
</ul>
<p>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.</p>
</section>
<section id="setting-up-a-multi-layer-perceptron-model-for-classification">
<h2>Setting up a Multi-layer perceptron model for classification<a class="headerlink" href="#setting-up-a-multi-layer-perceptron-model-for-classification" title="Link to this heading">#</a></h2>
<p>We are now gong to develop an example based on the MNIST data
base. This is a classification problem and we need to use our
cross-entropy function we discussed in connection with logistic
regression. The cross-entropy defines our cost function for the
classificaton problems with neural networks.</p>
<p>In binary classification with two classes <span class="math notranslate nohighlight">\((0, 1)\)</span> we define the
logistic/sigmoid function as the probability that a particular input
is in class <span class="math notranslate nohighlight">\(0\)</span> or <span class="math notranslate nohighlight">\(1\)</span>. This is possible because the logistic
function takes any input from the real numbers and inputs a number
between 0 and 1, and can therefore be interpreted as a probability. It
also has other nice properties, such as a derivative that is simple to
calculate.</p>
<p>For an input <span class="math notranslate nohighlight">\(\boldsymbol{a}\)</span> from the hidden layer, the probability that the input <span class="math notranslate nohighlight">\(\boldsymbol{x}\)</span>
is in class 0 or 1 is just. We let <span class="math notranslate nohighlight">\(\theta\)</span> represent the unknown weights and biases to be adjusted by our equations). The variable <span class="math notranslate nohighlight">\(x\)</span>
represents our activation values <span class="math notranslate nohighlight">\(z\)</span>. We have</p>
<div class="math notranslate nohighlight">
\[
P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} ,
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) ,
\]</div>
<p>where <span class="math notranslate nohighlight">\(y \in \{0, 1\}\)</span> and <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> represents the weights and biases
of our network.</p>
</section>
<section id="defining-the-cost-function">
<h2>Defining the cost function<a class="headerlink" href="#defining-the-cost-function" title="Link to this heading">#</a></h2>
<p>Our cost function is given as (see the Logistic regression lectures)</p>
<div class="math notranslate nohighlight">
\[
\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n
y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) .
\]</div>
<p>This last equality means that we can interpret our <em>cost</em> function as a sum over the <em>loss</em> function
for each point in the dataset <span class="math notranslate nohighlight">\(\mathcal{L}_i(\boldsymbol{\theta})\)</span>.<br />
The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather
than maximizing a negative number.</p>
<p>In <em>multiclass</em> classification it is common to treat each integer label as a so called <em>one-hot</em> vector:</p>
<p><span class="math notranslate nohighlight">\(y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,\)</span> and</p>
<p><span class="math notranslate nohighlight">\(y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,\)</span></p>
<p>i.e. a binary bit string of length <span class="math notranslate nohighlight">\(C\)</span>, where <span class="math notranslate nohighlight">\(C = 10\)</span> is the number of classes in the MNIST dataset (numbers from <span class="math notranslate nohighlight">\(0\)</span> to <span class="math notranslate nohighlight">\(9\)</span>)..</p>
<p>If <span class="math notranslate nohighlight">\(\boldsymbol{x}_i\)</span> is the <span class="math notranslate nohighlight">\(i\)</span>-th input (image), <span class="math notranslate nohighlight">\(y_{ic}\)</span> refers to the <span class="math notranslate nohighlight">\(c\)</span>-th component of the <span class="math notranslate nohighlight">\(i\)</span>-th
output vector <span class="math notranslate nohighlight">\(\boldsymbol{y}_i\)</span>.<br />
The probability of <span class="math notranslate nohighlight">\(\boldsymbol{x}_i\)</span> being in class <span class="math notranslate nohighlight">\(c\)</span> will be given by the softmax function:</p>
<div class="math notranslate nohighlight">
\[
P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}}
{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} ,
\]</div>
<p>which reduces to the logistic function in the binary case.<br />
The likelihood of this <span class="math notranslate nohighlight">\(C\)</span>-class classifier
is now given as:</p>
<div class="math notranslate nohighlight">
\[
P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .
\]</div>
<p>Again we take the negative log-likelihood to define our cost function:</p>
<div class="math notranslate nohighlight">
\[
\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}.
\]</div>
<p>See the logistic regression lectures for a full definition of the cost function.</p>
<p>The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!</p>
</section>
<section id="example-binary-classification-problem">
<h2>Example: binary classification problem<a class="headerlink" href="#example-binary-classification-problem" title="Link to this heading">#</a></h2>
<p>As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters <span class="math notranslate nohighlight">\(\beta\)</span> as</p>
<div class="math notranslate nohighlight">
\[
\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right),
\]</div>
<p>where we had defined the logistic (sigmoid) function</p>
<div class="math notranslate nohighlight">
\[
p(y_i =1\vert x_i,\boldsymbol{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}},
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}).
\]</div>
<p>The parameters <span class="math notranslate nohighlight">\(\boldsymbol{\beta}\)</span> were defined using a minimization method like gradient descent or Newton-Raphsons method.</p>
<p>Now we replace <span class="math notranslate nohighlight">\(x_i\)</span> with the activation <span class="math notranslate nohighlight">\(z_i^l\)</span> for a given layer <span class="math notranslate nohighlight">\(l\)</span> and the outputs as <span class="math notranslate nohighlight">\(y_i=a_i^l=f(z_i^l)\)</span>, with <span class="math notranslate nohighlight">\(z_i^l\)</span> now being a function of the weights <span class="math notranslate nohighlight">\(w_{ij}^l\)</span> and biases <span class="math notranslate nohighlight">\(b_i^l\)</span>.
We have then</p>
<div class="math notranslate nohighlight">
\[
a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}},
\]</div>
<p>with</p>
<div class="math notranslate nohighlight">
\[
z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,
\]</div>
<p>where the superscript <span class="math notranslate nohighlight">\(l-1\)</span> indicates that these are the outputs from layer <span class="math notranslate nohighlight">\(l-1\)</span>.
Our cost function at the final layer <span class="math notranslate nohighlight">\(l=L\)</span> is now</p>
<div class="math notranslate nohighlight">
\[
\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right),
\]</div>
<p>where we have defined the targets <span class="math notranslate nohighlight">\(t_i\)</span>. The derivatives of the cost function with respect to the output <span class="math notranslate nohighlight">\(a_i^L\)</span> are then easily calculated and we get</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial \mathcal{C}(\boldsymbol{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.
\]</div>
<p>In case we use another activation function than the logistic one, we need to evaluate other derivatives.</p>
</section>
<section id="the-softmax-function">
<h2>The Softmax function<a class="headerlink" href="#the-softmax-function" title="Link to this heading">#</a></h2>
<p>In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation <span class="math notranslate nohighlight">\(z_i^l\)</span>, that is we need</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial f(z_i^l)}{\partial w_{jk}^l} =
\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}.
\]</div>
<p>For the Softmax function we have</p>
<div class="math notranslate nohighlight">
\[
f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}.
\]</div>
<p>Its derivative with respect to <span class="math notranslate nohighlight">\(z_j^l\)</span> gives</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right),
\]</div>
<p>which in case of the simply binary model reduces to having <span class="math notranslate nohighlight">\(i=j\)</span>.</p>
</section>
<section id="developing-a-code-for-doing-neural-networks-with-back-propagation">
<h2>Developing a code for doing neural networks with back propagation<a class="headerlink" href="#developing-a-code-for-doing-neural-networks-with-back-propagation" title="Link to this heading">#</a></h2>
<p>One can identify a set of key steps when using neural networks to solve supervised learning problems:</p>
<ol class="arabic simple">
<li><p>Collect and pre-process data</p></li>
<li><p>Define model and architecture</p></li>
<li><p>Choose cost function and optimizer</p></li>
<li><p>Train the model</p></li>
<li><p>Evaluate model performance on test data</p></li>
<li><p>Adjust hyperparameters (if necessary, network architecture)</p></li>
</ol>
</section>
<section id="collect-and-pre-process-data">
<h2>Collect and pre-process data<a class="headerlink" href="#collect-and-pre-process-data" title="Link to this heading">#</a></h2>
<p>Here we will be using the MNIST dataset, which is readily available through the <strong>scikit-learn</strong>
package. You may also find it for example <a class="reference external" href="http://yann.lecun.com/exdb/mnist/">here</a>.<br />
The <em>MNIST</em> (Modified National Institute of Standards and Technology) database is a large database
of handwritten digits that is commonly used for training various image processing systems.<br />
The MNIST dataset consists of 70 000 images of size <span class="math notranslate nohighlight">\(28\times 28\)</span> pixels, each labeled from 0 to 9.<br />
The scikit-learn dataset we will use consists of a selection of 1797 images of size <span class="math notranslate nohighlight">\(8\times 8\)</span> collected and processed from this database.</p>
<p>To feed data into a feed-forward neural network we need to represent
the inputs as a design/feature matrix <span class="math notranslate nohighlight">\(X = (n_{inputs}, n_{features})\)</span>. Each
row represents an <em>input</em>, in this case a handwritten digit, and
each column represents a <em>feature</em>, in this case a pixel. The
correct answers, also known as <em>labels</em> or <em>targets</em> are
represented as a 1D array of integers
<span class="math notranslate nohighlight">\(Y = (n_{inputs}) = (5, 3, 1, 8,...)\)</span>.</p>
<p>As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from
measurements of height (in m)<br />
and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example:</p>
<div class="math notranslate nohighlight">
\[\begin{split} X = \begin{bmatrix}
1.85 &amp; 81\\
1.71 &amp; 65\\
1.95 &amp; 103\\
1.55 &amp; 42\\
1.63 &amp; 56
\end{bmatrix} ,\end{split}\]</div>
<p>and the targets would be:</p>
<div class="math notranslate nohighlight">
\[ Y = (23.7, 22.2, 27.1, 17.5, 21.1) \]</div>
<p>Since each input image is a 2D matrix, we need to flatten the image
(i.e. “unravel” the 2D matrix into a 1D array) to turn the data into a
design/feature matrix. This means we lose all spatial information in the
image, such as locality and translational invariance. More complicated
architectures such as Convolutional Neural Networks can take advantage
of such information, and are most commonly applied when analyzing
images.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># import necessary packages
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
# ensure the same random numbers appear every time
np.random.seed(0)
# display images in notebook
%matplotlib inline
plt.rcParams[&#39;figure.figsize&#39;] = (12,12)
# download MNIST dataset
digits = datasets.load_digits()
# define inputs and labels
inputs = digits.images
labels = digits.target
print(&quot;inputs = (n_inputs, pixel_width, pixel_height) = &quot; + str(inputs.shape))
print(&quot;labels = (n_inputs) = &quot; + str(labels.shape))
# flatten the image
# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
n_inputs = len(inputs)
inputs = inputs.reshape(n_inputs, -1)
print(&quot;X = (n_inputs, n_features) = &quot; + str(inputs.shape))
# choose some random images to display
indices = np.arange(n_inputs)
random_indices = np.random.choice(indices, size=5)
for i, image in enumerate(digits.images[random_indices]):
plt.subplot(1, 5, i+1)
plt.axis(&#39;off&#39;)
plt.imshow(image, cmap=plt.cm.gray_r, interpolation=&#39;nearest&#39;)
plt.title(&quot;Label: %d&quot; % digits.target[random_indices[i]])
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="train-and-test-datasets">
<h2>Train and test datasets<a class="headerlink" href="#train-and-test-datasets" title="Link to this heading">#</a></h2>
<p>Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.</p>
<p>We will reserve <span class="math notranslate nohighlight">\(80 \%\)</span> of our dataset for training and <span class="math notranslate nohighlight">\(20 \%\)</span> for testing.</p>
<p>It is important that the train and test datasets are drawn randomly from our dataset, to ensure
no bias in the sampling.<br />
Say you are taking measurements of weather data to predict the weather in the coming 5 days.
You dont want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data
collected from 12.00 to 24.00.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>from sklearn.model_selection import train_test_split
# one-liner from scikit-learn library
train_size = 0.8
test_size = 1 - train_size
X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
test_size=test_size)
# equivalently in numpy
def train_test_split_numpy(inputs, labels, train_size, test_size):
n_inputs = len(inputs)
inputs_shuffled = inputs.copy()
labels_shuffled = labels.copy()
np.random.shuffle(inputs_shuffled)
np.random.shuffle(labels_shuffled)
train_end = int(n_inputs*train_size)
X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
return X_train, X_test, Y_train, Y_test
#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
print(&quot;Number of training images: &quot; + str(len(X_train)))
print(&quot;Number of test images: &quot; + str(len(X_test)))
</pre></div>
</div>
</div>
</div>
</section>
<section id="define-model-and-architecture">
<h2>Define model and architecture<a class="headerlink" href="#define-model-and-architecture" title="Link to this heading">#</a></h2>
<p>Our simple feed-forward neural network will consist of an <em>input</em> layer, a single <em>hidden</em> layer and an <em>output</em> layer. The activation <span class="math notranslate nohighlight">\(y\)</span> of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have</p>
<div class="math notranslate nohighlight">
\[ z = \sum_{i=1}^n w_i a_i ,\]</div>
<div class="math notranslate nohighlight">
\[ y = f(z) ,\]</div>
<p>where <span class="math notranslate nohighlight">\(f\)</span> is the activation function, <span class="math notranslate nohighlight">\(a_i\)</span> represents input from neuron <span class="math notranslate nohighlight">\(i\)</span> in the preceding layer
and <span class="math notranslate nohighlight">\(w_i\)</span> is the weight to input <span class="math notranslate nohighlight">\(i\)</span>.<br />
The activation of the neurons in the input layer is just the features (e.g. a pixel value).</p>
<p>The simplest activation function for a neuron is the <em>Heaviside</em> function:</p>
<div class="math notranslate nohighlight">
\[\begin{split} f(z) =
\begin{cases}
1, &amp; z &gt; 0\\
0, &amp; \text{otherwise}
\end{cases}
\end{split}\]</div>
<p>A feed-forward neural network with this activation is known as a <em>perceptron</em>.<br />
For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer.<br />
This activation can be generalized to <span class="math notranslate nohighlight">\(k\)</span> classes (using e.g. the <em>one-against-all</em> strategy),
and we call these architectures <em>multiclass perceptrons</em>.</p>
<p>However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and<br />
Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function.</p>
<p>Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU).<br />
We will be using the sigmoid function <span class="math notranslate nohighlight">\(\sigma(x)\)</span>:</p>
<div class="math notranslate nohighlight">
\[ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,\]</div>
<p>which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.</p>
</section>
<section id="layers">
<h2>Layers<a class="headerlink" href="#layers" title="Link to this heading">#</a></h2>
<ul class="simple">
<li><p>Input</p></li>
</ul>
<p>Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.</p>
<ul class="simple">
<li><p>Hidden layer</p></li>
</ul>
<p>We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer.<br />
Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer.</p>
<ul class="simple">
<li><p>Output</p></li>
</ul>
<p>If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,
which could output 0 or 1 according to the Heaviside function. This would be an example of a <em>hard</em> classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a <em>soft</em> classifier, which outputs the probability of being in class 0 or 1.</p>
<p>For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.</p>
<p>Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons <span class="math notranslate nohighlight">\(j = 0,1,...,9\)</span>. The activation of each output neuron <span class="math notranslate nohighlight">\(j\)</span> will be according to the <em>softmax</em> function:</p>
<div class="math notranslate nohighlight">
\[ P(\text{class $j$} \mid \text{input $\boldsymbol{a}$}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}}
{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,\]</div>
<p>i.e. each neuron <span class="math notranslate nohighlight">\(j\)</span> outputs the probability of being in class <span class="math notranslate nohighlight">\(j\)</span> given an input from the hidden layer <span class="math notranslate nohighlight">\(\boldsymbol{a}\)</span>, with <span class="math notranslate nohighlight">\(\boldsymbol{w}_j\)</span> the weights of neuron <span class="math notranslate nohighlight">\(j\)</span> to the inputs.<br />
The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1.<br />
The exponent is just the weighted sum of inputs as before:</p>
<div class="math notranslate nohighlight">
\[ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.\]</div>
<p>Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500
weights to the output layer.</p>
</section>
<section id="weights-and-biases">
<h2>Weights and biases<a class="headerlink" href="#weights-and-biases" title="Link to this heading">#</a></h2>
<p>Typically weights are initialized with small values distributed around zero, drawn from a uniform
or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless.</p>
<p>Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range
of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron <span class="math notranslate nohighlight">\(j\)</span>, <span class="math notranslate nohighlight">\(b_j\)</span>:</p>
<div class="math notranslate nohighlight">
\[ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.\]</div>
<p>The bias weights <span class="math notranslate nohighlight">\(\boldsymbol{b}\)</span> are often initialized to zero, but a small value like <span class="math notranslate nohighlight">\(0.01\)</span> ensures all neurons have some output which can be backpropagated in the first training cycle.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># building our neural network
n_inputs, n_features = X_train.shape
n_hidden_neurons = 50
n_categories = 10
# we make the weights normally distributed using numpy.random.randn
# weights and bias in the hidden layer
hidden_weights = np.random.randn(n_features, n_hidden_neurons)
hidden_bias = np.zeros(n_hidden_neurons) + 0.01
# weights and bias in the output layer
output_weights = np.random.randn(n_hidden_neurons, n_categories)
output_bias = np.zeros(n_categories) + 0.01
</pre></div>
</div>
</div>
</div>
</section>
<section id="feed-forward-pass">
<h2>Feed-forward pass<a class="headerlink" href="#feed-forward-pass" title="Link to this heading">#</a></h2>
<p>Denote <span class="math notranslate nohighlight">\(F\)</span> the number of features, <span class="math notranslate nohighlight">\(H\)</span> the number of hidden neurons and <span class="math notranslate nohighlight">\(C\)</span> the number of categories.<br />
For each input image we calculate a weighted sum of input features (pixel values) to each neuron <span class="math notranslate nohighlight">\(j\)</span> in the hidden layer <span class="math notranslate nohighlight">\(l\)</span>:</p>
<div class="math notranslate nohighlight">
\[ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},\]</div>
<p>this is then passed through our activation function</p>
<div class="math notranslate nohighlight">
\[ a_{j}^{l} = f(z_{j}^{l}) .\]</div>
<p>We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron <span class="math notranslate nohighlight">\(j\)</span> in the output layer:</p>
<div class="math notranslate nohighlight">
\[ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.\]</div>
<p>Finally we calculate the output of neuron <span class="math notranslate nohighlight">\(j\)</span> in the output layer using the softmax function:</p>
<div class="math notranslate nohighlight">
\[ a_{j}^{L} = \frac{\exp{(z_j^{L})}}
{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .\]</div>
</section>
<section id="matrix-multiplications">
<h2>Matrix multiplications<a class="headerlink" href="#matrix-multiplications" title="Link to this heading">#</a></h2>
<p>Since our data has the dimensions <span class="math notranslate nohighlight">\(X = (n_{inputs}, n_{features})\)</span> and our weights to the hidden
layer have the dimensions<br />
<span class="math notranslate nohighlight">\(W_{hidden} = (n_{features}, n_{hidden})\)</span>,
we can easily feed the network all our training data in one go by taking the matrix product</p>
<div class="math notranslate nohighlight">
\[ X W^{h} = (n_{inputs}, n_{hidden}),\]</div>
<p>and obtain a matrix that holds the weighted sum of inputs to the hidden layer
for each input image and each hidden neuron.<br />
We also add the bias to obtain a matrix of weighted sums to the hidden layer <span class="math notranslate nohighlight">\(Z^{h}\)</span>:</p>
<div class="math notranslate nohighlight">
\[ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,\]</div>
<p>meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image.<br />
This is then passed through the activation:</p>
<div class="math notranslate nohighlight">
\[ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .\]</div>
<p>This is fed to the output layer:</p>
<div class="math notranslate nohighlight">
\[ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .\]</div>
<p>Finally we receive our output values for each image and each category by passing it through the softmax function:</p>
<div class="math notranslate nohighlight">
\[ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .\]</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># setup the feed-forward pass, subscript h = hidden layer
def sigmoid(x):
return 1/(1 + np.exp(-x))
def feed_forward(X):
# weighted sum of inputs to the hidden layer
z_h = np.matmul(X, hidden_weights) + hidden_bias
# activation in the hidden layer
a_h = sigmoid(z_h)
# weighted sum of inputs to the output layer
z_o = np.matmul(a_h, output_weights) + output_bias
# softmax output
# axis 0 holds each input and axis 1 the probabilities of each category
exp_term = np.exp(z_o)
probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
return probabilities
probabilities = feed_forward(X_train)
print(&quot;probabilities = (n_inputs, n_categories) = &quot; + str(probabilities.shape))
print(&quot;probability that image 0 is in category 0,1,2,...,9 = \n&quot; + str(probabilities[0]))
print(&quot;probabilities sum up to: &quot; + str(probabilities[0].sum()))
print()
# we obtain a prediction by taking the class with the highest likelihood
def predict(X):
probabilities = feed_forward(X)
return np.argmax(probabilities, axis=1)
predictions = predict(X_train)
print(&quot;predictions = (n_inputs) = &quot; + str(predictions.shape))
print(&quot;prediction for image 0: &quot; + str(predictions[0]))
print(&quot;correct label for image 0: &quot; + str(Y_train[0]))
</pre></div>
</div>
</div>
</div>
</section>
<section id="choose-cost-function-and-optimizer">
<h2>Choose cost function and optimizer<a class="headerlink" href="#choose-cost-function-and-optimizer" title="Link to this heading">#</a></h2>
<p>To measure how well our neural network is doing we need to introduce a cost function.<br />
We will call the function that gives the error of a single sample output the <em>loss</em> function, and the function
that gives the total error of our network across all samples the <em>cost</em> function.
A typical choice for multiclass classification is the <em>cross-entropy</em> loss, also known as the negative log likelihood.</p>
<p>In <em>multiclass</em> classification it is common to treat each integer label as a so called <em>one-hot</em> vector:</p>
<div class="math notranslate nohighlight">
\[ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,\]</div>
<div class="math notranslate nohighlight">
\[ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,\]</div>
<p>i.e. a binary bit string of length <span class="math notranslate nohighlight">\(C\)</span>, where <span class="math notranslate nohighlight">\(C = 10\)</span> is the number of classes in the MNIST dataset.</p>
<p>Let <span class="math notranslate nohighlight">\(y_{ic}\)</span> denote the <span class="math notranslate nohighlight">\(c\)</span>-th component of the <span class="math notranslate nohighlight">\(i\)</span>-th one-hot vector.<br />
We define the cost function <span class="math notranslate nohighlight">\(\mathcal{C}\)</span> as a sum over the cross-entropy loss for each point <span class="math notranslate nohighlight">\(\boldsymbol{x}_i\)</span> in the dataset.</p>
<p>In the one-hot representation only one of the terms in the loss function is non-zero, namely the
probability of the correct category <span class="math notranslate nohighlight">\(c'\)</span><br />
(i.e. the category <span class="math notranslate nohighlight">\(c'\)</span> such that <span class="math notranslate nohighlight">\(y_{ic'} = 1\)</span>). This means that the cross entropy loss only punishes you for how wrong
you got the correct label. The probability of category <span class="math notranslate nohighlight">\(c\)</span> is given by the softmax function. The vector <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> represents the parameters of our network, i.e. all the weights and biases.</p>
</section>
<section id="optimizing-the-cost-function">
<h2>Optimizing the cost function<a class="headerlink" href="#optimizing-the-cost-function" title="Link to this heading">#</a></h2>
<p>The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is <em>gradient descent</em> and its generalizations. The idea behind gradient descent
is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a <em>local</em> minimum of the cost function.<br />
Each parameter <span class="math notranslate nohighlight">\(\theta\)</span> is iteratively adjusted according to the rule</p>
<div class="math notranslate nohighlight">
\[ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,\]</div>
<p>where <span class="math notranslate nohighlight">\(\eta\)</span> is known as the <em>learning rate</em>, which controls how big a step we take towards the minimum.<br />
This update can be repeated for any number of iterations, or until we are satisfied with the result.</p>
<p>A simple and effective improvement is a variant called <em>Batch Gradient Descent</em>.<br />
Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient
on a subset of the data called a <em>minibatch</em>.<br />
If there are <span class="math notranslate nohighlight">\(N\)</span> data points and we have a minibatch size of <span class="math notranslate nohighlight">\(M\)</span>, the total number of batches
is <span class="math notranslate nohighlight">\(N/M\)</span>.<br />
We denote each minibatch <span class="math notranslate nohighlight">\(B_k\)</span>, with <span class="math notranslate nohighlight">\(k = 1, 2,...,N/M\)</span>. The gradient then becomes:</p>
<div class="math notranslate nohighlight">
\[ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad
\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,\]</div>
<p>i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.</p>
<p>This has two important benefits:</p>
<ol class="arabic simple">
<li><p>Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.</p></li>
<li><p>It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.</p></li>
</ol>
<p>The various optmization methods, with codes and algorithms, are discussed in our lectures on <a class="reference external" href="https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html">Gradient descent approaches</a>.</p>
</section>
<section id="regularization">
<h2>Regularization<a class="headerlink" href="#regularization" title="Link to this heading">#</a></h2>
<p>It is common to add an extra term to the cost function, proportional
to the size of the weights. This is equivalent to constraining the
size of the weights, so that they do not grow out of control.
Constraining the size of the weights means that the weights cannot
grow arbitrarily large to fit the training data, and in this way
reduces <em>overfitting</em>.</p>
<p>We will measure the size of the weights using the so called <em>L2-norm</em>, meaning our cost function becomes:</p>
<div class="math notranslate nohighlight">
\[ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad
\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2
= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,\]</div>
<p>i.e. we sum up all the weights squared. The factor <span class="math notranslate nohighlight">\(\lambda\)</span> is known as a regularization parameter.</p>
<p>In order to train the model, we need to calculate the derivative of
the cost function with respect to every bias and weight in the
network. In total our network has <span class="math notranslate nohighlight">\((64 + 1)\times 50=3250\)</span> weights in
the hidden layer and <span class="math notranslate nohighlight">\((50 + 1)\times 10=510\)</span> weights to the output
layer (<span class="math notranslate nohighlight">\(+1\)</span> for the bias), and the gradient must be calculated for
every parameter. We use the <em>backpropagation</em> algorithm discussed
above. This is a clever use of the chain rule that allows us to
calculate the gradient efficently.</p>
</section>
<section id="matrix-multiplication">
<h2>Matrix multiplication<a class="headerlink" href="#matrix-multiplication" title="Link to this heading">#</a></h2>
<p>To more efficently train our network these equations are implemented using matrix operations.<br />
The error in the output layer is calculated simply as, with <span class="math notranslate nohighlight">\(\boldsymbol{t}\)</span> being our targets,</p>
<div class="math notranslate nohighlight">
\[ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .\]</div>
<p>The gradient for the output weights is calculated as</p>
<div class="math notranslate nohighlight">
\[ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,\]</div>
<p>where <span class="math notranslate nohighlight">\(\boldsymbol{a} = (n_{inputs}, n_{hidden})\)</span>. This simply means that we are summing up the gradients for each input.<br />
Since we are going backwards we have to transpose the activation matrix.</p>
<p>The gradient with respect to the output bias is then</p>
<div class="math notranslate nohighlight">
\[ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .\]</div>
<p>The error in the hidden layer is</p>
<div class="math notranslate nohighlight">
\[ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,\]</div>
<p>where <span class="math notranslate nohighlight">\(f'(a_{h})\)</span> is the derivative of the activation in the hidden layer. The matrix products mean
that we are summing up the products for each neuron in the output layer. The symbol <span class="math notranslate nohighlight">\(\circ\)</span> denotes
the <em>Hadamard product</em>, meaning element-wise multiplication.</p>
<p>This again gives us the gradients in the hidden layer:</p>
<div class="math notranslate nohighlight">
\[ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,\]</div>
<div class="math notranslate nohighlight">
\[ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .\]</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># to categorical turns our integer vector into a onehot representation
from sklearn.metrics import accuracy_score
# one-hot in numpy
def to_categorical_numpy(integer_vector):
n_inputs = len(integer_vector)
n_categories = np.max(integer_vector) + 1
onehot_vector = np.zeros((n_inputs, n_categories))
onehot_vector[range(n_inputs), integer_vector] = 1
return onehot_vector
#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
def feed_forward_train(X):
# weighted sum of inputs to the hidden layer
z_h = np.matmul(X, hidden_weights) + hidden_bias
# activation in the hidden layer
a_h = sigmoid(z_h)
# weighted sum of inputs to the output layer
z_o = np.matmul(a_h, output_weights) + output_bias
# softmax output
# axis 0 holds each input and axis 1 the probabilities of each category
exp_term = np.exp(z_o)
probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
# for backpropagation need activations in hidden and output layers
return a_h, probabilities
def backpropagation(X, Y):
a_h, probabilities = feed_forward_train(X)
# error in the output layer
error_output = probabilities - Y
# error in the hidden layer
error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
# gradients for the output layer
output_weights_gradient = np.matmul(a_h.T, error_output)
output_bias_gradient = np.sum(error_output, axis=0)
# gradient for the hidden layer
hidden_weights_gradient = np.matmul(X.T, error_hidden)
hidden_bias_gradient = np.sum(error_hidden, axis=0)
return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
print(&quot;Old accuracy on training data: &quot; + str(accuracy_score(predict(X_train), Y_train)))
eta = 0.01
lmbd = 0.01
for i in range(1000):
# calculate gradients
dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
# regularization term gradients
dWo += lmbd * output_weights
dWh += lmbd * hidden_weights
# update weights and biases
output_weights -= eta * dWo
output_bias -= eta * dBo
hidden_weights -= eta * dWh
hidden_bias -= eta * dBh
print(&quot;New accuracy on training data: &quot; + str(accuracy_score(predict(X_train), Y_train)))
</pre></div>
</div>
</div>
</div>
</section>
<section id="improving-performance">
<h2>Improving performance<a class="headerlink" href="#improving-performance" title="Link to this heading">#</a></h2>
<p>As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image.<br />
In order to obtain a network that does something useful, we will have to do a bit more work.</p>
<p>The choice of <em>hyperparameters</em> such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a <em>grid-search</em> is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates <span class="math notranslate nohighlight">\(\eta = 10^{-6}, 10^{-5},...,10^{-1}\)</span> with different regularization parameters <span class="math notranslate nohighlight">\(\lambda = 10^{-6},...,10^{-0}\)</span>.</p>
<p>Next, we havent implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an <em>iteration</em>, and a full training period
going through the entire dataset (<span class="math notranslate nohighlight">\(n/M\)</span> batches) an <em>epoch</em>.</p>
<p>If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers.<br />
Andrew Ng goes through some of these considerations in this <a class="reference external" href="https://youtu.be/F1ka6a13S9I">video</a>. You can find a summary of the video <a class="reference external" href="https://kevinzakka.github.io/2016/09/26/applying-deep-learning/">here</a>.</p>
</section>
<section id="full-object-oriented-implementation">
<h2>Full object-oriented implementation<a class="headerlink" href="#full-object-oriented-implementation" title="Link to this heading">#</a></h2>
<p>It is very natural to think of the network as an object, with specific instances of the network
being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>class NeuralNetwork:
def __init__(
self,
X_data,
Y_data,
n_hidden_neurons=50,
n_categories=10,
epochs=10,
batch_size=100,
eta=0.1,
lmbd=0.0):
self.X_data_full = X_data
self.Y_data_full = Y_data
self.n_inputs = X_data.shape[0]
self.n_features = X_data.shape[1]
self.n_hidden_neurons = n_hidden_neurons
self.n_categories = n_categories
self.epochs = epochs
self.batch_size = batch_size
self.iterations = self.n_inputs // self.batch_size
self.eta = eta
self.lmbd = lmbd
self.create_biases_and_weights()
def create_biases_and_weights(self):
self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
self.output_bias = np.zeros(self.n_categories) + 0.01
def feed_forward(self):
# feed-forward for training
self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
self.a_h = sigmoid(self.z_h)
self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
exp_term = np.exp(self.z_o)
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
def feed_forward_out(self, X):
# feed-forward for output
z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
a_h = sigmoid(z_h)
z_o = np.matmul(a_h, self.output_weights) + self.output_bias
exp_term = np.exp(z_o)
probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
return probabilities
def backpropagation(self):
error_output = self.probabilities - self.Y_data
error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
self.output_bias_gradient = np.sum(error_output, axis=0)
self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
if self.lmbd &gt; 0.0:
self.output_weights_gradient += self.lmbd * self.output_weights
self.hidden_weights_gradient += self.lmbd * self.hidden_weights
self.output_weights -= self.eta * self.output_weights_gradient
self.output_bias -= self.eta * self.output_bias_gradient
self.hidden_weights -= self.eta * self.hidden_weights_gradient
self.hidden_bias -= self.eta * self.hidden_bias_gradient
def predict(self, X):
probabilities = self.feed_forward_out(X)
return np.argmax(probabilities, axis=1)
def predict_probabilities(self, X):
probabilities = self.feed_forward_out(X)
return probabilities
def train(self):
data_indices = np.arange(self.n_inputs)
for i in range(self.epochs):
for j in range(self.iterations):
# pick datapoints with replacement
chosen_datapoints = np.random.choice(
data_indices, size=self.batch_size, replace=False
)
# minibatch training data
self.X_data = self.X_data_full[chosen_datapoints]
self.Y_data = self.Y_data_full[chosen_datapoints]
self.feed_forward()
self.backpropagation()
</pre></div>
</div>
</div>
</div>
</section>
<section id="evaluate-model-performance-on-test-data">
<h2>Evaluate model performance on test data<a class="headerlink" href="#evaluate-model-performance-on-test-data" title="Link to this heading">#</a></h2>
<p>To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data.<br />
We measure the performance of the network using the <em>accuracy</em> score.<br />
The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of <span class="math notranslate nohighlight">\(1\)</span>.</p>
<div class="math notranslate nohighlight">
\[ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,\]</div>
<p>where <span class="math notranslate nohighlight">\(I\)</span> is the indicator function, <span class="math notranslate nohighlight">\(1\)</span> if <span class="math notranslate nohighlight">\(\tilde{y}_i = y_i\)</span> and <span class="math notranslate nohighlight">\(0\)</span> otherwise.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>epochs = 100
batch_size = 100
dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
dnn.train()
test_predict = dnn.predict(X_test)
# accuracy score from scikit library
print(&quot;Accuracy score on test set: &quot;, accuracy_score(Y_test, test_predict))
# equivalent in numpy
def accuracy_score_numpy(Y_test, Y_pred):
return np.sum(Y_test == Y_pred) / len(Y_test)
#print(&quot;Accuracy score on test set: &quot;, accuracy_score_numpy(Y_test, test_predict))
</pre></div>
</div>
</div>
</div>
</section>
<section id="adjust-hyperparameters">
<h2>Adjust hyperparameters<a class="headerlink" href="#adjust-hyperparameters" title="Link to this heading">#</a></h2>
<p>We now perform a grid search to find the optimal hyperparameters for the network.<br />
Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around <span class="math notranslate nohighlight">\(98\%\)</span> (<span class="math notranslate nohighlight">\(2\%\)</span> error rate).</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>eta_vals = np.logspace(-5, 1, 7)
lmbd_vals = np.logspace(-5, 1, 7)
# store the models for later use
DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
# grid search
for i, eta in enumerate(eta_vals):
for j, lmbd in enumerate(lmbd_vals):
dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
dnn.train()
DNN_numpy[i][j] = dnn
test_predict = dnn.predict(X_test)
print(&quot;Learning rate = &quot;, eta)
print(&quot;Lambda = &quot;, lmbd)
print(&quot;Accuracy score on test set: &quot;, accuracy_score(Y_test, test_predict))
print()
</pre></div>
</div>
</div>
</div>
</section>
<section id="visualization">
<h2>Visualization<a class="headerlink" href="#visualization" title="Link to this heading">#</a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># visual representation of grid search
# uses seaborn heatmap, you can also do this with matplotlib imshow
import seaborn as sns
sns.set()
train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
for i in range(len(eta_vals)):
for j in range(len(lmbd_vals)):
dnn = DNN_numpy[i][j]
train_pred = dnn.predict(X_train)
test_pred = dnn.predict(X_test)
train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=&quot;viridis&quot;)
ax.set_title(&quot;Training Accuracy&quot;)
ax.set_ylabel(&quot;$\eta$&quot;)
ax.set_xlabel(&quot;$\lambda$&quot;)
plt.show()
fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=&quot;viridis&quot;)
ax.set_title(&quot;Test Accuracy&quot;)
ax.set_ylabel(&quot;$\eta$&quot;)
ax.set_xlabel(&quot;$\lambda$&quot;)
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="scikit-learn-implementation">
<h2>scikit-learn implementation<a class="headerlink" href="#scikit-learn-implementation" title="Link to this heading">#</a></h2>
<p><strong>scikit-learn</strong> focuses more
on traditional machine learning methods, such as regression,
clustering, decision trees, etc. As such, it has only two types of
neural networks: Multi Layer Perceptron outputting continuous values,
<em>MPLRegressor</em>, and Multi Layer Perceptron outputting labels,
<em>MLPClassifier</em>. We will see how simple it is to use these classes.</p>
<p><strong>scikit-learn</strong> implements a few improvements from our neural network,
such as early stopping, a varying learning rate, different
optimization methods, etc. We would therefore expect a better
performance overall.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>from sklearn.neural_network import MLPClassifier
# store models for later use
DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
for i, eta in enumerate(eta_vals):
for j, lmbd in enumerate(lmbd_vals):
dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation=&#39;logistic&#39;,
alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
dnn.fit(X_train, Y_train)
DNN_scikit[i][j] = dnn
print(&quot;Learning rate = &quot;, eta)
print(&quot;Lambda = &quot;, lmbd)
print(&quot;Accuracy score on test set: &quot;, dnn.score(X_test, Y_test))
print()
</pre></div>
</div>
</div>
</div>
</section>
<section id="id1">
<h2>Visualization<a class="headerlink" href="#id1" title="Link to this heading">#</a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># optional
# visual representation of grid search
# uses seaborn heatmap, could probably do this in matplotlib
import seaborn as sns
sns.set()
train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
for i in range(len(eta_vals)):
for j in range(len(lmbd_vals)):
dnn = DNN_scikit[i][j]
train_pred = dnn.predict(X_train)
test_pred = dnn.predict(X_test)
train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=&quot;viridis&quot;)
ax.set_title(&quot;Training Accuracy&quot;)
ax.set_ylabel(&quot;$\eta$&quot;)
ax.set_xlabel(&quot;$\lambda$&quot;)
plt.show()
fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=&quot;viridis&quot;)
ax.set_title(&quot;Test Accuracy&quot;)
ax.set_ylabel(&quot;$\eta$&quot;)
ax.set_xlabel(&quot;$\lambda$&quot;)
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="building-neural-networks-in-tensorflow-and-keras">
<h2>Building neural networks in Tensorflow and Keras<a class="headerlink" href="#building-neural-networks-in-tensorflow-and-keras" title="Link to this heading">#</a></h2>
<p>Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn
and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy
and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer.</p>
<p>In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite
clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or
NumPy arrays.</p>
</section>
<section id="tensorflow">
<h2>Tensorflow<a class="headerlink" href="#tensorflow" title="Link to this heading">#</a></h2>
<p>Tensorflow is an open source library machine learning library
developed by the Google Brain team for internal use. It was released
under the Apache 2.0 open source license in November 9, 2015.</p>
<p>Tensorflow is a computational framework that allows you to construct
machine learning models at different levels of abstraction, from
high-level, object-oriented APIs like Keras, down to the C++ kernels
that Tensorflow is built upon. The higher levels of abstraction are
simpler to use, but less flexible, and our choice of implementation
should reflect the problems we are trying to solve.</p>
<p><a class="reference external" href="https://www.tensorflow.org/guide/graphs">Tensorflow uses</a> so-called graphs to represent your computation
in terms of the dependencies between individual operations, such that you first build a Tensorflow <em>graph</em>
to represent your model, and then create a Tensorflow <em>session</em> to run the graph.</p>
<p>In this guide we will analyze the same data as we did in our NumPy and
scikit-learn tutorial, gathered from the MNIST database of images. We
will give an introduction to the lower level Python Application
Program Interfaces (APIs), and see how we use them to build our graph.
Then we will build (effectively) the same graph in Keras, to see just
how simple solving a machine learning problem can be.</p>
<p>To install tensorflow on Unix/Linux systems, use pip as</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>pip3 install tensorflow
</pre></div>
</div>
</div>
</div>
<p>and/or if you use <strong>anaconda</strong>, just write (or install from the graphical user interface)
(current release of CPU-only TensorFlow)</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>conda create -n tf tensorflow
conda activate tf
</pre></div>
</div>
</div>
</div>
<p>To install the current release of GPU TensorFlow</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>conda create -n tf-gpu tensorflow-gpu
conda activate tf-gpu
</pre></div>
</div>
</div>
</div>
</section>
<section id="using-keras">
<h2>Using Keras<a class="headerlink" href="#using-keras" title="Link to this heading">#</a></h2>
<p>Keras is a high level <a class="reference external" href="https://en.wikipedia.org/wiki/Application_programming_interface">neural network</a>
that supports Tensorflow, CTNK and Theano as backends.<br />
If you have Anaconda installed you may run the following command</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>conda install keras
</pre></div>
</div>
</div>
</div>
<p>You can look up the <a class="reference external" href="https://keras.io/">instructions here</a> for more information.</p>
<p>We will to a large extent use <strong>keras</strong> in this course.</p>
</section>
<section id="id2">
<h2>Collect and pre-process data<a class="headerlink" href="#id2" title="Link to this heading">#</a></h2>
<p>Let us look again at the MINST data set.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># import necessary packages
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn import datasets
# ensure the same random numbers appear every time
np.random.seed(0)
# display images in notebook
%matplotlib inline
plt.rcParams[&#39;figure.figsize&#39;] = (12,12)
# download MNIST dataset
digits = datasets.load_digits()
# define inputs and labels
inputs = digits.images
labels = digits.target
print(&quot;inputs = (n_inputs, pixel_width, pixel_height) = &quot; + str(inputs.shape))
print(&quot;labels = (n_inputs) = &quot; + str(labels.shape))
# flatten the image
# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
n_inputs = len(inputs)
inputs = inputs.reshape(n_inputs, -1)
print(&quot;X = (n_inputs, n_features) = &quot; + str(inputs.shape))
# choose some random images to display
indices = np.arange(n_inputs)
random_indices = np.random.choice(indices, size=5)
for i, image in enumerate(digits.images[random_indices]):
plt.subplot(1, 5, i+1)
plt.axis(&#39;off&#39;)
plt.imshow(image, cmap=plt.cm.gray_r, interpolation=&#39;nearest&#39;)
plt.title(&quot;Label: %d&quot; % digits.target[random_indices[i]])
plt.show()
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>from tensorflow.keras.layers import Input
from tensorflow.keras.models import Sequential #This allows appending layers to existing models
from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer
from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)
from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)
from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function
from sklearn.model_selection import train_test_split
# one-hot representation of labels
labels = to_categorical(labels)
# split into train and test data
train_size = 0.8
test_size = 1 - train_size
X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
test_size=test_size)
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>
epochs = 100
batch_size = 100
n_neurons_layer1 = 100
n_neurons_layer2 = 50
n_categories = 10
eta_vals = np.logspace(-5, 1, 7)
lmbd_vals = np.logspace(-5, 1, 7)
def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
model = Sequential()
model.add(Dense(n_neurons_layer1, activation=&#39;sigmoid&#39;, kernel_regularizer=regularizers.l2(lmbd)))
model.add(Dense(n_neurons_layer2, activation=&#39;sigmoid&#39;, kernel_regularizer=regularizers.l2(lmbd)))
model.add(Dense(n_categories, activation=&#39;softmax&#39;))
sgd = optimizers.SGD(lr=eta)
model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=sgd, metrics=[&#39;accuracy&#39;])
return model
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
for i, eta in enumerate(eta_vals):
for j, lmbd in enumerate(lmbd_vals):
DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
eta=eta, lmbd=lmbd)
DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
scores = DNN.evaluate(X_test, Y_test)
DNN_keras[i][j] = DNN
print(&quot;Learning rate = &quot;, eta)
print(&quot;Lambda = &quot;, lmbd)
print(&quot;Test accuracy: %.3f&quot; % scores[1])
print()
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># optional
# visual representation of grid search
# uses seaborn heatmap, could probably do this in matplotlib
import seaborn as sns
sns.set()
train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
for i in range(len(eta_vals)):
for j in range(len(lmbd_vals)):
DNN = DNN_keras[i][j]
train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=&quot;viridis&quot;)
ax.set_title(&quot;Training Accuracy&quot;)
ax.set_ylabel(&quot;$\eta$&quot;)
ax.set_xlabel(&quot;$\lambda$&quot;)
plt.show()
fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=&quot;viridis&quot;)
ax.set_title(&quot;Test Accuracy&quot;)
ax.set_ylabel(&quot;$\eta$&quot;)
ax.set_xlabel(&quot;$\lambda$&quot;)
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="building-a-neural-network-code">
<h2>Building a neural network code<a class="headerlink" href="#building-a-neural-network-code" title="Link to this heading">#</a></h2>
<p>Here we present a flexible object oriented codebase
for a feed forward neural network, along with a demonstration of how
to use it. Before we get into the details of the neural network, we
will first present some implementations of various schedulers, cost
functions and activation functions that can be used together with the
neural network.</p>
<p>The codes here were developed by Eric Reber and Gregor Kajda during spring 2023.</p>
<section id="learning-rate-methods">
<h3>Learning rate methods<a class="headerlink" href="#learning-rate-methods" title="Link to this heading">#</a></h3>
<p>The code below shows object oriented implementations of the Constant,
Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All
of the classes belong to the shared abstract Scheduler class, and
share the update_change() and reset() methods allowing for any of the
schedulers to be seamlessly used during the training stage, as will
later be shown in the fit() method of the neural
network. Update_change() only has one parameter, the gradient
(<span class="math notranslate nohighlight">\(δ^l_ja^{l1}_k\)</span>), and returns the change which will be subtracted
from the weights. The reset() function takes no parameters, and resets
the desired variables. For Constant and Momentum, reset does nothing.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>import autograd.numpy as np
class Scheduler:
&quot;&quot;&quot;
Abstract class for Schedulers
&quot;&quot;&quot;
def __init__(self, eta):
self.eta = eta
# should be overwritten
def update_change(self, gradient):
raise NotImplementedError
# overwritten if needed
def reset(self):
pass
class Constant(Scheduler):
def __init__(self, eta):
super().__init__(eta)
def update_change(self, gradient):
return self.eta * gradient
def reset(self):
pass
class Momentum(Scheduler):
def __init__(self, eta: float, momentum: float):
super().__init__(eta)
self.momentum = momentum
self.change = 0
def update_change(self, gradient):
self.change = self.momentum * self.change + self.eta * gradient
return self.change
def reset(self):
pass
class Adagrad(Scheduler):
def __init__(self, eta):
super().__init__(eta)
self.G_t = None
def update_change(self, gradient):
delta = 1e-8 # avoid division ny zero
if self.G_t is None:
self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
self.G_t += gradient @ gradient.T
G_t_inverse = 1 / (
delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
)
return self.eta * gradient * G_t_inverse
def reset(self):
self.G_t = None
class AdagradMomentum(Scheduler):
def __init__(self, eta, momentum):
super().__init__(eta)
self.G_t = None
self.momentum = momentum
self.change = 0
def update_change(self, gradient):
delta = 1e-8 # avoid division ny zero
if self.G_t is None:
self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
self.G_t += gradient @ gradient.T
G_t_inverse = 1 / (
delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
)
self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse
return self.change
def reset(self):
self.G_t = None
class RMS_prop(Scheduler):
def __init__(self, eta, rho):
super().__init__(eta)
self.rho = rho
self.second = 0.0
def update_change(self, gradient):
delta = 1e-8 # avoid division ny zero
self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient
return self.eta * gradient / (np.sqrt(self.second + delta))
def reset(self):
self.second = 0.0
class Adam(Scheduler):
def __init__(self, eta, rho, rho2):
super().__init__(eta)
self.rho = rho
self.rho2 = rho2
self.moment = 0
self.second = 0
self.n_epochs = 1
def update_change(self, gradient):
delta = 1e-8 # avoid division ny zero
self.moment = self.rho * self.moment + (1 - self.rho) * gradient
self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient
moment_corrected = self.moment / (1 - self.rho**self.n_epochs)
second_corrected = self.second / (1 - self.rho2**self.n_epochs)
return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))
def reset(self):
self.n_epochs += 1
self.moment = 0
self.second = 0
</pre></div>
</div>
</div>
</div>
</section>
<section id="usage-of-the-above-learning-rate-schedulers">
<h3>Usage of the above learning rate schedulers<a class="headerlink" href="#usage-of-the-above-learning-rate-schedulers" title="Link to this heading">#</a></h3>
<p>To initalize a scheduler, simply create the object and pass in the
necessary parameters such as the learning rate and the momentum as
shown below. As the Scheduler class is an abstract class it should not
called directly, and will raise an error upon usage.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)
adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
</pre></div>
</div>
</div>
</div>
<p>Here is a small example for how a segment of code using schedulers
could look. Switching out the schedulers is simple.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>weights = np.ones((3,3))
print(f&quot;Before scheduler:\n{weights=}&quot;)
epochs = 10
for e in range(epochs):
gradient = np.random.rand(3, 3)
change = adam_scheduler.update_change(gradient)
weights = weights - change
adam_scheduler.reset()
print(f&quot;\nAfter scheduler:\n{weights=}&quot;)
</pre></div>
</div>
</div>
</div>
</section>
<section id="cost-functions">
<h3>Cost functions<a class="headerlink" href="#cost-functions" title="Link to this heading">#</a></h3>
<p>Here we discuss cost functions that can be used when creating the
neural network. Every cost function takes the target vector as its
parameter, and returns a function valued only at <span class="math notranslate nohighlight">\(x\)</span> such that it may
easily be differentiated.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>import autograd.numpy as np
def CostOLS(target):
def func(X):
return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)
return func
def CostLogReg(target):
def func(X):
return -(1.0 / target.shape[0]) * np.sum(
(target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))
)
return func
def CostCrossEntropy(target):
def func(X):
return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))
return func
</pre></div>
</div>
</div>
</div>
<p>Below we give a short example of how these cost function may be used
to obtain results if you wish to test them out on your own using
AutoGrads automatics differentiation.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>from autograd import grad
target = np.array([[1, 2, 3]]).T
a = np.array([[4, 5, 6]]).T
cost_func = CostCrossEntropy
cost_func_derivative = grad(cost_func(target))
valued_at_a = cost_func_derivative(a)
print(f&quot;Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}&quot;)
</pre></div>
</div>
</div>
</div>
</section>
<section id="id3">
<h3>Activation functions<a class="headerlink" href="#id3" title="Link to this heading">#</a></h3>
<p>Finally, before we look at the neural network, we will look at the
activation functions which can be specified between the hidden layers
and as the output function. Each function can be valued for any given
vector or matrix X, and can be differentiated via derivate().</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>import autograd.numpy as np
from autograd import elementwise_grad
def identity(X):
return X
def sigmoid(X):
try:
return 1.0 / (1 + np.exp(-X))
except FloatingPointError:
return np.where(X &gt; np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))
def softmax(X):
X = X - np.max(X, axis=-1, keepdims=True)
delta = 10e-10
return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)
def RELU(X):
return np.where(X &gt; np.zeros(X.shape), X, np.zeros(X.shape))
def LRELU(X):
delta = 10e-4
return np.where(X &gt; np.zeros(X.shape), X, delta * X)
def derivate(func):
if func.__name__ == &quot;RELU&quot;:
def func(X):
return np.where(X &gt; 0, 1, 0)
return func
elif func.__name__ == &quot;LRELU&quot;:
def func(X):
delta = 10e-4
return np.where(X &gt; 0, 1, delta)
return func
else:
return elementwise_grad(func)
</pre></div>
</div>
</div>
</div>
<p>Below follows a short demonstration of how to use an activation
function. The derivative of the activation function will be important
when calculating the output delta term during backpropagation. Note
that derivate() can also be used for cost functions for a more
generalized approach.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>z = np.array([[4, 5, 6]]).T
print(f&quot;Input to activation function:\n{z}&quot;)
act_func = sigmoid
a = act_func(z)
print(f&quot;\nOutput from {act_func.__name__} activation function:\n{a}&quot;)
act_func_derivative = derivate(act_func)
valued_at_z = act_func_derivative(a)
print(f&quot;\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}&quot;)
</pre></div>
</div>
</div>
</div>
</section>
<section id="the-neural-network">
<h3>The Neural Network<a class="headerlink" href="#the-neural-network" title="Link to this heading">#</a></h3>
<p>Now that we have gotten a good understanding of the implementation of
some important components, we can take a look at an object oriented
implementation of a feed forward neural network. The feed forward
neural network has been implemented as a class named FFNN, which can
be initiated as a regressor or classifier dependant on the choice of
cost function. The FFNN can have any number of input nodes, hidden
layers with any amount of hidden nodes, and any amount of output nodes
meaning it can perform multiclass classification as well as binary
classification and regression problems. Although there is a lot of
code present, it makes for an easy to use and generalizeable interface
for creating many types of neural networks as will be demonstrated
below.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>import math
import autograd.numpy as np
import sys
import warnings
from autograd import grad, elementwise_grad
from random import random, seed
from copy import deepcopy, copy
from typing import Tuple, Callable
from sklearn.utils import resample
warnings.simplefilter(&quot;error&quot;)
class FFNN:
&quot;&quot;&quot;
Description:
------------
Feed Forward Neural Network with interface enabling flexible design of a
nerual networks architecture and the specification of activation function
in the hidden layers and output layer respectively. This model can be used
for both regression and classification problems, depending on the output function.
Attributes:
------------
I dimensions (tuple[int]): A list of positive integers, which specifies the
number of nodes in each of the networks layers. The first integer in the array
defines the number of nodes in the input layer, the second integer defines number
of nodes in the first hidden layer and so on until the last number, which
specifies the number of nodes in the output layer.
II hidden_func (Callable): The activation function for the hidden layers
III output_func (Callable): The activation function for the output layer
IV cost_func (Callable): Our cost function
V seed (int): Sets random seed, makes results reproducible
&quot;&quot;&quot;
def __init__(
self,
dimensions: tuple[int],
hidden_func: Callable = sigmoid,
output_func: Callable = lambda x: x,
cost_func: Callable = CostOLS,
seed: int = None,
):
self.dimensions = dimensions
self.hidden_func = hidden_func
self.output_func = output_func
self.cost_func = cost_func
self.seed = seed
self.weights = list()
self.schedulers_weight = list()
self.schedulers_bias = list()
self.a_matrices = list()
self.z_matrices = list()
self.classification = None
self.reset_weights()
self._set_classification()
def fit(
self,
X: np.ndarray,
t: np.ndarray,
scheduler: Scheduler,
batches: int = 1,
epochs: int = 100,
lam: float = 0,
X_val: np.ndarray = None,
t_val: np.ndarray = None,
):
&quot;&quot;&quot;
Description:
------------
This function performs the training the neural network by performing the feedforward and backpropagation
algorithm to update the networks weights.
Parameters:
------------
I X (np.ndarray) : training data
II t (np.ndarray) : target data
III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)
IV scheduler_args (list[int]) : list of all arguments necessary for scheduler
Optional Parameters:
------------
V batches (int) : number of batches the datasets are split into, default equal to 1
VI epochs (int) : number of iterations used to train the network, default equal to 100
VII lam (float) : regularization hyperparameter lambda
VIII X_val (np.ndarray) : validation set
IX t_val (np.ndarray) : validation target set
Returns:
------------
I scores (dict) : A dictionary containing the performance metrics of the model.
The number of the metrics depends on the parameters passed to the fit-function.
&quot;&quot;&quot;
# setup
if self.seed is not None:
np.random.seed(self.seed)
val_set = False
if X_val is not None and t_val is not None:
val_set = True
# creating arrays for score metrics
train_errors = np.empty(epochs)
train_errors.fill(np.nan)
val_errors = np.empty(epochs)
val_errors.fill(np.nan)
train_accs = np.empty(epochs)
train_accs.fill(np.nan)
val_accs = np.empty(epochs)
val_accs.fill(np.nan)
self.schedulers_weight = list()
self.schedulers_bias = list()
batch_size = X.shape[0] // batches
X, t = resample(X, t)
# this function returns a function valued only at X
cost_function_train = self.cost_func(t)
if val_set:
cost_function_val = self.cost_func(t_val)
# create schedulers for each weight matrix
for i in range(len(self.weights)):
self.schedulers_weight.append(copy(scheduler))
self.schedulers_bias.append(copy(scheduler))
print(f&quot;{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}&quot;)
try:
for e in range(epochs):
for i in range(batches):
# allows for minibatch gradient descent
if i == batches - 1:
# If the for loop has reached the last batch, take all thats left
X_batch = X[i * batch_size :, :]
t_batch = t[i * batch_size :, :]
else:
X_batch = X[i * batch_size : (i + 1) * batch_size, :]
t_batch = t[i * batch_size : (i + 1) * batch_size, :]
self._feedforward(X_batch)
self._backpropagate(X_batch, t_batch, lam)
# reset schedulers for each epoch (some schedulers pass in this call)
for scheduler in self.schedulers_weight:
scheduler.reset()
for scheduler in self.schedulers_bias:
scheduler.reset()
# computing performance metrics
pred_train = self.predict(X)
train_error = cost_function_train(pred_train)
train_errors[e] = train_error
if val_set:
pred_val = self.predict(X_val)
val_error = cost_function_val(pred_val)
val_errors[e] = val_error
if self.classification:
train_acc = self._accuracy(self.predict(X), t)
train_accs[e] = train_acc
if val_set:
val_acc = self._accuracy(pred_val, t_val)
val_accs[e] = val_acc
# printing progress bar
progression = e / epochs
print_length = self._progress_bar(
progression,
train_error=train_errors[e],
train_acc=train_accs[e],
val_error=val_errors[e],
val_acc=val_accs[e],
)
except KeyboardInterrupt:
# allows for stopping training at any point and seeing the result
pass
# visualization of training progression (similiar to tensorflow progression bar)
sys.stdout.write(&quot;\r&quot; + &quot; &quot; * print_length)
sys.stdout.flush()
self._progress_bar(
1,
train_error=train_errors[e],
train_acc=train_accs[e],
val_error=val_errors[e],
val_acc=val_accs[e],
)
sys.stdout.write(&quot;&quot;)
# return performance metrics for the entire run
scores = dict()
scores[&quot;train_errors&quot;] = train_errors
if val_set:
scores[&quot;val_errors&quot;] = val_errors
if self.classification:
scores[&quot;train_accs&quot;] = train_accs
if val_set:
scores[&quot;val_accs&quot;] = val_accs
return scores
def predict(self, X: np.ndarray, *, threshold=0.5):
&quot;&quot;&quot;
Description:
------------
Performs prediction after training of the network has been finished.
Parameters:
------------
I X (np.ndarray): The design matrix, with n rows of p features each
Optional Parameters:
------------
II threshold (float) : sets minimal value for a prediction to be predicted as the positive class
in classification problems
Returns:
------------
I z (np.ndarray): A prediction vector (row) for each row in our design matrix
This vector is thresholded if regression=False, meaning that classification results
in a vector of 1s and 0s, while regressions in an array of decimal numbers
&quot;&quot;&quot;
predict = self._feedforward(X)
if self.classification:
return np.where(predict &gt; threshold, 1, 0)
else:
return predict
def reset_weights(self):
&quot;&quot;&quot;
Description:
------------
Resets/Reinitializes the weights in order to train the network for a new problem.
&quot;&quot;&quot;
if self.seed is not None:
np.random.seed(self.seed)
self.weights = list()
for i in range(len(self.dimensions) - 1):
weight_array = np.random.randn(
self.dimensions[i] + 1, self.dimensions[i + 1]
)
weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01
self.weights.append(weight_array)
def _feedforward(self, X: np.ndarray):
&quot;&quot;&quot;
Description:
------------
Calculates the activation of each layer starting at the input and ending at the output.
Each following activation is calculated from a weighted sum of each of the preceeding
activations (except in the case of the input layer).
Parameters:
------------
I X (np.ndarray): The design matrix, with n rows of p features each
Returns:
------------
I z (np.ndarray): A prediction vector (row) for each row in our design matrix
&quot;&quot;&quot;
# reset matrices
self.a_matrices = list()
self.z_matrices = list()
# if X is just a vector, make it into a matrix
if len(X.shape) == 1:
X = X.reshape((1, X.shape[0]))
# Add a coloumn of zeros as the first coloumn of the design matrix, in order
# to add bias to our data
bias = np.ones((X.shape[0], 1)) * 0.01
X = np.hstack([bias, X])
# a^0, the nodes in the input layer (one a^0 for each row in X - where the
# exponent indicates layer number).
a = X
self.a_matrices.append(a)
self.z_matrices.append(a)
# The feed forward algorithm
for i in range(len(self.weights)):
if i &lt; len(self.weights) - 1:
z = a @ self.weights[i]
self.z_matrices.append(z)
a = self.hidden_func(z)
# bias column again added to the data here
bias = np.ones((a.shape[0], 1)) * 0.01
a = np.hstack([bias, a])
self.a_matrices.append(a)
else:
try:
# a^L, the nodes in our output layers
z = a @ self.weights[i]
a = self.output_func(z)
self.a_matrices.append(a)
self.z_matrices.append(z)
except Exception as OverflowError:
print(
&quot;OverflowError in fit() in FFNN\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling&quot;
)
# this will be a^L
return a
def _backpropagate(self, X, t, lam):
&quot;&quot;&quot;
Description:
------------
Performs the backpropagation algorithm. In other words, this method
calculates the gradient of all the layers starting at the
output layer, and moving from right to left accumulates the gradient until
the input layer is reached. Each layers respective weights are updated while
the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).
Parameters:
------------
I X (np.ndarray): The design matrix, with n rows of p features each.
II t (np.ndarray): The target vector, with n rows of p targets.
III lam (float32): regularization parameter used to punish the weights in case of overfitting
Returns:
------------
No return value.
&quot;&quot;&quot;
out_derivative = derivate(self.output_func)
hidden_derivative = derivate(self.hidden_func)
for i in range(len(self.weights) - 1, -1, -1):
# delta terms for output
if i == len(self.weights) - 1:
# for multi-class classification
if (
self.output_func.__name__ == &quot;softmax&quot;
):
delta_matrix = self.a_matrices[i + 1] - t
# for single class classification
else:
cost_func_derivative = grad(self.cost_func(t))
delta_matrix = out_derivative(
self.z_matrices[i + 1]
) * cost_func_derivative(self.a_matrices[i + 1])
# delta terms for hidden layer
else:
delta_matrix = (
self.weights[i + 1][1:, :] @ delta_matrix.T
).T * hidden_derivative(self.z_matrices[i + 1])
# calculate gradient
gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix
gradient_bias = np.sum(delta_matrix, axis=0).reshape(
1, delta_matrix.shape[1]
)
# regularization term
gradient_weights += self.weights[i][1:, :] * lam
# use scheduler
update_matrix = np.vstack(
[
self.schedulers_bias[i].update_change(gradient_bias),
self.schedulers_weight[i].update_change(gradient_weights),
]
)
# update weights and bias
self.weights[i] -= update_matrix
def _accuracy(self, prediction: np.ndarray, target: np.ndarray):
&quot;&quot;&quot;
Description:
------------
Calculates accuracy of given prediction to target
Parameters:
------------
I prediction (np.ndarray): vector of predicitons output network
(1s and 0s in case of classification, and real numbers in case of regression)
II target (np.ndarray): vector of true values (What the network ideally should predict)
Returns:
------------
A floating point number representing the percentage of correctly classified instances.
&quot;&quot;&quot;
assert prediction.size == target.size
return np.average((target == prediction))
def _set_classification(self):
&quot;&quot;&quot;
Description:
------------
Decides if FFNN acts as classifier (True) og regressor (False),
sets self.classification during init()
&quot;&quot;&quot;
self.classification = False
if (
self.cost_func.__name__ == &quot;CostLogReg&quot;
or self.cost_func.__name__ == &quot;CostCrossEntropy&quot;
):
self.classification = True
def _progress_bar(self, progression, **kwargs):
&quot;&quot;&quot;
Description:
------------
Displays progress of training
&quot;&quot;&quot;
print_length = 40
num_equals = int(progression * print_length)
num_not = print_length - num_equals
arrow = &quot;&gt;&quot; if num_equals &gt; 0 else &quot;&quot;
bar = &quot;[&quot; + &quot;=&quot; * (num_equals - 1) + arrow + &quot;-&quot; * num_not + &quot;]&quot;
perc_print = self._format(progression * 100, decimals=5)
line = f&quot; {bar} {perc_print}% &quot;
for key in kwargs:
if not np.isnan(kwargs[key]):
value = self._format(kwargs[key], decimals=4)
line += f&quot;| {key}: {value} &quot;
sys.stdout.write(&quot;\r&quot; + line)
sys.stdout.flush()
return len(line)
def _format(self, value, decimals=4):
&quot;&quot;&quot;
Description:
------------
Formats decimal numbers for progress bar
&quot;&quot;&quot;
if value &gt; 0:
v = value
elif value &lt; 0:
v = -10 * value
else:
v = 1
n = 1 + math.floor(math.log10(v))
if n &gt;= decimals - 1:
return str(round(value))
return f&quot;{value:.{decimals-n-1}f}&quot;
</pre></div>
</div>
</div>
</div>
<p>Before we make a model, we will quickly generate a dataset we can use
for our linear regression problem as shown below</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>import autograd.numpy as np
from sklearn.model_selection import train_test_split
def SkrankeFunction(x, y):
return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)
def create_X(x, y, n):
if len(x.shape) &gt; 1:
x = np.ravel(x)
y = np.ravel(y)
N = len(x)
l = int((n + 1) * (n + 2) / 2) # Number of elements in beta
X = np.ones((N, l))
for i in range(1, n + 1):
q = int((i) * (i + 1) / 2)
for k in range(i + 1):
X[:, q + k] = (x ** (i - k)) * (y**k)
return X
step=0.5
x = np.arange(0, 1, step)
y = np.arange(0, 1, step)
x, y = np.meshgrid(x, y)
target = SkrankeFunction(x, y)
target = target.reshape(target.shape[0], 1)
poly_degree=3
X = create_X(x, y, poly_degree)
X_train, X_test, t_train, t_test = train_test_split(X, target)
</pre></div>
</div>
</div>
</div>
<p>Now that we have our dataset ready for the regression, we can create
our regressor. Note that with the seed parameter, we can make sure our
results stay the same every time we run the neural network. For
inititialization, we simply specify the dimensions (we wish the amount
of input nodes to be equal to the datapoints, and the output to
predict one value).</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>input_nodes = X_train.shape[1]
output_nodes = 1
linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)
</pre></div>
</div>
</div>
</div>
<p>We then fit our model with our training data using the scheduler of our choice.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>linear_regression.reset_weights() # reset weights such that previous runs or reruns don&#39;t affect the weights
scheduler = Constant(eta=1e-3)
scores = linear_regression.fit(X_train, t_train, scheduler)
</pre></div>
</div>
</div>
</div>
<p>Due to the progress bar we can see the MSE (train_error) throughout
the FFNNs training. Note that the fit() function has some optional
parameters with defualt arguments. For example, the regularization
hyperparameter can be left ignored if not needed, and equally the FFNN
will by default run for 100 epochs. These can easily be changed, such
as for example:</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>linear_regression.reset_weights() # reset weights such that previous runs or reruns don&#39;t affect the weights
scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)
</pre></div>
</div>
</div>
</div>
<p>We see that given more epochs to train on, the regressor reaches a lower MSE.</p>
<p>Let us then switch to a binary classification. We use a binary
classification dataset, and follow a similar setup to the regression
case.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>from sklearn.datasets import load_breast_cancer
from sklearn.preprocessing import MinMaxScaler
wisconsin = load_breast_cancer()
X = wisconsin.data
target = wisconsin.target
target = target.reshape(target.shape[0], 1)
X_train, X_val, t_train, t_val = train_test_split(X, target)
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_val = scaler.transform(X_val)
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>input_nodes = X_train.shape[1]
output_nodes = 1
logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
</pre></div>
</div>
</div>
</div>
<p>We will now make use of our validation data by passing it into our fit function as a keyword argument</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>logistic_regression.reset_weights() # reset weights such that previous runs or reruns don&#39;t affect the weights
scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
</pre></div>
</div>
</div>
</div>
<p>Finally, we will create a neural network with 2 hidden layers with activation functions.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>input_nodes = X_train.shape[1]
hidden_nodes1 = 100
hidden_nodes2 = 30
output_nodes = 1
dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>neural_network.reset_weights() # reset weights such that previous runs or reruns don&#39;t affect the weights
scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)
</pre></div>
</div>
</div>
</div>
</section>
<section id="multiclass-classification">
<h3>Multiclass classification<a class="headerlink" href="#multiclass-classification" title="Link to this heading">#</a></h3>
<p>Finally, we will demonstrate the use case of multiclass classification
using our FFNN with the famous MNIST dataset, which contain images of
digits between the range of 0 to 9.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>from sklearn.datasets import load_digits
def onehot(target: np.ndarray):
onehot = np.zeros((target.size, target.max() + 1))
onehot[np.arange(target.size), target] = 1
return onehot
digits = load_digits()
X = digits.data
target = digits.target
target = onehot(target)
input_nodes = 64
hidden_nodes1 = 100
hidden_nodes2 = 30
output_nodes = 10
dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)
multiclass.reset_weights() # reset weights such that previous runs or reruns don&#39;t affect the weights
scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)
scores = multiclass.fit(X, target, scheduler, epochs=1000)
</pre></div>
</div>
</div>
</div>
</section>
</section>
<section id="testing-the-xor-gate-and-other-gates">
<h2>Testing the XOR gate and other gates<a class="headerlink" href="#testing-the-xor-gate-and-other-gates" title="Link to this heading">#</a></h2>
<p>Let us now use our code to test the XOR gate.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)
# The XOR gate
yXOR = np.array( [[ 0], [1] ,[1], [0]])
input_nodes = X.shape[1]
output_nodes = 1
logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)
logistic_regression.reset_weights() # reset weights such that previous runs or reruns don&#39;t affect the weights
scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999)
scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)
</pre></div>
</div>
</div>
</div>
<p>Not bad, but the results depend strongly on the learning reate. Try different learning rates.</p>
</section>
</section>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
name: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</article>
<footer class="prev-next-footer d-print-none">
<div class="prev-next-area">
<a class="left-prev"
href="exercisesweek41.html"
title="previous page">
<i class="fa-solid fa-angle-left"></i>
<div class="prev-next-info">
<p class="prev-next-subtitle">previous</p>
<p class="prev-next-title">Exercises week 41</p>
</div>
</a>
<a class="right-next"
href="exercisesweek42.html"
title="next page">
<div class="prev-next-info">
<p class="prev-next-subtitle">next</p>
<p class="prev-next-title">Exercises week 42</p>
</div>
<i class="fa-solid fa-angle-right"></i>
</a>
</div>
</footer>
</div>
<div class="bd-sidebar-secondary bd-toc"><div class="sidebar-secondary-items sidebar-secondary__inner">
<div class="sidebar-secondary-item">
<div class="page-toc tocsection onthispage">
<i class="fa-solid fa-list"></i> Contents
</div>
<nav class="bd-toc-nav page-toc">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#lecture-october-13-2025">Lecture October 13, 2025</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#readings-and-videos">Readings and videos</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#material-for-the-lab-sessions-on-tuesday-and-wednesday">Material for the lab sessions on Tuesday and Wednesday</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#lecture-material-writing-a-code-which-implements-a-feed-forward-neural-network">Lecture material: Writing a code which implements a feed-forward neural network</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#mathematics-of-deep-learning">Mathematics of deep learning</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#reminder-on-books-with-hands-on-material-and-codes">Reminder on books with hands-on material and codes</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#reading-recommendations">Reading recommendations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#reminder-from-last-week-first-network-example-simple-percepetron-with-one-input">Reminder from last week: First network example, simple percepetron with one input</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-a-simple-neural-network-with-no-hidden-layer">Layout of a simple neural network with no hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#optimizing-the-parameters">Optimizing the parameters</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#adding-a-hidden-layer">Adding a hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-a-simple-neural-network-with-one-hidden-layer">Layout of a simple neural network with one hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-derivatives">The derivatives</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#important-observations">Important observations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-training">The training</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#code-example">Code example</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#simple-neural-network-and-the-back-propagation-equations">Simple neural network and the back propagation equations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-a-simple-neural-network-with-two-input-nodes-one-hidden-layer-with-two-hidden-noeds-and-one-output-node">Layout of a simple neural network with two input nodes, one hidden layer with two hidden noeds and one output node</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-ouput-layer">The ouput layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#compact-expressions">Compact expressions</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#output-layer">Output layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#explicit-derivatives">Explicit derivatives</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#derivatives-of-the-hidden-layer">Derivatives of the hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#final-expression">Final expression</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#completing-the-list">Completing the list</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#final-expressions-for-the-biases-of-the-hidden-layer">Final expressions for the biases of the hidden layer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#gradient-expressions">Gradient expressions</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-equations-for-a-neural-network">Setting up the equations for a neural network</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-a-neural-network-with-three-hidden-layers-last-layer-l-l-4-first-layer-l-0">Layout of a neural network with three hidden layers (last layer = <span class="math notranslate nohighlight">\(l=L=4\)</span>, first layer <span class="math notranslate nohighlight">\(l=0\)</span>)</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#definitions">Definitions</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#inputs-to-the-activation-function">Inputs to the activation function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layout-of-input-to-first-hidden-layer-l-1-from-input-layer-l-0">Layout of input to first hidden layer <span class="math notranslate nohighlight">\(l=1\)</span> from input layer <span class="math notranslate nohighlight">\(l=0\)</span></a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#derivatives-and-the-chain-rule">Derivatives and the chain rule</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#derivative-of-the-cost-function">Derivative of the cost function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-back-propagation-equations-for-a-neural-network">The back propagation equations for a neural network</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#analyzing-the-last-results">Analyzing the last results</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-considerations">More considerations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#derivatives-in-terms-of-z-j-l">Derivatives in terms of <span class="math notranslate nohighlight">\(z_j^L\)</span></a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#bringing-it-together">Bringing it together</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#final-back-propagating-equation">Final back propagating equation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#using-the-chain-rule-and-summing-over-all-k-entries">Using the chain rule and summing over all <span class="math notranslate nohighlight">\(k\)</span> entries</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-back-propagation-algorithm-and-algorithm-for-a-feed-forward-nn-initalizations">Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-back-propagation-algorithm-part-1">Setting up the back propagation algorithm, part 1</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-back-propagation-algorithm-part-2">Setting up the back propagation algorithm, part 2</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-the-back-propagation-algorithm-part-3">Setting up the Back propagation algorithm, part 3</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#updating-the-gradients">Updating the gradients</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#activation-functions">Activation functions</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#activation-functions-logistic-and-hyperbolic-ones">Activation functions, Logistic and Hyperbolic ones</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#relevance">Relevance</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#vanishing-gradients">Vanishing gradients</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#exploding-gradients">Exploding gradients</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#is-the-logistic-activation-function-sigmoid-our-choice">Is the Logistic activation function (Sigmoid) our choice?</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#logistic-function-as-the-root-of-problems">Logistic function as the root of problems</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-derivative-of-the-logistic-funtion">The derivative of the Logistic funtion</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#insights-from-the-paper-by-glorot-and-bengio">Insights from the paper by Glorot and Bengio</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-relu-function-family">The RELU function family</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#elu-function">ELU function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#which-activation-function-should-we-use">Which activation function should we use?</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-on-activation-functions-output-layers">More on activation functions, output layers</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#fine-tuning-neural-network-hyperparameters">Fine-tuning neural network hyperparameters</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#hidden-layers">Hidden layers</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#batch-normalization">Batch Normalization</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#dropout">Dropout</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#gradient-clipping">Gradient Clipping</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#a-top-down-perspective-on-neural-networks">A top-down perspective on Neural networks</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-top-down-perspectives">More top-down perspectives</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#limitations-of-supervised-learning-with-deep-networks">Limitations of supervised learning with deep networks</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#limitations-of-nns">Limitations of NNs</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#homogeneous-data">Homogeneous data</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-limitations">More limitations</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setting-up-a-multi-layer-perceptron-model-for-classification">Setting up a Multi-layer perceptron model for classification</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#defining-the-cost-function">Defining the cost function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#example-binary-classification-problem">Example: binary classification problem</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-softmax-function">The Softmax function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#developing-a-code-for-doing-neural-networks-with-back-propagation">Developing a code for doing neural networks with back propagation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#collect-and-pre-process-data">Collect and pre-process data</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#train-and-test-datasets">Train and test datasets</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#define-model-and-architecture">Define model and architecture</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#layers">Layers</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#weights-and-biases">Weights and biases</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#feed-forward-pass">Feed-forward pass</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#matrix-multiplications">Matrix multiplications</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#choose-cost-function-and-optimizer">Choose cost function and optimizer</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#optimizing-the-cost-function">Optimizing the cost function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#regularization">Regularization</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#matrix-multiplication">Matrix multiplication</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#improving-performance">Improving performance</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#full-object-oriented-implementation">Full object-oriented implementation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#evaluate-model-performance-on-test-data">Evaluate model performance on test data</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#adjust-hyperparameters">Adjust hyperparameters</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#visualization">Visualization</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#scikit-learn-implementation">scikit-learn implementation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#id1">Visualization</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#building-neural-networks-in-tensorflow-and-keras">Building neural networks in Tensorflow and Keras</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#tensorflow">Tensorflow</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#using-keras">Using Keras</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#id2">Collect and pre-process data</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#building-a-neural-network-code">Building a neural network code</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#learning-rate-methods">Learning rate methods</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#usage-of-the-above-learning-rate-schedulers">Usage of the above learning rate schedulers</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#cost-functions">Cost functions</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#id3">Activation functions</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#the-neural-network">The Neural Network</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#multiclass-classification">Multiclass classification</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#testing-the-xor-gate-and-other-gates">Testing the XOR gate and other gates</a></li>
</ul>
</nav></div>
</div></div>
</div>
<footer class="bd-footer-content">
<div class="bd-footer-content__inner container">
<div class="footer-item">
<p class="component-author">
By Morten Hjorth-Jensen
</p>
</div>
<div class="footer-item">
<p class="copyright">
© Copyright 2023.
<br/>
</p>
</div>
<div class="footer-item">
</div>
<div class="footer-item">
</div>
</div>
</footer>
</main>
</div>
</div>
<!-- Scripts loaded after <body> so the DOM is not blocked -->
<script src="_static/scripts/bootstrap.js?digest=dfe6caa3a7d634c4db9b"></script>
<script src="_static/scripts/pydata-sphinx-theme.js?digest=dfe6caa3a7d634c4db9b"></script>
<footer class="bd-footer">
</footer>
</body>
</html>