Files
FYS-STK4155/doc/pub/week43/html/week43.html
T
Morten Hjorth-Jensen d488bb07cf update week 43
2025-10-20 07:32:29 +02:00

5203 lines
364 KiB
HTML

<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week43.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=week43 --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 43: Deep Learning: Constructing a Neural Network code and solving differential equations">
<title>Week 43: Deep Learning: Constructing a Neural Network code and solving differential equations</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': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Exercises and lab session week 43',
2,
None,
'exercises-and-lab-session-week-43'),
('Using Automatic differentiation',
2,
None,
'using-automatic-differentiation'),
('Back propagation and automatic differentiation',
2,
None,
'back-propagation-and-automatic-differentiation'),
('Lecture Monday October 20',
2,
None,
'lecture-monday-october-20'),
('Setting up the back propagation algorithm and algorithm for a '
'feed forward NN, initalizations',
2,
None,
'setting-up-the-back-propagation-algorithm-and-algorithm-for-a-feed-forward-nn-initalizations'),
('Setting up the back propagation algorithm, part 1',
2,
None,
'setting-up-the-back-propagation-algorithm-part-1'),
('Setting up the back propagation algorithm, part 2',
2,
None,
'setting-up-the-back-propagation-algorithm-part-2'),
('Setting up the Back propagation algorithm, part 3',
2,
None,
'setting-up-the-back-propagation-algorithm-part-3'),
('Updating the gradients', 2, None, 'updating-the-gradients'),
('Activation functions', 2, None, 'activation-functions'),
('Activation functions, examples',
3,
None,
'activation-functions-examples'),
('The RELU function family', 2, None, 'the-relu-function-family'),
('ELU function', 2, None, 'elu-function'),
('Which activation function should we use?',
2,
None,
'which-activation-function-should-we-use'),
('More on activation functions, output layers',
2,
None,
'more-on-activation-functions-output-layers'),
('Building neural networks in Tensorflow and Keras',
2,
None,
'building-neural-networks-in-tensorflow-and-keras'),
('Tensorflow', 2, None, 'tensorflow'),
('Using Keras', 2, None, 'using-keras'),
('Collect and pre-process data',
2,
None,
'collect-and-pre-process-data'),
('Using Pytorch with the full MNIST data set',
2,
None,
'using-pytorch-with-the-full-mnist-data-set'),
('And a similar example using Tensorflow with Keras',
2,
None,
'and-a-similar-example-using-tensorflow-with-keras'),
('Building our own neural network code',
2,
None,
'building-our-own-neural-network-code'),
('Learning rate methods', 3, None, 'learning-rate-methods'),
('Usage of the above learning rate schedulers',
3,
None,
'usage-of-the-above-learning-rate-schedulers'),
('Cost functions', 3, None, 'cost-functions'),
('Activation functions', 3, None, 'activation-functions'),
('The Neural Network', 3, None, 'the-neural-network'),
('Multiclass classification',
3,
None,
'multiclass-classification'),
('Testing the XOR gate and other gates',
2,
None,
'testing-the-xor-gate-and-other-gates'),
('Solving differential equations with Deep Learning',
2,
None,
'solving-differential-equations-with-deep-learning'),
('Ordinary Differential Equations first',
2,
None,
'ordinary-differential-equations-first'),
('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')]}
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 43: Deep Learning: Constructing a Neural Network code and solving differential equations</h1>
</center> <!-- document title -->
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b>
</center>
<!-- institution -->
<center>
<b>Department of Physics, University of Oslo, Norway</b>
</center>
<br>
<center>
<h4>October 20, 2025</h4>
</center> <!-- date -->
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plans-for-week-43">Plans for week 43 </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Material for the lecture on Monday October 20, 2025</b>
<p>
<ul>
<li> Building our own Feed-forward Neural Network with intro to Tensorflow</li>
<li> Solving differential equations with Neural Networks
<!-- * Video of lecture at <a href="https://youtu.be/vkBNTn-MLqs" target="_blank"><tt>https://youtu.be/vkBNTn-MLqs</tt></a> -->
<!-- * Video os second part, solving differential equations with neural networks at <a href="https://youtu.be/2N8To65I2wQ" target="_blank"><tt>https://youtu.be/2N8To65I2wQ</tt></a> -->
<!-- * Whiteboard notes on solving differential equations at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOct21.pdf" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOct21.pdf</tt></a> --></li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="exercises-and-lab-session-week-43">Exercises and lab session week 43 </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Lab sessions on Tuesday and Wednesday</b>
<p>
<ul>
<li> Exercise on writing your own neural network code</li>
<li> The exercises this week will be continued next week as well</li>
<li> Discussion of project 2</li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="using-automatic-differentiation">Using Automatic differentiation </h2>
<p>In our discussions of ordinary differential equations and neural network codes
we will also study the usage of Autograd, see for example <a href="https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola" target="_blank"><tt>https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola</tt></a> in computing gradients for deep learning. For the documentation of Autograd and examples see the Autograd documentation at <a href="https://github.com/HIPS/autograd" target="_blank"><tt>https://github.com/HIPS/autograd</tt></a> and the lecture slides from week 40, see <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html" target="_blank"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html</tt></a>.
</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 <a href="http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf" target="_blank"><tt>http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf</tt></a></li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lecture-monday-october-20">Lecture Monday October 20 </h2>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-back-propagation-algorithm-and-algorithm-for-a-feed-forward-nn-initalizations">Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations </h2>
<p>This is a reminder from last week.</p>
<div class="alert alert-block alert-block alert-text-normal">
<b>The architecture (our model)</b>
<p>
<ol>
<li> Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)</li>
<li> Define the number of hidden layers and hidden nodes</li>
<li> Define activation functions for hidden layers and output layers</li>
<li> Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates</li>
<li> Define cost function and possible regularization terms with hyperparameters</li>
<li> Initialize weights and biases</li>
<li> Fix number of iterations for the feed forward part and back propagation part</li>
</ol>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-back-propagation-algorithm-part-1">Setting up the back propagation algorithm, part 1 </h2>
<p>Let us write this out in the form of an algorithm.</p>
<p><b>First</b>, we set up the input data \( \boldsymbol{x} \) and the activations
\( \boldsymbol{z}_1 \) of the input layer and compute the activation function and
the pertinent outputs \( \boldsymbol{a}^1 \).
</p>
<p><b>Secondly</b>, we perform then the feed forward till we reach the output
layer and compute all \( \boldsymbol{z}_l \) of the input layer and compute the
activation function and the pertinent outputs \( \boldsymbol{a}^l \) for
\( l=1,2,3,\dots,L \).
</p>
<p><b>Notation</b>: The first hidden layer has \( l=1 \) as label and the final output layer has \( l=L \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-back-propagation-algorithm-part-2">Setting up the back propagation algorithm, part 2 </h2>
<p>Thereafter we compute the ouput error \( \boldsymbol{\delta}^L \) by computing all</p>
$$
\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}.
$$
<p>Then we compute the back propagate error for each \( l=L-1,L-2,\dots,1 \) as</p>
$$
\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l).
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-back-propagation-algorithm-part-3">Setting up the Back propagation algorithm, part 3 </h2>
<p>Finally, we update the weights and the biases using gradient descent
for each \( l=L-1,L-2,\dots,1 \) (the first hidden layer) and update the weights and biases
according to the rules
</p>
$$
w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1},
$$
$$
b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l,
$$
<p>with \( \eta \) being the learning rate.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="updating-the-gradients">Updating the gradients </h2>
<p>With the back propagate error for each \( l=L-1,L-2,\dots,1 \) as</p>
$$
\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l),
$$
<p>we update the weights and the biases using gradient descent for each \( l=L-1,L-2,\dots,1 \) and update the weights and biases according to the rules</p>
$$
w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1},
$$
$$
b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l,
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="activation-functions">Activation functions </h2>
<p>A property that characterizes a neural network, other than its
connectivity, is the choice of activation function(s). The following
restrictions are imposed on an activation function for an FFNN to
fulfill the universal approximation theorem
</p>
<ul>
<li> Non-constant</li>
<li> Bounded</li>
<li> Monotonically-increasing</li>
<li> Continuous</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h3 id="activation-functions-examples">Activation functions, examples </h3>
<p>Typical examples are the logistic <em>Sigmoid</em></p>
$$
\sigma(x) = \frac{1}{1 + e^{-x}},
$$
<p>and the <em>hyperbolic tangent</em> function</p>
$$
\sigma(x) = \tanh(x)
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-relu-function-family">The RELU function family </h2>
<p>The ReLU activation function suffers from a problem known as the dying
ReLUs: during training, some neurons effectively die, meaning they
stop outputting anything other than 0.
</p>
<p>In some cases, you may find that half of your network&#8217;s neurons are
dead, especially if you used a large learning rate. During training,
if a neuron&#8217;s weights get updated such that the weighted sum of the
neuron&#8217;s inputs is negative, it will start outputting 0. When this
happen, the neuron is unlikely to come back to life since the gradient
of the ReLU function is 0 when its input is negative.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="elu-function">ELU function </h2>
<p>To solve this problem, nowadays practitioners use a variant of the
ReLU function, such as the leaky ReLU discussed above or the so-called
exponential linear unit (ELU) function
</p>
$$
ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="which-activation-function-should-we-use">Which activation function should we use? </h2>
<p>In general it seems that the ELU activation function is better than
the leaky ReLU function (and its variants), which is better than
ReLU. ReLU performs better than \( \tanh \) which in turn performs better
than the logistic function.
</p>
<p>If runtime performance is an issue, then you may opt for the leaky
ReLU function over the ELU function If you don&#8217;t want to tweak yet
another hyperparameter, you may just use the default \( \alpha \) of
\( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have spare time and
computing power, you can use cross-validation or bootstrap to evaluate
other activation functions.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-on-activation-functions-output-layers">More on activation functions, output layers </h2>
<p>In most cases you can use the ReLU activation function in the hidden
layers (or one of its variants).
</p>
<p>It is a bit faster to compute than other activation functions, and the
gradient descent optimization does in general not get stuck.
</p>
<b>For the output layer:</b>
<ul>
<li> For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).</li>
<li> For regression tasks, you can simply use no activation function at all.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="building-neural-networks-in-tensorflow-and-keras">Building neural networks in Tensorflow and Keras </h2>
<p>Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn
and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy
and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer.
</p>
<p>In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite
clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or
NumPy arrays.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="tensorflow">Tensorflow </h2>
<p>Tensorflow is an open source library machine learning library
developed by the Google Brain team for internal use. It was released
under the Apache 2.0 open source license in November 9, 2015.
</p>
<p>Tensorflow is a computational framework that allows you to construct
machine learning models at different levels of abstraction, from
high-level, object-oriented APIs like Keras, down to the C++ kernels
that Tensorflow is built upon. The higher levels of abstraction are
simpler to use, but less flexible, and our choice of implementation
should reflect the problems we are trying to solve.
</p>
<p><a href="https://www.tensorflow.org/guide/graphs" target="_blank">Tensorflow uses</a> so-called graphs to represent your computation
in terms of the dependencies between individual operations, such that you first build a Tensorflow <em>graph</em>
to represent your model, and then create a Tensorflow <em>session</em> to run the graph.
</p>
<p>In this guide we will analyze the same data as we did in our NumPy and
scikit-learn tutorial, gathered from the MNIST database of images. We
will give an introduction to the lower level Python Application
Program Interfaces (APIs), and see how we use them to build our graph.
Then we will build (effectively) the same graph in Keras, to see just
how simple solving a machine learning problem can be.
</p>
<p>To install tensorflow on Unix/Linux systems, use pip as</p>
<!-- 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%;">pip3 install tensorflow
</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>and/or if you use <b>anaconda</b>, just write (or install from the graphical user interface)
(current release of CPU-only TensorFlow)
</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%;">conda create <span style="color: #666666">-</span>n tf tensorflow
conda activate tf
</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>To install the current release of GPU TensorFlow</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%;">conda create <span style="color: #666666">-</span>n tf<span style="color: #666666">-</span>gpu tensorflow<span style="color: #666666">-</span>gpu
conda activate tf<span style="color: #666666">-</span>gpu
</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-keras">Using Keras </h2>
<p>Keras is a high level <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank">neural network</a>
that supports Tensorflow, CTNK and Theano as backends.
If you have Anaconda installed you may run the following command
</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%;">conda install keras
</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 look up the <a href="https://keras.io/" target="_blank">instructions here</a> for more information.</p>
<p>We will to a large extent use <b>keras</b> in this course. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="collect-and-pre-process-data">Collect and pre-process data </h2>
<p>Let us look again at the MINST data set.</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"># 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">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">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: #008000">print</span>(<span style="color: #BA2121">&quot;inputs = (n_inputs, pixel_width, pixel_height) = &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"># flatten the image</span>
<span style="color: #408080; font-style: italic"># the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64</span>
n_inputs <span style="color: #666666">=</span> <span style="color: #008000">len</span>(inputs)
inputs <span style="color: #666666">=</span> inputs<span style="color: #666666">.</span>reshape(n_inputs, <span style="color: #666666">-1</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;X = (n_inputs, n_features) = &quot;</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(inputs<span style="color: #666666">.</span>shape))
<span style="color: #408080; font-style: italic"># choose some random images to display</span>
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>
<!-- 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.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: #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"># one-hot 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>
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>
<!-- 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%;">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>
n_neurons_layer1 <span style="color: #666666">=</span> <span style="color: #666666">100</span>
n_neurons_layer2 <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>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">create_neural_network_keras</span>(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
model <span style="color: #666666">=</span> Sequential()
model<span style="color: #666666">.</span>add(Dense(n_neurons_layer1, activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;sigmoid&#39;</span>, kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lmbd)))
model<span style="color: #666666">.</span>add(Dense(n_neurons_layer2, activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;sigmoid&#39;</span>, kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lmbd)))
model<span style="color: #666666">.</span>add(Dense(n_categories, activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;softmax&#39;</span>))
sgd <span style="color: #666666">=</span> optimizers<span style="color: #666666">.</span>SGD(learning_rate<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
</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>
<!-- 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%;">DNN_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):
DNN <span style="color: #666666">=</span> create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
eta<span style="color: #666666">=</span>eta, lmbd<span style="color: #666666">=</span>lmbd)
DNN<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> DNN<span style="color: #666666">.</span>evaluate(X_test, Y_test)
DNN_keras[i][j] <span style="color: #666666">=</span> DNN
<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>
<!-- 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"># optional</span>
<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)):
DNN <span style="color: #666666">=</span> DNN_keras[i][j]
train_accuracy[i][j] <span style="color: #666666">=</span> DNN<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> DNN<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="using-pytorch-with-the-full-mnist-data-set">Using Pytorch with the full MNIST data set </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">torch</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">torch.nn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">nn</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">torch.optim</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">optim</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">torchvision</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">torchvision.transforms</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">transforms</span>
<span style="color: #408080; font-style: italic"># Device configuration: use GPU if available</span>
device <span style="color: #666666">=</span> torch<span style="color: #666666">.</span>device(<span style="color: #BA2121">&quot;cuda&quot;</span> <span style="color: #008000; font-weight: bold">if</span> torch<span style="color: #666666">.</span>cuda<span style="color: #666666">.</span>is_available() <span style="color: #008000; font-weight: bold">else</span> <span style="color: #BA2121">&quot;cpu&quot;</span>)
<span style="color: #408080; font-style: italic"># MNIST dataset (downloads if not already present)</span>
transform <span style="color: #666666">=</span> transforms<span style="color: #666666">.</span>Compose([
transforms<span style="color: #666666">.</span>ToTensor(),
transforms<span style="color: #666666">.</span>Normalize((<span style="color: #666666">0.5</span>,), (<span style="color: #666666">0.5</span>,)) <span style="color: #408080; font-style: italic"># normalize to mean=0.5, std=0.5 (approx. [-1,1] pixel range)</span>
])
train_dataset <span style="color: #666666">=</span> torchvision<span style="color: #666666">.</span>datasets<span style="color: #666666">.</span>MNIST(root<span style="color: #666666">=</span><span style="color: #BA2121">&#39;./data&#39;</span>, train<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, download<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, transform<span style="color: #666666">=</span>transform)
test_dataset <span style="color: #666666">=</span> torchvision<span style="color: #666666">.</span>datasets<span style="color: #666666">.</span>MNIST(root<span style="color: #666666">=</span><span style="color: #BA2121">&#39;./data&#39;</span>, train<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>, download<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, transform<span style="color: #666666">=</span>transform)
train_loader <span style="color: #666666">=</span> torch<span style="color: #666666">.</span>utils<span style="color: #666666">.</span>data<span style="color: #666666">.</span>DataLoader(train_dataset, batch_size<span style="color: #666666">=64</span>, shuffle<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
test_loader <span style="color: #666666">=</span> torch<span style="color: #666666">.</span>utils<span style="color: #666666">.</span>data<span style="color: #666666">.</span>DataLoader(test_dataset, batch_size<span style="color: #666666">=64</span>, shuffle<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">NeuralNet</span>(nn<span style="color: #666666">.</span>Module):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>):
<span style="color: #008000">super</span>(NeuralNet, <span style="color: #008000">self</span>)<span style="color: #666666">.</span><span style="color: #0000FF">__init__</span>()
<span style="color: #008000">self</span><span style="color: #666666">.</span>fc1 <span style="color: #666666">=</span> nn<span style="color: #666666">.</span>Linear(<span style="color: #666666">28*28</span>, <span style="color: #666666">100</span>) <span style="color: #408080; font-style: italic"># first hidden layer (784 -&gt; 100)</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>fc2 <span style="color: #666666">=</span> nn<span style="color: #666666">.</span>Linear(<span style="color: #666666">100</span>, <span style="color: #666666">100</span>) <span style="color: #408080; font-style: italic"># second hidden layer (100 -&gt; 100)</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>fc3 <span style="color: #666666">=</span> nn<span style="color: #666666">.</span>Linear(<span style="color: #666666">100</span>, <span style="color: #666666">10</span>) <span style="color: #408080; font-style: italic"># output layer (100 -&gt; 10 classes)</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">forward</span>(<span style="color: #008000">self</span>, x):
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>view(x<span style="color: #666666">.</span>size(<span style="color: #666666">0</span>), <span style="color: #666666">-1</span>) <span style="color: #408080; font-style: italic"># flatten images into vectors of size 784</span>
x <span style="color: #666666">=</span> torch<span style="color: #666666">.</span>relu(<span style="color: #008000">self</span><span style="color: #666666">.</span>fc1(x)) <span style="color: #408080; font-style: italic"># hidden layer 1 + ReLU activation</span>
x <span style="color: #666666">=</span> torch<span style="color: #666666">.</span>relu(<span style="color: #008000">self</span><span style="color: #666666">.</span>fc2(x)) <span style="color: #408080; font-style: italic"># hidden layer 2 + ReLU activation</span>
x <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>fc3(x) <span style="color: #408080; font-style: italic"># output layer (logits for 10 classes)</span>
<span style="color: #008000; font-weight: bold">return</span> x
model <span style="color: #666666">=</span> NeuralNet()<span style="color: #666666">.</span>to(device)
criterion <span style="color: #666666">=</span> nn<span style="color: #666666">.</span>CrossEntropyLoss()
optimizer <span style="color: #666666">=</span> optim<span style="color: #666666">.</span>SGD(model<span style="color: #666666">.</span>parameters(), lr<span style="color: #666666">=0.01</span>, weight_decay<span style="color: #666666">=1e-4</span>)
num_epochs <span style="color: #666666">=</span> <span style="color: #666666">10</span>
<span style="color: #008000; font-weight: bold">for</span> epoch <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_epochs):
model<span style="color: #666666">.</span>train() <span style="color: #408080; font-style: italic"># set model to training mode</span>
running_loss <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
<span style="color: #008000; font-weight: bold">for</span> images, labels <span style="color: #AA22FF; font-weight: bold">in</span> train_loader:
<span style="color: #408080; font-style: italic"># Move data to device (GPU if available, else CPU)</span>
images, labels <span style="color: #666666">=</span> images<span style="color: #666666">.</span>to(device), labels<span style="color: #666666">.</span>to(device)
optimizer<span style="color: #666666">.</span>zero_grad() <span style="color: #408080; font-style: italic"># reset gradients to zero</span>
outputs <span style="color: #666666">=</span> model(images) <span style="color: #408080; font-style: italic"># forward pass: compute predictions</span>
loss <span style="color: #666666">=</span> criterion(outputs, labels) <span style="color: #408080; font-style: italic"># compute cross-entropy loss</span>
loss<span style="color: #666666">.</span>backward() <span style="color: #408080; font-style: italic"># backpropagate to compute gradients</span>
optimizer<span style="color: #666666">.</span>step() <span style="color: #408080; font-style: italic"># update weights using SGD step </span>
running_loss <span style="color: #666666">+=</span> loss<span style="color: #666666">.</span>item()
<span style="color: #408080; font-style: italic"># Compute average loss over all batches in this epoch</span>
avg_loss <span style="color: #666666">=</span> running_loss <span style="color: #666666">/</span> <span style="color: #008000">len</span>(train_loader)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Epoch </span><span style="color: #BB6688; font-weight: bold">{</span>epoch<span style="color: #666666">+1</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">/</span><span style="color: #BB6688; font-weight: bold">{</span>num_epochs<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">, Loss: </span><span style="color: #BB6688; font-weight: bold">{</span>avg_loss<span style="color: #BB6688; font-weight: bold">:</span><span style="color: #BA2121">.4f</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #408080; font-style: italic">#Evaluation on the Test Set</span>
model<span style="color: #666666">.</span>eval() <span style="color: #408080; font-style: italic"># set model to evaluation mode </span>
correct <span style="color: #666666">=</span> <span style="color: #666666">0</span>
total <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">with</span> torch<span style="color: #666666">.</span>no_grad(): <span style="color: #408080; font-style: italic"># disable gradient calculation for evaluation </span>
<span style="color: #008000; font-weight: bold">for</span> images, labels <span style="color: #AA22FF; font-weight: bold">in</span> test_loader:
images, labels <span style="color: #666666">=</span> images<span style="color: #666666">.</span>to(device), labels<span style="color: #666666">.</span>to(device)
outputs <span style="color: #666666">=</span> model(images)
_, predicted <span style="color: #666666">=</span> torch<span style="color: #666666">.</span>max(outputs, dim<span style="color: #666666">=1</span>) <span style="color: #408080; font-style: italic"># class with highest score</span>
total <span style="color: #666666">+=</span> labels<span style="color: #666666">.</span>size(<span style="color: #666666">0</span>)
correct <span style="color: #666666">+=</span> (predicted <span style="color: #666666">==</span> labels)<span style="color: #666666">.</span>sum()<span style="color: #666666">.</span>item()
accuracy <span style="color: #666666">=</span> <span style="color: #666666">100</span> <span style="color: #666666">*</span> correct <span style="color: #666666">/</span> total
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Test Accuracy: </span><span style="color: #BB6688; font-weight: bold">{</span>accuracy<span style="color: #BB6688; font-weight: bold">:</span><span style="color: #BA2121">.2f</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">%&quot;</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="and-a-similar-example-using-tensorflow-with-keras">And a similar example using Tensorflow 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">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</span> <span style="color: #008000; font-weight: bold">import</span> keras
<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> layers, regularizers
<span style="color: #408080; font-style: italic"># Check for GPU (TensorFlow will use it automatically if available)</span>
gpus <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>config<span style="color: #666666">.</span>list_physical_devices(<span style="color: #BA2121">&#39;GPU&#39;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;GPUs available: </span><span style="color: #BB6688; font-weight: bold">{</span>gpus<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #408080; font-style: italic"># 1) Load and preprocess MNIST</span>
(x_train, y_train), (x_test, y_test) <span style="color: #666666">=</span> keras<span style="color: #666666">.</span>datasets<span style="color: #666666">.</span>mnist<span style="color: #666666">.</span>load_data()
<span style="color: #408080; font-style: italic"># Normalize to [0, 1]</span>
x_train <span style="color: #666666">=</span> (x_train<span style="color: #666666">.</span>astype(<span style="color: #BA2121">&quot;float32&quot;</span>) <span style="color: #666666">/</span> <span style="color: #666666">255.0</span>)
x_test <span style="color: #666666">=</span> (x_test<span style="color: #666666">.</span>astype(<span style="color: #BA2121">&quot;float32&quot;</span>) <span style="color: #666666">/</span> <span style="color: #666666">255.0</span>)
<span style="color: #408080; font-style: italic"># 2) Build the model: 784 -&gt; 100 -&gt; 100 -&gt; 10</span>
l2_reg <span style="color: #666666">=</span> <span style="color: #666666">1e-4</span> <span style="color: #408080; font-style: italic"># L2 regularization strength</span>
model <span style="color: #666666">=</span> keras<span style="color: #666666">.</span>Sequential([
layers<span style="color: #666666">.</span>Input(shape<span style="color: #666666">=</span>(<span style="color: #666666">28</span>, <span style="color: #666666">28</span>)),
layers<span style="color: #666666">.</span>Flatten(),
layers<span style="color: #666666">.</span>Dense(<span style="color: #666666">100</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">&quot;relu&quot;</span>,
kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(l2_reg)),
layers<span style="color: #666666">.</span>Dense(<span style="color: #666666">100</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">&quot;relu&quot;</span>,
kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(l2_reg)),
layers<span style="color: #666666">.</span>Dense(<span style="color: #666666">10</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">&quot;softmax&quot;</span>) <span style="color: #408080; font-style: italic"># output probabilities for 10 classes</span>
])
<span style="color: #408080; font-style: italic"># 3) Compile with SGD + weight decay via L2 regularizers</span>
model<span style="color: #666666">.</span>compile(
optimizer<span style="color: #666666">=</span>keras<span style="color: #666666">.</span>optimizers<span style="color: #666666">.</span>SGD(learning_rate<span style="color: #666666">=0.01</span>),
loss<span style="color: #666666">=</span><span style="color: #BA2121">&quot;sparse_categorical_crossentropy&quot;</span>,
metrics<span style="color: #666666">=</span>[<span style="color: #BA2121">&quot;accuracy&quot;</span>],
)
model<span style="color: #666666">.</span>summary()
<span style="color: #408080; font-style: italic"># 4) Train</span>
history <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(
x_train, y_train,
epochs<span style="color: #666666">=10</span>,
batch_size<span style="color: #666666">=64</span>,
validation_split<span style="color: #666666">=0.1</span>, <span style="color: #408080; font-style: italic"># optional: monitor validation during training</span>
verbose<span style="color: #666666">=1</span>
)
<span style="color: #408080; font-style: italic"># 5) Evaluate on test set</span>
test_loss, test_acc <span style="color: #666666">=</span> model<span style="color: #666666">.</span>evaluate(x_test, y_test, verbose<span style="color: #666666">=0</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Test accuracy: </span><span style="color: #BB6688; font-weight: bold">{</span>test_acc<span style="color: #BB6688; font-weight: bold">:</span><span style="color: #BA2121">.4f</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">, Test loss: </span><span style="color: #BB6688; font-weight: bold">{</span>test_loss<span style="color: #BB6688; font-weight: bold">:</span><span style="color: #BA2121">.4f</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</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="building-our-own-neural-network-code">Building our own neural network code </h2>
<p>Here we present a flexible object oriented codebase
for a feed forward neural network, along with a demonstration of how
to use it. Before we get into the details of the neural network, we
will first present some implementations of various schedulers, cost
functions and activation functions that can be used together with the
neural network.
</p>
<p>The codes here were developed by Eric Reber and Gregor Kajda during spring 2023.</p>
<h3 id="learning-rate-methods">Learning rate methods </h3>
<p>The code below shows object oriented implementations of the Constant,
Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All
of the classes belong to the shared abstract Scheduler class, and
share the update_change() and reset() methods allowing for any of the
schedulers to be seamlessly used during the training stage, as will
later be shown in the fit() method of the neural
network. Update_change() only has one parameter, the gradient
(\( &#948;^l_ja^{l&#8722;1}_k \)), and returns the change which will be subtracted
from the weights. The reset() function takes no parameters, and resets
the desired variables. For Constant and Momentum, reset does nothing.
</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">class</span> <span style="color: #0000FF; font-weight: bold">Scheduler</span>:
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Abstract class for Schedulers</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, eta):
<span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">=</span> eta
<span style="color: #408080; font-style: italic"># should be overwritten</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">update_change</span>(<span style="color: #008000">self</span>, gradient):
<span style="color: #008000; font-weight: bold">raise</span> <span style="color: #D2413A; font-weight: bold">NotImplementedError</span>
<span style="color: #408080; font-style: italic"># overwritten if needed</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">reset</span>(<span style="color: #008000">self</span>):
<span style="color: #008000; font-weight: bold">pass</span>
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">Constant</span>(Scheduler):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, eta):
<span style="color: #008000">super</span>()<span style="color: #666666">.</span><span style="color: #0000FF">__init__</span>(eta)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">update_change</span>(<span style="color: #008000">self</span>, gradient):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> gradient
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">reset</span>(<span style="color: #008000">self</span>):
<span style="color: #008000; font-weight: bold">pass</span>
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">Momentum</span>(Scheduler):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, eta: <span style="color: #008000">float</span>, momentum: <span style="color: #008000">float</span>):
<span style="color: #008000">super</span>()<span style="color: #666666">.</span><span style="color: #0000FF">__init__</span>(eta)
<span style="color: #008000">self</span><span style="color: #666666">.</span>momentum <span style="color: #666666">=</span> momentum
<span style="color: #008000">self</span><span style="color: #666666">.</span>change <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">update_change</span>(<span style="color: #008000">self</span>, gradient):
<span style="color: #008000">self</span><span style="color: #666666">.</span>change <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>momentum <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>change <span style="color: #666666">+</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> gradient
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>change
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">reset</span>(<span style="color: #008000">self</span>):
<span style="color: #008000; font-weight: bold">pass</span>
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">Adagrad</span>(Scheduler):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, eta):
<span style="color: #008000">super</span>()<span style="color: #666666">.</span><span style="color: #0000FF">__init__</span>(eta)
<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">update_change</span>(<span style="color: #008000">self</span>, gradient):
delta <span style="color: #666666">=</span> <span style="color: #666666">1e-8</span> <span style="color: #408080; font-style: italic"># avoid division ny zero</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #AA22FF; font-weight: bold">is</span> <span style="color: #008000; font-weight: bold">None</span>:
<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((gradient<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], gradient<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>]))
<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #666666">+=</span> gradient <span style="color: #666666">@</span> gradient<span style="color: #666666">.</span>T
G_t_inverse <span style="color: #666666">=</span> <span style="color: #666666">1</span> <span style="color: #666666">/</span> (
delta <span style="color: #666666">+</span> np<span style="color: #666666">.</span>sqrt(np<span style="color: #666666">.</span>reshape(np<span style="color: #666666">.</span>diagonal(<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t), (<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], <span style="color: #666666">1</span>)))
)
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> gradient <span style="color: #666666">*</span> G_t_inverse
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">reset</span>(<span style="color: #008000">self</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">AdagradMomentum</span>(Scheduler):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, eta, momentum):
<span style="color: #008000">super</span>()<span style="color: #666666">.</span><span style="color: #0000FF">__init__</span>(eta)
<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>momentum <span style="color: #666666">=</span> momentum
<span style="color: #008000">self</span><span style="color: #666666">.</span>change <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">update_change</span>(<span style="color: #008000">self</span>, gradient):
delta <span style="color: #666666">=</span> <span style="color: #666666">1e-8</span> <span style="color: #408080; font-style: italic"># avoid division ny zero</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #AA22FF; font-weight: bold">is</span> <span style="color: #008000; font-weight: bold">None</span>:
<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((gradient<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], gradient<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>]))
<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #666666">+=</span> gradient <span style="color: #666666">@</span> gradient<span style="color: #666666">.</span>T
G_t_inverse <span style="color: #666666">=</span> <span style="color: #666666">1</span> <span style="color: #666666">/</span> (
delta <span style="color: #666666">+</span> np<span style="color: #666666">.</span>sqrt(np<span style="color: #666666">.</span>reshape(np<span style="color: #666666">.</span>diagonal(<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t), (<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], <span style="color: #666666">1</span>)))
)
<span style="color: #008000">self</span><span style="color: #666666">.</span>change <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>change <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>momentum <span style="color: #666666">+</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> gradient <span style="color: #666666">*</span> G_t_inverse
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>change
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">reset</span>(<span style="color: #008000">self</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>G_t <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">RMS_prop</span>(Scheduler):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, eta, rho):
<span style="color: #008000">super</span>()<span style="color: #666666">.</span><span style="color: #0000FF">__init__</span>(eta)
<span style="color: #008000">self</span><span style="color: #666666">.</span>rho <span style="color: #666666">=</span> rho
<span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">update_change</span>(<span style="color: #008000">self</span>, gradient):
delta <span style="color: #666666">=</span> <span style="color: #666666">1e-8</span> <span style="color: #408080; font-style: italic"># avoid division ny zero</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>rho <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">+</span> (<span style="color: #666666">1</span> <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>rho) <span style="color: #666666">*</span> gradient <span style="color: #666666">*</span> gradient
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> gradient <span style="color: #666666">/</span> (np<span style="color: #666666">.</span>sqrt(<span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">+</span> delta))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">reset</span>(<span style="color: #008000">self</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">Adam</span>(Scheduler):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, eta, rho, rho2):
<span style="color: #008000">super</span>()<span style="color: #666666">.</span><span style="color: #0000FF">__init__</span>(eta)
<span style="color: #008000">self</span><span style="color: #666666">.</span>rho <span style="color: #666666">=</span> rho
<span style="color: #008000">self</span><span style="color: #666666">.</span>rho2 <span style="color: #666666">=</span> rho2
<span style="color: #008000">self</span><span style="color: #666666">.</span>moment <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>n_epochs <span style="color: #666666">=</span> <span style="color: #666666">1</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">update_change</span>(<span style="color: #008000">self</span>, gradient):
delta <span style="color: #666666">=</span> <span style="color: #666666">1e-8</span> <span style="color: #408080; font-style: italic"># avoid division ny zero</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>moment <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>rho <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>moment <span style="color: #666666">+</span> (<span style="color: #666666">1</span> <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>rho) <span style="color: #666666">*</span> gradient
<span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>rho2 <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">+</span> (<span style="color: #666666">1</span> <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>rho2) <span style="color: #666666">*</span> gradient <span style="color: #666666">*</span> gradient
moment_corrected <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>moment <span style="color: #666666">/</span> (<span style="color: #666666">1</span> <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>rho<span style="color: #666666">**</span><span style="color: #008000">self</span><span style="color: #666666">.</span>n_epochs)
second_corrected <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">/</span> (<span style="color: #666666">1</span> <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>rho2<span style="color: #666666">**</span><span style="color: #008000">self</span><span style="color: #666666">.</span>n_epochs)
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> moment_corrected <span style="color: #666666">/</span> (np<span style="color: #666666">.</span>sqrt(second_corrected <span style="color: #666666">+</span> delta))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">reset</span>(<span style="color: #008000">self</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>n_epochs <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>moment <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>second <span style="color: #666666">=</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>
<h3 id="usage-of-the-above-learning-rate-schedulers">Usage of the above learning rate schedulers </h3>
<p>To initalize a scheduler, simply create the object and pass in the
necessary parameters such as the learning rate and the momentum as
shown below. As the Scheduler class is an abstract class it should not
called directly, and will raise an error upon usage.
</p>
<!-- 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%;">momentum_scheduler <span style="color: #666666">=</span> Momentum(eta<span style="color: #666666">=1e-3</span>, momentum<span style="color: #666666">=0.9</span>)
adam_scheduler <span style="color: #666666">=</span> Adam(eta<span style="color: #666666">=1e-3</span>, rho<span style="color: #666666">=0.9</span>, rho2<span style="color: #666666">=0.999</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>
<p>Here is a small example for how a segment of code using schedulers
could look. Switching out the schedulers is simple.
</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%;">weights <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ones((<span style="color: #666666">3</span>,<span style="color: #666666">3</span>))
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Before scheduler:</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BB6688; font-weight: bold">{</span>weights<span style="color: #BB6688; font-weight: bold">=}</span><span style="color: #BA2121">&quot;</span>)
epochs <span style="color: #666666">=</span> <span style="color: #666666">10</span>
<span style="color: #008000; font-weight: bold">for</span> e <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(epochs):
gradient <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">3</span>, <span style="color: #666666">3</span>)
change <span style="color: #666666">=</span> adam_scheduler<span style="color: #666666">.</span>update_change(gradient)
weights <span style="color: #666666">=</span> weights <span style="color: #666666">-</span> change
adam_scheduler<span style="color: #666666">.</span>reset()
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">After scheduler:</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BB6688; font-weight: bold">{</span>weights<span style="color: #BB6688; font-weight: bold">=}</span><span style="color: #BA2121">&quot;</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>
<h3 id="cost-functions">Cost functions </h3>
<p>Here we discuss cost functions that can be used when creating the
neural network. Every cost function takes the target vector as its
parameter, and returns a function valued only at \( x \) such that it may
easily be differentiated.
</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">def</span> <span style="color: #0000FF">CostOLS</span>(target):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">func</span>(X):
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1.0</span> <span style="color: #666666">/</span> target<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>]) <span style="color: #666666">*</span> np<span style="color: #666666">.</span>sum((target <span style="color: #666666">-</span> X) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
<span style="color: #008000; font-weight: bold">return</span> func
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">CostLogReg</span>(target):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">func</span>(X):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>(<span style="color: #666666">1.0</span> <span style="color: #666666">/</span> target<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>]) <span style="color: #666666">*</span> np<span style="color: #666666">.</span>sum(
(target <span style="color: #666666">*</span> np<span style="color: #666666">.</span>log(X <span style="color: #666666">+</span> <span style="color: #666666">10e-10</span>)) <span style="color: #666666">+</span> ((<span style="color: #666666">1</span> <span style="color: #666666">-</span> target) <span style="color: #666666">*</span> np<span style="color: #666666">.</span>log(<span style="color: #666666">1</span> <span style="color: #666666">-</span> X <span style="color: #666666">+</span> <span style="color: #666666">10e-10</span>))
)
<span style="color: #008000; font-weight: bold">return</span> func
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">CostCrossEntropy</span>(target):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">func</span>(X):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>(<span style="color: #666666">1.0</span> <span style="color: #666666">/</span> target<span style="color: #666666">.</span>size) <span style="color: #666666">*</span> np<span style="color: #666666">.</span>sum(target <span style="color: #666666">*</span> np<span style="color: #666666">.</span>log(X <span style="color: #666666">+</span> <span style="color: #666666">10e-10</span>))
<span style="color: #008000; font-weight: bold">return</span> func
</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>Below we give a short example of how these cost function may be used
to obtain results if you wish to test them out on your own using
AutoGrad's automatics differentiation.
</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">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad
target <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">1</span>, <span style="color: #666666">2</span>, <span style="color: #666666">3</span>]])<span style="color: #666666">.</span>T
a <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">4</span>, <span style="color: #666666">5</span>, <span style="color: #666666">6</span>]])<span style="color: #666666">.</span>T
cost_func <span style="color: #666666">=</span> CostCrossEntropy
cost_func_derivative <span style="color: #666666">=</span> grad(cost_func(target))
valued_at_a <span style="color: #666666">=</span> cost_func_derivative(a)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Derivative of cost function </span><span style="color: #BB6688; font-weight: bold">{</span>cost_func<span style="color: #666666">.</span><span style="color: #19177C">__name__</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> valued at a:</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BB6688; font-weight: bold">{</span>valued_at_a<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</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>
<h3 id="activation-functions">Activation functions </h3>
<p>Finally, before we look at the neural network, we will look at the
activation functions which can be specified between the hidden layers
and as the output function. Each function can be valued for any given
vector or matrix X, and can be differentiated via derivate().
</p>
<!-- 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> elementwise_grad
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">identity</span>(X):
<span style="color: #008000; font-weight: bold">return</span> X
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(X):
<span style="color: #008000; font-weight: bold">try</span>:
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1.0</span> <span style="color: #666666">/</span> (<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>X))
<span style="color: #008000; font-weight: bold">except</span> <span style="color: #D2413A; font-weight: bold">FloatingPointError</span>:
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>where(X <span style="color: #666666">&gt;</span> np<span style="color: #666666">.</span>zeros(X<span style="color: #666666">.</span>shape), np<span style="color: #666666">.</span>ones(X<span style="color: #666666">.</span>shape), np<span style="color: #666666">.</span>zeros(X<span style="color: #666666">.</span>shape))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">softmax</span>(X):
X <span style="color: #666666">=</span> X <span style="color: #666666">-</span> np<span style="color: #666666">.</span>max(X, axis<span style="color: #666666">=-1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
delta <span style="color: #666666">=</span> <span style="color: #666666">10e-10</span>
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>exp(X) <span style="color: #666666">/</span> (np<span style="color: #666666">.</span>sum(np<span style="color: #666666">.</span>exp(X), axis<span style="color: #666666">=-1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>) <span style="color: #666666">+</span> delta)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">RELU</span>(X):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>where(X <span style="color: #666666">&gt;</span> np<span style="color: #666666">.</span>zeros(X<span style="color: #666666">.</span>shape), X, np<span style="color: #666666">.</span>zeros(X<span style="color: #666666">.</span>shape))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">LRELU</span>(X):
delta <span style="color: #666666">=</span> <span style="color: #666666">10e-4</span>
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>where(X <span style="color: #666666">&gt;</span> np<span style="color: #666666">.</span>zeros(X<span style="color: #666666">.</span>shape), X, delta <span style="color: #666666">*</span> X)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">derivate</span>(func):
<span style="color: #008000; font-weight: bold">if</span> func<span style="color: #666666">.</span><span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&quot;RELU&quot;</span>:
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">func</span>(X):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>where(X <span style="color: #666666">&gt;</span> <span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0</span>)
<span style="color: #008000; font-weight: bold">return</span> func
<span style="color: #008000; font-weight: bold">elif</span> func<span style="color: #666666">.</span><span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&quot;LRELU&quot;</span>:
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">func</span>(X):
delta <span style="color: #666666">=</span> <span style="color: #666666">10e-4</span>
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>where(X <span style="color: #666666">&gt;</span> <span style="color: #666666">0</span>, <span style="color: #666666">1</span>, delta)
<span style="color: #008000; font-weight: bold">return</span> func
<span style="color: #008000; font-weight: bold">else</span>:
<span style="color: #008000; font-weight: bold">return</span> elementwise_grad(func)
</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>Below follows a short demonstration of how to use an activation
function. The derivative of the activation function will be important
when calculating the output delta term during backpropagation. Note
that derivate() can also be used for cost functions for a more
generalized approach.
</p>
<!-- 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%;">z <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">4</span>, <span style="color: #666666">5</span>, <span style="color: #666666">6</span>]])<span style="color: #666666">.</span>T
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;Input to activation function:</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BB6688; font-weight: bold">{</span>z<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
act_func <span style="color: #666666">=</span> sigmoid
a <span style="color: #666666">=</span> act_func(z)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">Output from </span><span style="color: #BB6688; font-weight: bold">{</span>act_func<span style="color: #666666">.</span><span style="color: #19177C">__name__</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> activation function:</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BB6688; font-weight: bold">{</span>a<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
act_func_derivative <span style="color: #666666">=</span> derivate(act_func)
valued_at_z <span style="color: #666666">=</span> act_func_derivative(a)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">Derivative of </span><span style="color: #BB6688; font-weight: bold">{</span>act_func<span style="color: #666666">.</span><span style="color: #19177C">__name__</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> activation function valued at z:</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BB6688; font-weight: bold">{</span>valued_at_z<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</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>
<h3 id="the-neural-network">The Neural Network </h3>
<p>Now that we have gotten a good understanding of the implementation of
some important components, we can take a look at an object oriented
implementation of a feed forward neural network. The feed forward
neural network has been implemented as a class named FFNN, which can
be initiated as a regressor or classifier dependant on the choice of
cost function. The FFNN can have any number of input nodes, hidden
layers with any amount of hidden nodes, and any amount of output nodes
meaning it can perform multiclass classification as well as binary
classification and regression problems. Although there is a lot of
code present, it makes for an easy to use and generalizeable interface
for creating many types of neural networks as will be demonstrated
below.
</p>
<!-- 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">math</span>
<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">import</span> <span style="color: #0000FF; font-weight: bold">sys</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">warnings</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">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">copy</span> <span style="color: #008000; font-weight: bold">import</span> deepcopy, copy
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">typing</span> <span style="color: #008000; font-weight: bold">import</span> Tuple, Callable
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.utils</span> <span style="color: #008000; font-weight: bold">import</span> resample
warnings<span style="color: #666666">.</span>simplefilter(<span style="color: #BA2121">&quot;error&quot;</span>)
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">FFNN</span>:
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> Feed Forward Neural Network with interface enabling flexible design of a</span>
<span style="color: #BA2121; font-style: italic"> nerual networks architecture and the specification of activation function</span>
<span style="color: #BA2121; font-style: italic"> in the hidden layers and output layer respectively. This model can be used</span>
<span style="color: #BA2121; font-style: italic"> for both regression and classification problems, depending on the output function.</span>
<span style="color: #BA2121; font-style: italic"> Attributes:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> I dimensions (tuple[int]): A list of positive integers, which specifies the</span>
<span style="color: #BA2121; font-style: italic"> number of nodes in each of the networks layers. The first integer in the array</span>
<span style="color: #BA2121; font-style: italic"> defines the number of nodes in the input layer, the second integer defines number</span>
<span style="color: #BA2121; font-style: italic"> of nodes in the first hidden layer and so on until the last number, which</span>
<span style="color: #BA2121; font-style: italic"> specifies the number of nodes in the output layer.</span>
<span style="color: #BA2121; font-style: italic"> II hidden_func (Callable): The activation function for the hidden layers</span>
<span style="color: #BA2121; font-style: italic"> III output_func (Callable): The activation function for the output layer</span>
<span style="color: #BA2121; font-style: italic"> IV cost_func (Callable): Our cost function</span>
<span style="color: #BA2121; font-style: italic"> V seed (int): Sets random seed, makes results reproducible</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(
<span style="color: #008000">self</span>,
dimensions: <span style="color: #008000">tuple</span>[<span style="color: #008000">int</span>],
hidden_func: Callable <span style="color: #666666">=</span> sigmoid,
output_func: Callable <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">lambda</span> x: x,
cost_func: Callable <span style="color: #666666">=</span> CostOLS,
seed: <span style="color: #008000">int</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>,
):
<span style="color: #008000">self</span><span style="color: #666666">.</span>dimensions <span style="color: #666666">=</span> dimensions
<span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_func <span style="color: #666666">=</span> hidden_func
<span style="color: #008000">self</span><span style="color: #666666">.</span>output_func <span style="color: #666666">=</span> output_func
<span style="color: #008000">self</span><span style="color: #666666">.</span>cost_func <span style="color: #666666">=</span> cost_func
<span style="color: #008000">self</span><span style="color: #666666">.</span>seed <span style="color: #666666">=</span> seed
<span style="color: #008000">self</span><span style="color: #666666">.</span>weights <span style="color: #666666">=</span> <span style="color: #008000">list</span>()
<span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_weight <span style="color: #666666">=</span> <span style="color: #008000">list</span>()
<span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_bias <span style="color: #666666">=</span> <span style="color: #008000">list</span>()
<span style="color: #008000">self</span><span style="color: #666666">.</span>a_matrices <span style="color: #666666">=</span> <span style="color: #008000">list</span>()
<span style="color: #008000">self</span><span style="color: #666666">.</span>z_matrices <span style="color: #666666">=</span> <span style="color: #008000">list</span>()
<span style="color: #008000">self</span><span style="color: #666666">.</span>classification <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>reset_weights()
<span style="color: #008000">self</span><span style="color: #666666">.</span>_set_classification()
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">fit</span>(
<span style="color: #008000">self</span>,
X: np<span style="color: #666666">.</span>ndarray,
t: np<span style="color: #666666">.</span>ndarray,
scheduler: Scheduler,
batches: <span style="color: #008000">int</span> <span style="color: #666666">=</span> <span style="color: #666666">1</span>,
epochs: <span style="color: #008000">int</span> <span style="color: #666666">=</span> <span style="color: #666666">100</span>,
lam: <span style="color: #008000">float</span> <span style="color: #666666">=</span> <span style="color: #666666">0</span>,
X_val: np<span style="color: #666666">.</span>ndarray <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>,
t_val: np<span style="color: #666666">.</span>ndarray <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>,
):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> This function performs the training the neural network by performing the feedforward and backpropagation</span>
<span style="color: #BA2121; font-style: italic"> algorithm to update the networks weights.</span>
<span style="color: #BA2121; font-style: italic"> Parameters:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> I X (np.ndarray) : training data</span>
<span style="color: #BA2121; font-style: italic"> II t (np.ndarray) : target data</span>
<span style="color: #BA2121; font-style: italic"> III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)</span>
<span style="color: #BA2121; font-style: italic"> IV scheduler_args (list[int]) : list of all arguments necessary for scheduler</span>
<span style="color: #BA2121; font-style: italic"> Optional Parameters:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> V batches (int) : number of batches the datasets are split into, default equal to 1</span>
<span style="color: #BA2121; font-style: italic"> VI epochs (int) : number of iterations used to train the network, default equal to 100</span>
<span style="color: #BA2121; font-style: italic"> VII lam (float) : regularization hyperparameter lambda</span>
<span style="color: #BA2121; font-style: italic"> VIII X_val (np.ndarray) : validation set</span>
<span style="color: #BA2121; font-style: italic"> IX t_val (np.ndarray) : validation target set</span>
<span style="color: #BA2121; font-style: italic"> Returns:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> I scores (dict) : A dictionary containing the performance metrics of the model.</span>
<span style="color: #BA2121; font-style: italic"> The number of the metrics depends on the parameters passed to the fit-function.</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
<span style="color: #408080; font-style: italic"># setup </span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>seed <span style="color: #AA22FF; font-weight: bold">is</span> <span style="color: #AA22FF; font-weight: bold">not</span> <span style="color: #008000; font-weight: bold">None</span>:
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #008000">self</span><span style="color: #666666">.</span>seed)
val_set <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">False</span>
<span style="color: #008000; font-weight: bold">if</span> X_val <span style="color: #AA22FF; font-weight: bold">is</span> <span style="color: #AA22FF; font-weight: bold">not</span> <span style="color: #008000; font-weight: bold">None</span> <span style="color: #AA22FF; font-weight: bold">and</span> t_val <span style="color: #AA22FF; font-weight: bold">is</span> <span style="color: #AA22FF; font-weight: bold">not</span> <span style="color: #008000; font-weight: bold">None</span>:
val_set <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">True</span>
<span style="color: #408080; font-style: italic"># creating arrays for score metrics</span>
train_errors <span style="color: #666666">=</span> np<span style="color: #666666">.</span>empty(epochs)
train_errors<span style="color: #666666">.</span>fill(np<span style="color: #666666">.</span>nan)
val_errors <span style="color: #666666">=</span> np<span style="color: #666666">.</span>empty(epochs)
val_errors<span style="color: #666666">.</span>fill(np<span style="color: #666666">.</span>nan)
train_accs <span style="color: #666666">=</span> np<span style="color: #666666">.</span>empty(epochs)
train_accs<span style="color: #666666">.</span>fill(np<span style="color: #666666">.</span>nan)
val_accs <span style="color: #666666">=</span> np<span style="color: #666666">.</span>empty(epochs)
val_accs<span style="color: #666666">.</span>fill(np<span style="color: #666666">.</span>nan)
<span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_weight <span style="color: #666666">=</span> <span style="color: #008000">list</span>()
<span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_bias <span style="color: #666666">=</span> <span style="color: #008000">list</span>()
batch_size <span style="color: #666666">=</span> X<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>] <span style="color: #666666">//</span> batches
X, t <span style="color: #666666">=</span> resample(X, t)
<span style="color: #408080; font-style: italic"># this function returns a function valued only at X</span>
cost_function_train <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>cost_func(t)
<span style="color: #008000; font-weight: bold">if</span> val_set:
cost_function_val <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>cost_func(t_val)
<span style="color: #408080; font-style: italic"># create schedulers for each weight matrix</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: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>weights)):
<span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_weight<span style="color: #666666">.</span>append(copy(scheduler))
<span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_bias<span style="color: #666666">.</span>append(copy(scheduler))
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&quot;</span><span style="color: #BB6688; font-weight: bold">{</span>scheduler<span style="color: #666666">.</span><span style="color: #19177C">__class__</span><span style="color: #666666">.</span><span style="color: #19177C">__name__</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">: Eta=</span><span style="color: #BB6688; font-weight: bold">{</span>scheduler<span style="color: #666666">.</span>eta<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">, Lambda=</span><span style="color: #BB6688; font-weight: bold">{</span>lam<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</span>)
<span style="color: #008000; font-weight: bold">try</span>:
<span style="color: #008000; font-weight: bold">for</span> e <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(epochs):
<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>(batches):
<span style="color: #408080; font-style: italic"># allows for minibatch gradient descent</span>
<span style="color: #008000; font-weight: bold">if</span> i <span style="color: #666666">==</span> batches <span style="color: #666666">-</span> <span style="color: #666666">1</span>:
<span style="color: #408080; font-style: italic"># If the for loop has reached the last batch, take all thats left</span>
X_batch <span style="color: #666666">=</span> X[i <span style="color: #666666">*</span> batch_size :, :]
t_batch <span style="color: #666666">=</span> t[i <span style="color: #666666">*</span> batch_size :, :]
<span style="color: #008000; font-weight: bold">else</span>:
X_batch <span style="color: #666666">=</span> X[i <span style="color: #666666">*</span> batch_size : (i <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #666666">*</span> batch_size, :]
t_batch <span style="color: #666666">=</span> t[i <span style="color: #666666">*</span> batch_size : (i <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #666666">*</span> batch_size, :]
<span style="color: #008000">self</span><span style="color: #666666">.</span>_feedforward(X_batch)
<span style="color: #008000">self</span><span style="color: #666666">.</span>_backpropagate(X_batch, t_batch, lam)
<span style="color: #408080; font-style: italic"># reset schedulers for each epoch (some schedulers pass in this call)</span>
<span style="color: #008000; font-weight: bold">for</span> scheduler <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_weight:
scheduler<span style="color: #666666">.</span>reset()
<span style="color: #008000; font-weight: bold">for</span> scheduler <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_bias:
scheduler<span style="color: #666666">.</span>reset()
<span style="color: #408080; font-style: italic"># computing performance metrics</span>
pred_train <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>predict(X)
train_error <span style="color: #666666">=</span> cost_function_train(pred_train)
train_errors[e] <span style="color: #666666">=</span> train_error
<span style="color: #008000; font-weight: bold">if</span> val_set:
pred_val <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>predict(X_val)
val_error <span style="color: #666666">=</span> cost_function_val(pred_val)
val_errors[e] <span style="color: #666666">=</span> val_error
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>classification:
train_acc <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_accuracy(<span style="color: #008000">self</span><span style="color: #666666">.</span>predict(X), t)
train_accs[e] <span style="color: #666666">=</span> train_acc
<span style="color: #008000; font-weight: bold">if</span> val_set:
val_acc <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_accuracy(pred_val, t_val)
val_accs[e] <span style="color: #666666">=</span> val_acc
<span style="color: #408080; font-style: italic"># printing progress bar</span>
progression <span style="color: #666666">=</span> e <span style="color: #666666">/</span> epochs
print_length <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_progress_bar(
progression,
train_error<span style="color: #666666">=</span>train_errors[e],
train_acc<span style="color: #666666">=</span>train_accs[e],
val_error<span style="color: #666666">=</span>val_errors[e],
val_acc<span style="color: #666666">=</span>val_accs[e],
)
<span style="color: #008000; font-weight: bold">except</span> <span style="color: #D2413A; font-weight: bold">KeyboardInterrupt</span>:
<span style="color: #408080; font-style: italic"># allows for stopping training at any point and seeing the result</span>
<span style="color: #008000; font-weight: bold">pass</span>
<span style="color: #408080; font-style: italic"># visualization of training progression (similiar to tensorflow progression bar)</span>
sys<span style="color: #666666">.</span>stdout<span style="color: #666666">.</span>write(<span style="color: #BA2121">&quot;</span><span style="color: #BB6622; font-weight: bold">\r</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">+</span> <span style="color: #BA2121">&quot; &quot;</span> <span style="color: #666666">*</span> print_length)
sys<span style="color: #666666">.</span>stdout<span style="color: #666666">.</span>flush()
<span style="color: #008000">self</span><span style="color: #666666">.</span>_progress_bar(
<span style="color: #666666">1</span>,
train_error<span style="color: #666666">=</span>train_errors[e],
train_acc<span style="color: #666666">=</span>train_accs[e],
val_error<span style="color: #666666">=</span>val_errors[e],
val_acc<span style="color: #666666">=</span>val_accs[e],
)
sys<span style="color: #666666">.</span>stdout<span style="color: #666666">.</span>write(<span style="color: #BA2121">&quot;&quot;</span>)
<span style="color: #408080; font-style: italic"># return performance metrics for the entire run</span>
scores <span style="color: #666666">=</span> <span style="color: #008000">dict</span>()
scores[<span style="color: #BA2121">&quot;train_errors&quot;</span>] <span style="color: #666666">=</span> train_errors
<span style="color: #008000; font-weight: bold">if</span> val_set:
scores[<span style="color: #BA2121">&quot;val_errors&quot;</span>] <span style="color: #666666">=</span> val_errors
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>classification:
scores[<span style="color: #BA2121">&quot;train_accs&quot;</span>] <span style="color: #666666">=</span> train_accs
<span style="color: #008000; font-weight: bold">if</span> val_set:
scores[<span style="color: #BA2121">&quot;val_accs&quot;</span>] <span style="color: #666666">=</span> val_accs
<span style="color: #008000; font-weight: bold">return</span> scores
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">predict</span>(<span style="color: #008000">self</span>, X: np<span style="color: #666666">.</span>ndarray, <span style="color: #666666">*</span>, threshold<span style="color: #666666">=0.5</span>):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> Performs prediction after training of the network has been finished.</span>
<span style="color: #BA2121; font-style: italic"> Parameters:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> I X (np.ndarray): The design matrix, with n rows of p features each</span>
<span style="color: #BA2121; font-style: italic"> Optional Parameters:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> II threshold (float) : sets minimal value for a prediction to be predicted as the positive class</span>
<span style="color: #BA2121; font-style: italic"> in classification problems</span>
<span style="color: #BA2121; font-style: italic"> Returns:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> I z (np.ndarray): A prediction vector (row) for each row in our design matrix</span>
<span style="color: #BA2121; font-style: italic"> This vector is thresholded if regression=False, meaning that classification results</span>
<span style="color: #BA2121; font-style: italic"> in a vector of 1s and 0s, while regressions in an array of decimal numbers</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
predict <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_feedforward(X)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>classification:
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>where(predict <span style="color: #666666">&gt;</span> threshold, <span style="color: #666666">1</span>, <span style="color: #666666">0</span>)
<span style="color: #008000; font-weight: bold">else</span>:
<span style="color: #008000; font-weight: bold">return</span> predict
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">reset_weights</span>(<span style="color: #008000">self</span>):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> Resets/Reinitializes the weights in order to train the network for a new problem.</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>seed <span style="color: #AA22FF; font-weight: bold">is</span> <span style="color: #AA22FF; font-weight: bold">not</span> <span style="color: #008000; font-weight: bold">None</span>:
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #008000">self</span><span style="color: #666666">.</span>seed)
<span style="color: #008000">self</span><span style="color: #666666">.</span>weights <span style="color: #666666">=</span> <span style="color: #008000">list</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: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>dimensions) <span style="color: #666666">-</span> <span style="color: #666666">1</span>):
weight_array <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(
<span style="color: #008000">self</span><span style="color: #666666">.</span>dimensions[i] <span style="color: #666666">+</span> <span style="color: #666666">1</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>dimensions[i <span style="color: #666666">+</span> <span style="color: #666666">1</span>]
)
weight_array[<span style="color: #666666">0</span>, :] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #008000">self</span><span style="color: #666666">.</span>dimensions[i <span style="color: #666666">+</span> <span style="color: #666666">1</span>]) <span style="color: #666666">*</span> <span style="color: #666666">0.01</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>weights<span style="color: #666666">.</span>append(weight_array)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">_feedforward</span>(<span style="color: #008000">self</span>, X: np<span style="color: #666666">.</span>ndarray):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> Calculates the activation of each layer starting at the input and ending at the output.</span>
<span style="color: #BA2121; font-style: italic"> Each following activation is calculated from a weighted sum of each of the preceeding</span>
<span style="color: #BA2121; font-style: italic"> activations (except in the case of the input layer).</span>
<span style="color: #BA2121; font-style: italic"> Parameters:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> I X (np.ndarray): The design matrix, with n rows of p features each</span>
<span style="color: #BA2121; font-style: italic"> Returns:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> I z (np.ndarray): A prediction vector (row) for each row in our design matrix</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
<span style="color: #408080; font-style: italic"># reset matrices</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>a_matrices <span style="color: #666666">=</span> <span style="color: #008000">list</span>()
<span style="color: #008000">self</span><span style="color: #666666">.</span>z_matrices <span style="color: #666666">=</span> <span style="color: #008000">list</span>()
<span style="color: #408080; font-style: italic"># if X is just a vector, make it into a matrix</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">len</span>(X<span style="color: #666666">.</span>shape) <span style="color: #666666">==</span> <span style="color: #666666">1</span>:
X <span style="color: #666666">=</span> X<span style="color: #666666">.</span>reshape((<span style="color: #666666">1</span>, X<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>]))
<span style="color: #408080; font-style: italic"># Add a coloumn of zeros as the first coloumn of the design matrix, in order</span>
<span style="color: #408080; font-style: italic"># to add bias to our data</span>
bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ones((X<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], <span style="color: #666666">1</span>)) <span style="color: #666666">*</span> <span style="color: #666666">0.01</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>hstack([bias, X])
<span style="color: #408080; font-style: italic"># a^0, the nodes in the input layer (one a^0 for each row in X - where the</span>
<span style="color: #408080; font-style: italic"># exponent indicates layer number).</span>
a <span style="color: #666666">=</span> X
<span style="color: #008000">self</span><span style="color: #666666">.</span>a_matrices<span style="color: #666666">.</span>append(a)
<span style="color: #008000">self</span><span style="color: #666666">.</span>z_matrices<span style="color: #666666">.</span>append(a)
<span style="color: #408080; font-style: italic"># The feed forward algorithm</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: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>weights)):
<span style="color: #008000; font-weight: bold">if</span> i <span style="color: #666666">&lt;</span> <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>weights) <span style="color: #666666">-</span> <span style="color: #666666">1</span>:
z <span style="color: #666666">=</span> a <span style="color: #666666">@</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>weights[i]
<span style="color: #008000">self</span><span style="color: #666666">.</span>z_matrices<span style="color: #666666">.</span>append(z)
a <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_func(z)
<span style="color: #408080; font-style: italic"># bias column again added to the data here</span>
bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ones((a<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], <span style="color: #666666">1</span>)) <span style="color: #666666">*</span> <span style="color: #666666">0.01</span>
a <span style="color: #666666">=</span> np<span style="color: #666666">.</span>hstack([bias, a])
<span style="color: #008000">self</span><span style="color: #666666">.</span>a_matrices<span style="color: #666666">.</span>append(a)
<span style="color: #008000; font-weight: bold">else</span>:
<span style="color: #008000; font-weight: bold">try</span>:
<span style="color: #408080; font-style: italic"># a^L, the nodes in our output layers</span>
z <span style="color: #666666">=</span> a <span style="color: #666666">@</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>weights[i]
a <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>output_func(z)
<span style="color: #008000">self</span><span style="color: #666666">.</span>a_matrices<span style="color: #666666">.</span>append(a)
<span style="color: #008000">self</span><span style="color: #666666">.</span>z_matrices<span style="color: #666666">.</span>append(z)
<span style="color: #008000; font-weight: bold">except</span> <span style="color: #D2413A; font-weight: bold">Exception</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #D2413A; font-weight: bold">OverflowError</span>:
<span style="color: #008000">print</span>(
<span style="color: #BA2121">&quot;OverflowError in fit() in FFNN</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">HOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling&quot;</span>
)
<span style="color: #408080; font-style: italic"># this will be a^L</span>
<span style="color: #008000; font-weight: bold">return</span> a
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">_backpropagate</span>(<span style="color: #008000">self</span>, X, t, lam):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> Performs the backpropagation algorithm. In other words, this method</span>
<span style="color: #BA2121; font-style: italic"> calculates the gradient of all the layers starting at the</span>
<span style="color: #BA2121; font-style: italic"> output layer, and moving from right to left accumulates the gradient until</span>
<span style="color: #BA2121; font-style: italic"> the input layer is reached. Each layers respective weights are updated while</span>
<span style="color: #BA2121; font-style: italic"> the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).</span>
<span style="color: #BA2121; font-style: italic"> Parameters:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> I X (np.ndarray): The design matrix, with n rows of p features each.</span>
<span style="color: #BA2121; font-style: italic"> II t (np.ndarray): The target vector, with n rows of p targets.</span>
<span style="color: #BA2121; font-style: italic"> III lam (float32): regularization parameter used to punish the weights in case of overfitting</span>
<span style="color: #BA2121; font-style: italic"> Returns:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> No return value.</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
out_derivative <span style="color: #666666">=</span> derivate(<span style="color: #008000">self</span><span style="color: #666666">.</span>output_func)
hidden_derivative <span style="color: #666666">=</span> derivate(<span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_func)
<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>(<span style="color: #008000">self</span><span style="color: #666666">.</span>weights) <span style="color: #666666">-</span> <span style="color: #666666">1</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">-1</span>):
<span style="color: #408080; font-style: italic"># delta terms for output</span>
<span style="color: #008000; font-weight: bold">if</span> i <span style="color: #666666">==</span> <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>weights) <span style="color: #666666">-</span> <span style="color: #666666">1</span>:
<span style="color: #408080; font-style: italic"># for multi-class classification</span>
<span style="color: #008000; font-weight: bold">if</span> (
<span style="color: #008000">self</span><span style="color: #666666">.</span>output_func<span style="color: #666666">.</span><span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&quot;softmax&quot;</span>
):
delta_matrix <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>a_matrices[i <span style="color: #666666">+</span> <span style="color: #666666">1</span>] <span style="color: #666666">-</span> t
<span style="color: #408080; font-style: italic"># for single class classification</span>
<span style="color: #008000; font-weight: bold">else</span>:
cost_func_derivative <span style="color: #666666">=</span> grad(<span style="color: #008000">self</span><span style="color: #666666">.</span>cost_func(t))
delta_matrix <span style="color: #666666">=</span> out_derivative(
<span style="color: #008000">self</span><span style="color: #666666">.</span>z_matrices[i <span style="color: #666666">+</span> <span style="color: #666666">1</span>]
) <span style="color: #666666">*</span> cost_func_derivative(<span style="color: #008000">self</span><span style="color: #666666">.</span>a_matrices[i <span style="color: #666666">+</span> <span style="color: #666666">1</span>])
<span style="color: #408080; font-style: italic"># delta terms for hidden layer</span>
<span style="color: #008000; font-weight: bold">else</span>:
delta_matrix <span style="color: #666666">=</span> (
<span style="color: #008000">self</span><span style="color: #666666">.</span>weights[i <span style="color: #666666">+</span> <span style="color: #666666">1</span>][<span style="color: #666666">1</span>:, :] <span style="color: #666666">@</span> delta_matrix<span style="color: #666666">.</span>T
)<span style="color: #666666">.</span>T <span style="color: #666666">*</span> hidden_derivative(<span style="color: #008000">self</span><span style="color: #666666">.</span>z_matrices[i <span style="color: #666666">+</span> <span style="color: #666666">1</span>])
<span style="color: #408080; font-style: italic"># calculate gradient</span>
gradient_weights <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>a_matrices[i][:, <span style="color: #666666">1</span>:]<span style="color: #666666">.</span>T <span style="color: #666666">@</span> delta_matrix
gradient_bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(delta_matrix, axis<span style="color: #666666">=0</span>)<span style="color: #666666">.</span>reshape(
<span style="color: #666666">1</span>, delta_matrix<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]
)
<span style="color: #408080; font-style: italic"># regularization term</span>
gradient_weights <span style="color: #666666">+=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>weights[i][<span style="color: #666666">1</span>:, :] <span style="color: #666666">*</span> lam
<span style="color: #408080; font-style: italic"># use scheduler</span>
update_matrix <span style="color: #666666">=</span> np<span style="color: #666666">.</span>vstack(
[
<span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_bias[i]<span style="color: #666666">.</span>update_change(gradient_bias),
<span style="color: #008000">self</span><span style="color: #666666">.</span>schedulers_weight[i]<span style="color: #666666">.</span>update_change(gradient_weights),
]
)
<span style="color: #408080; font-style: italic"># update weights and bias</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>weights[i] <span style="color: #666666">-=</span> update_matrix
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">_accuracy</span>(<span style="color: #008000">self</span>, prediction: np<span style="color: #666666">.</span>ndarray, target: np<span style="color: #666666">.</span>ndarray):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> Calculates accuracy of given prediction to target</span>
<span style="color: #BA2121; font-style: italic"> Parameters:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> I prediction (np.ndarray): vector of predicitons output network</span>
<span style="color: #BA2121; font-style: italic"> (1s and 0s in case of classification, and real numbers in case of regression)</span>
<span style="color: #BA2121; font-style: italic"> II target (np.ndarray): vector of true values (What the network ideally should predict)</span>
<span style="color: #BA2121; font-style: italic"> Returns:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> A floating point number representing the percentage of correctly classified instances.</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
<span style="color: #008000; font-weight: bold">assert</span> prediction<span style="color: #666666">.</span>size <span style="color: #666666">==</span> target<span style="color: #666666">.</span>size
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>average((target <span style="color: #666666">==</span> prediction))
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">_set_classification</span>(<span style="color: #008000">self</span>):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> Decides if FFNN acts as classifier (True) og regressor (False),</span>
<span style="color: #BA2121; font-style: italic"> sets self.classification during init()</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>classification <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">False</span>
<span style="color: #008000; font-weight: bold">if</span> (
<span style="color: #008000">self</span><span style="color: #666666">.</span>cost_func<span style="color: #666666">.</span><span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&quot;CostLogReg&quot;</span>
<span style="color: #AA22FF; font-weight: bold">or</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>cost_func<span style="color: #666666">.</span><span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&quot;CostCrossEntropy&quot;</span>
):
<span style="color: #008000">self</span><span style="color: #666666">.</span>classification <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">True</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">_progress_bar</span>(<span style="color: #008000">self</span>, progression, <span style="color: #666666">**</span>kwargs):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> Displays progress of training</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
print_length <span style="color: #666666">=</span> <span style="color: #666666">40</span>
num_equals <span style="color: #666666">=</span> <span style="color: #008000">int</span>(progression <span style="color: #666666">*</span> print_length)
num_not <span style="color: #666666">=</span> print_length <span style="color: #666666">-</span> num_equals
arrow <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;&gt;&quot;</span> <span style="color: #008000; font-weight: bold">if</span> num_equals <span style="color: #666666">&gt;</span> <span style="color: #666666">0</span> <span style="color: #008000; font-weight: bold">else</span> <span style="color: #BA2121">&quot;&quot;</span>
bar <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;[&quot;</span> <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;=&quot;</span> <span style="color: #666666">*</span> (num_equals <span style="color: #666666">-</span> <span style="color: #666666">1</span>) <span style="color: #666666">+</span> arrow <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;-&quot;</span> <span style="color: #666666">*</span> num_not <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;]&quot;</span>
perc_print <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_format(progression <span style="color: #666666">*</span> <span style="color: #666666">100</span>, decimals<span style="color: #666666">=5</span>)
line <span style="color: #666666">=</span> <span style="color: #BA2121">f&quot; </span><span style="color: #BB6688; font-weight: bold">{</span>bar<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> </span><span style="color: #BB6688; font-weight: bold">{</span>perc_print<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">% &quot;</span>
<span style="color: #008000; font-weight: bold">for</span> key <span style="color: #AA22FF; font-weight: bold">in</span> kwargs:
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> np<span style="color: #666666">.</span>isnan(kwargs[key]):
value <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_format(kwargs[key], decimals<span style="color: #666666">=4</span>)
line <span style="color: #666666">+=</span> <span style="color: #BA2121">f&quot;| </span><span style="color: #BB6688; font-weight: bold">{</span>key<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">: </span><span style="color: #BB6688; font-weight: bold">{</span>value<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> &quot;</span>
sys<span style="color: #666666">.</span>stdout<span style="color: #666666">.</span>write(<span style="color: #BA2121">&quot;</span><span style="color: #BB6622; font-weight: bold">\r</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">+</span> line)
sys<span style="color: #666666">.</span>stdout<span style="color: #666666">.</span>flush()
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">len</span>(line)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">_format</span>(<span style="color: #008000">self</span>, value, decimals<span style="color: #666666">=4</span>):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Description:</span>
<span style="color: #BA2121; font-style: italic"> ------------</span>
<span style="color: #BA2121; font-style: italic"> Formats decimal numbers for progress bar</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
<span style="color: #008000; font-weight: bold">if</span> value <span style="color: #666666">&gt;</span> <span style="color: #666666">0</span>:
v <span style="color: #666666">=</span> value
<span style="color: #008000; font-weight: bold">elif</span> value <span style="color: #666666">&lt;</span> <span style="color: #666666">0</span>:
v <span style="color: #666666">=</span> <span style="color: #666666">-10</span> <span style="color: #666666">*</span> value
<span style="color: #008000; font-weight: bold">else</span>:
v <span style="color: #666666">=</span> <span style="color: #666666">1</span>
n <span style="color: #666666">=</span> <span style="color: #666666">1</span> <span style="color: #666666">+</span> math<span style="color: #666666">.</span>floor(math<span style="color: #666666">.</span>log10(v))
<span style="color: #008000; font-weight: bold">if</span> n <span style="color: #666666">&gt;=</span> decimals <span style="color: #666666">-</span> <span style="color: #666666">1</span>:
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">str</span>(<span style="color: #008000">round</span>(value))
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #BA2121">f&quot;</span><span style="color: #BB6688; font-weight: bold">{</span>value<span style="color: #BB6688; font-weight: bold">:</span><span style="color: #BA2121">.</span><span style="color: #BB6688; font-weight: bold">{</span>decimals<span style="color: #666666">-</span>n<span style="color: #666666">-1</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">f</span><span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&quot;</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>
<p>Before we make a model, we will quickly generate a dataset we can use
for our linear regression problem as shown 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">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">SkrankeFunction</span>(x, y):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>ravel(<span style="color: #666666">0</span> <span style="color: #666666">+</span> <span style="color: #666666">1*</span>x <span style="color: #666666">+</span> <span style="color: #666666">2*</span>y <span style="color: #666666">+</span> <span style="color: #666666">3*</span>x<span style="color: #666666">**2</span> <span style="color: #666666">+</span> <span style="color: #666666">4*</span>x<span style="color: #666666">*</span>y <span style="color: #666666">+</span> <span style="color: #666666">5*</span>y<span style="color: #666666">**2</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">create_X</span>(x, y, n):
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">len</span>(x<span style="color: #666666">.</span>shape) <span style="color: #666666">&gt;</span> <span style="color: #666666">1</span>:
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ravel(x)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ravel(y)
N <span style="color: #666666">=</span> <span style="color: #008000">len</span>(x)
l <span style="color: #666666">=</span> <span style="color: #008000">int</span>((n <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #666666">*</span> (n <span style="color: #666666">+</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> <span style="color: #666666">2</span>) <span style="color: #408080; font-style: italic"># Number of elements in beta</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ones((N, l))
<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>, n <span style="color: #666666">+</span> <span style="color: #666666">1</span>):
q <span style="color: #666666">=</span> <span style="color: #008000">int</span>((i) <span style="color: #666666">*</span> (i <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #666666">/</span> <span style="color: #666666">2</span>)
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(i <span style="color: #666666">+</span> <span style="color: #666666">1</span>):
X[:, q <span style="color: #666666">+</span> k] <span style="color: #666666">=</span> (x <span style="color: #666666">**</span> (i <span style="color: #666666">-</span> k)) <span style="color: #666666">*</span> (y<span style="color: #666666">**</span>k)
<span style="color: #008000; font-weight: bold">return</span> X
step<span style="color: #666666">=0.5</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, step)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, step)
x, y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(x, y)
target <span style="color: #666666">=</span> SkrankeFunction(x, y)
target <span style="color: #666666">=</span> target<span style="color: #666666">.</span>reshape(target<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], <span style="color: #666666">1</span>)
poly_degree<span style="color: #666666">=3</span>
X <span style="color: #666666">=</span> create_X(x, y, poly_degree)
X_train, X_test, t_train, t_test <span style="color: #666666">=</span> train_test_split(X, target)
</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>Now that we have our dataset ready for the regression, we can create
our regressor. Note that with the seed parameter, we can make sure our
results stay the same every time we run the neural network. For
inititialization, we simply specify the dimensions (we wish the amount
of input nodes to be equal to the datapoints, and the output to
predict one value).
</p>
<!-- 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%;">input_nodes <span style="color: #666666">=</span> X_train<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]
output_nodes <span style="color: #666666">=</span> <span style="color: #666666">1</span>
linear_regression <span style="color: #666666">=</span> FFNN((input_nodes, output_nodes), output_func<span style="color: #666666">=</span>identity, cost_func<span style="color: #666666">=</span>CostOLS, seed<span style="color: #666666">=2023</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>
<p>We then fit our model with our training data using the scheduler of our choice.</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%;">linear_regression<span style="color: #666666">.</span>reset_weights() <span style="color: #408080; font-style: italic"># reset weights such that previous runs or reruns don&#39;t affect the weights</span>
scheduler <span style="color: #666666">=</span> Constant(eta<span style="color: #666666">=1e-3</span>)
scores <span style="color: #666666">=</span> linear_regression<span style="color: #666666">.</span>fit(X_train, t_train, scheduler)
</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>Due to the progress bar we can see the MSE (train_error) throughout
the FFNN's training. Note that the fit() function has some optional
parameters with defualt arguments. For example, the regularization
hyperparameter can be left ignored if not needed, and equally the FFNN
will by default run for 100 epochs. These can easily be changed, such
as for example:
</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%;">linear_regression<span style="color: #666666">.</span>reset_weights() <span style="color: #408080; font-style: italic"># reset weights such that previous runs or reruns don&#39;t affect the weights</span>
scores <span style="color: #666666">=</span> linear_regression<span style="color: #666666">.</span>fit(X_train, t_train, scheduler, lam<span style="color: #666666">=1e-4</span>, epochs<span style="color: #666666">=1000</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>
<p>We see that given more epochs to train on, the regressor reaches a lower MSE.</p>
<p>Let us then switch to a binary classification. We use a binary
classification dataset, and follow a similar setup to the regression
case.
</p>
<!-- 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">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> MinMaxScaler
wisconsin <span style="color: #666666">=</span> load_breast_cancer()
X <span style="color: #666666">=</span> wisconsin<span style="color: #666666">.</span>data
target <span style="color: #666666">=</span> wisconsin<span style="color: #666666">.</span>target
target <span style="color: #666666">=</span> target<span style="color: #666666">.</span>reshape(target<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], <span style="color: #666666">1</span>)
X_train, X_val, t_train, t_val <span style="color: #666666">=</span> train_test_split(X, target)
scaler <span style="color: #666666">=</span> MinMaxScaler()
scaler<span style="color: #666666">.</span>fit(X_train)
X_train <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_train)
X_val <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_val)
</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>
<!-- 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%;">input_nodes <span style="color: #666666">=</span> X_train<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]
output_nodes <span style="color: #666666">=</span> <span style="color: #666666">1</span>
logistic_regression <span style="color: #666666">=</span> FFNN((input_nodes, output_nodes), output_func<span style="color: #666666">=</span>sigmoid, cost_func<span style="color: #666666">=</span>CostLogReg, seed<span style="color: #666666">=2023</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>
<p>We will now make use of our validation data by passing it into our fit function as a keyword argument</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%;">logistic_regression<span style="color: #666666">.</span>reset_weights() <span style="color: #408080; font-style: italic"># reset weights such that previous runs or reruns don&#39;t affect the weights</span>
scheduler <span style="color: #666666">=</span> Adam(eta<span style="color: #666666">=1e-3</span>, rho<span style="color: #666666">=0.9</span>, rho2<span style="color: #666666">=0.999</span>)
scores <span style="color: #666666">=</span> logistic_regression<span style="color: #666666">.</span>fit(X_train, t_train, scheduler, epochs<span style="color: #666666">=1000</span>, X_val<span style="color: #666666">=</span>X_val, t_val<span style="color: #666666">=</span>t_val)
</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>Finally, we will create a neural network with 2 hidden layers with activation functions.</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%;">input_nodes <span style="color: #666666">=</span> X_train<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]
hidden_nodes1 <span style="color: #666666">=</span> <span style="color: #666666">100</span>
hidden_nodes2 <span style="color: #666666">=</span> <span style="color: #666666">30</span>
output_nodes <span style="color: #666666">=</span> <span style="color: #666666">1</span>
dims <span style="color: #666666">=</span> (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
neural_network <span style="color: #666666">=</span> FFNN(dims, hidden_func<span style="color: #666666">=</span>RELU, output_func<span style="color: #666666">=</span>sigmoid, cost_func<span style="color: #666666">=</span>CostLogReg, seed<span style="color: #666666">=2023</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>
<!-- 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%;">neural_network<span style="color: #666666">.</span>reset_weights() <span style="color: #408080; font-style: italic"># reset weights such that previous runs or reruns don&#39;t affect the weights</span>
scheduler <span style="color: #666666">=</span> Adam(eta<span style="color: #666666">=1e-4</span>, rho<span style="color: #666666">=0.9</span>, rho2<span style="color: #666666">=0.999</span>)
scores <span style="color: #666666">=</span> neural_network<span style="color: #666666">.</span>fit(X_train, t_train, scheduler, epochs<span style="color: #666666">=1000</span>, X_val<span style="color: #666666">=</span>X_val, t_val<span style="color: #666666">=</span>t_val)
</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>
<h3 id="multiclass-classification">Multiclass classification </h3>
<p>Finally, we will demonstrate the use case of multiclass classification
using our FFNN with the famous MNIST dataset, which contain images of
digits between the range of 0 to 9.
</p>
<!-- 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">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_digits
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">onehot</span>(target: np<span style="color: #666666">.</span>ndarray):
onehot <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((target<span style="color: #666666">.</span>size, target<span style="color: #666666">.</span>max() <span style="color: #666666">+</span> <span style="color: #666666">1</span>))
onehot[np<span style="color: #666666">.</span>arange(target<span style="color: #666666">.</span>size), target] <span style="color: #666666">=</span> <span style="color: #666666">1</span>
<span style="color: #008000; font-weight: bold">return</span> onehot
digits <span style="color: #666666">=</span> load_digits()
X <span style="color: #666666">=</span> digits<span style="color: #666666">.</span>data
target <span style="color: #666666">=</span> digits<span style="color: #666666">.</span>target
target <span style="color: #666666">=</span> onehot(target)
input_nodes <span style="color: #666666">=</span> <span style="color: #666666">64</span>
hidden_nodes1 <span style="color: #666666">=</span> <span style="color: #666666">100</span>
hidden_nodes2 <span style="color: #666666">=</span> <span style="color: #666666">30</span>
output_nodes <span style="color: #666666">=</span> <span style="color: #666666">10</span>
dims <span style="color: #666666">=</span> (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)
multiclass <span style="color: #666666">=</span> FFNN(dims, hidden_func<span style="color: #666666">=</span>LRELU, output_func<span style="color: #666666">=</span>softmax, cost_func<span style="color: #666666">=</span>CostCrossEntropy)
multiclass<span style="color: #666666">.</span>reset_weights() <span style="color: #408080; font-style: italic"># reset weights such that previous runs or reruns don&#39;t affect the weights</span>
scheduler <span style="color: #666666">=</span> Adam(eta<span style="color: #666666">=1e-4</span>, rho<span style="color: #666666">=0.9</span>, rho2<span style="color: #666666">=0.999</span>)
scores <span style="color: #666666">=</span> multiclass<span style="color: #666666">.</span>fit(X, target, scheduler, epochs<span style="color: #666666">=1000</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="testing-the-xor-gate-and-other-gates">Testing the XOR gate and other gates </h2>
<p>Let us now use our code to test the XOR gate.</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%;">X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([ [<span style="color: #666666">0</span>, <span style="color: #666666">0</span>], [<span style="color: #666666">0</span>, <span style="color: #666666">1</span>], [<span style="color: #666666">1</span>, <span style="color: #666666">0</span>],[<span style="color: #666666">1</span>, <span style="color: #666666">1</span>]],dtype<span style="color: #666666">=</span>np<span style="color: #666666">.</span>float64)
<span style="color: #408080; font-style: italic"># The XOR gate</span>
yXOR <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array( [[ <span style="color: #666666">0</span>], [<span style="color: #666666">1</span>] ,[<span style="color: #666666">1</span>], [<span style="color: #666666">0</span>]])
input_nodes <span style="color: #666666">=</span> X<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]
output_nodes <span style="color: #666666">=</span> <span style="color: #666666">1</span>
logistic_regression <span style="color: #666666">=</span> FFNN((input_nodes, output_nodes), output_func<span style="color: #666666">=</span>sigmoid, cost_func<span style="color: #666666">=</span>CostLogReg, seed<span style="color: #666666">=2023</span>)
logistic_regression<span style="color: #666666">.</span>reset_weights() <span style="color: #408080; font-style: italic"># reset weights such that previous runs or reruns don&#39;t affect the weights</span>
scheduler <span style="color: #666666">=</span> Adam(eta<span style="color: #666666">=1e-1</span>, rho<span style="color: #666666">=0.9</span>, rho2<span style="color: #666666">=0.999</span>)
scores <span style="color: #666666">=</span> logistic_regression<span style="color: #666666">.</span>fit(X, yXOR, scheduler, epochs<span style="color: #666666">=1000</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>
<p>Not bad, but the results depend strongly on the learning reate. Try different learning rates.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="solving-differential-equations-with-deep-learning">Solving differential equations 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>Physics informed neural networks</b>
<p>
<p><a href="https://link.springer.com/article/10.1007/s10915-022-01939-z" target="_blank">Scientific Machine Learning Through Physics&#8211;Informed Neural Networks: Where we are and What&#8217;s Next</a>, by Cuomo et al</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-first">Ordinary Differential Equations first </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>
<span style="color: #408080; font-style: italic"># deep_params is a list, len() should be used</span>
N_hidden <span style="color: #666666">=</span> <span style="color: #008000">len</span>(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>(deep_params, x):
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
<span style="color: #408080; font-style: italic"># deep_params is a list, len() should be used</span>
N_hidden <span style="color: #666666">=</span> <span style="color: #008000">len</span>(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: #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>
<span style="color: #408080; font-style: italic"># deep_params is a list, len() should be used</span>
N_hidden <span style="color: #666666">=</span> <span style="color: #008000">len</span>(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: #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>
<span style="color: #408080; font-style: italic"># deep_params is a list, len() should be used</span>
N_hidden <span style="color: #666666">=</span> <span style="color: #008000">len</span>(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: #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> <span style="color: #008000">len</span>(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> <span style="color: #008000">len</span>(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>add_suplot(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>add_suplot(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>add_suplot(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> <span style="color: #008000">len</span>(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>add_suplot(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>add_suplot(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>add_suplot(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>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>