Files
FYS-STK4155/doc/pub/week42/html/week42.html
T
Morten Hjorth-Jensen 20e0d26bc3 update
2022-10-21 15:37:52 +02:00

4428 lines
271 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.
<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week42.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=week42 --no_mako
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/doconce/doconce/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Week 42 Solving differential equations and Convolutional (CNN)">
<title>Week 42 Solving differential equations and Convolutional (CNN)</title>
<style type="text/css">
/* bloodish style */
body {
font-family: Helvetica, Verdana, Arial, Sans-serif;
color: #404040;
background: #ffffff;
}
h1 { font-size: 1.8em; color: #8A0808; }
h2 { font-size: 1.6em; color: #8A0808; }
h3 { font-size: 1.4em; color: #8A0808; }
h4 { font-size: 1.2em; color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
p { text-indent: 0px; }
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-style: normal; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa; }div.highlight {
border: 1px solid #cfcfcf;
border-radius: 2px;
line-height: 1.21429em;
}
div.cell {
width: 100%;
padding: 5px 5px 5px 0;
margin: 0;
outline: none;
}
div.input {
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.inner_cell {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
box-flex: 1;
flex: 1;
}
div.input_area {
border: 1px solid #cfcfcf;
border-radius: 4px;
background: #f7f7f7;
line-height: 1.21429em;
}
div.input_area > div.highlight {
margin: .4em;
border: none;
padding: 0;
background-color: transparent;
}
div.output_wrapper {
position: relative;
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
.output {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
div.output_area {
padding: 0;
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.output_subarea {
padding: .4em .4em 0 .4em;
box-flex: 1;
flex: 1;
}
div.output_text {
text-align: left;
color: #000;
line-height: 1.21429em;
}
.alert-text-small { font-size: 80%; }
.alert-text-large { font-size: 130%; }
.alert-text-normal { font-size: 90%; }
.alert {
padding:8px 35px 8px 14px; margin-bottom:18px;
text-shadow:0 1px 0 rgba(255,255,255,0.5);
border:1px solid #bababa;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
color: #555;
background-color: #f8f8f8;
background-position: 10px 5px;
background-repeat: no-repeat;
background-size: 38px;
padding-left: 55px;
width: 75%;
}
.alert-block {padding-top:14px; padding-bottom:14px}
.alert-block > p, .alert-block > ul {margin-bottom:1em}
.alert li {margin-top: 1em}
.alert-block p+p {margin-top:5px}
.alert-notice { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_notice.png); }
.alert-summary { background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_summary.png); }
.alert-warning { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_warning.png); }
.alert-question {background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_question.png); }
div { text-align: justify; text-justify: inter-word; }
.tab {
padding-left: 1.5em;
}
div.toc p,a {
line-height: 1.3;
margin-top: 1.1;
margin-bottom: 1.1;
}
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Plan for week 42', 2, None, 'plan-for-week-42'),
('Using Automatic differentiation',
2,
None,
'using-automatic-differentiation'),
('Back propagation and automatic differentiation',
2,
None,
'back-propagation-and-automatic-differentiation'),
('Solving ODEs with Deep Learning',
2,
None,
'solving-odes-with-deep-learning'),
('Ordinary Differential Equations',
2,
None,
'ordinary-differential-equations'),
('The trial solution', 2, None, 'the-trial-solution'),
('Minimization process', 2, None, 'minimization-process'),
('Minimizing the cost function using gradient descent and '
'automatic differentiation',
2,
None,
'minimizing-the-cost-function-using-gradient-descent-and-automatic-differentiation'),
('Example: Exponential decay',
2,
None,
'example-exponential-decay'),
('The function to solve for',
2,
None,
'the-function-to-solve-for'),
('The trial solution', 2, None, 'the-trial-solution'),
('Setup of Network', 2, None, 'setup-of-network'),
('Reformulating the problem',
2,
None,
'reformulating-the-problem'),
('More technicalities', 2, None, 'more-technicalities'),
('More details', 2, None, 'more-details'),
('A possible implementation of a neural network',
2,
None,
'a-possible-implementation-of-a-neural-network'),
('Technicalities', 2, None, 'technicalities'),
('Final technicalities I', 2, None, 'final-technicalities-i'),
('Final technicalities II', 2, None, 'final-technicalities-ii'),
('Final technicalities III', 2, None, 'final-technicalities-iii'),
('Final technicalities IV', 2, None, 'final-technicalities-iv'),
('Back propagation', 2, None, 'back-propagation'),
('Gradient descent', 2, None, 'gradient-descent'),
('The code for solving the ODE',
2,
None,
'the-code-for-solving-the-ode'),
('The network with one input layer, specified number of hidden '
'layers, and one output layer',
2,
None,
'the-network-with-one-input-layer-specified-number-of-hidden-layers-and-one-output-layer'),
('Example: Population growth',
2,
None,
'example-population-growth'),
('Setting up the problem', 2, None, 'setting-up-the-problem'),
('The trial solution', 2, None, 'the-trial-solution'),
('The program using Autograd',
2,
None,
'the-program-using-autograd'),
('Using forward Euler to solve the ODE',
2,
None,
'using-forward-euler-to-solve-the-ode'),
('Example: Solving the one dimensional Poisson equation',
2,
None,
'example-solving-the-one-dimensional-poisson-equation'),
('The specific equation to solve for',
2,
None,
'the-specific-equation-to-solve-for'),
('Solving the equation using Autograd',
2,
None,
'solving-the-equation-using-autograd'),
('Comparing with a numerical scheme',
2,
None,
'comparing-with-a-numerical-scheme'),
('Setting up the code', 2, None, 'setting-up-the-code'),
('Partial Differential Equations',
2,
None,
'partial-differential-equations'),
('Type of problem', 2, None, 'type-of-problem'),
('Network requirements', 2, None, 'network-requirements'),
('More details', 2, None, 'more-details'),
('Example: The diffusion equation',
2,
None,
'example-the-diffusion-equation'),
('Defining the problem', 2, None, 'defining-the-problem'),
('Setting up the network using Autograd',
2,
None,
'setting-up-the-network-using-autograd'),
('Setting up the network using Autograd; The trial solution',
2,
None,
'setting-up-the-network-using-autograd-the-trial-solution'),
('Why the jacobian?', 2, None, 'why-the-jacobian'),
('Setting up the network using Autograd; The full program',
2,
None,
'setting-up-the-network-using-autograd-the-full-program'),
('Example: Solving the wave equation with Neural Networks',
2,
None,
'example-solving-the-wave-equation-with-neural-networks'),
('The problem to solve for', 2, None, 'the-problem-to-solve-for'),
('The trial solution', 2, None, 'the-trial-solution'),
('The analytical solution', 2, None, 'the-analytical-solution'),
('Solving the wave equation - the full program using Autograd',
2,
None,
'solving-the-wave-equation-the-full-program-using-autograd'),
('Resources on differential equations and deep learning',
2,
None,
'resources-on-differential-equations-and-deep-learning'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('What is the Difference', 2, None, 'what-is-the-difference'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('Key Idea', 2, None, 'key-idea'),
('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'),
('Convolution Examples: Polynomial multiplication',
2,
None,
'convolution-examples-polynomial-multiplication'),
('Efficient Polynomial Multiplication',
2,
None,
'efficient-polynomial-multiplication'),
('A more efficient way of coding the above Convolution',
2,
None,
'a-more-efficient-way-of-coding-the-above-convolution'),
('Convolution Examples: Principle of Superposition and Periodic '
'Forces (Fourier Transforms)',
2,
None,
'convolution-examples-principle-of-superposition-and-periodic-forces-fourier-transforms'),
('Principle of Superposition',
2,
None,
'principle-of-superposition'),
('Simple Code Example', 2, None, 'simple-code-example'),
('Wrapping up Fourier transforms',
2,
None,
'wrapping-up-fourier-transforms'),
('Finding the Coefficients', 2, None, 'finding-the-coefficients'),
('Final words on Fourier Transforms',
2,
None,
'final-words-on-fourier-transforms'),
('Two-dimensional Objects', 2, None, 'two-dimensional-objects'),
('Cross-Correlation', 2, None, 'cross-correlation'),
('More on Dimensionalities', 2, None, 'more-on-dimensionalities'),
('Further Dimensionality Remarks',
2,
None,
'further-dimensionality-remarks'),
('CNNs in more detail, Lecture from IN5400',
2,
None,
'cnns-in-more-detail-lecture-from-in5400'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model')]}
end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "AMS" },
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
}
});
</script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- ------------------- main content ---------------------- -->
<center>
<h1>Week 42 Solving differential equations and Convolutional (CNN)</h1>
</center> <!-- document title -->
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<!-- institution(s) -->
<center>
[1] <b>Department of Physics, University of Oslo</b>
</center>
<center>
[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b>
</center>
<br>
<center>
<h4>Oct 21, 2022</h4>
</center> <!-- date -->
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plan-for-week-42">Plan for week 42 </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ul>
<li> Thursday: Solving differential equations with Neural Networks and intro to <b>Tensorflow</b> with examples.</li>
<ul>
<li> <a href="https://youtu.be/MdYT6uwOkT0" target="_blank">Video of lecture</a></li>
</ul>
<li> Friday: Convolutional Neural Networks.</li>
<ul>
<li> <a href="https://youtu.be/3bDkrB-E7cU" target="_blank">Video of lecture</a></li>
</ul>
<li> Reading recommendations:
<ol type="a"></li>
<li> See lecture notes for week 42 at <a href="https://compphysics.github.io/MachineLearning/doc/web/course.html." target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/web/course.html.</tt></a></li>
<li> For Tensorflow and Keras, see lecture notes from week 41</li>
<li> For neural networks we recommend Goodfellow et al chapters 6 and 7. For CNNs, see Goodfellow et al chapter 9. See also chapter 11 and 12 on practicalities and applications</li>
<li> Reading suggestions for implementation of CNNs: <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf" target="_blank">Aurelien Geron's chapter 13</a>.</li>
</ol>
</ul>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b>Excellent lectures on CNNs and Neural Networks</b>
<p>
<ul>
<li> <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi" target="_blank">Video on Deep Learning</a></li>
<li> <a href="https://www.youtube.com/watch?v=iaSUYvmCekI&ab_channel=AlexanderAmini" target="_blank">Video on Convolutional Neural Networks from MIT</a></li>
<li> <a href="https://www.youtube.com/watch?v=bNb2fEVKeEo&list=PLC1qU-LWwrF64f4QKQT-Vg5Wr4qEE1Zxk&index=6&ab_channel=StanfordUniversitySchoolofEngineering" target="_blank">Video on CNNs from Stanford</a></li>
</ul>
</div>
<p>m</p>
<div class="alert alert-block alert-block alert-text-normal">
<b>And Lecture material on CNNs</b>
<p>
<ul>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/v19/material/week5/in5400_2019_week5_convolutional_nerual_networks.pdf" target="_blank">Lectures from IN5400 spring 2019</a></li>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/v21/lecture-slides/in5400_2021_w5_lecture_convolutions.pdf" target="_blank">Lectures from IN5400 spring 2021</a></li>
<li> <a href="http://neuralnetworksanddeeplearning.com/chap6.html" target="_blank">See also Michael Nielsen's Lectures</a></li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="using-automatic-differentiation">Using Automatic differentiation </h2>
<p>a
In our discussions of ordinary differential equations
we will also study the usage of <a href="https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola" target="_blank">Autograd</a> in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from <a href="https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html" target="_blank">week 39</a> and the <a href="https://github.com/HIPS/autograd" target="_blank">Autograd documentation</a>.
t
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="back-propagation-and-automatic-differentiation">Back propagation and automatic differentiation </h2>
<p>For more details on the back propagation algorithm and automatic differentiation see</p>
<ol>
<li> <a href="https://www.jmlr.org/papers/volume18/17-468/17-468.pdf" target="_blank"><tt>https://www.jmlr.org/papers/volume18/17-468/17-468.pdf</tt></a></li>
<li> <a href="https://deepimaging.github.io/lectures/lecture_11_Backpropagation.pdf" target="_blank"><tt>https://deepimaging.github.io/lectures/lecture_11_Backpropagation.pdf</tt></a></li>
<li> Slides 12-44 at URL":http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf"</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="solving-odes-with-deep-learning">Solving ODEs with Deep Learning </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>The Universal Approximation Theorem states that a neural network can
approximate any function at a single hidden layer along with one input
and output layer to any given precision.
</p>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b>Book on solving differential equations with ML methods</b>
<p>
<p><a href="https://www.springer.com/gp/book/9789401798150" target="_blank">An Introduction to Neural Network Methods for Differential Equations</a>, by Yadav and Kumar.</p>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b>Master thesis on applying deep learning to problems in mechanics</b>
<p>
<p><a href="https://www.duo.uio.no/handle/10852/79212" target="_blank">Using Deep Reinforcement Learning for Active Flow Control</a>, by Marius Holm</p>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b>Thanks to Kristine Baluka Hein</b>
<p>
<p>The lectures on differential equations were developed by Kristine Baluka Hein, now PhD student at IFI.
A great thanks to Kristine.
</p>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="ordinary-differential-equations">Ordinary Differential Equations </h2>
<p>An ordinary differential equation (ODE) is an equation involving functions having one variable.</p>
<p>In general, an ordinary differential equation looks like</p>
$$
\begin{equation} \label{ode}
f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) = 0
\end{equation}
$$
<p>where \( g(x) \) is the function to find, and \( g^{(n)}(x) \) is the \( n \)-th derivative of \( g(x) \).</p>
<p>The \( f\left(x, g(x), g'(x), g''(x), \, \dots \, , g^{(n)}(x)\right) \) is just a way to write that there is an expression involving \( x \) and \( g(x), \ g'(x), \ g''(x), \, \dots \, , \text{ and } g^{(n)}(x) \) on the left side of the equality sign in \eqref{ode}.
The highest order of derivative, that is the value of \( n \), determines to the order of the equation.
The equation is referred to as a \( n \)-th order ODE.
Along with \eqref{ode}, some additional conditions of the function \( g(x) \) are typically given
for the solution to be unique.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-trial-solution">The trial solution </h2>
<p>Let the trial solution \( g_t(x) \) be</p>
$$
\begin{equation}
g_t(x) = h_1(x) + h_2(x,N(x,P))
\label{_auto1}
\end{equation}
$$
<p>where \( h_1(x) \) is a function that makes \( g_t(x) \) satisfy a given set
of conditions, \( N(x,P) \) a neural network with weights and biases
described by \( P \) and \( h_2(x, N(x,P)) \) some expression involving the
neural network. The role of the function \( h_2(x, N(x,P)) \), is to
ensure that the output from \( N(x,P) \) is zero when \( g_t(x) \) is
evaluated at the values of \( x \) where the given conditions must be
satisfied. The function \( h_1(x) \) should alone make \( g_t(x) \) satisfy
the conditions.
</p>
<p>But what about the network \( N(x,P) \)?</p>
<p>As described previously, an optimization method could be used to minimize the parameters of a neural network, that being its weights and biases, through backward propagation.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="minimization-process">Minimization process </h2>
<p>For the minimization to be defined, we need to have a cost function at hand to minimize.</p>
<p>It is given that \( f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) \) should be equal to zero in \eqref{ode}.
We can choose to consider the mean squared error as the cost function for an input \( x \).
Since we are looking at one input, the cost function is just \( f \) squared.
The cost function \( c\left(x, P \right) \) can therefore be expressed as
</p>
$$
C\left(x, P\right) = \big(f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right)\big)^2
$$
<p>If \( N \) inputs are given as a vector \( \boldsymbol{x} \) with elements \( x_i \) for \( i = 1,\dots,N \),
the cost function becomes
</p>
$$
\begin{equation} \label{cost}
C\left(\boldsymbol{x}, P\right) = \frac{1}{N} \sum_{i=1}^N \big(f\left(x_i, \, g(x_i), \, g'(x_i), \, g''(x_i), \, \dots \, , \, g^{(n)}(x_i)\right)\big)^2
\end{equation}
$$
<p>The neural net should then find the parameters \( P \) that minimizes the cost function in
\eqref{cost} for a set of \( N \) training samples \( x_i \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="minimizing-the-cost-function-using-gradient-descent-and-automatic-differentiation">Minimizing the cost function using gradient descent and automatic differentiation </h2>
<p>To perform the minimization using gradient descent, the gradient of \( C\left(\boldsymbol{x}, P\right) \) is needed.
It might happen so that finding an analytical expression of the gradient of \( C(\boldsymbol{x}, P) \) from \eqref{cost} gets too messy, depending on which cost function one desires to use.
</p>
<p>Luckily, there exists libraries that makes the job for us through automatic differentiation.
Automatic differentiation is a method of finding the derivatives numerically with very high precision.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="example-exponential-decay">Example: Exponential decay </h2>
<p>An exponential decay of a quantity \( g(x) \) is described by the equation</p>
$$
\begin{equation} \label{solve_expdec}
g'(x) = -\gamma g(x)
\end{equation}
$$
<p>with \( g(0) = g_0 \) for some chosen initial value \( g_0 \).</p>
<p>The analytical solution of \eqref{solve_expdec} is</p>
$$
\begin{equation}
g(x) = g_0 \exp\left(-\gamma x\right)
\label{_auto2}
\end{equation}
$$
<p>Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of \eqref{solve_expdec}.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-function-to-solve-for">The function to solve for </h2>
<p>The program will use a neural network to solve</p>
$$
\begin{equation} \label{solveode}
g'(x) = -\gamma g(x)
\end{equation}
$$
<p>where \( g(0) = g_0 \) with \( \gamma \) and \( g_0 \) being some chosen values.</p>
<p>In this example, \( \gamma = 2 \) and \( g_0 = 10 \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-trial-solution">The trial solution </h2>
<p>To begin with, a trial solution \( g_t(t) \) must be chosen. A general trial solution for ordinary differential equations could be</p>
$$
g_t(x, P) = h_1(x) + h_2(x, N(x, P))
$$
<p>with \( h_1(x) \) ensuring that \( g_t(x) \) satisfies some conditions and \( h_2(x,N(x, P)) \) an expression involving \( x \) and the output from the neural network \( N(x,P) \) with \( P \) being the collection of the weights and biases for each layer. For now, it is assumed that the network consists of one input layer, one hidden layer, and one output layer.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setup-of-network">Setup of Network </h2>
<p>In this network, there are no weights and bias at the input layer, so \( P = \{ P_{\text{hidden}}, P_{\text{output}} \} \).
If there are \( N_{\text{hidden} } \) neurons in the hidden layer, then \( P_{\text{hidden}} \) is a \( N_{\text{hidden} } \times (1 + N_{\text{input}}) \) matrix, given that there are \( N_{\text{input}} \) neurons in the input layer.
</p>
<p>The first column in \( P_{\text{hidden} } \) represents the bias for each neuron in the hidden layer and the second column represents the weights for each neuron in the hidden layer from the input layer.
If there are \( N_{\text{output} } \) neurons in the output layer, then \( P_{\text{output}} \) is a \( N_{\text{output} } \times (1 + N_{\text{hidden} }) \) matrix.
</p>
<p>Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron.</p>
<p>It is given that \( g(0) = g_0 \). The trial solution must fulfill this condition to be a proper solution of \eqref{solveode}. A possible way to ensure that \( g_t(0, P) = g_0 \), is to let \( F(N(x,P)) = x \cdot N(x,P) \) and \( A(x) = g_0 \). This gives the following trial solution:</p>
$$
\begin{equation} \label{trial}
g_t(x, P) = g_0 + x \cdot N(x, P)
\end{equation}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="reformulating-the-problem">Reformulating the problem </h2>
<p>We wish that our neural network manages to minimize a given cost function.</p>
<p>A reformulation of out equation, \eqref{solveode}, must therefore be done,
such that it describes the problem a neural network can solve for.
</p>
<p>The neural network must find the set of weights and biases \( P \) such that the trial solution in \eqref{trial} satisfies \eqref{solveode}.</p>
<p>The trial solution</p>
$$
g_t(x, P) = g_0 + x \cdot N(x, P)
$$
<p>has been chosen such that it already solves the condition \( g(0) = g_0 \). What remains, is to find \( P \) such that</p>
$$
\begin{equation} \label{nnmin}
g_t'(x, P) = - \gamma g_t(x, P)
\end{equation}
$$
<p>is fulfilled as <em>best as possible</em>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-technicalities">More technicalities </h2>
<p>The left hand side and right hand side of \eqref{nnmin} must be computed separately, and then the neural network must choose weights and biases, contained in \( P \), such that the sides are equal as best as possible.
This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero.
In this case, the difference squared shows to be an appropriate measurement of how erroneous the trial solution is with respect to \( P \) of the neural network.
</p>
<p>This gives the following cost function our neural network must solve for:</p>
$$
\min_{P}\Big\{ \big(g_t'(x, P) - ( -\gamma g_t(x, P) \big)^2 \Big\}
$$
<p>(the notation \( \min_{P}\{ f(x, P) \} \) means that we desire to find \( P \) that yields the minimum of \( f(x, P) \))</p>
<p>or, in terms of weights and biases for the hidden and output layer in our network:</p>
$$
\min_{P_{\text{hidden} }, \ P_{\text{output} }}\Big\{ \big(g_t'(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) - ( -\gamma g_t(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) \big)^2 \Big\}
$$
<p>for an input value \( x \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-details">More details </h2>
<p>If the neural network evaluates \( g_t(x, P) \) at more values for \( x \), say \( N \) values \( x_i \) for \( i = 1, \dots, N \), then the <em>total</em> error to minimize becomes</p>
$$
\begin{equation} \label{min}
\min_{P}\Big\{\frac{1}{N} \sum_{i=1}^N \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \Big\}
\end{equation}
$$
<p>Letting \( \boldsymbol{x} \) be a vector with elements \( x_i \) and \( C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \) denote the cost function, the minimization problem that our network must solve, becomes</p>
$$
\min_{P} C(\boldsymbol{x}, P)
$$
<p>In terms of \( P_{\text{hidden} } \) and \( P_{\text{output} } \), this could also be expressed as</p>
<p>$$
\min_{P_{\text{hidden} }, \ P_{\text{output} }} C(\boldsymbol{x}, \{P_{\text{hidden} }, P_{\text{output} }\})
$$
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-possible-implementation-of-a-neural-network">A possible implementation of a neural network </h2>
<p>For simplicity, it is assumed that the input is an array \( \boldsymbol{x} = (x_1, \dots, x_N) \) with \( N \) elements. It is at these points the neural network should find \( P \) such that it fulfills \eqref{min}.</p>
<p>First, the neural network must feed forward the inputs.
This means that \( \boldsymbol{x}s \) must be passed through an input layer, a hidden layer and a output layer. The input layer in this case, does not need to process the data any further.
The input layer will consist of \( N_{\text{input} } \) neurons, passing its element to each neuron in the hidden layer. The number of neurons in the hidden layer will be \( N_{\text{hidden} } \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="technicalities">Technicalities </h2>
<p>For the \( i \)-th in the hidden layer with weight \( w_i^{\text{hidden} } \) and bias \( b_i^{\text{hidden} } \), the weighting from the \( j \)-th neuron at the input layer is:</p>
$$
\begin{aligned}
z_{i,j}^{\text{hidden}} &= b_i^{\text{hidden}} + w_i^{\text{hidden}}x_j \\
&=
\begin{pmatrix}
b_i^{\text{hidden}} & w_i^{\text{hidden}}
\end{pmatrix}
\begin{pmatrix}
1 \\
x_j
\end{pmatrix}
\end{aligned}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-technicalities-i">Final technicalities I </h2>
<p>The result after weighting the inputs at the \( i \)-th hidden neuron can be written as a vector:</p>
$$
\begin{aligned}
\boldsymbol{z}_{i}^{\text{hidden}} &= \Big( b_i^{\text{hidden}} + w_i^{\text{hidden}}x_1 , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_2, \ \dots \, , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_N\Big) \\
&=
\begin{pmatrix}
b_i^{\text{hidden}} & w_i^{\text{hidden}}
\end{pmatrix}
\begin{pmatrix}
1 & 1 & \dots & 1 \\
x_1 & x_2 & \dots & x_N
\end{pmatrix} \\
&= \boldsymbol{p}_{i, \text{hidden}}^T X
\end{aligned}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-technicalities-ii">Final technicalities II </h2>
<p>The vector \( \boldsymbol{p}_{i, \text{hidden}}^T \) constitutes each row in \( P_{\text{hidden} } \), which contains the weights for the neural network to minimize according to \eqref{min}.</p>
<p>After having found \( \boldsymbol{z}_{i}^{\text{hidden}} \) for every \( i \)-th neuron within the hidden layer, the vector will be sent to an activation function \( a_i(\boldsymbol{z}) \).</p>
<p>In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron:</p>
$$
f(z) = \frac{1}{1 + \exp{(-z)}}
$$
<p>It is possible to use other activations functions for the hidden layer also.</p>
<p>The output \( \boldsymbol{x}_i^{\text{hidden}} \) from each \( i \)-th hidden neuron is:</p>
<p>$$
\boldsymbol{x}_i^{\text{hidden} } = f\big( \boldsymbol{z}_{i}^{\text{hidden}} \big)
$$
</p>
<p>The outputs \( \boldsymbol{x}_i^{\text{hidden} } \) are then sent to the output layer.</p>
<p>The output layer consists of one neuron in this case, and combines the
output from each of the neurons in the hidden layers. The output layer
combines the results from the hidden layer using some weights \( w_i^{\text{output}} \)
and biases \( b_i^{\text{output}} \). In this case,
it is assumes that the number of neurons in the output layer is one.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-technicalities-iii">Final technicalities III </h2>
<p>The procedure of weighting the output neuron \( j \) in the hidden layer to the \( i \)-th neuron in the output layer is similar as for the hidden layer described previously.</p>
$$
\begin{aligned}
z_{1,j}^{\text{output}} & =
\begin{pmatrix}
b_1^{\text{output}} & \boldsymbol{w}_1^{\text{output}}
\end{pmatrix}
\begin{pmatrix}
1 \\
\boldsymbol{x}_j^{\text{hidden}}
\end{pmatrix}
\end{aligned}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-technicalities-iv">Final technicalities IV </h2>
<p>Expressing \( z_{1,j}^{\text{output}} \) as a vector gives the following way of weighting the inputs from the hidden layer:</p>
$$
\boldsymbol{z}_{1}^{\text{output}} =
\begin{pmatrix}
b_1^{\text{output}} & \boldsymbol{w}_1^{\text{output}}
\end{pmatrix}
\begin{pmatrix}
1 & 1 & \dots & 1 \\
\boldsymbol{x}_1^{\text{hidden}} & \boldsymbol{x}_2^{\text{hidden}} & \dots & \boldsymbol{x}_N^{\text{hidden}}
\end{pmatrix}
$$
<p>In this case we seek a continuous range of values since we are approximating a function. This means that after computing \( \boldsymbol{z}_{1}^{\text{output}} \) the neural network has finished its feed forward step, and \( \boldsymbol{z}_{1}^{\text{output}} \) is the final output of the network.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="back-propagation">Back propagation </h2>
<p>The next step is to decide how the parameters should be changed such that they minimize the cost function.</p>
<p>The chosen cost function for this problem is</p>
$$
C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2
$$
<p>In order to minimize the cost function, an optimization method must be chosen.</p>
<p>Here, gradient descent with a constant step size has been chosen.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="gradient-descent">Gradient descent </h2>
<p>The idea of the gradient descent algorithm is to update parameters in
a direction where the cost function decreases goes to a minimum.
</p>
<p>In general, the update of some parameters \( \boldsymbol{\omega} \) given a cost
function defined by some weights \( \boldsymbol{\omega} \), \( C(\boldsymbol{x},
\boldsymbol{\omega}) \), goes as follows:
</p>
$$
\boldsymbol{\omega}_{\text{new} } = \boldsymbol{\omega} - \lambda \nabla_{\boldsymbol{\omega}} C(\boldsymbol{x}, \boldsymbol{\omega})
$$
<p>for a number of iterations or until $ \big|\big| \boldsymbol{\omega}_{\text{new} } - \boldsymbol{\omega} \big|\big|$ becomes smaller than some given tolerance.</p>
<p>The value of \( \lambda \) decides how large steps the algorithm must take
in the direction of $ \nabla_{\boldsymbol{\omega}} C(\boldsymbol{x}, \boldsymbol{\omega})$.
The notation \( \nabla_{\boldsymbol{\omega}} \) express the gradient with respect
to the elements in \( \boldsymbol{\omega} \).
</p>
<p>In our case, we have to minimize the cost function \( C(\boldsymbol{x}, P) \) with
respect to the two sets of weights and biases, that is for the hidden
layer \( P_{\text{hidden} } \) and for the output layer \( P_{\text{output}
} \) .
</p>
<p>This means that \( P_{\text{hidden} } \) and \( P_{\text{output} } \) is updated by</p>
$$
\begin{aligned}
P_{\text{hidden},\text{new}} &= P_{\text{hidden}} - \lambda \nabla_{P_{\text{hidden}}} C(\boldsymbol{x}, P) \\
P_{\text{output},\text{new}} &= P_{\text{output}} - \lambda \nabla_{P_{\text{output}}} C(\boldsymbol{x}, P)
\end{aligned}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-code-for-solving-the-ode">The code for solving the ODE </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
<span style="color: #408080; font-style: italic"># Assuming one input, hidden, and output layer</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">neural_network</span>(params, x):
<span style="color: #408080; font-style: italic"># Find the weights (including and biases) for the hidden and output layer.</span>
<span style="color: #408080; font-style: italic"># Assume that params is a list of parameters for each layer.</span>
<span style="color: #408080; font-style: italic"># The biases are the first element for each array in params,</span>
<span style="color: #408080; font-style: italic"># and the weights are the remaning elements in each array in params.</span>
w_hidden <span style="color: #666666">=</span> params[<span style="color: #666666">0</span>]
w_output <span style="color: #666666">=</span> params[<span style="color: #666666">1</span>]
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
x_input <span style="color: #666666">=</span> x
<span style="color: #408080; font-style: italic">## Hidden layer:</span>
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
x_input <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_input ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_input)
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
<span style="color: #408080; font-style: italic">## Output layer:</span>
<span style="color: #408080; font-style: italic"># Include bias:</span>
x_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_hidden ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_hidden)
x_output <span style="color: #666666">=</span> z_output
<span style="color: #008000; font-weight: bold">return</span> x_output
<span style="color: #408080; font-style: italic"># The trial solution using the deep neural network:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(x,params, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
<span style="color: #008000; font-weight: bold">return</span> g0 <span style="color: #666666">+</span> x<span style="color: #666666">*</span>neural_network(params,x)
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g</span>(x, g_trial, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>g_trial
<span style="color: #408080; font-style: italic"># The cost function:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x):
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
g_t <span style="color: #666666">=</span> g_trial(x,P)
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the neural network</span>
d_net_out <span style="color: #666666">=</span> elementwise_grad(neural_network,<span style="color: #666666">1</span>)(P,x)
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
d_g_t <span style="color: #666666">=</span> elementwise_grad(g_trial,<span style="color: #666666">0</span>)(x,P)
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
func <span style="color: #666666">=</span> g(x, g_t)
err_sqr <span style="color: #666666">=</span> (d_g_t <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> np<span style="color: #666666">.</span>size(err_sqr)
<span style="color: #408080; font-style: italic"># Solve the exponential decay ODE using neural network with one input, hidden, and output layer</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_neural_network</span>(x, num_neurons_hidden, num_iter, lmb):
<span style="color: #408080; font-style: italic">## Set up initial weights and biases</span>
<span style="color: #408080; font-style: italic"># For the hidden layer</span>
p0 <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons_hidden, <span style="color: #666666">2</span> )
<span style="color: #408080; font-style: italic"># For the output layer</span>
p1 <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
P <span style="color: #666666">=</span> [p0, p1]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function(P, x))
<span style="color: #408080; font-style: italic">## Start finding the optimal weights using gradient descent</span>
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
cost_function_grad <span style="color: #666666">=</span> grad(cost_function,<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
<span style="color: #408080; font-style: italic"># The cost_grad consist now of two arrays;</span>
<span style="color: #408080; font-style: italic"># one for the gradient w.r.t P_hidden and</span>
<span style="color: #408080; font-style: italic"># one for the gradient w.r.t P_output</span>
cost_grad <span style="color: #666666">=</span> cost_function_grad(P, x)
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> P[<span style="color: #666666">0</span>] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_grad[<span style="color: #666666">0</span>]
P[<span style="color: #666666">1</span>] <span style="color: #666666">=</span> P[<span style="color: #666666">1</span>] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_grad[<span style="color: #666666">1</span>]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function(P, x))
<span style="color: #008000; font-weight: bold">return</span> P
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(x, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
<span style="color: #008000; font-weight: bold">return</span> g0<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>x)
<span style="color: #408080; font-style: italic"># Solve the given problem</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&#39;__main__&#39;</span>:
<span style="color: #408080; font-style: italic"># Set seed such that the weight are initialized</span>
<span style="color: #408080; font-style: italic"># with same weights and biases for every run.</span>
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">15</span>)
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
N <span style="color: #666666">=</span> <span style="color: #666666">10</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, N)
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
num_hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">10</span>
num_iter <span style="color: #666666">=</span> <span style="color: #666666">10000</span>
lmb <span style="color: #666666">=</span> <span style="color: #666666">0.001</span>
<span style="color: #408080; font-style: italic"># Use the network</span>
P <span style="color: #666666">=</span> solve_ode_neural_network(x, num_hidden_neurons, num_iter, lmb)
<span style="color: #408080; font-style: italic"># Print the deviation from the trial solution and true solution</span>
res <span style="color: #666666">=</span> g_trial(x,P)
res_analytical <span style="color: #666666">=</span> g_analytic(x)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Max absolute difference: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(res <span style="color: #666666">-</span> res_analytical)))
<span style="color: #408080; font-style: italic"># Plot the results</span>
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</span>)
plt<span style="color: #666666">.</span>plot(x, res_analytical)
plt<span style="color: #666666">.</span>plot(x, res[<span style="color: #666666">0</span>,:])
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(x)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-network-with-one-input-layer-specified-number-of-hidden-layers-and-one-output-layer">The network with one input layer, specified number of hidden layers, and one output layer </h2>
<p>It is also possible to extend the construction of our network into a more general one, allowing the network to contain more than one hidden layers.</p>
<p>The number of neurons within each hidden layer are given as a list of integers in the program below.</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
<span style="color: #408080; font-style: italic"># The neural network with one input layer and one output layer,</span>
<span style="color: #408080; font-style: italic"># but with number of hidden layers specified by the user.</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consists of</span>
<span style="color: #408080; font-style: italic"># parameters to all the hidden</span>
<span style="color: #408080; font-style: italic"># layers AND the output layer.</span>
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
x_input <span style="color: #666666">=</span> x
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
x_prev <span style="color: #666666">=</span> x_input
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
w_hidden <span style="color: #666666">=</span> deep_params[l]
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
x_prev <span style="color: #666666">=</span> x_hidden
<span style="color: #408080; font-style: italic">## Output layer:</span>
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
<span style="color: #408080; font-style: italic"># Include bias:</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
x_output <span style="color: #666666">=</span> z_output
<span style="color: #008000; font-weight: bold">return</span> x_output
<span style="color: #408080; font-style: italic"># The trial solution using the deep neural network:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x,params, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
<span style="color: #008000; font-weight: bold">return</span> g0 <span style="color: #666666">+</span> x<span style="color: #666666">*</span>deep_neural_network(params, x)
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g</span>(x, g_trial, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>g_trial
<span style="color: #408080; font-style: italic"># The same cost function as before, but calls deep_neural_network instead.</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the neural network</span>
d_net_out <span style="color: #666666">=</span> elementwise_grad(deep_neural_network,<span style="color: #666666">1</span>)(P,x)
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
d_g_t <span style="color: #666666">=</span> elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>)(x,P)
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
func <span style="color: #666666">=</span> g(x, g_t)
err_sqr <span style="color: #666666">=</span> (d_g_t <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> np<span style="color: #666666">.</span>size(err_sqr)
<span style="color: #408080; font-style: italic"># Solve the exponential decay ODE using neural network with one input and one output layer,</span>
<span style="color: #408080; font-style: italic"># but with specified number of hidden layers from the user.</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
<span style="color: #408080; font-style: italic"># The number of elements in the list num_hidden_neurons thus represents</span>
<span style="color: #408080; font-style: italic"># the number of hidden layers.</span>
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
<span style="color: #408080; font-style: italic">## Set up initial weights and biases</span>
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
<span style="color: #408080; font-style: italic"># For the output layer</span>
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function_deep(P, x))
<span style="color: #408080; font-style: italic">## Start finding the optimal weights using gradient descent</span>
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
cost_function_deep_grad <span style="color: #666666">=</span> grad(cost_function_deep,<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
<span style="color: #408080; font-style: italic"># The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases</span>
<span style="color: #408080; font-style: italic"># in the hidden layers and output layers evaluated at x.</span>
cost_deep_grad <span style="color: #666666">=</span> cost_function_deep_grad(P, x)
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_deep_grad[l]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function_deep(P, x))
<span style="color: #008000; font-weight: bold">return</span> P
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(x, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
<span style="color: #008000; font-weight: bold">return</span> g0<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>x)
<span style="color: #408080; font-style: italic"># Solve the given problem</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&#39;__main__&#39;</span>:
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">15</span>)
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
N <span style="color: #666666">=</span> <span style="color: #666666">10</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, N)
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
num_hidden_neurons <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">10</span>,<span style="color: #666666">10</span>])
num_iter <span style="color: #666666">=</span> <span style="color: #666666">10000</span>
lmb <span style="color: #666666">=</span> <span style="color: #666666">0.001</span>
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)
res <span style="color: #666666">=</span> g_trial_deep(x,P)
res_analytical <span style="color: #666666">=</span> g_analytic(x)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Performance of a deep neural network solving an ODE compared to the analytical solution&#39;</span>)
plt<span style="color: #666666">.</span>plot(x, res_analytical)
plt<span style="color: #666666">.</span>plot(x, res[<span style="color: #666666">0</span>,:])
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;dnn&#39;</span>])
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(x)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="example-population-growth">Example: Population growth </h2>
<p>A logistic model of population growth assumes that a population converges toward an equilibrium.
The population growth can be modeled by
</p>
$$
\begin{equation} \label{log}
g'(t) = \alpha g(t)(A - g(t))
\end{equation}
$$
<p>where \( g(t) \) is the population density at time \( t \), \( \alpha > 0 \) the growth rate and \( A > 0 \) is the maximum population number in the environment.
Also, at \( t = 0 \) the population has the size \( g(0) = g_0 \), where \( g_0 \) is some chosen constant.
</p>
<p>In this example, similar network as for the exponential decay using Autograd has been used to solve the equation. However, as the implementation might suffer from e.g numerical instability
and high execution time (this might be more apparent in the examples solving PDEs),
using a library like TensorFlow is recommended.
Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-problem">Setting up the problem </h2>
<p>Here, we will model a population \( g(t) \) in an environment having carrying capacity \( A \).
The population follows the model
</p>
$$
\begin{equation} \label{solveode_population}
g'(t) = \alpha g(t)(A - g(t))
\end{equation}
$$
<p>where \( g(0) = g_0 \).</p>
<p>In this example, we let \( \alpha = 2 \), \( A = 1 \), and \( g_0 = 1.2 \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-trial-solution">The trial solution </h2>
<p>We will get a slightly different trial solution, as the boundary conditions are different
compared to the case for exponential decay.
</p>
<p>A possible trial solution satisfying the condition \( g(0) = g_0 \) could be</p>
<p>$$
h_1(t) = g_0 + t \cdot N(t,P)
$$
</p>
<p>with \( N(t,P) \) being the output from the neural network with weights and biases for each layer collected in the set \( P \).</p>
<p>The analytical solution is</p>
<p>$$
g(t) = \frac{Ag_0}{g_0 + (A - g_0)\exp(-\alpha A t)}
$$
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-program-using-autograd">The program using Autograd </h2>
<p>The network will be the similar as for the exponential decay example, but with some small modifications for our problem.</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
<span style="color: #408080; font-style: italic"># Function to get the parameters.</span>
<span style="color: #408080; font-style: italic"># Done such that one can easily change the paramaters after one&#39;s liking.</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">get_parameters</span>():
alpha <span style="color: #666666">=</span> <span style="color: #666666">2</span>
A <span style="color: #666666">=</span> <span style="color: #666666">1</span>
g0 <span style="color: #666666">=</span> <span style="color: #666666">1.2</span>
<span style="color: #008000; font-weight: bold">return</span> alpha, A, g0
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(P, x):
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(P) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
x_input <span style="color: #666666">=</span> x
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
x_prev <span style="color: #666666">=</span> x_input
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
w_hidden <span style="color: #666666">=</span> P[l]
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
x_prev <span style="color: #666666">=</span> x_hidden
<span style="color: #408080; font-style: italic">## Output layer:</span>
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
w_output <span style="color: #666666">=</span> P[<span style="color: #666666">-1</span>]
<span style="color: #408080; font-style: italic"># Include bias:</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
x_output <span style="color: #666666">=</span> z_output
<span style="color: #008000; font-weight: bold">return</span> x_output
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
d_g_t <span style="color: #666666">=</span> elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>)(x,P)
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
func <span style="color: #666666">=</span> f(x, g_t)
err_sqr <span style="color: #666666">=</span> (d_g_t <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> np<span style="color: #666666">.</span>size(err_sqr)
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(x, g_trial):
alpha,A, g0 <span style="color: #666666">=</span> get_parameters()
<span style="color: #008000; font-weight: bold">return</span> alpha<span style="color: #666666">*</span>g_trial<span style="color: #666666">*</span>(A <span style="color: #666666">-</span> g_trial)
<span style="color: #408080; font-style: italic"># The trial solution using the deep neural network:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x, params):
alpha,A, g0 <span style="color: #666666">=</span> get_parameters()
<span style="color: #008000; font-weight: bold">return</span> g0 <span style="color: #666666">+</span> x<span style="color: #666666">*</span>deep_neural_network(params,x)
<span style="color: #408080; font-style: italic"># The analytical solution:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(t):
alpha,A, g0 <span style="color: #666666">=</span> get_parameters()
<span style="color: #008000; font-weight: bold">return</span> A<span style="color: #666666">*</span>g0<span style="color: #666666">/</span>(g0 <span style="color: #666666">+</span> (A <span style="color: #666666">-</span> g0)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>alpha<span style="color: #666666">*</span>A<span style="color: #666666">*</span>t))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
<span style="color: #408080; font-style: italic"># For the output layer</span>
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function_deep(P, x))
<span style="color: #408080; font-style: italic">## Start finding the optimal weigths using gradient descent</span>
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
cost_function_deep_grad <span style="color: #666666">=</span> grad(cost_function_deep,<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
<span style="color: #408080; font-style: italic"># The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases</span>
<span style="color: #408080; font-style: italic"># in the hidden layers and output layers evaluated at x.</span>
cost_deep_grad <span style="color: #666666">=</span> cost_function_deep_grad(P, x)
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_deep_grad[l]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function_deep(P, x))
<span style="color: #008000; font-weight: bold">return</span> P
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&#39;__main__&#39;</span>:
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">4155</span>)
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
Nt <span style="color: #666666">=</span> <span style="color: #666666">10</span>
T <span style="color: #666666">=</span> <span style="color: #666666">1</span>
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,T, Nt)
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">100</span>, <span style="color: #666666">50</span>, <span style="color: #666666">25</span>]
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
lmb <span style="color: #666666">=</span> <span style="color: #666666">1e-3</span>
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)
g_dnn_ag <span style="color: #666666">=</span> g_trial_deep(t,P)
g_analytical <span style="color: #666666">=</span> g_analytic(t)
<span style="color: #408080; font-style: italic"># Find the maximum absolute difference between the solutons:</span>
diff_ag <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> g_analytical))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>diff_ag)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</span>)
plt<span style="color: #666666">.</span>plot(t, g_analytical)
plt<span style="color: #666666">.</span>plot(t, g_dnn_ag[<span style="color: #666666">0</span>,:])
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;t&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(t)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="using-forward-euler-to-solve-the-ode">Using forward Euler to solve the ODE </h2>
<p>A straightforward way of solving an ODE numerically, is to use Euler's method.</p>
<p>Euler's method uses Taylor series to approximate the value at a function \( f \) at a step \( \Delta x \) from \( x \):</p>
<p>$$
f(x + \Delta x) \approx f(x) + \Delta x f'(x)
$$
</p>
<p>In our case, using Euler's method to approximate the value of \( g \) at a step \( \Delta t \) from \( t \) yields</p>
$$
\begin{aligned}
g(t + \Delta t) &\approx g(t) + \Delta t g'(t) \\
&= g(t) + \Delta t \big(\alpha g(t)(A - g(t))\big)
\end{aligned}
$$
<p>along with the condition that \( g(0) = g_0 \).</p>
<p>Let \( t_i = i \cdot \Delta t \) where \( \Delta t = \frac{T}{N_t-1} \) where \( T \) is the final time our solver must solve for and \( N_t \) the number of values for \( t \in [0, T] \) for \( i = 0, \dots, N_t-1 \).</p>
<p>For \( i \geq 1 \), we have that</p>
$$
\begin{aligned}
t_i &= i\Delta t \\
&= (i - 1)\Delta t + \Delta t \\
&= t_{i-1} + \Delta t
\end{aligned}
$$
<p>Now, if \( g_i = g(t_i) \) then</p>
$$
\begin{equation}
\begin{aligned}
g_i &= g(t_i) \\
&= g(t_{i-1} + \Delta t) \\
&\approx g(t_{i-1}) + \Delta t \big(\alpha g(t_{i-1})(A - g(t_{i-1}))\big) \\
&= g_{i-1} + \Delta t \big(\alpha g_{i-1}(A - g_{i-1})\big)
\end{aligned}
\end{equation} \label{odenum}
$$
<p>for \( i \geq 1 \) and \( g_0 = g(t_0) = g(0) = g_0 \).</p>
<p>Equation \eqref{odenum} could be implemented in the following way,
extending the program that uses the network using Autograd:
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Assume that all function definitions from the example program using Autograd</span>
<span style="color: #408080; font-style: italic"># are located here.</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&#39;__main__&#39;</span>:
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">4155</span>)
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
Nt <span style="color: #666666">=</span> <span style="color: #666666">10</span>
T <span style="color: #666666">=</span> <span style="color: #666666">1</span>
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,T, Nt)
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">100</span>,<span style="color: #666666">50</span>,<span style="color: #666666">25</span>]
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
lmb <span style="color: #666666">=</span> <span style="color: #666666">1e-3</span>
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)
g_dnn_ag <span style="color: #666666">=</span> g_trial_deep(t,P)
g_analytical <span style="color: #666666">=</span> g_analytic(t)
<span style="color: #408080; font-style: italic"># Find the maximum absolute difference between the solutons:</span>
diff_ag <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> g_analytical))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>diff_ag)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</span>)
plt<span style="color: #666666">.</span>plot(t, g_analytical)
plt<span style="color: #666666">.</span>plot(t, g_dnn_ag[<span style="color: #666666">0</span>,:])
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;t&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(t)&#39;</span>)
<span style="color: #408080; font-style: italic">## Find an approximation to the funtion using forward Euler</span>
alpha, A, g0 <span style="color: #666666">=</span> get_parameters()
dt <span style="color: #666666">=</span> T<span style="color: #666666">/</span>(Nt <span style="color: #666666">-</span> <span style="color: #666666">1</span>)
<span style="color: #408080; font-style: italic"># Perform forward Euler to solve the ODE</span>
g_euler <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(Nt)
g_euler[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> g0
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,Nt):
g_euler[i] <span style="color: #666666">=</span> g_euler[i<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> dt<span style="color: #666666">*</span>(alpha<span style="color: #666666">*</span>g_euler[i<span style="color: #666666">-1</span>]<span style="color: #666666">*</span>(A <span style="color: #666666">-</span> g_euler[i<span style="color: #666666">-1</span>]))
<span style="color: #408080; font-style: italic"># Print the errors done by each method</span>
diff1 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_euler <span style="color: #666666">-</span> g_analytical))
diff2 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag[<span style="color: #666666">0</span>,:] <span style="color: #666666">-</span> g_analytical))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Max absolute difference between Euler method and analytical: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>diff1)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Max absolute difference between deep neural network and analytical: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>diff2)
<span style="color: #408080; font-style: italic"># Plot results</span>
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>plot(t,g_euler)
plt<span style="color: #666666">.</span>plot(t,g_analytical)
plt<span style="color: #666666">.</span>plot(t,g_dnn_ag[<span style="color: #666666">0</span>,:])
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;euler&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;dnn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Time t&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(t)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="example-solving-the-one-dimensional-poisson-equation">Example: Solving the one dimensional Poisson equation </h2>
<p>The Poisson equation for \( g(x) \) in one dimension is</p>
$$
\begin{equation} \label{poisson}
-g''(x) = f(x)
\end{equation}
$$
<p>where \( f(x) \) is a given function for \( x \in (0,1) \).</p>
<p>The conditions that \( g(x) \) is chosen to fulfill, are</p>
$$
\begin{align*}
g(0) &= 0 \\
g(1) &= 0
\end{align*}
$$
<p>This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used.
The results from the networks can then be compared to the analytical solution.
In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-specific-equation-to-solve-for">The specific equation to solve for </h2>
<p>Here, the function \( g(x) \) to solve for follows the equation</p>
$$
-g''(x) = f(x),\qquad x \in (0,1)
$$
<p>where \( f(x) \) is a given function, along with the chosen conditions</p>
$$
\begin{aligned}
g(0) = g(1) = 0
\end{aligned}\label{cond}
$$
<p>In this example, we consider the case when \( f(x) = (3x + x^2)\exp(x) \).</p>
<p>For this case, a possible trial solution satisfying the conditions could be</p>
$$
g_t(x) = x \cdot (1-x) \cdot N(P,x)
$$
<p>The analytical solution for this problem is</p>
$$
g(x) = x(1 - x)\exp(x)
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="solving-the-equation-using-autograd">Solving the equation using Autograd </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
x_input <span style="color: #666666">=</span> x
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
x_prev <span style="color: #666666">=</span> x_input
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
w_hidden <span style="color: #666666">=</span> deep_params[l]
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
x_prev <span style="color: #666666">=</span> x_hidden
<span style="color: #408080; font-style: italic">## Output layer:</span>
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
<span style="color: #408080; font-style: italic"># Include bias:</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
x_output <span style="color: #666666">=</span> z_output
<span style="color: #008000; font-weight: bold">return</span> x_output
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
<span style="color: #408080; font-style: italic"># For the output layer</span>
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function_deep(P, x))
<span style="color: #408080; font-style: italic">## Start finding the optimal weigths using gradient descent</span>
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
cost_function_deep_grad <span style="color: #666666">=</span> grad(cost_function_deep,<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
<span style="color: #408080; font-style: italic"># The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases</span>
<span style="color: #408080; font-style: italic"># in the hidden layers and output layers evaluated at x.</span>
cost_deep_grad <span style="color: #666666">=</span> cost_function_deep_grad(P, x)
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_deep_grad[l]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function_deep(P, x))
<span style="color: #008000; font-weight: bold">return</span> P
<span style="color: #408080; font-style: italic">## Set up the cost function specified for this Poisson equation:</span>
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(x):
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">3*</span>x <span style="color: #666666">+</span> x<span style="color: #666666">**2</span>)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(x)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
d2_g_t <span style="color: #666666">=</span> elementwise_grad(elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>))(x,P)
right_side <span style="color: #666666">=</span> f(x)
err_sqr <span style="color: #666666">=</span> (<span style="color: #666666">-</span>d2_g_t <span style="color: #666666">-</span> right_side)<span style="color: #666666">**2</span>
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
<span style="color: #008000; font-weight: bold">return</span> cost_sum<span style="color: #666666">/</span>np<span style="color: #666666">.</span>size(err_sqr)
<span style="color: #408080; font-style: italic"># The trial solution:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x,P):
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>deep_neural_network(P,x)
<span style="color: #408080; font-style: italic"># The analytic solution;</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(x):
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(x)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&#39;__main__&#39;</span>:
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">4155</span>)
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
Nx <span style="color: #666666">=</span> <span style="color: #666666">10</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>, Nx)
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">200</span>,<span style="color: #666666">100</span>]
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
lmb <span style="color: #666666">=</span> <span style="color: #666666">1e-3</span>
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)
g_dnn_ag <span style="color: #666666">=</span> g_trial_deep(x,P)
g_analytical <span style="color: #666666">=</span> g_analytic(x)
<span style="color: #408080; font-style: italic"># Find the maximum absolute difference between the solutons:</span>
max_diff <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> g_analytical))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>max_diff)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</span>)
plt<span style="color: #666666">.</span>plot(x, g_analytical)
plt<span style="color: #666666">.</span>plot(x, g_dnn_ag[<span style="color: #666666">0</span>,:])
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(x)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="comparing-with-a-numerical-scheme">Comparing with a numerical scheme </h2>
<p>The Poisson equation is possible to solve using Taylor series to approximate the second derivative.</p>
<p>Using Taylor series, the second derivative can be expressed as</p>
<p>$$
g''(x) = \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2} + E_{\Delta x}(x)
$$
</p>
<p>where \( \Delta x \) is a small step size and \( E_{\Delta x}(x) \) being the error term.</p>
<p>Looking away from the error terms gives an approximation to the second derivative:</p>
$$
\begin{equation} \label{approx}
g''(x) \approx \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2}
\end{equation}
$$
<p>If \( x_i = i \Delta x = x_{i-1} + \Delta x \) and \( g_i = g(x_i) \) for \( i = 1,\dots N_x - 2 \) with \( N_x \) being the number of values for \( x \), \eqref{approx} becomes</p>
$$
\begin{aligned}
g''(x_i) &\approx \frac{g(x_i + \Delta x) - 2g(x_i) + g(x_i -\Delta x)}{\Delta x^2} \\
&= \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2}
\end{aligned}
$$
<p>Since we know from our problem that</p>
$$
\begin{aligned}
-g''(x) &= f(x) \\
&= (3x + x^2)\exp(x)
\end{aligned}
$$
<p>along with the conditions \( g(0) = g(1) = 0 \),
the following scheme can be used to find an approximate solution for \( g(x) \) numerically:
</p>
$$
\begin{equation}
\begin{aligned}
-\Big( \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2} \Big) &= f(x_i) \\
-g_{i+1} + 2g_i - g_{i-1} &= \Delta x^2 f(x_i)
\end{aligned}
\end{equation} \label{odesys}
$$
<p>for \( i = 1, \dots, N_x - 2 \) where \( g_0 = g_{N_x - 1} = 0 \) and \( f(x_i) = (3x_i + x_i^2)\exp(x_i) \), which is given for our specific problem.</p>
<p>The equation can be rewritten into a matrix equation:</p>
$$
\begin{aligned}
\begin{pmatrix}
2 & -1 & 0 & \dots & 0 \\
-1 & 2 & -1 & \dots & 0 \\
\vdots & & \ddots & & \vdots \\
0 & \dots & -1 & 2 & -1 \\
0 & \dots & 0 & -1 & 2\\
\end{pmatrix}
\begin{pmatrix}
g_1 \\
g_2 \\
\vdots \\
g_{N_x - 3} \\
g_{N_x - 2}
\end{pmatrix}
&=
\Delta x^2
\begin{pmatrix}
f(x_1) \\
f(x_2) \\
\vdots \\
f(x_{N_x - 3}) \\
f(x_{N_x - 2})
\end{pmatrix} \\
\boldsymbol{A}\boldsymbol{g} &= \boldsymbol{f},
\end{aligned}
$$
<p>which makes it possible to solve for the vector \( \boldsymbol{g} \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-code">Setting up the code </h2>
<p>We can then compare the result from this numerical scheme with the output from our network using Autograd:</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
x_input <span style="color: #666666">=</span> x
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
x_prev <span style="color: #666666">=</span> x_input
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
w_hidden <span style="color: #666666">=</span> deep_params[l]
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
x_prev <span style="color: #666666">=</span> x_hidden
<span style="color: #408080; font-style: italic">## Output layer:</span>
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
<span style="color: #408080; font-style: italic"># Include bias:</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
x_output <span style="color: #666666">=</span> z_output
<span style="color: #008000; font-weight: bold">return</span> x_output
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
<span style="color: #408080; font-style: italic"># For the output layer</span>
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function_deep(P, x))
<span style="color: #408080; font-style: italic">## Start finding the optimal weigths using gradient descent</span>
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
cost_function_deep_grad <span style="color: #666666">=</span> grad(cost_function_deep,<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
<span style="color: #408080; font-style: italic"># The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases</span>
<span style="color: #408080; font-style: italic"># in the hidden layers and output layers evaluated at x.</span>
cost_deep_grad <span style="color: #666666">=</span> cost_function_deep_grad(P, x)
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_deep_grad[l]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost_function_deep(P, x))
<span style="color: #008000; font-weight: bold">return</span> P
<span style="color: #408080; font-style: italic">## Set up the cost function specified for this Poisson equation:</span>
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(x):
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">3*</span>x <span style="color: #666666">+</span> x<span style="color: #666666">**2</span>)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(x)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
d2_g_t <span style="color: #666666">=</span> elementwise_grad(elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>))(x,P)
right_side <span style="color: #666666">=</span> f(x)
err_sqr <span style="color: #666666">=</span> (<span style="color: #666666">-</span>d2_g_t <span style="color: #666666">-</span> right_side)<span style="color: #666666">**2</span>
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
<span style="color: #008000; font-weight: bold">return</span> cost_sum<span style="color: #666666">/</span>np<span style="color: #666666">.</span>size(err_sqr)
<span style="color: #408080; font-style: italic"># The trial solution:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x,P):
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>deep_neural_network(P,x)
<span style="color: #408080; font-style: italic"># The analytic solution;</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(x):
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(x)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&#39;__main__&#39;</span>:
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">4155</span>)
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
Nx <span style="color: #666666">=</span> <span style="color: #666666">10</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>, Nx)
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">200</span>,<span style="color: #666666">100</span>]
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
lmb <span style="color: #666666">=</span> <span style="color: #666666">1e-3</span>
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)
g_dnn_ag <span style="color: #666666">=</span> g_trial_deep(x,P)
g_analytical <span style="color: #666666">=</span> g_analytic(x)
<span style="color: #408080; font-style: italic"># Find the maximum absolute difference between the solutons:</span>
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</span>)
plt<span style="color: #666666">.</span>plot(x, g_analytical)
plt<span style="color: #666666">.</span>plot(x, g_dnn_ag[<span style="color: #666666">0</span>,:])
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(x)&#39;</span>)
<span style="color: #408080; font-style: italic">## Perform the computation using the numerical scheme</span>
dx <span style="color: #666666">=</span> <span style="color: #666666">1/</span>(Nx <span style="color: #666666">-</span> <span style="color: #666666">1</span>)
<span style="color: #408080; font-style: italic"># Set up the matrix A</span>
A <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx<span style="color: #666666">-2</span>,Nx<span style="color: #666666">-2</span>))
A[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">2</span>
A[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,Nx<span style="color: #666666">-3</span>):
A[i,i<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
A[i,i] <span style="color: #666666">=</span> <span style="color: #666666">2</span>
A[i,i<span style="color: #666666">+1</span>] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
A[Nx <span style="color: #666666">-</span> <span style="color: #666666">3</span>, Nx <span style="color: #666666">-</span> <span style="color: #666666">4</span>] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
A[Nx <span style="color: #666666">-</span> <span style="color: #666666">3</span>, Nx <span style="color: #666666">-</span> <span style="color: #666666">3</span>] <span style="color: #666666">=</span> <span style="color: #666666">2</span>
<span style="color: #408080; font-style: italic"># Set up the vector f</span>
f_vec <span style="color: #666666">=</span> dx<span style="color: #666666">**2</span> <span style="color: #666666">*</span> f(x[<span style="color: #666666">1</span>:<span style="color: #666666">-1</span>])
<span style="color: #408080; font-style: italic"># Solve the equation</span>
g_res <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>solve(A,f_vec)
g_vec <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(Nx)
g_vec[<span style="color: #666666">1</span>:<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> g_res
<span style="color: #408080; font-style: italic"># Print the differences between each method</span>
max_diff1 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> g_analytical))
max_diff2 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_vec <span style="color: #666666">-</span> g_analytical))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The max absolute difference between the analytical solution and DNN Autograd: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>max_diff1)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;The max absolute difference between the analytical solution and numerical scheme: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>max_diff2)
<span style="color: #408080; font-style: italic"># Plot the results</span>
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>plot(x,g_vec)
plt<span style="color: #666666">.</span>plot(x,g_analytical)
plt<span style="color: #666666">.</span>plot(x,g_dnn_ag[<span style="color: #666666">0</span>,:])
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;numerical scheme&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;dnn&#39;</span>])
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="partial-differential-equations">Partial Differential Equations </h2>
<p>A partial differential equation (PDE) has a solution here the function
is defined by multiple variables. The equation may involve all kinds
of combinations of which variables the function is differentiated with
respect to.
</p>
<p>In general, a partial differential equation for a function \( g(x_1,\dots,x_N) \) with \( N \) variables may be expressed as</p>
$$
\begin{equation} \label{PDE}
f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) = 0
\end{equation}
$$
<p>where \( f \) is an expression involving all kinds of possible mixed derivatives of \( g(x_1,\dots,x_N) \) up to an order \( n \). In order for the solution to be unique, some additional conditions must also be given.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="type-of-problem">Type of problem </h2>
<p>The problem our network must solve for, is similar to the ODE case.
We must have a trial solution \( g_t \) at hand.
</p>
<p>For instance, the trial solution could be expressed as</p>
$$
\begin{align*}
g_t(x_1,\dots,x_N) = h_1(x_1,\dots,x_N) + h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P))
\end{align*}
$$
<p>where \( h_1(x_1,\dots,x_N) \) is a function that ensures \( g_t(x_1,\dots,x_N) \) satisfies some given conditions.
The neural network \( N(x_1,\dots,x_N,P) \) has weights and biases described by \( P \) and \( h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P)) \) is an expression using the output from the neural network in some way.
</p>
<p>The role of the function \( h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P)) \), is to ensure that the output of \( N(x_1,\dots,x_N,P) \) is zero when \( g_t(x_1,\dots,x_N) \) is evaluated at the values of \( x_1,\dots,x_N \) where the given conditions must be satisfied. The function \( h_1(x_1,\dots,x_N) \) should alone make \( g_t(x_1,\dots,x_N) \) satisfy the conditions.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="network-requirements">Network requirements </h2>
<p>The network tries then the minimize the cost function following the
same ideas as described for the ODE case, but now with more than one
variables to consider. The concept still remains the same; find a set
of parameters \( P \) such that the expression \( f \) in \eqref{PDE} is as
close to zero as possible.
</p>
<p>As for the ODE case, the cost function is the mean squared error that
the network must try to minimize. The cost function for the network to
minimize is
</p>
$$
\begin{equation*}
C\left(x_1, \dots, x_N, P\right) = \left( f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) \right)^2
\end{equation*}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-details">More details </h2>
<p>If we let \( \boldsymbol{x} = \big( x_1, \dots, x_N \big) \) be an array containing the values for \( x_1, \dots, x_N \) respectively, the cost function can be reformulated into the following:</p>
$$
C\left(\boldsymbol{x}, P\right) = f\left( \left( \boldsymbol{x}, \frac{\partial g(\boldsymbol{x}) }{\partial x_1}, \dots , \frac{\partial g(\boldsymbol{x}) }{\partial x_N}, \frac{\partial g(\boldsymbol{x}) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\boldsymbol{x}) }{\partial x_N^n} \right) \right)^2
$$
<p>If we also have \( M \) different sets of values for \( x_1, \dots, x_N \), that is \( \boldsymbol{x}_i = \big(x_1^{(i)}, \dots, x_N^{(i)}\big) \) for \( i = 1,\dots,M \) being the rows in matrix \( X \), the cost function can be generalized into</p>
$$
\begin{equation*}
C\left(X, P \right) = \sum_{i=1}^M f\left( \left( \boldsymbol{x}_i, \frac{\partial g(\boldsymbol{x}_i) }{\partial x_1}, \dots , \frac{\partial g(\boldsymbol{x}_i) }{\partial x_N}, \frac{\partial g(\boldsymbol{x}_i) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\boldsymbol{x}_i) }{\partial x_N^n} \right) \right)^2.
\end{equation*}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="example-the-diffusion-equation">Example: The diffusion equation </h2>
<p>In one spatial dimension, the equation reads</p>
$$
\begin{equation*}
\frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2}
\end{equation*}
$$
<p>where a possible choice of conditions are</p>
$$
\begin{align*}
g(0,t) &= 0 ,\qquad t \geq 0 \\
g(1,t) &= 0, \qquad t \geq 0 \\
g(x,0) &= u(x),\qquad x\in [0,1]
\end{align*}
$$
<p>with \( u(x) \) being some given function.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="defining-the-problem">Defining the problem </h2>
<p>For this case, we want to find \( g(x,t) \) such that</p>
$$
\begin{equation}
\frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2}
\end{equation} \label{diffonedim}
$$
<p>and</p>
$$
\begin{align*}
g(0,t) &= 0 ,\qquad t \geq 0 \\
g(1,t) &= 0, \qquad t \geq 0 \\
g(x,0) &= u(x),\qquad x\in [0,1]
\end{align*}
$$
<p>with \( u(x) = \sin(\pi x) \).</p>
<p>First, let us set up the deep neural network.
The deep neural network will follow the same structure as discussed in the examples solving the ODEs.
First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-network-using-autograd">Setting up the network using Autograd </h2>
<p>The only change to do here, is to extend our network such that
functions of multiple parameters are correctly handled. In this case
we have two variables in our function to solve for, that is time \( t \)
and position \( x \). The variables will be represented by a
one-dimensional array in the program. The program will evaluate the
network at each possible pair \( (x,t) \), given an array for the desired
\( x \)-values and \( t \)-values to approximate the solution at.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
<span style="color: #408080; font-style: italic"># x is now a point and a 1D numpy array; make it a column vector</span>
num_coordinates <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">0</span>)
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(num_coordinates,<span style="color: #666666">-1</span>)
num_points <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">1</span>)
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
x_input <span style="color: #666666">=</span> x
x_prev <span style="color: #666666">=</span> x_input
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
w_hidden <span style="color: #666666">=</span> deep_params[l]
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
x_prev <span style="color: #666666">=</span> x_hidden
<span style="color: #408080; font-style: italic">## Output layer:</span>
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
<span style="color: #408080; font-style: italic"># Include bias:</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
x_output <span style="color: #666666">=</span> z_output
<span style="color: #008000; font-weight: bold">return</span> x_output[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-network-using-autograd-the-trial-solution">Setting up the network using Autograd; The trial solution </h2>
<p>The cost function must then iterate through the given arrays
containing values for \( x \) and \( t \), defines a point \( (x,t) \) the deep
neural network and the trial solution is evaluated at, and then finds
the Jacobian of the trial solution.
</p>
<p>A possible trial solution for this PDE is</p>
<p>$$
g_t(x,t) = h_1(x,t) + x(1-x)tN(x,t,P)
$$
</p>
<p>with \( A(x,t) \) being a function ensuring that \( g_t(x,t) \) satisfies our given conditions, and \( N(x,t,P) \) being the output from the deep neural network using weights and biases for each layer from \( P \).</p>
<p>To fulfill the conditions, \( A(x,t) \) could be:</p>
<p>$$
h_1(x,t) = (1-t)\Big(u(x) - \big((1-x)u(0) + x u(1)\big)\Big) = (1-t)u(x) = (1-t)\sin(\pi x)
$$
since \( (0) = u(1) = 0 \) and \( u(x) = \sin(\pi x) \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="why-the-jacobian">Why the jacobian? </h2>
<p>The Jacobian is used because the program must find the derivative of
the trial solution with respect to \( x \) and \( t \).
</p>
<p>This gives the necessity of computing the Jacobian matrix, as we want
to evaluate the gradient with respect to \( x \) and \( t \) (note that the
Jacobian of a scalar-valued multivariate function is simply its
gradient).
</p>
<p>In Autograd, the differentiation is by default done with respect to
the first input argument of your Python function. Since the points is
an array representing \( x \) and \( t \), the Jacobian is calculated using
the values of \( x \) and \( t \).
</p>
<p>To find the second derivative with respect to \( x \) and \( t \), the
Jacobian can be found for the second time. The result is a Hessian
matrix, which is the matrix containing all the possible second order
mixed derivatives of \( g(x,t) \).
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Set up the trial function:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">u</span>(x):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(point,P):
x,t <span style="color: #666666">=</span> point
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1-</span>t)<span style="color: #666666">*</span>u(x) <span style="color: #666666">+</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>t<span style="color: #666666">*</span>deep_neural_network(P,point)
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(point):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">0.</span>
<span style="color: #408080; font-style: italic"># The cost function:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x, t):
cost_sum <span style="color: #666666">=</span> <span style="color: #666666">0</span>
g_t_jacobian_func <span style="color: #666666">=</span> jacobian(g_trial)
g_t_hessian_func <span style="color: #666666">=</span> hessian(g_trial)
<span style="color: #008000; font-weight: bold">for</span> x_ <span style="color: #AA22FF; font-weight: bold">in</span> x:
<span style="color: #008000; font-weight: bold">for</span> t_ <span style="color: #AA22FF; font-weight: bold">in</span> t:
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_,t_])
g_t <span style="color: #666666">=</span> g_trial(point,P)
g_t_jacobian <span style="color: #666666">=</span> g_t_jacobian_func(point,P)
g_t_hessian <span style="color: #666666">=</span> g_t_hessian_func(point,P)
g_t_dt <span style="color: #666666">=</span> g_t_jacobian[<span style="color: #666666">1</span>]
g_t_d2x <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
func <span style="color: #666666">=</span> f(point)
err_sqr <span style="color: #666666">=</span> ( (g_t_dt <span style="color: #666666">-</span> g_t_d2x) <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
cost_sum <span style="color: #666666">+=</span> err_sqr
<span style="color: #008000; font-weight: bold">return</span> cost_sum
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-network-using-autograd-the-full-program">Setting up the network using Autograd; The full program </h2>
<p>Having set up the network, along with the trial solution and cost function, we can now see how the deep neural network performs by comparing the results to the analytical solution.</p>
<p>The analytical solution of our problem is</p>
<p>$$
g(x,t) = \exp(-\pi^2 t)\sin(\pi x)
$$
</p>
<p>A possible way to implement a neural network solving the PDE, is given below.
Be aware, though, that it is fairly slow for the parameters used.
A better result is possible, but requires more iterations, and thus longer time to complete.
</p>
<p>Indeed, the program below is not optimal in its implementation, but rather serves as an example on how to implement and use a neural network to solve a PDE.
Using TensorFlow results in a much better execution time. Try it!
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> jacobian,hessian,grad
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> axes3d
<span style="color: #408080; font-style: italic">## Set up the network</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
<span style="color: #408080; font-style: italic"># x is now a point and a 1D numpy array; make it a column vector</span>
num_coordinates <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">0</span>)
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(num_coordinates,<span style="color: #666666">-1</span>)
num_points <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">1</span>)
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
x_input <span style="color: #666666">=</span> x
x_prev <span style="color: #666666">=</span> x_input
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
w_hidden <span style="color: #666666">=</span> deep_params[l]
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
x_prev <span style="color: #666666">=</span> x_hidden
<span style="color: #408080; font-style: italic">## Output layer:</span>
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
<span style="color: #408080; font-style: italic"># Include bias:</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
x_output <span style="color: #666666">=</span> z_output
<span style="color: #008000; font-weight: bold">return</span> x_output[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
<span style="color: #408080; font-style: italic">## Define the trial solution and cost function</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">u</span>(x):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(point,P):
x,t <span style="color: #666666">=</span> point
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1-</span>t)<span style="color: #666666">*</span>u(x) <span style="color: #666666">+</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>t<span style="color: #666666">*</span>deep_neural_network(P,point)
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(point):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">0.</span>
<span style="color: #408080; font-style: italic"># The cost function:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x, t):
cost_sum <span style="color: #666666">=</span> <span style="color: #666666">0</span>
g_t_jacobian_func <span style="color: #666666">=</span> jacobian(g_trial)
g_t_hessian_func <span style="color: #666666">=</span> hessian(g_trial)
<span style="color: #008000; font-weight: bold">for</span> x_ <span style="color: #AA22FF; font-weight: bold">in</span> x:
<span style="color: #008000; font-weight: bold">for</span> t_ <span style="color: #AA22FF; font-weight: bold">in</span> t:
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_,t_])
g_t <span style="color: #666666">=</span> g_trial(point,P)
g_t_jacobian <span style="color: #666666">=</span> g_t_jacobian_func(point,P)
g_t_hessian <span style="color: #666666">=</span> g_t_hessian_func(point,P)
g_t_dt <span style="color: #666666">=</span> g_t_jacobian[<span style="color: #666666">1</span>]
g_t_d2x <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
func <span style="color: #666666">=</span> f(point)
err_sqr <span style="color: #666666">=</span> ( (g_t_dt <span style="color: #666666">-</span> g_t_d2x) <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
cost_sum <span style="color: #666666">+=</span> err_sqr
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span>( np<span style="color: #666666">.</span>size(x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>size(t) )
<span style="color: #408080; font-style: italic">## For comparison, define the analytical solution</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(point):
x,t <span style="color: #666666">=</span> point
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">**2*</span>t)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
<span style="color: #408080; font-style: italic">## Set up a function for training the network to solve for the equation</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_pde_deep_neural_network</span>(x,t, num_neurons, num_iter, lmb):
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># 2 since we have two points, +1 to include bias</span>
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
<span style="color: #408080; font-style: italic"># For the output layer</span>
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Initial cost: &#39;</span>,cost_function(P, x, t))
cost_function_grad <span style="color: #666666">=</span> grad(cost_function,<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
cost_grad <span style="color: #666666">=</span> cost_function_grad(P, x , t)
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_grad[l]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Final cost: &#39;</span>,cost_function(P, x, t))
<span style="color: #008000; font-weight: bold">return</span> P
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&#39;__main__&#39;</span>:
<span style="color: #408080; font-style: italic">### Use the neural network:</span>
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">15</span>)
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
Nx <span style="color: #666666">=</span> <span style="color: #666666">10</span>; Nt <span style="color: #666666">=</span> <span style="color: #666666">10</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, Nx)
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,Nt)
<span style="color: #408080; font-style: italic">## Set up the parameters for the network</span>
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">100</span>, <span style="color: #666666">25</span>]
num_iter <span style="color: #666666">=</span> <span style="color: #666666">250</span>
lmb <span style="color: #666666">=</span> <span style="color: #666666">0.01</span>
P <span style="color: #666666">=</span> solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)
<span style="color: #408080; font-style: italic">## Store the results</span>
g_dnn_ag <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx, Nt))
G_analytical <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx, Nt))
<span style="color: #008000; font-weight: bold">for</span> i,x_ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(x):
<span style="color: #008000; font-weight: bold">for</span> j, t_ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(t):
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_, t_])
g_dnn_ag[i,j] <span style="color: #666666">=</span> g_trial(point,P)
G_analytical[i,j] <span style="color: #666666">=</span> g_analytic(point)
<span style="color: #408080; font-style: italic"># Find the map difference between the analytical and the computed solution</span>
diff_ag <span style="color: #666666">=</span> np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> G_analytical)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Max absolute difference between the analytical solution and the network: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(diff_ag))
<span style="color: #408080; font-style: italic">## Plot the solutions in two dimensions, that being in position and time</span>
T,X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(t,x)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Solution from the deep neural network w/ </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> layer&#39;</span><span style="color: #666666">%</span><span style="color: #008000">len</span>(num_hidden_neurons))
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,g_dnn_ag,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</span>);
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Analytical solution&#39;</span>)
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,G_analytical,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</span>);
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Difference&#39;</span>)
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,diff_ag,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</span>);
<span style="color: #408080; font-style: italic">## Take some slices of the 3D plots just to see the solutions at particular times</span>
indx1 <span style="color: #666666">=</span> <span style="color: #666666">0</span>
indx2 <span style="color: #666666">=</span> <span style="color: #008000">int</span>(Nt<span style="color: #666666">/2</span>)
indx3 <span style="color: #666666">=</span> Nt<span style="color: #666666">-1</span>
t1 <span style="color: #666666">=</span> t[indx1]
t2 <span style="color: #666666">=</span> t[indx2]
t3 <span style="color: #666666">=</span> t[indx3]
<span style="color: #408080; font-style: italic"># Slice the results from the DNN</span>
res1 <span style="color: #666666">=</span> g_dnn_ag[:,indx1]
res2 <span style="color: #666666">=</span> g_dnn_ag[:,indx2]
res3 <span style="color: #666666">=</span> g_dnn_ag[:,indx3]
<span style="color: #408080; font-style: italic"># Slice the analytical results</span>
res_analytical1 <span style="color: #666666">=</span> G_analytical[:,indx1]
res_analytical2 <span style="color: #666666">=</span> G_analytical[:,indx2]
res_analytical3 <span style="color: #666666">=</span> G_analytical[:,indx3]
<span style="color: #408080; font-style: italic"># Plot the slices</span>
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>t1)
plt<span style="color: #666666">.</span>plot(x, res1)
plt<span style="color: #666666">.</span>plot(x,res_analytical1)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>])
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>t2)
plt<span style="color: #666666">.</span>plot(x, res2)
plt<span style="color: #666666">.</span>plot(x,res_analytical2)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>])
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>t3)
plt<span style="color: #666666">.</span>plot(x, res3)
plt<span style="color: #666666">.</span>plot(x,res_analytical3)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>])
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="example-solving-the-wave-equation-with-neural-networks">Example: Solving the wave equation with Neural Networks </h2>
<p>The wave equation is</p>
$$
\begin{equation*}
\frac{\partial^2 g(x,t)}{\partial t^2} = c^2\frac{\partial^2 g(x,t)}{\partial x^2}
\end{equation*}
$$
<p>with \( c \) being the specified wave speed.</p>
<p>Here, the chosen conditions are</p>
$$
\begin{align*}
g(0,t) &= 0 \\
g(1,t) &= 0 \\
g(x,0) &= u(x) \\
\frac{\partial g(x,t)}{\partial t} \Big |_{t = 0} &= v(x)
\end{align*}
$$
<p>where \( \frac{\partial g(x,t)}{\partial t} \Big |_{t = 0} \) means the derivative of \( g(x,t) \) with respect to \( t \) is evaluated at \( t = 0 \), and \( u(x) \) and \( v(x) \) being given functions.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-problem-to-solve-for">The problem to solve for </h2>
<p>The wave equation to solve for, is</p>
$$
\begin{equation} \label{wave}
\frac{\partial^2 g(x,t)}{\partial t^2} = c^2 \frac{\partial^2 g(x,t)}{\partial x^2}
\end{equation}
$$
<p>where \( c \) is the given wave speed.
The chosen conditions for this equation are
</p>
$$
\begin{aligned}
g(0,t) &= 0, &t \geq 0 \\
g(1,t) &= 0, &t \geq 0 \\
g(x,0) &= u(x), &x\in[0,1] \\
\frac{\partial g(x,t)}{\partial t}\Big |_{t = 0} &= v(x), &x \in [0,1]
\end{aligned} \label{condwave}
$$
<p>In this example, let \( c = 1 \) and \( u(x) = \sin(\pi x) \) and \( v(x) = -\pi\sin(\pi x) \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-trial-solution">The trial solution </h2>
<p>Setting up the network is done in similar matter as for the example of solving the diffusion equation.
The only things we have to change, is the trial solution such that it satisfies the conditions from \eqref{condwave} and the cost function.
</p>
<p>The trial solution becomes slightly different since we have other conditions than in the example of solving the diffusion equation. Here, a possible trial solution \( g_t(x,t) \) is</p>
<p>$$
g_t(x,t) = h_1(x,t) + x(1-x)t^2N(x,t,P)
$$
</p>
<p>where</p>
<p>$$
h_1(x,t) = (1-t^2)u(x) + tv(x)
$$
</p>
<p>Note that this trial solution satisfies the conditions only if \( u(0) = v(0) = u(1) = v(1) = 0 \), which is the case in this example.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-analytical-solution">The analytical solution </h2>
<p>The analytical solution for our specific problem, is</p>
<p>$$
g(x,t) = \sin(\pi x)\cos(\pi t) - \sin(\pi x)\sin(\pi t)
$$
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="solving-the-wave-equation-the-full-program-using-autograd">Solving the wave equation - the full program using Autograd </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> hessian,grad
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> axes3d
<span style="color: #408080; font-style: italic">## Set up the trial function:</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">u</span>(x):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">v</span>(x):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">h1</span>(point):
x,t <span style="color: #666666">=</span> point
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1</span> <span style="color: #666666">-</span> t<span style="color: #666666">**2</span>)<span style="color: #666666">*</span>u(x) <span style="color: #666666">+</span> t<span style="color: #666666">*</span>v(x)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(point,P):
x,t <span style="color: #666666">=</span> point
<span style="color: #008000; font-weight: bold">return</span> h1(point) <span style="color: #666666">+</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>t<span style="color: #666666">**2*</span>deep_neural_network(P,point)
<span style="color: #408080; font-style: italic">## Define the cost function</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x, t):
cost_sum <span style="color: #666666">=</span> <span style="color: #666666">0</span>
g_t_hessian_func <span style="color: #666666">=</span> hessian(g_trial)
<span style="color: #008000; font-weight: bold">for</span> x_ <span style="color: #AA22FF; font-weight: bold">in</span> x:
<span style="color: #008000; font-weight: bold">for</span> t_ <span style="color: #AA22FF; font-weight: bold">in</span> t:
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_,t_])
g_t_hessian <span style="color: #666666">=</span> g_t_hessian_func(point,P)
g_t_d2x <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
g_t_d2t <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">1</span>][<span style="color: #666666">1</span>]
err_sqr <span style="color: #666666">=</span> ( (g_t_d2t <span style="color: #666666">-</span> g_t_d2x) )<span style="color: #666666">**2</span>
cost_sum <span style="color: #666666">+=</span> err_sqr
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> (np<span style="color: #666666">.</span>size(t) <span style="color: #666666">*</span> np<span style="color: #666666">.</span>size(x))
<span style="color: #408080; font-style: italic">## The neural network</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
<span style="color: #408080; font-style: italic"># x is now a point and a 1D numpy array; make it a column vector</span>
num_coordinates <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">0</span>)
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(num_coordinates,<span style="color: #666666">-1</span>)
num_points <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">1</span>)
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
x_input <span style="color: #666666">=</span> x
x_prev <span style="color: #666666">=</span> x_input
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
w_hidden <span style="color: #666666">=</span> deep_params[l]
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
x_prev <span style="color: #666666">=</span> x_hidden
<span style="color: #408080; font-style: italic">## Output layer:</span>
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
<span style="color: #408080; font-style: italic"># Include bias:</span>
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
x_output <span style="color: #666666">=</span> z_output
<span style="color: #008000; font-weight: bold">return</span> x_output[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
<span style="color: #408080; font-style: italic">## The analytical solution</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(point):
x,t <span style="color: #666666">=</span> point
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>cos(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>t) <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>t)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_pde_deep_neural_network</span>(x,t, num_neurons, num_iter, lmb):
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># 2 since we have two points, +1 to include bias</span>
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
<span style="color: #408080; font-style: italic"># For the output layer</span>
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Initial cost: &#39;</span>,cost_function(P, x, t))
cost_function_grad <span style="color: #666666">=</span> grad(cost_function,<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
cost_grad <span style="color: #666666">=</span> cost_function_grad(P, x , t)
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_grad[l]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Final cost: &#39;</span>,cost_function(P, x, t))
<span style="color: #008000; font-weight: bold">return</span> P
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&#39;__main__&#39;</span>:
<span style="color: #408080; font-style: italic">### Use the neural network:</span>
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">15</span>)
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
Nx <span style="color: #666666">=</span> <span style="color: #666666">10</span>; Nt <span style="color: #666666">=</span> <span style="color: #666666">10</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, Nx)
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,Nt)
<span style="color: #408080; font-style: italic">## Set up the parameters for the network</span>
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">50</span>,<span style="color: #666666">20</span>]
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
lmb <span style="color: #666666">=</span> <span style="color: #666666">0.01</span>
P <span style="color: #666666">=</span> solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)
<span style="color: #408080; font-style: italic">## Store the results</span>
res <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx, Nt))
res_analytical <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx, Nt))
<span style="color: #008000; font-weight: bold">for</span> i,x_ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(x):
<span style="color: #008000; font-weight: bold">for</span> j, t_ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(t):
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_, t_])
res[i,j] <span style="color: #666666">=</span> g_trial(point,P)
res_analytical[i,j] <span style="color: #666666">=</span> g_analytic(point)
diff <span style="color: #666666">=</span> np<span style="color: #666666">.</span>abs(res <span style="color: #666666">-</span> res_analytical)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Max difference between analytical and solution from nn: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(diff))
<span style="color: #408080; font-style: italic">## Plot the solutions in two dimensions, that being in position and time</span>
T,X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(t,x)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Solution from the deep neural network w/ </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> layer&#39;</span><span style="color: #666666">%</span><span style="color: #008000">len</span>(num_hidden_neurons))
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,res,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</span>);
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Analytical solution&#39;</span>)
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,res_analytical,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</span>);
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Difference&#39;</span>)
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,diff,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</span>);
<span style="color: #408080; font-style: italic">## Take some slices of the 3D plots just to see the solutions at particular times</span>
indx1 <span style="color: #666666">=</span> <span style="color: #666666">0</span>
indx2 <span style="color: #666666">=</span> <span style="color: #008000">int</span>(Nt<span style="color: #666666">/2</span>)
indx3 <span style="color: #666666">=</span> Nt<span style="color: #666666">-1</span>
t1 <span style="color: #666666">=</span> t[indx1]
t2 <span style="color: #666666">=</span> t[indx2]
t3 <span style="color: #666666">=</span> t[indx3]
<span style="color: #408080; font-style: italic"># Slice the results from the DNN</span>
res1 <span style="color: #666666">=</span> res[:,indx1]
res2 <span style="color: #666666">=</span> res[:,indx2]
res3 <span style="color: #666666">=</span> res[:,indx3]
<span style="color: #408080; font-style: italic"># Slice the analytical results</span>
res_analytical1 <span style="color: #666666">=</span> res_analytical[:,indx1]
res_analytical2 <span style="color: #666666">=</span> res_analytical[:,indx2]
res_analytical3 <span style="color: #666666">=</span> res_analytical[:,indx3]
<span style="color: #408080; font-style: italic"># Plot the slices</span>
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>t1)
plt<span style="color: #666666">.</span>plot(x, res1)
plt<span style="color: #666666">.</span>plot(x,res_analytical1)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>])
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>t2)
plt<span style="color: #666666">.</span>plot(x, res2)
plt<span style="color: #666666">.</span>plot(x,res_analytical2)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>])
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>t3)
plt<span style="color: #666666">.</span>plot(x, res3)
plt<span style="color: #666666">.</span>plot(x,res_analytical3)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>])
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resources-on-differential-equations-and-deep-learning">Resources on differential equations and deep learning </h2>
<ol>
<li> <a href="https://pdfs.semanticscholar.org/d061/df393e0e8fbfd0ea24976458b7d42419040d.pdf" target="_blank">Artificial neural networks for solving ordinary and partial differential equations by I.E. Lagaris et al</a></li>
<li> <a href="https://becominghuman.ai/neural-networks-for-solving-differential-equations-fa230ac5e04c" target="_blank">Neural networks for solving differential equations by A. Honchar</a></li>
<li> <a href="http://cs229.stanford.edu/proj2013/ChiaramonteKiener-SolvingDifferentialEquationsUsingNeuralNetworks.pdf" target="_blank">Solving differential equations using neural networks by M.M Chiaramonte and M. Kiener</a></li>
<li> <a href="https://www.springer.com/us/book/9783540225515" target="_blank">Introduction to Partial Differential Equations by A. Tveito, R. Winther</a></li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="convolutional-neural-networks-recognizing-images">Convolutional Neural Networks (recognizing images) </h2>
<p>Convolutional neural networks (CNNs) were developed during the last
decade of the previous century, with a focus on character recognition
tasks. Nowadays, CNNs are a central element in the spectacular success
of deep learning methods. The success in for example image
classifications have made them a central tool for most machine
learning practitioners.
</p>
<p>CNNs are very similar to ordinary Neural Networks.
They are made up of neurons that have learnable weights and
biases. Each neuron receives some inputs, performs a dot product and
optionally follows it with a non-linearity. The whole network still
expresses a single differentiable score function: from the raw image
pixels on one end to class scores at the other. And they still have a
loss function (for example Softmax) on the last (fully-connected) layer
and all the tips/tricks we developed for learning regular Neural
Networks still apply (back propagation, gradient descent etc etc).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="what-is-the-difference">What is the Difference </h2>
<p><b>CNN architectures make the explicit assumption that
the inputs are images, which allows us to encode certain properties
into the architecture. These then make the forward function more
efficient to implement and vastly reduce the amount of parameters in
the network.</b>
</p>
<p>Here we provide only a superficial overview, for the more interested, we recommend highly the course
<a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" target="_blank">IN5400 &#8211; Machine Learning for Image Analysis</a>
and the slides of <a href="http://cs231n.github.io/convolutional-networks/" target="_blank">CS231</a>.
</p>
<p>Another good read is the article here <a href="https://arxiv.org/pdf/1603.07285.pdf" target="_blank"><tt>https://arxiv.org/pdf/1603.07285.pdf</tt></a>. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="neural-networks-vs-cnns">Neural Networks vs CNNs </h2>
<p>Neural networks are defined as <b>affine transformations</b>, that is
a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an
output (to which a bias vector is usually added before passing the result
through a nonlinear activation function). This is applicable to any type of input, be it an
image, a sound clip or an unordered collection of features: whatever their
dimensionality, their representation can always be flattened into a vector
before the transformation.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc">Why CNNS for images, sound files, medical images from CT scans etc? </h2>
<p>However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic
structure. More formally, they share these important properties:
</p>
<ul>
<li> They are stored as multi-dimensional arrays (think of the pixels of a figure) .</li>
<li> They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).</li>
<li> One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).</li>
</ul>
<p>These properties are not exploited when an affine transformation is applied; in
fact, all the axes are treated in the same way and the topological information
is not taken into account. Still, taking advantage of the implicit structure of
the data may prove very handy in solving some tasks, like computer vision and
speech recognition, and in these cases it would be best to preserve it. This is
where discrete convolutions come into play.
</p>
<p>A discrete convolution is a linear transformation that preserves this notion of
ordering. It is sparse (only a few input units contribute to a given output
unit) and reuses parameters (the same weights are applied to multiple locations
in the input).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="regular-nns-don-t-scale-well-to-full-images">Regular NNs don&#8217;t scale well to full images </h2>
<p>As an example, consider
an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a
single fully-connected neuron in a first hidden layer of a regular
Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still
seems manageable, but clearly this fully-connected structure does not
scale to larger images. For example, an image of more respectable
size, say \( 200\times 200\times 3 \), would lead to neurons that have
\( 200\times 200\times 3 = 120,000 \) weights.
</p>
<p>We could have
several such neurons, and the parameters would add up quickly! Clearly,
this full connectivity is wasteful and the huge number of parameters
would quickly lead to possible overfitting.
</p>
<center> <!-- FIGURE -->
<hr class="figure">
<center>
<p class="caption">Figure 1: A regular 3-layer Neural Network. </p>
</center>
<p><img src="figslides/nn.jpeg" width="500" align="bottom"></p>
</center>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="3d-volumes-of-neurons">3D volumes of neurons </h2>
<p>Convolutional Neural Networks take advantage of the fact that the
input consists of images and they constrain the architecture in a more
sensible way.
</p>
<p>In particular, unlike a regular Neural Network, the
layers of a CNN have neurons arranged in 3 dimensions: width,
height, depth. (Note that the word depth here refers to the third
dimension of an activation volume, not to the depth of a full Neural
Network, which can refer to the total number of layers in a network.)
</p>
<p>To understand it better, the above example of an image
with an input volume of
activations has dimensions \( 32\times 32\times 3 \) (width, height,
depth respectively).
</p>
<p>The neurons in a layer will
only be connected to a small region of the layer before it, instead of
all of the neurons in a fully-connected manner. Moreover, the final
output layer could for this specific image have dimensions \( 1\times 1 \times 10 \),
because by the
end of the CNN architecture we will reduce the full image into a
single vector of class scores, arranged along the depth
dimension.
</p>
<center> <!-- FIGURE -->
<hr class="figure">
<center>
<p class="caption">Figure 2: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). </p>
</center>
<p><img src="figslides/cnn.jpeg" width="500" align="bottom"></p>
</center>
<!-- !split -->
<h2 id="layers-used-to-build-cnns">Layers used to build CNNs </h2>
<p>A simple CNN is a sequence of layers, and every layer of a CNN
transforms one volume of activations to another through a
differentiable function. We use three main types of layers to build
CNN architectures: Convolutional Layer, Pooling Layer, and
Fully-Connected Layer (exactly as seen in regular Neural Networks). We
will stack these layers to form a full CNN architecture.
</p>
<p>A simple CNN for image classification could have the architecture:</p>
<ul>
<li> <b>INPUT</b> (\( 32\times 32 \times 3 \)) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.</li>
<li> <b>CONV</b> (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as \( [32\times 32\times 12] \) if we decided to use 12 filters.</li>
<li> <b>RELU</b> layer will apply an elementwise activation function, such as the \( max(0,x) \) thresholding at zero. This leaves the size of the volume unchanged (\( [32\times 32\times 12] \)).</li>
<li> <b>POOL</b> (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as \( [16\times 16\times 12] \).</li>
<li> <b>FC</b> (i.e. fully-connected) layer will compute the class scores, resulting in volume of size \( [1\times 1\times 10] \), where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="transforming-images">Transforming images </h2>
<p>CNNs transform the original image layer by layer from the original
pixel values to the final class scores.
</p>
<p>Observe that some layers contain
parameters and other don&#8217;t. In particular, the CNN layers perform
transformations that are a function of not only the activations in the
input volume, but also of the parameters (the weights and biases of
the neurons). On the other hand, the RELU/POOL layers will implement a
fixed function. The parameters in the CONV/FC layers will be trained
with gradient descent so that the class scores that the CNN computes
are consistent with the labels in the training set for each image.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cnns-in-brief">CNNs in brief </h2>
<p>In summary:</p>
<ul>
<li> A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)</li>
<li> There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)</li>
<li> Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function</li>
<li> Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don&#8217;t)</li>
<li> Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn&#8217;t)</li>
</ul>
<p>For more material on convolutional networks, we strongly recommend
the course
<a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" target="_blank">IN5400 &#8211; Machine Learning for Image Analysis</a>
and the slides of <a href="http://cs231n.github.io/convolutional-networks/" target="_blank">CS231</a> which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). <a href="http://neuralnetworksanddeeplearning.com/chap6.html" target="_blank">Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs</a>.
</p>
<p>The textbook by Goodfellow et al, see chapter 9 contains an in depth discussion as well.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="key-idea">Key Idea </h2>
<p>A dense neural network is representd by an affine operation (like matrix-matrix multiplication) where all parameters are included.</p>
<p>The key idea in CNNs for say imaging is that in images neighbor pixels tend to be related! So we connect
only neighboring neurons in the input instead of connecting all with the first hidden layer.
</p>
<p>We say we perform a filtering (convolution is the mathematical operation). </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="mathematics-of-cnns">Mathematics of CNNs </h2>
<p>The mathematics of CNNs is based on the mathematical operation of
<b>convolution</b>. In mathematics (in particular in functional analysis),
convolution is represented by mathematical operation (integration,
summation etc) on two function in order to produce a third function
that expresses how the shape of one gets modified by the other.
Convolution has a plethora of applications in a variety of disciplines, spanning from statistics to signal processing, computer vision, solutions of differential equations,linear algebra, engineering, and yes, machine learning.
</p>
<p>Mathematically, convolution is defined as follows (one-dimensional example):
Let us define a continuous function \( y(t) \) given by
</p>
$$
y(t) = \int x(a) w(t-a) da,
$$
<p>where \( x(a) \) represents a so-called input and \( w(t-a) \) is normally called the weight function or kernel.</p>
<p>The above integral is written in a more compact form as</p>
$$
y(t) = \left(x * w\right)(t).
$$
<p>The discretized version reads</p>
$$
y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a).
$$
<p>Computing the inverse of the above convolution operations is known as deconvolution.</p>
<p>How can we use this? And what does it mean? Let us study some familiar examples first.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="convolution-examples-polynomial-multiplication">Convolution Examples: Polynomial multiplication </h2>
<p>We have already met such an example in project 1 when we tried to set
up the design matrix for a two-dimensional function. This was an
example of polynomial multiplication. Let us recast such a problem in terms of the convolution operation.
Let us look a the following polynomials to second and third order, respectively:
</p>
$$
p(t) = \alpha_0+\alpha_1 t+\alpha_2 t^2,
$$
<p>and</p>
$$
s(t) = \beta_0+\beta_1 t+\beta_2 t^2+\beta_3 t^3.
$$
<p>The polynomial multiplication gives us a new polynomial of degree \( 5 \)</p>
$$
z(t) = \delta_0+\delta_1 t+\delta_2 t^2+\delta_3 t^3+\delta_4 t^4+\delta_5 t^5.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="efficient-polynomial-multiplication">Efficient Polynomial Multiplication </h2>
<p>Computing polynomial products can be implemented efficiently if we rewrite the more brute force multiplications using convolution.
We note first that the new coefficients are given as
</p>
$$
\begin{split}
\delta_0=&\alpha_0\beta_0\\
\delta_1=&\alpha_1\beta_0+\alpha_1\beta_0\\
\delta_2=&\alpha_0\beta_2+\alpha_1\beta_1+\alpha_2\beta_0\\
\delta_3=&\alpha_1\beta_2+\alpha_2\beta_1+\alpha_0\beta_3\\
\delta_4=&\alpha_2\beta_2+\alpha_1\beta_3\\
\delta_5=&\alpha_2\beta_3.\\
\end{split}
$$
<p>We note that \( \alpha_i=0 \) except for \( i\in \left\{0,1,2\right\} \) and \( \beta_i=0 \) except for \( i\in\left\{0,1,2,3\right\} \).</p>
<p>We can then rewrite the coefficients \( \delta_j \) using a discrete convolution as</p>
$$
\delta_j = \sum_{i=-\infty}^{i=\infty}\alpha_i\beta_{j-i}=(\alpha * \beta)_j,
$$
<p>or as a double sum with restriction \( l=i+j \)</p>
$$
\delta_l = \sum_{ij}\alpha_i\beta_{j}.
$$
<p>Do you see a potential drawback with these equations?</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-more-efficient-way-of-coding-the-above-convolution">A more efficient way of coding the above Convolution </h2>
<p>Since we only have a finite number of \( \alpha \) and \( \beta \) values
which are non-zero, we can rewrite the above convolution expressions
as a matrix-vector multiplication
</p>
$$
\boldsymbol{\delta}=\begin{bmatrix}\alpha_0 & 0 & 0 & 0 \\
\alpha_1 & \alpha_0 & 0 & 0 \\
\alpha_2 & \alpha_1 & \alpha_0 & 0 \\
0 & \alpha_2 & \alpha_1 & \alpha_0 \\
0 & 0 & \alpha_2 & \alpha_1 \\
0 & 0 & 0 & \alpha_2
\end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}.
$$
<p>The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding \( \beta \) and a vector holding \( \alpha \).
In this case we have
</p>
$$
\boldsymbol{\delta}=\begin{bmatrix}\beta_0 & 0 & 0 \\
\beta_1 & \beta_0 & 0 \\
\beta_2 & \beta_1 & \beta_0 \\
\beta_3 & \beta_2 & \beta_1 \\
0 & \beta_3 & \beta_2 \\
0 & 0 & \beta_3
\end{bmatrix}\begin{bmatrix} \alpha_0 \\ \alpha_1 \\ \alpha_2\end{bmatrix}.
$$
<p>Note that the use of these matrices is for mathematical purposes only and not implementation purposes.
When implementing the above equation we do not encode (and allocate memory) the matrices explicitely.
We rather code the convolutions in the minimal memory footprint that they require.
</p>
<p>Does the number of floating point operations change here when we use the commutative property?</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="convolution-examples-principle-of-superposition-and-periodic-forces-fourier-transforms">Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms) </h2>
<p>For problems with so-called harmonic oscillations, given by for example the following differential equation</p>
$$
m\frac{d^2x}{dt^2}+\eta\frac{dx}{dt}+x(t)=F(t),
$$
<p>where \( F(t) \) is an applied external force acting on the system (often called a driving force), one can use the theory of Fourier transformations to find the solutions of this type of equations.</p>
<p>If one has several driving forces, \( F(t)=\sum_n F_n(t) \), one can find
the particular solution to each \( F_n \), \( x_{pn}(t) \), and the particular
solution for the entire driving force is then given by a series like
</p>
$$
\begin{equation}
x_p(t)=\sum_nx_{pn}(t).
\label{_auto3}
\end{equation}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="principle-of-superposition">Principle of Superposition </h2>
<p>This is known as the principle of superposition. It only applies when
the homogenous equation is linear. If there were an anharmonic term
such as \( x^3 \) in the homogenous equation, then when one summed various
solutions, \( x=(\sum_n x_n)^2 \), one would get cross
terms. Superposition is especially useful when \( F(t) \) can be written
as a sum of sinusoidal terms, because the solutions for each
sinusoidal (sine or cosine) term is analytic.
</p>
<p>Driving forces are often periodic, even when they are not
sinusoidal. Periodicity implies that for some time \( \tau \)
</p>
$$
\begin{eqnarray}
F(t+\tau)=F(t).
\end{eqnarray}
$$
<p>One example of a non-sinusoidal periodic force is a square wave. Many
components in electric circuits are non-linear, e.g. diodes, which
makes many wave forms non-sinusoidal even when the circuits are being
driven by purely sinusoidal sources.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="simple-code-example">Simple Code Example </h2>
<p>The code here shows a typical example of such a square wave generated using the functionality included in the <b>scipy</b> Python package. We have used a period of \( \tau=0.2 \).</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">math</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">scipy</span> <span style="color: #008000; font-weight: bold">import</span> signal
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #408080; font-style: italic"># number of points </span>
n <span style="color: #666666">=</span> <span style="color: #666666">500</span>
<span style="color: #408080; font-style: italic"># start and final times </span>
t0 <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
tn <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
<span style="color: #408080; font-style: italic"># Period </span>
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(t0, tn, n, endpoint<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
SqrSignal <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)
SqrSignal <span style="color: #666666">=</span> <span style="color: #666666">1.0+</span>signal<span style="color: #666666">.</span>square(<span style="color: #666666">2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*5*</span>t)
plt<span style="color: #666666">.</span>plot(t, SqrSignal)
plt<span style="color: #666666">.</span>ylim(<span style="color: #666666">-0.5</span>, <span style="color: #666666">2.5</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>For the sinusoidal example the
period is \( \tau=2\pi/\omega \). However, higher harmonics can also
satisfy the periodicity requirement. In general, any force that
satisfies the periodicity requirement can be expressed as a sum over
harmonics,
</p>
$$
\begin{equation}
F(t)=\frac{f_0}{2}+\sum_{n>0} f_n\cos(2n\pi t/\tau)+g_n\sin(2n\pi t/\tau).
\label{_auto4}
\end{equation}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="wrapping-up-fourier-transforms">Wrapping up Fourier transforms </h2>
<p>We can write down the answer for
\( x_{pn}(t) \), by substituting \( f_n/m \) or \( g_n/m \) for \( F_0/m \). By
writing each factor \( 2n\pi t/\tau \) as \( n\omega t \), with \( \omega\equiv
2\pi/\tau \),
</p>
$$
\begin{equation}
\label{eq:fourierdef1}
F(t)=\frac{f_0}{2}+\sum_{n>0}f_n\cos(n\omega t)+g_n\sin(n\omega t).
\end{equation}
$$
<p>The solutions for \( x(t) \) then come from replacing \( \omega \) with
\( n\omega \) for each term in the particular solution,
</p>
$$
\begin{eqnarray}
x_p(t)&=&\frac{f_0}{2k}+\sum_{n>0} \alpha_n\cos(n\omega t-\delta_n)+\beta_n\sin(n\omega t-\delta_n),\\
\nonumber
\alpha_n&=&\frac{f_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\
\nonumber
\beta_n&=&\frac{g_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\
\nonumber
\delta_n&=&\tan^{-1}\left(\frac{2\beta n\omega}{\omega_0^2-n^2\omega^2}\right).
\end{eqnarray}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="finding-the-coefficients">Finding the Coefficients </h2>
<p>Because the forces have been applied for a long time, any non-zero
damping eliminates the homogenous parts of the solution, so one need
only consider the particular solution for each \( n \).
</p>
<p>The problem is considered solved if one can find expressions for the
coefficients \( f_n \) and \( g_n \), even though the solutions are expressed
as an infinite sum. The coefficients can be extracted from the
function \( F(t) \) by
</p>
$$
\begin{eqnarray}
\label{eq:fourierdef2}
f_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\cos(2n\pi t/\tau),\\
\nonumber
g_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\sin(2n\pi t/\tau).
\end{eqnarray}
$$
<p>To check the consistency of these expressions and to verify
Eq. \eqref{eq:fourierdef2}, one can insert the expansion of \( F(t) \) in
Eq. \eqref{eq:fourierdef1} into the expression for the coefficients in
Eq. \eqref{eq:fourierdef2} and see whether
</p>
$$
\begin{eqnarray}
f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~\left\{
\frac{f_0}{2}+\sum_{m>0}f_m\cos(m\omega t)+g_m\sin(m\omega t)
\right\}\cos(n\omega t).
\end{eqnarray}
$$
<p>Immediately, one can throw away all the terms with \( g_m \) because they
convolute an even and an odd function. The term with \( f_0/2 \)
disappears because \( \cos(n\omega t) \) is equally positive and negative
over the interval and will integrate to zero. For all the terms
\( f_m\cos(m\omega t) \) appearing in the sum, one can use angle addition
formulas to see that \( \cos(m\omega t)\cos(n\omega
t)=(1/2)(\cos[(m+n)\omega t]+\cos[(m-n)\omega t] \). This will integrate
to zero unless \( m=n \). In that case the \( m=n \) term gives
</p>
$$
\begin{equation}
\int_{-\tau/2}^{\tau/2}dt~\cos^2(m\omega t)=\frac{\tau}{2},
\label{_auto5}
\end{equation}
$$
<p>and</p>
$$
\begin{eqnarray}
f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~f_n/2\\
\nonumber
&=&f_n~\checkmark.
\end{eqnarray}
$$
<p>The same method can be used to check for the consistency of \( g_n \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-words-on-fourier-transforms">Final words on Fourier Transforms </h2>
<p>The code here uses the Fourier series applied to a
square wave signal. The code here
visualizes the various approximations given by Fourier series compared
with a square wave with period \( T=0.2 \) (dimensionless time), width \( 0.1 \) and max value of the force \( F=2 \). We
see that when we increase the number of components in the Fourier
series, the Fourier series approximation gets closer and closer to the
square wave signal.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">math</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">scipy</span> <span style="color: #008000; font-weight: bold">import</span> signal
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #408080; font-style: italic"># number of points </span>
n <span style="color: #666666">=</span> <span style="color: #666666">500</span>
<span style="color: #408080; font-style: italic"># start and final times </span>
t0 <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
tn <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
<span style="color: #408080; font-style: italic"># Period </span>
T <span style="color: #666666">=0.2</span>
<span style="color: #408080; font-style: italic"># Max value of square signal </span>
Fmax<span style="color: #666666">=</span> <span style="color: #666666">2.0</span>
<span style="color: #408080; font-style: italic"># Width of signal </span>
Width <span style="color: #666666">=</span> <span style="color: #666666">0.1</span>
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(t0, tn, n, endpoint<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
SqrSignal <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)
FourierSeriesSignal <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)
SqrSignal <span style="color: #666666">=</span> <span style="color: #666666">1.0+</span>signal<span style="color: #666666">.</span>square(<span style="color: #666666">2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*5*</span>t<span style="color: #666666">+</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>Width<span style="color: #666666">/</span>T)
a0 <span style="color: #666666">=</span> Fmax<span style="color: #666666">*</span>Width<span style="color: #666666">/</span>T
FourierSeriesSignal <span style="color: #666666">=</span> a0
Factor <span style="color: #666666">=</span> <span style="color: #666666">2.0*</span>Fmax<span style="color: #666666">/</span>np<span style="color: #666666">.</span>pi
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,<span style="color: #666666">500</span>):
FourierSeriesSignal <span style="color: #666666">+=</span> Factor<span style="color: #666666">/</span>(i)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>i<span style="color: #666666">*</span>Width<span style="color: #666666">/</span>T)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>cos(i<span style="color: #666666">*</span>t<span style="color: #666666">*2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">/</span>T)
plt<span style="color: #666666">.</span>plot(t, SqrSignal)
plt<span style="color: #666666">.</span>plot(t, FourierSeriesSignal)
plt<span style="color: #666666">.</span>ylim(<span style="color: #666666">-0.5</span>, <span style="color: #666666">2.5</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="two-dimensional-objects">Two-dimensional Objects </h2>
<p>We often use convolutions over more than one dimension at a time. If
we have a two-dimensional image \( I \) as input, we can have a <b>filter</b>
defined by a two-dimensional <b>kernel</b> \( K \). This leads to an output \( S \)
</p>
$$
S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(m,n)K(i-m,j-n).
$$
<p>Convolution is a commutatitave process, which means we can rewrite this equation as</p>
$$
S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i-m,j-n)K(m,n).
$$
<p>Normally the latter is more straightforward to implement in a machine elarning library since there is less variation in the range of values of \( m \) and \( n \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cross-correlation">Cross-Correlation </h2>
<p>Many deep learning libraries implement cross-correlation instead of convolution</p>
$$
S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i+m,j-+)K(m,n).
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-on-dimensionalities">More on Dimensionalities </h2>
<p>In feilds like signal processing (and imaging as well), one designs
so-called filters. These filters are defined by the convolutions and
are often hand-crafted. One may specify filters for smoothing, edge
detection, frequency reshaping, and similar operations. However with
neural networks the idea is to automatically learn the filters and use
many of them in conjunction with non-linear operations (activation
functions).
</p>
<p>As an example consider a neural network operating on sound sequence
data. Assume that we an input vector \( \boldsymbol{x} \) of length \( d=10^6 \). We
construct then a neural network with onle hidden layer only with
\( 10^4 \) nodes. This means that we will have a weight matrix with
\( 10^4\times 10^6=10^{10} \) weights to be determined, together with \( 10^4 \) biases.
</p>
<p>Assume furthermore that we have an output layer which is meant to train whether the sound sequence represents a human voice (true) or something else (false).
It means that we have only one output node. But since this output node connects to \( 10^4 \) nodes in the hidden layer, there are in total \( 10^4 \) weights to be determined for the output layer, plus one bias. In total we have
</p>
$$
\mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \approx 10^{10},
$$
<p>that is ten billion parameters to determine. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="further-dimensionality-remarks">Further Dimensionality Remarks </h2>
<p>In today&#8217;s architecture one can train such neural networks, however
this is a huge number of parameters for the task at hand. In general,
it is a very wasteful and inefficient use of dense matrices as
parameters. Just as importantly, such trained network parameters are
very specific for the type of input data on which they were trained
and the network is not likely to generalize easily to variations in
the input.
</p>
<p>The main principles that justify convolutions is locality of
information and repetion of patterns within the signal. Sound samples
of the input in adjacent spots are much more likely to affect each
other than those that are very far away. Similarly, sounds are
repeated in multiple times in the signal. While slightly simplistic,
reasoning about such a sound example demonstrates this. The same
principles then apply to images and other similar data.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cnns-in-more-detail-lecture-from-in5400">CNNs in more detail, Lecture from IN5400 </h2>
<ul>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/v19/material/week5/in5400_2019_week5_convolutional_nerual_networks.pdf" target="_blank">Lectures from IN5400 spring 2019</a></li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras </h2>
<p>As discussed above, CNNs are neural networks built from the assumption that the inputs
to the network are 2D images. This is important because the number of features or pixels in images
grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
</p>
<p>As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
are the <b>convolutional</b> and <b>pooling</b> layers stacked in pairs between the input and the hidden layer.
In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
matrices, typically 1 for each color dimension (Red, Green, Blue).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-it-up">Setting it up </h2>
<p>It means that to represent the entire
dataset of images, we require a 4D matrix or <b>tensor</b>. This tensor has the dimensions:
</p>
$$
(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-mnist-dataset-again">The MNIST dataset again </h2>
<p>The MNIST dataset consists of grayscale images with a pixel size of
\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each
neuron in the first hidden layer.
</p>
<p>If we were to analyze images of size \( 128\times 128 \) we would require
\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were
dealing with color images, as most images are, we have an image matrix
of size \( 128\times 128 \) for each color dimension (Red, Green, Blue),
meaning 3 times the number of weights \( = 49152 \) are required for every
single neuron in the first hidden layer.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="strong-correlations">Strong correlations </h2>
<p>Images typically have strong local correlations, meaning that a small
part of the image varies little from its neighboring regions. If for
example we have an image of a blue car, we can roughly assume that a
small blue part of the image is surrounded by other blue regions.
</p>
<p>Therefore, instead of connecting every single pixel to a neuron in the
first hidden layer, as we have previously done with deep neural
networks, we can instead connect each neuron to a small part of the
image (in all 3 RGB depth dimensions). The size of each small area is
fixed, and known as a <a href="https://en.wikipedia.org/wiki/Receptive_field" target="_blank">receptive</a>.
</p>
<!-- !split -->
<h2 id="layers-of-a-cnn">Layers of a CNN </h2>
<p>The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
The input image is typically a square matrix of depth 3.
</p>
<p>A <b>convolution</b> is performed on the image which outputs
a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as <b>filters</b>.
</p>
<p>Each filter slides along the input image, taking the dot product
between each small part of the image and the filter, in all depth
dimensions. This is then passed through a non-linear function,
typically the <b>Rectified Linear (ReLu)</b> function, which serves as the
activation of the neurons in the first convolutional layer. This is
further passed through a <b>pooling layer</b>, which reduces the size of the
convolutional layer, e.g. by taking the maximum or average across some
small regions, and this serves as input to the next convolutional
layer.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="systematic-reduction">Systematic reduction </h2>
<p>By systematically reducing the size of the input volume, through
convolution and pooling, the network should create representations of
small parts of the input, and then from them assemble representations
of larger areas. The final pooling layer is flattened to serve as
input to a hidden layer, such that each neuron in the final pooling
layer is connected to every single neuron in the hidden layer. This
then serves as input to the output layer, e.g. a softmax output for
classification.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="prerequisites-collect-and-pre-process-data">Prerequisites: Collect and pre-process data </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># import necessary packages</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> datasets
<span style="color: #408080; font-style: italic"># ensure the same random numbers appear every time</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># display images in notebook</span>
<span style="color: #666666">%</span>matplotlib inline
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;figure.figsize&#39;</span>] <span style="color: #666666">=</span> (<span style="color: #666666">12</span>,<span style="color: #666666">12</span>)
<span style="color: #408080; font-style: italic"># download MNIST dataset</span>
digits <span style="color: #666666">=</span> datasets<span style="color: #666666">.</span>load_digits()
<span style="color: #408080; font-style: italic"># define inputs and labels</span>
inputs <span style="color: #666666">=</span> digits<span style="color: #666666">.</span>images
labels <span style="color: #666666">=</span> digits<span style="color: #666666">.</span>target
<span style="color: #408080; font-style: italic"># RGB images have a depth of 3</span>
<span style="color: #408080; font-style: italic"># our images are grayscale so they should have a depth of 1</span>
inputs <span style="color: #666666">=</span> inputs[:,:,:,np<span style="color: #666666">.</span>newaxis]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;inputs = (n_inputs, pixel_width, pixel_height, depth) = &quot;</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(inputs<span style="color: #666666">.</span>shape))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;labels = (n_inputs) = &quot;</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(labels<span style="color: #666666">.</span>shape))
<span style="color: #408080; font-style: italic"># choose some random images to display</span>
n_inputs <span style="color: #666666">=</span> <span style="color: #008000">len</span>(inputs)
indices <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(n_inputs)
random_indices <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>choice(indices, size<span style="color: #666666">=5</span>)
<span style="color: #008000; font-weight: bold">for</span> i, image <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(digits<span style="color: #666666">.</span>images[random_indices]):
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">1</span>, <span style="color: #666666">5</span>, i<span style="color: #666666">+1</span>)
plt<span style="color: #666666">.</span>axis(<span style="color: #BA2121">&#39;off&#39;</span>)
plt<span style="color: #666666">.</span>imshow(image, cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>gray_r, interpolation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;nearest&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Label: </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">%</span> digits<span style="color: #666666">.</span>target[random_indices[i]])
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="importing-keras-and-tensorflow">Importing Keras and Tensorflow </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras</span> <span style="color: #008000; font-weight: bold">import</span> datasets, layers, models
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras.layers</span> <span style="color: #008000; font-weight: bold">import</span> Input
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras.models</span> <span style="color: #008000; font-weight: bold">import</span> Sequential <span style="color: #408080; font-style: italic">#This allows appending layers to existing models</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras.layers</span> <span style="color: #008000; font-weight: bold">import</span> Dense <span style="color: #408080; font-style: italic">#This allows defining the characteristics of a particular layer</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras</span> <span style="color: #008000; font-weight: bold">import</span> optimizers <span style="color: #408080; font-style: italic">#This allows using whichever optimiser we want (sgd,adam,RMSprop)</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras</span> <span style="color: #008000; font-weight: bold">import</span> regularizers <span style="color: #408080; font-style: italic">#This allows using whichever regularizer we want (l1,l2,l1_l2)</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras.utils</span> <span style="color: #008000; font-weight: bold">import</span> to_categorical <span style="color: #408080; font-style: italic">#This allows using categorical cross entropy as the cost function</span>
<span style="color: #408080; font-style: italic">#from tensorflow.keras import Conv2D</span>
<span style="color: #408080; font-style: italic">#from tensorflow.keras import MaxPooling2D</span>
<span style="color: #408080; font-style: italic">#from tensorflow.keras import Flatten</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #408080; font-style: italic"># representation of labels</span>
labels <span style="color: #666666">=</span> to_categorical(labels)
<span style="color: #408080; font-style: italic"># split into train and test data</span>
<span style="color: #408080; font-style: italic"># one-liner from scikit-learn library</span>
train_size <span style="color: #666666">=</span> <span style="color: #666666">0.8</span>
test_size <span style="color: #666666">=</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> train_size
X_train, X_test, Y_train, Y_test <span style="color: #666666">=</span> train_test_split(inputs, labels, train_size<span style="color: #666666">=</span>train_size,
test_size<span style="color: #666666">=</span>test_size)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split -->
<h2 id="running-with-keras">Running with Keras </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">create_convolutional_neural_network_keras</span>(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd):
model <span style="color: #666666">=</span> Sequential()
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(n_filters, (receptive_field, receptive_field), input_shape<span style="color: #666666">=</span>input_shape, padding<span style="color: #666666">=</span><span style="color: #BA2121">&#39;same&#39;</span>,
activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>, kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lmbd)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>MaxPooling2D(pool_size<span style="color: #666666">=</span>(<span style="color: #666666">2</span>, <span style="color: #666666">2</span>)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Flatten())
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dense(n_neurons_connected, activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>, kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lmbd)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dense(n_categories, activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;softmax&#39;</span>, kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lmbd)))
sgd <span style="color: #666666">=</span> optimizers<span style="color: #666666">.</span>SGD(lr<span style="color: #666666">=</span>eta)
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">&#39;categorical_crossentropy&#39;</span>, optimizer<span style="color: #666666">=</span>sgd, metrics<span style="color: #666666">=</span>[<span style="color: #BA2121">&#39;accuracy&#39;</span>])
<span style="color: #008000; font-weight: bold">return</span> model
epochs <span style="color: #666666">=</span> <span style="color: #666666">100</span>
batch_size <span style="color: #666666">=</span> <span style="color: #666666">100</span>
input_shape <span style="color: #666666">=</span> X_train<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>:<span style="color: #666666">4</span>]
receptive_field <span style="color: #666666">=</span> <span style="color: #666666">3</span>
n_filters <span style="color: #666666">=</span> <span style="color: #666666">10</span>
n_neurons_connected <span style="color: #666666">=</span> <span style="color: #666666">50</span>
n_categories <span style="color: #666666">=</span> <span style="color: #666666">10</span>
eta_vals <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-5</span>, <span style="color: #666666">1</span>, <span style="color: #666666">7</span>)
lmbd_vals <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-5</span>, <span style="color: #666666">1</span>, <span style="color: #666666">7</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-part">Final part </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">CNN_keras <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)), dtype<span style="color: #666666">=</span><span style="color: #008000">object</span>)
<span style="color: #008000; font-weight: bold">for</span> i, eta <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(eta_vals):
<span style="color: #008000; font-weight: bold">for</span> j, lmbd <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(lmbd_vals):
CNN <span style="color: #666666">=</span> create_convolutional_neural_network_keras(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd)
CNN<span style="color: #666666">.</span>fit(X_train, Y_train, epochs<span style="color: #666666">=</span>epochs, batch_size<span style="color: #666666">=</span>batch_size, verbose<span style="color: #666666">=0</span>)
scores <span style="color: #666666">=</span> CNN<span style="color: #666666">.</span>evaluate(X_test, Y_test)
CNN_keras[i][j] <span style="color: #666666">=</span> CNN
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Learning rate = &quot;</span>, eta)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Lambda = &quot;</span>, lmbd)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test accuracy: </span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">%</span> scores[<span style="color: #666666">1</span>])
<span style="color: #008000">print</span>()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-visualization">Final visualization </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># visual representation of grid search</span>
<span style="color: #408080; font-style: italic"># uses seaborn heatmap, could probably do this in matplotlib</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">seaborn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">sns</span>
sns<span style="color: #666666">.</span>set()
train_accuracy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)))
test_accuracy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)))
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">len</span>(eta_vals)):
<span style="color: #008000; font-weight: bold">for</span> j <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">len</span>(lmbd_vals)):
CNN <span style="color: #666666">=</span> CNN_keras[i][j]
train_accuracy[i][j] <span style="color: #666666">=</span> CNN<span style="color: #666666">.</span>evaluate(X_train, Y_train)[<span style="color: #666666">1</span>]
test_accuracy[i][j] <span style="color: #666666">=</span> CNN<span style="color: #666666">.</span>evaluate(X_test, Y_test)[<span style="color: #666666">1</span>]
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots(figsize <span style="color: #666666">=</span> (<span style="color: #666666">10</span>, <span style="color: #666666">10</span>))
sns<span style="color: #666666">.</span>heatmap(train_accuracy, annot<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, ax<span style="color: #666666">=</span>ax, cmap<span style="color: #666666">=</span><span style="color: #BA2121">&quot;viridis&quot;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&quot;Training Accuracy&quot;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&quot;$\eta$&quot;</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&quot;$\lambda$&quot;</span>)
plt<span style="color: #666666">.</span>show()
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots(figsize <span style="color: #666666">=</span> (<span style="color: #666666">10</span>, <span style="color: #666666">10</span>))
sns<span style="color: #666666">.</span>heatmap(test_accuracy, annot<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, ax<span style="color: #666666">=</span>ax, cmap<span style="color: #666666">=</span><span style="color: #BA2121">&quot;viridis&quot;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&quot;Test Accuracy&quot;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&quot;$\eta$&quot;</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&quot;$\lambda$&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-cifar01-data-set">The CIFAR01 data set </h2>
<p>The CIFAR10 dataset contains 60,000 color images in 10 classes, with
6,000 images in each class. The dataset is divided into 50,000
training images and 10,000 testing images. The classes are mutually
exclusive and there is no overlap between them.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">tensorflow</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">tf</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras</span> <span style="color: #008000; font-weight: bold">import</span> datasets, layers, models
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #408080; font-style: italic"># We import the data set</span>
(train_images, train_labels), (test_images, test_labels) <span style="color: #666666">=</span> datasets<span style="color: #666666">.</span>cifar10<span style="color: #666666">.</span>load_data()
<span style="color: #408080; font-style: italic"># Normalize pixel values to be between 0 and 1 by dividing by 255. </span>
train_images, test_images <span style="color: #666666">=</span> train_images <span style="color: #666666">/</span> <span style="color: #666666">255.0</span>, test_images <span style="color: #666666">/</span> <span style="color: #666666">255.0</span>
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="verifying-the-data-set">Verifying the data set </h2>
<p>To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">class_names <span style="color: #666666">=</span> [<span style="color: #BA2121">&#39;airplane&#39;</span>, <span style="color: #BA2121">&#39;automobile&#39;</span>, <span style="color: #BA2121">&#39;bird&#39;</span>, <span style="color: #BA2121">&#39;cat&#39;</span>, <span style="color: #BA2121">&#39;deer&#39;</span>,
<span style="color: #BA2121">&#39;dog&#39;</span>, <span style="color: #BA2121">&#39;frog&#39;</span>, <span style="color: #BA2121">&#39;horse&#39;</span>, <span style="color: #BA2121">&#39;ship&#39;</span>, <span style="color: #BA2121">&#39;truck&#39;</span>]
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">25</span>):
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">5</span>,<span style="color: #666666">5</span>,i<span style="color: #666666">+1</span>)
plt<span style="color: #666666">.</span>xticks([])
plt<span style="color: #666666">.</span>yticks([])
plt<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">False</span>)
plt<span style="color: #666666">.</span>imshow(train_images[i], cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>binary)
<span style="color: #408080; font-style: italic"># The CIFAR labels happen to be arrays, </span>
<span style="color: #408080; font-style: italic"># which is why you need the extra index</span>
plt<span style="color: #666666">.</span>xlabel(class_names[train_labels[i][<span style="color: #666666">0</span>]])
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="set-up-the-model">Set up the model </h2>
<p>The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.</p>
<p>As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">model <span style="color: #666666">=</span> models<span style="color: #666666">.</span>Sequential()
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(<span style="color: #666666">32</span>, (<span style="color: #666666">3</span>, <span style="color: #666666">3</span>), activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>, input_shape<span style="color: #666666">=</span>(<span style="color: #666666">32</span>, <span style="color: #666666">32</span>, <span style="color: #666666">3</span>)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>MaxPooling2D((<span style="color: #666666">2</span>, <span style="color: #666666">2</span>)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(<span style="color: #666666">64</span>, (<span style="color: #666666">3</span>, <span style="color: #666666">3</span>), activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>MaxPooling2D((<span style="color: #666666">2</span>, <span style="color: #666666">2</span>)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(<span style="color: #666666">64</span>, (<span style="color: #666666">3</span>, <span style="color: #666666">3</span>), activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>))
<span style="color: #408080; font-style: italic"># Let&#39;s display the architecture of our model so far.</span>
model<span style="color: #666666">.</span>summary()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="add-dense-layers-on-top">Add Dense layers on top </h2>
<p>To complete our model, you will feed the last output tensor from the
convolutional base (of shape (4, 4, 64)) into one or more Dense layers
to perform classification. Dense layers take vectors as input (which
are 1D), while the current output is a 3D tensor. First, you will
flatten (or unroll) the 3D output to 1D, then add one or more Dense
layers on top. CIFAR has 10 output classes, so you use a final Dense
layer with 10 outputs and a softmax activation.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Flatten())
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dense(<span style="color: #666666">64</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dense(<span style="color: #666666">10</span>))
Here<span style="color: #BA2121">&#39;s the complete architecture of our model.</span>
model<span style="color: #666666">.</span>summary()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="compile-and-train-the-model">Compile and train the model </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">model<span style="color: #666666">.</span>compile(optimizer<span style="color: #666666">=</span><span style="color: #BA2121">&#39;adam&#39;</span>,
loss<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>keras<span style="color: #666666">.</span>losses<span style="color: #666666">.</span>SparseCategoricalCrossentropy(from_logits<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>),
metrics<span style="color: #666666">=</span>[<span style="color: #BA2121">&#39;accuracy&#39;</span>])
history <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(train_images, train_labels, epochs<span style="color: #666666">=10</span>,
validation_data<span style="color: #666666">=</span>(test_images, test_labels))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="finally-evaluate-the-model">Finally, evaluate the model </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">plt<span style="color: #666666">.</span>plot(history<span style="color: #666666">.</span>history[<span style="color: #BA2121">&#39;accuracy&#39;</span>], label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;accuracy&#39;</span>)
plt<span style="color: #666666">.</span>plot(history<span style="color: #666666">.</span>history[<span style="color: #BA2121">&#39;val_accuracy&#39;</span>], label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;val_accuracy&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Epoch&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;Accuracy&#39;</span>)
plt<span style="color: #666666">.</span>ylim([<span style="color: #666666">0.5</span>, <span style="color: #666666">1</span>])
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&#39;lower right&#39;</span>)
test_loss, test_acc <span style="color: #666666">=</span> model<span style="color: #666666">.</span>evaluate(test_images, test_labels, verbose<span style="color: #666666">=2</span>)
<span style="color: #008000">print</span>(test_acc)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>