6806 lines
477 KiB
HTML
6806 lines
477 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'),
|
|
('Using Automatic differentiation',
|
|
2,
|
|
None,
|
|
'using-automatic-differentiation'),
|
|
('Back propagation and automatic differentiation',
|
|
2,
|
|
None,
|
|
'back-propagation-and-automatic-differentiation'),
|
|
('Material for exercises week 43 and week 44',
|
|
2,
|
|
None,
|
|
'material-for-exercises-week-43-and-week-44'),
|
|
('Writing our first neural network code, testing it for the OR '
|
|
'and XOR gates',
|
|
2,
|
|
None,
|
|
'writing-our-first-neural-network-code-testing-it-for-the-or-and-xor-gates'),
|
|
('The AND and XOR Gates', 2, None, 'the-and-and-xor-gates'),
|
|
('Representing the Data Sets',
|
|
2,
|
|
None,
|
|
'representing-the-data-sets'),
|
|
('Setting up dimensionalities by hand',
|
|
2,
|
|
None,
|
|
'setting-up-dimensionalities-by-hand'),
|
|
('Setting up the Neural Network',
|
|
2,
|
|
None,
|
|
'setting-up-the-neural-network'),
|
|
('The Code using Scikit-Learn',
|
|
2,
|
|
None,
|
|
'the-code-using-scikit-learn'),
|
|
('Building a neural network code',
|
|
2,
|
|
None,
|
|
'building-a-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'),
|
|
('Lecture Thursday October 26',
|
|
2,
|
|
None,
|
|
'lecture-thursday-october-26'),
|
|
('Developing a code for doing neural networks with back '
|
|
'propagation',
|
|
2,
|
|
None,
|
|
'developing-a-code-for-doing-neural-networks-with-back-propagation'),
|
|
('Collect and pre-process data',
|
|
2,
|
|
None,
|
|
'collect-and-pre-process-data'),
|
|
('Train and test datasets', 2, None, 'train-and-test-datasets'),
|
|
('Define model and architecture',
|
|
2,
|
|
None,
|
|
'define-model-and-architecture'),
|
|
('Layers', 2, None, 'layers'),
|
|
('Weights and biases', 2, None, 'weights-and-biases'),
|
|
('Feed-forward pass', 2, None, 'feed-forward-pass'),
|
|
('Matrix multiplications', 2, None, 'matrix-multiplications'),
|
|
('Choose cost function and optimizer',
|
|
2,
|
|
None,
|
|
'choose-cost-function-and-optimizer'),
|
|
('Optimizing the cost function',
|
|
2,
|
|
None,
|
|
'optimizing-the-cost-function'),
|
|
('Regularization', 2, None, 'regularization'),
|
|
('Matrix multiplication', 2, None, 'matrix-multiplication'),
|
|
('Improving performance', 2, None, 'improving-performance'),
|
|
('Full object-oriented implementation',
|
|
2,
|
|
None,
|
|
'full-object-oriented-implementation'),
|
|
('Evaluate model performance on test data',
|
|
2,
|
|
None,
|
|
'evaluate-model-performance-on-test-data'),
|
|
('Adjust hyperparameters', 2, None, 'adjust-hyperparameters'),
|
|
('Visualization', 2, None, 'visualization'),
|
|
('scikit-learn implementation',
|
|
2,
|
|
None,
|
|
'scikit-learn-implementation'),
|
|
('Visualization', 2, None, 'visualization'),
|
|
('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'),
|
|
('The Breast Cancer Data, now with Keras',
|
|
2,
|
|
None,
|
|
'the-breast-cancer-data-now-with-keras'),
|
|
('Fine-tuning neural network hyperparameters',
|
|
2,
|
|
None,
|
|
'fine-tuning-neural-network-hyperparameters'),
|
|
('Hidden layers', 2, None, 'hidden-layers'),
|
|
('Which activation function should I use?',
|
|
2,
|
|
None,
|
|
'which-activation-function-should-i-use'),
|
|
('Is the Logistic activation function (Sigmoid) our choice?',
|
|
2,
|
|
None,
|
|
'is-the-logistic-activation-function-sigmoid-our-choice'),
|
|
('The derivative of the Logistic funtion',
|
|
2,
|
|
None,
|
|
'the-derivative-of-the-logistic-funtion'),
|
|
('The RELU function family', 2, None, 'the-relu-function-family'),
|
|
('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'),
|
|
('Batch Normalization', 2, None, 'batch-normalization'),
|
|
('Dropout', 2, None, 'dropout'),
|
|
('Gradient Clipping', 2, None, 'gradient-clipping'),
|
|
('A very nice website on Neural Networks',
|
|
2,
|
|
None,
|
|
'a-very-nice-website-on-neural-networks'),
|
|
('A top-down perspective on Neural networks',
|
|
2,
|
|
None,
|
|
'a-top-down-perspective-on-neural-networks'),
|
|
('Limitations of supervised learning with deep networks',
|
|
2,
|
|
None,
|
|
'limitations-of-supervised-learning-with-deep-networks'),
|
|
('Solving ODEs with Deep Learning',
|
|
2,
|
|
None,
|
|
'solving-odes-with-deep-learning'),
|
|
('Ordinary Differential Equations',
|
|
2,
|
|
None,
|
|
'ordinary-differential-equations'),
|
|
('The trial solution', 2, None, 'the-trial-solution'),
|
|
('Minimization process', 2, None, 'minimization-process'),
|
|
('Minimizing the cost function using gradient descent and '
|
|
'automatic differentiation',
|
|
2,
|
|
None,
|
|
'minimizing-the-cost-function-using-gradient-descent-and-automatic-differentiation'),
|
|
('Example: Exponential decay',
|
|
2,
|
|
None,
|
|
'example-exponential-decay'),
|
|
('The function to solve for',
|
|
2,
|
|
None,
|
|
'the-function-to-solve-for'),
|
|
('The trial solution', 2, None, 'the-trial-solution'),
|
|
('Setup of Network', 2, None, 'setup-of-network'),
|
|
('Reformulating the problem',
|
|
2,
|
|
None,
|
|
'reformulating-the-problem'),
|
|
('More technicalities', 2, None, 'more-technicalities'),
|
|
('More details', 2, None, 'more-details'),
|
|
('A possible implementation of a neural network',
|
|
2,
|
|
None,
|
|
'a-possible-implementation-of-a-neural-network'),
|
|
('Technicalities', 2, None, 'technicalities'),
|
|
('Final technicalities I', 2, None, 'final-technicalities-i'),
|
|
('Final technicalities II', 2, None, 'final-technicalities-ii'),
|
|
('Final technicalities III', 2, None, 'final-technicalities-iii'),
|
|
('Final technicalities IV', 2, None, 'final-technicalities-iv'),
|
|
('Back propagation', 2, None, 'back-propagation'),
|
|
('Gradient descent', 2, None, 'gradient-descent'),
|
|
('The code for solving the ODE',
|
|
2,
|
|
None,
|
|
'the-code-for-solving-the-ode'),
|
|
('The network with one input layer, specified number of hidden '
|
|
'layers, and one output layer',
|
|
2,
|
|
None,
|
|
'the-network-with-one-input-layer-specified-number-of-hidden-layers-and-one-output-layer'),
|
|
('Example: Population growth',
|
|
2,
|
|
None,
|
|
'example-population-growth'),
|
|
('Setting up the problem', 2, None, 'setting-up-the-problem'),
|
|
('The trial solution', 2, None, 'the-trial-solution'),
|
|
('The program using Autograd',
|
|
2,
|
|
None,
|
|
'the-program-using-autograd'),
|
|
('Using forward Euler to solve the ODE',
|
|
2,
|
|
None,
|
|
'using-forward-euler-to-solve-the-ode'),
|
|
('Example: Solving the one dimensional Poisson equation',
|
|
2,
|
|
None,
|
|
'example-solving-the-one-dimensional-poisson-equation'),
|
|
('The specific equation to solve for',
|
|
2,
|
|
None,
|
|
'the-specific-equation-to-solve-for'),
|
|
('Solving the equation using Autograd',
|
|
2,
|
|
None,
|
|
'solving-the-equation-using-autograd'),
|
|
('Comparing with a numerical scheme',
|
|
2,
|
|
None,
|
|
'comparing-with-a-numerical-scheme'),
|
|
('Setting up the code', 2, None, 'setting-up-the-code'),
|
|
('Partial Differential Equations',
|
|
2,
|
|
None,
|
|
'partial-differential-equations'),
|
|
('Type of problem', 2, None, 'type-of-problem'),
|
|
('Network requirements', 2, None, 'network-requirements'),
|
|
('More details', 2, None, 'more-details'),
|
|
('Example: The diffusion equation',
|
|
2,
|
|
None,
|
|
'example-the-diffusion-equation'),
|
|
('Defining the problem', 2, None, 'defining-the-problem'),
|
|
('Setting up the network using Autograd',
|
|
2,
|
|
None,
|
|
'setting-up-the-network-using-autograd'),
|
|
('Setting up the network using Autograd; The trial solution',
|
|
2,
|
|
None,
|
|
'setting-up-the-network-using-autograd-the-trial-solution'),
|
|
('Why the jacobian?', 2, None, 'why-the-jacobian'),
|
|
('Setting up the network using Autograd; The full program',
|
|
2,
|
|
None,
|
|
'setting-up-the-network-using-autograd-the-full-program'),
|
|
('Example: Solving the wave equation with Neural Networks',
|
|
2,
|
|
None,
|
|
'example-solving-the-wave-equation-with-neural-networks'),
|
|
('The problem to solve for', 2, None, 'the-problem-to-solve-for'),
|
|
('The trial solution', 2, None, 'the-trial-solution'),
|
|
('The analytical solution', 2, None, 'the-analytical-solution'),
|
|
('Solving the wave equation - the full program using Autograd',
|
|
2,
|
|
None,
|
|
'solving-the-wave-equation-the-full-program-using-autograd'),
|
|
('Resources on differential equations and deep learning',
|
|
2,
|
|
None,
|
|
'resources-on-differential-equations-and-deep-learning')]}
|
|
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> [1, 2]
|
|
</center>
|
|
<!-- institution(s) -->
|
|
<center>
|
|
[1] <b>Department of Physics, University of Oslo</b>
|
|
</center>
|
|
<center>
|
|
[2] <b>Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University</b>
|
|
</center>
|
|
<br>
|
|
<center>
|
|
<h4>Oct 26, 2023</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 active learning sessions on Tuesday and Wednesday</b>
|
|
<p>
|
|
<ul>
|
|
<li> Exercise on writing your own neural network code, application to the OR and XOR gates</li>
|
|
<li> The exercises this week will be continued next week as well</li>
|
|
<li> Discussion of project 2</li>
|
|
<li> <a href="https://youtu.be/Ia6wwDLxqtM" target="_blank">Video of lab session</a></li>
|
|
</ul>
|
|
</div>
|
|
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Material for the lecture on Thursday October 26, 2023</b>
|
|
<p>
|
|
<ul>
|
|
<li> Building our own Feed-forward Neural Network and discussion of project 2, continuation from last week</li>
|
|
<li> Solving differential equations with Neural Networks and intro to <b>Tensorflow</b> with examples.</li>
|
|
<li> <a href="https://youtu.be/_-AwbBh4G-8" target="_blank">Video of lecture</a></li>
|
|
<li> <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesOct26.pdf" target="_blank">Whiteboard notes</a></li>
|
|
<li> Readings and Videos:</li>
|
|
<ul>
|
|
<li> These lecture notes</li>
|
|
<li> <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf" target="_blank">Aurelien Geron's chapters 10-11</a></li>
|
|
<li> For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7.</li>
|
|
<li> <a href="https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs" target="_blank">Neural Networks demystified</a></li>
|
|
<li> <a href="https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex" target="_blank">Building Neural Networks from scratch</a></li>
|
|
<li> <a href="https://www.youtube.com/watch?v=CqOfi41LfDw" target="_blank">Video on Neural Networks</a></li>
|
|
<li> <a href="https://www.youtube.com/watch?v=Ilg3gGewQ5U" target="_blank">Video on the back propagation algorithm</a></li>
|
|
</ul>
|
|
</ul>
|
|
<p>I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at <a href="http://neuralnetworksanddeeplearning.com/chap4.html" target="_blank"><tt>http://neuralnetworksanddeeplearning.com/chap4.html</tt></a>.</p>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="using-automatic-differentiation">Using Automatic differentiation </h2>
|
|
<p>a
|
|
In our discussions of ordinary differential equations
|
|
we will also study the usage of <a href="https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola" target="_blank">Autograd</a> in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from <a href="https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html" target="_blank">week 39</a> and the <a href="https://github.com/HIPS/autograd" target="_blank">Autograd documentation</a>.
|
|
t
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="back-propagation-and-automatic-differentiation">Back propagation and automatic differentiation </h2>
|
|
|
|
<p>For more details on the back propagation algorithm and automatic differentiation see</p>
|
|
<ol>
|
|
<li> <a href="https://www.jmlr.org/papers/volume18/17-468/17-468.pdf" target="_blank"><tt>https://www.jmlr.org/papers/volume18/17-468/17-468.pdf</tt></a></li>
|
|
<li> <a href="https://deepimaging.github.io/lectures/lecture_11_Backpropagation.pdf" target="_blank"><tt>https://deepimaging.github.io/lectures/lecture_11_Backpropagation.pdf</tt></a></li>
|
|
<li> Slides 12-44 at URL":http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf"</li>
|
|
</ol>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="material-for-exercises-week-43-and-week-44">Material for exercises week 43 and week 44 </h2>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="writing-our-first-neural-network-code-testing-it-for-the-or-and-xor-gates">Writing our first neural network code, testing it for the OR and XOR gates </h2>
|
|
|
|
<p>During week 41 we discussed three different types of gates, the
|
|
so-called XOR, the OR and the AND gates. In order to develop a code
|
|
for neural networks, it can be useful to set up a simpler system with
|
|
only two inputs and one output. This can make it easier to debug and
|
|
study the feed forward pass and the back propagation part. In the
|
|
exercise this and next week, we propose to study this system with just
|
|
one hidden layer and two hidden nodes. There is only one output node
|
|
and we can choose to use either a simple regression case (fitting a
|
|
line) or just a binary classification case with the corss-entropy as
|
|
cost function.
|
|
</p>
|
|
|
|
<p>Their inputs and outputs can be
|
|
summarized using the following tables, first for the OR gate with
|
|
inputs \( x_1 \) and \( x_2 \) and outputs \( y \):
|
|
</p>
|
|
|
|
<table class="dotable" border="1">
|
|
<thead>
|
|
<tr><td align="center">\( x_1 \)</td> <td align="center">\( x_2 \)</td> <td align="center">\( y \)</td> </tr>
|
|
</thead>
|
|
<tbody>
|
|
<tr><td align="center"> 0 </td> <td align="center"> 0 </td> <td align="center"> 0 </td> </tr>
|
|
<tr><td align="center"> 0 </td> <td align="center"> 1 </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 1 </td> <td align="center"> 0 </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 1 </td> <td align="center"> 1 </td> <td align="center"> 1 </td> </tr>
|
|
</tbody>
|
|
</table>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-and-and-xor-gates">The AND and XOR Gates </h2>
|
|
|
|
<p>The AND gate is defined as</p>
|
|
|
|
<table class="dotable" border="1">
|
|
<thead>
|
|
<tr><td align="center">\( x_1 \)</td> <td align="center">\( x_2 \)</td> <td align="center">\( y \)</td> </tr>
|
|
</thead>
|
|
<tbody>
|
|
<tr><td align="center"> 0 </td> <td align="center"> 0 </td> <td align="center"> 0 </td> </tr>
|
|
<tr><td align="center"> 0 </td> <td align="center"> 1 </td> <td align="center"> 0 </td> </tr>
|
|
<tr><td align="center"> 1 </td> <td align="center"> 0 </td> <td align="center"> 0 </td> </tr>
|
|
<tr><td align="center"> 1 </td> <td align="center"> 1 </td> <td align="center"> 1 </td> </tr>
|
|
</tbody>
|
|
</table>
|
|
|
|
<p>And finally we have the XOR gate</p>
|
|
|
|
<table class="dotable" border="1">
|
|
<thead>
|
|
<tr><td align="center">\( x_1 \)</td> <td align="center">\( x_2 \)</td> <td align="center">\( y \)</td> </tr>
|
|
</thead>
|
|
<tbody>
|
|
<tr><td align="center"> 0 </td> <td align="center"> 0 </td> <td align="center"> 0 </td> </tr>
|
|
<tr><td align="center"> 0 </td> <td align="center"> 1 </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 1 </td> <td align="center"> 0 </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 1 </td> <td align="center"> 1 </td> <td align="center"> 0 </td> </tr>
|
|
</tbody>
|
|
</table>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="representing-the-data-sets">Representing the Data Sets </h2>
|
|
|
|
<p>Our design matrix is defined by the input values \( x_1 \) and \( x_2 \). Since we have four possible outputs, our design matrix reads</p>
|
|
|
|
$$
|
|
\boldsymbol{X}=\begin{bmatrix} 0 & 0 \\
|
|
0 & 1 \\
|
|
1 & 0 \\
|
|
1 & 1 \end{bmatrix},
|
|
$$
|
|
|
|
<p>while the vector of outputs is \( \boldsymbol{y}^T=[0,1,1,0] \) for the XOR gate, \( \boldsymbol{y}^T=[0,0,0,1] \) for the AND gate and \( \boldsymbol{y}^T=[0,1,1,1] \) for the OR gate.</p>
|
|
|
|
<p>Your tasks here are</p>
|
|
|
|
<ol>
|
|
<li> Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs.</li>
|
|
<li> Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function.</li>
|
|
<li> Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output.</li>
|
|
<li> Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets.</li>
|
|
<li> Set up the cost function (cross entropy for classification of binary cases).</li>
|
|
<li> Calculate the gradients needed for the back propagation part.</li>
|
|
<li> Use the gradients to train the network in the back propagation part. Think of using automatic differentiation.</li>
|
|
<li> Train the network and study your results and compare with results obtained either with <b>scikit-learn</b> or <b>TensorFlow</b>.</li>
|
|
</ol>
|
|
<p>Everything you develop here can be used directly into the code for the project.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="setting-up-dimensionalities-by-hand">Setting up dimensionalities by hand </h2>
|
|
|
|
<p>It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by</p>
|
|
$$
|
|
\boldsymbol{W_h}=\begin{bmatrix} 1 & 1 \\
|
|
1 & 1 \end{bmatrix},
|
|
$$
|
|
|
|
<p>Multiplying \( \boldsymbol{X} \) and \( \boldsymbol{W} \) gives</p>
|
|
|
|
$$
|
|
\boldsymbol{X}{W}_h=\begin{bmatrix} 0 & 0 \\
|
|
1 & 1 \\
|
|
1 & 1 \\
|
|
2 & 2 \end{bmatrix},
|
|
$$
|
|
|
|
<p>Assume also that the bias vector for the hidden layer is</p>
|
|
$$
|
|
\boldsymbol{b}_h=\begin{bmatrix} 0 \\
|
|
-1\end{bmatrix},
|
|
$$
|
|
|
|
<p>Adding it gives us the input to the activation function of the hidden layer</p>
|
|
$$
|
|
\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h=\begin{bmatrix} 0 & -1 \\
|
|
1 & 0 \\
|
|
1 & 0 \\
|
|
2 & 1 \end{bmatrix},
|
|
$$
|
|
|
|
<p>Let us then assume that our activation function is the RELU function, which simply means that we take the max of \( 0 \) and the elements of the input argument \( \boldsymbol{z}_h \), that is we have</p>
|
|
$$
|
|
\boldsymbol{a}_h=\mathrm{RELU}(\boldsymbol{z}_h=\boldsymbol{X}\boldsymbol{W}_h+\boldsymbol{b}_h)=\begin{bmatrix} 0 & 0 \\
|
|
1 & 0 \\
|
|
1 & 0 \\
|
|
2 & 1 \end{bmatrix},
|
|
$$
|
|
|
|
<p>Assume also that the bias of the output layer is zero and that the weights of the output layer are</p>
|
|
$$
|
|
\boldsymbol{w}_o=\begin{bmatrix} 1 \\
|
|
-2\end{bmatrix},
|
|
$$
|
|
|
|
<p>and multiplying with \( \boldsymbol{a}_h \) gives the output</p>
|
|
$$
|
|
\boldsymbol{a}_o=\begin{bmatrix} 0 & 0 \\
|
|
1 & 0 \\
|
|
1 & 0 \\
|
|
2 & 1 \end{bmatrix}\begin{bmatrix} 1 \\
|
|
-2\end{bmatrix}=\begin{bmatrix} 0 \\ 1 \\ 1 \\0\end{bmatrix},
|
|
$$
|
|
|
|
<p>the wanted result. Pay attention to the dimensionalities as well.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="setting-up-the-neural-network">Setting up the Neural Network </h2>
|
|
|
|
<p>We define first our design matrix and the various output vectors for the different gates.</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: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic">Simple code that tests XOR, OR and AND gates with linear regression</span>
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># import necessary packages</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> datasets
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(x):
|
|
<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>x))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">feed_forward</span>(X):
|
|
<span style="color: #408080; font-style: italic"># weighted sum of inputs to the hidden layer</span>
|
|
z_h <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(X, hidden_weights) <span style="color: #666666">+</span> hidden_bias
|
|
<span style="color: #408080; font-style: italic"># activation in the hidden layer</span>
|
|
a_h <span style="color: #666666">=</span> sigmoid(z_h)
|
|
|
|
<span style="color: #408080; font-style: italic"># weighted sum of inputs to the output layer</span>
|
|
z_o <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(a_h, output_weights) <span style="color: #666666">+</span> output_bias
|
|
<span style="color: #408080; font-style: italic"># softmax output</span>
|
|
<span style="color: #408080; font-style: italic"># axis 0 holds each input and axis 1 the probabilities of each category</span>
|
|
probabilities <span style="color: #666666">=</span> sigmoid(z_o)
|
|
<span style="color: #008000; font-weight: bold">return</span> probabilities
|
|
|
|
|
|
<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"># Design matrix</span>
|
|
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>])
|
|
<span style="color: #408080; font-style: italic"># The OR gate</span>
|
|
yOR <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">1</span>])
|
|
<span style="color: #408080; font-style: italic"># The AND gate</span>
|
|
yAND <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: #408080; font-style: italic"># Defining the neural network</span>
|
|
n_inputs, n_features <span style="color: #666666">=</span> X<span style="color: #666666">.</span>shape
|
|
n_hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">2</span>
|
|
n_categories <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
n_features <span style="color: #666666">=</span> <span style="color: #666666">2</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># we make the weights normally distributed using numpy.random.randn</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># weights and bias in the hidden layer</span>
|
|
hidden_weights <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(n_features, n_hidden_neurons)
|
|
hidden_bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n_hidden_neurons) <span style="color: #666666">+</span> <span style="color: #666666">0.01</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># weights and bias in the output layer</span>
|
|
output_weights <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(n_hidden_neurons, n_categories)
|
|
output_bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n_categories) <span style="color: #666666">+</span> <span style="color: #666666">0.01</span>
|
|
|
|
probabilities <span style="color: #666666">=</span> feed_forward(X)
|
|
<span style="color: #008000">print</span>(probabilities)
|
|
</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 an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-code-using-scikit-learn">The Code using Scikit-Learn </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># import necessary packages</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.neural_network</span> <span style="color: #008000; font-weight: bold">import</span> MLPClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
|
|
<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>
|
|
|
|
<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"># Design matrix</span>
|
|
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>])
|
|
<span style="color: #408080; font-style: italic"># The OR gate</span>
|
|
yOR <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">1</span>])
|
|
<span style="color: #408080; font-style: italic"># The AND gate</span>
|
|
yAND <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: #408080; font-style: italic"># Defining the neural network</span>
|
|
n_hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">2</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: #408080; font-style: italic"># store models for later use</span>
|
|
DNN_scikit <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>)
|
|
epochs <span style="color: #666666">=</span> <span style="color: #666666">100</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> MLPClassifier(hidden_layer_sizes<span style="color: #666666">=</span>(n_hidden_neurons), activation<span style="color: #666666">=</span><span style="color: #BA2121">'logistic'</span>,
|
|
alpha<span style="color: #666666">=</span>lmbd, learning_rate_init<span style="color: #666666">=</span>eta, max_iter<span style="color: #666666">=</span>epochs)
|
|
dnn<span style="color: #666666">.</span>fit(X, yXOR)
|
|
DNN_scikit[i][j] <span style="color: #666666">=</span> dnn
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Learning rate = "</span>, eta)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Lambda = "</span>, lmbd)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Accuracy score on data set: "</span>, dnn<span style="color: #666666">.</span>score(X, yXOR))
|
|
<span style="color: #008000">print</span>()
|
|
|
|
sns<span style="color: #666666">.</span>set()
|
|
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_scikit[i][j]
|
|
test_pred <span style="color: #666666">=</span> dnn<span style="color: #666666">.</span>predict(X)
|
|
test_accuracy[i][j] <span style="color: #666666">=</span> accuracy_score(yXOR, test_pred)
|
|
|
|
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">"viridis"</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">"Test Accuracy"</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"$\eta$"</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"$\lambda$"</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="building-a-neural-network-code">Building a 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
|
|
(\( δ^l_ja^{l−1}_k \)), and returns the change which will be subtracted
|
|
from the weights. The reset() function takes no parameters, and resets
|
|
the desired variables. For Constant and Momentum, reset does nothing.
|
|
</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">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Abstract class for Schedulers</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</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"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">"</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"</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">"</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"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">"</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">></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">></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">></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">"RELU"</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">></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">"LRELU"</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">></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"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">"</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"</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">"</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"</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">"</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">"error"</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">"""</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"> """</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">"""</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"> """</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"</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">"</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">"</span><span style="color: #BB6622; font-weight: bold">\r</span><span style="color: #BA2121">"</span> <span style="color: #666666">+</span> <span style="color: #BA2121">" "</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">""</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">"train_errors"</span>] <span style="color: #666666">=</span> train_errors
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> val_set:
|
|
scores[<span style="color: #BA2121">"val_errors"</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">"train_accs"</span>] <span style="color: #666666">=</span> train_accs
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> val_set:
|
|
scores[<span style="color: #BA2121">"val_accs"</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">"""</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"> """</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">></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">"""</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"> """</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">"""</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"> """</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"><</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">"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"</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">"""</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"> """</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">"softmax"</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">"""</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"> """</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">"""</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"> """</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">"CostLogReg"</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">"CostCrossEntropy"</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">"""</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"> """</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">">"</span> <span style="color: #008000; font-weight: bold">if</span> num_equals <span style="color: #666666">></span> <span style="color: #666666">0</span> <span style="color: #008000; font-weight: bold">else</span> <span style="color: #BA2121">""</span>
|
|
bar <span style="color: #666666">=</span> <span style="color: #BA2121">"["</span> <span style="color: #666666">+</span> <span style="color: #BA2121">"="</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">"-"</span> <span style="color: #666666">*</span> num_not <span style="color: #666666">+</span> <span style="color: #BA2121">"]"</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" </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">% "</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"| </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"> "</span>
|
|
sys<span style="color: #666666">.</span>stdout<span style="color: #666666">.</span>write(<span style="color: #BA2121">"</span><span style="color: #BB6622; font-weight: bold">\r</span><span style="color: #BA2121">"</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">"""</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"> """</span>
|
|
<span style="color: #008000; font-weight: bold">if</span> value <span style="color: #666666">></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"><</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">>=</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"</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">"</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">></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'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'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'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'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'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'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="lecture-thursday-october-26">Lecture Thursday October 26 </h2>
|
|
|
|
<!-- !split -->
|
|
<h2 id="developing-a-code-for-doing-neural-networks-with-back-propagation">Developing a code for doing neural networks with back propagation </h2>
|
|
|
|
<p>We repeat some of the elements discussed last week. The first part of
|
|
the material for Thursday was contained in the slides for last
|
|
week as well. We will repeat some of the topics here before we move into
|
|
applications to differential equations and other examples.
|
|
</p>
|
|
|
|
<p>One can identify a set of key steps when using neural networks to solve supervised learning problems: </p>
|
|
|
|
<ol>
|
|
<li> Collect and pre-process data</li>
|
|
<li> Define model and architecture</li>
|
|
<li> Choose cost function and optimizer</li>
|
|
<li> Train the model</li>
|
|
<li> Evaluate model performance on test data</li>
|
|
<li> Adjust hyperparameters (if necessary, network architecture)</li>
|
|
</ol>
|
|
<!-- !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>Here we will be using the MNIST dataset, which is readily available through the <b>scikit-learn</b>
|
|
package. You may also find it for example <a href="http://yann.lecun.com/exdb/mnist/" target="_blank">here</a>.
|
|
The <em>MNIST</em> (Modified National Institute of Standards and Technology) database is a large database
|
|
of handwritten digits that is commonly used for training various image processing systems.
|
|
The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9.
|
|
The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database.
|
|
</p>
|
|
|
|
<p>To feed data into a feed-forward neural network we need to represent
|
|
the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each
|
|
row represents an <em>input</em>, in this case a handwritten digit, and
|
|
each column represents a <em>feature</em>, in this case a pixel. The
|
|
correct answers, also known as <em>labels</em> or <em>targets</em> are
|
|
represented as a 1D array of integers
|
|
\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \).
|
|
</p>
|
|
|
|
<p>As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from
|
|
measurements of height (in m)
|
|
and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example:
|
|
</p>
|
|
|
|
<p>$$ X = \begin{bmatrix}
|
|
1.85 & 81\\
|
|
1.71 & 65\\
|
|
1.95 & 103\\
|
|
1.55 & 42\\
|
|
1.63 & 56
|
|
\end{bmatrix} ,$$
|
|
</p>
|
|
|
|
<p>and the targets would be: </p>
|
|
|
|
<p>$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ </p>
|
|
|
|
<p>Since each input image is a 2D matrix, we need to flatten the image
|
|
(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a
|
|
design/feature matrix. This means we lose all spatial information in the
|
|
image, such as locality and translational invariance. More complicated
|
|
architectures such as Convolutional Neural Networks can take advantage
|
|
of such information, and are most commonly applied when analyzing
|
|
images.
|
|
</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># import necessary packages</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> datasets
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># ensure the same random numbers appear every time</span>
|
|
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">0</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># display images in notebook</span>
|
|
<span style="color: #666666">%</span>matplotlib inline
|
|
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">'figure.figsize'</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">"inputs = (n_inputs, pixel_width, pixel_height) = "</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">"labels = (n_inputs) = "</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">"X = (n_inputs, n_features) = "</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">'off'</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">'nearest'</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Label: </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121">"</span> <span style="color: #666666">%</span> digits<span style="color: #666666">.</span>target[random_indices[i]])
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="train-and-test-datasets">Train and test datasets </h2>
|
|
|
|
<p>Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. </p>
|
|
|
|
<p>We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing. </p>
|
|
|
|
<p>It is important that the train and test datasets are drawn randomly from our dataset, to ensure
|
|
no bias in the sampling.
|
|
Say you are taking measurements of weather data to predict the weather in the coming 5 days.
|
|
You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data
|
|
collected from 12.00 to 24.00.
|
|
</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.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
|
|
<span style="color: #408080; font-style: italic"># one-liner from scikit-learn library</span>
|
|
train_size <span style="color: #666666">=</span> <span style="color: #666666">0.8</span>
|
|
test_size <span style="color: #666666">=</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> train_size
|
|
X_train, X_test, Y_train, Y_test <span style="color: #666666">=</span> train_test_split(inputs, labels, train_size<span style="color: #666666">=</span>train_size,
|
|
test_size<span style="color: #666666">=</span>test_size)
|
|
|
|
<span style="color: #408080; font-style: italic"># equivalently in numpy</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">train_test_split_numpy</span>(inputs, labels, train_size, test_size):
|
|
n_inputs <span style="color: #666666">=</span> <span style="color: #008000">len</span>(inputs)
|
|
inputs_shuffled <span style="color: #666666">=</span> inputs<span style="color: #666666">.</span>copy()
|
|
labels_shuffled <span style="color: #666666">=</span> labels<span style="color: #666666">.</span>copy()
|
|
|
|
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>shuffle(inputs_shuffled)
|
|
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>shuffle(labels_shuffled)
|
|
|
|
train_end <span style="color: #666666">=</span> <span style="color: #008000">int</span>(n_inputs<span style="color: #666666">*</span>train_size)
|
|
X_train, X_test <span style="color: #666666">=</span> inputs_shuffled[:train_end], inputs_shuffled[train_end:]
|
|
Y_train, Y_test <span style="color: #666666">=</span> labels_shuffled[:train_end], labels_shuffled[train_end:]
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> X_train, X_test, Y_train, Y_test
|
|
|
|
<span style="color: #408080; font-style: italic">#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Number of training images: "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(<span style="color: #008000">len</span>(X_train)))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Number of test images: "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(<span style="color: #008000">len</span>(X_test)))
|
|
</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="define-model-and-architecture">Define model and architecture </h2>
|
|
|
|
<p>Our simple feed-forward neural network will consist of an <em>input</em> layer, a single <em>hidden</em> layer and an <em>output</em> layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have </p>
|
|
|
|
<p>$$ z = \sum_{i=1}^n w_i a_i ,$$</p>
|
|
|
|
<p>$$ y = f(z) ,$$</p>
|
|
|
|
<p>where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer
|
|
and \( w_i \) is the weight to input \( i \).
|
|
The activation of the neurons in the input layer is just the features (e.g. a pixel value).
|
|
</p>
|
|
|
|
<p>The simplest activation function for a neuron is the <em>Heaviside</em> function:</p>
|
|
|
|
<p>$$ f(z) =
|
|
\begin{cases}
|
|
1, & z > 0\\
|
|
0, & \text{otherwise}
|
|
\end{cases}
|
|
$$
|
|
</p>
|
|
|
|
<p>A feed-forward neural network with this activation is known as a <em>perceptron</em>.
|
|
For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer.
|
|
This activation can be generalized to \( k \) classes (using e.g. the <em>one-against-all</em> strategy),
|
|
and we call these architectures <em>multiclass perceptrons</em>.
|
|
</p>
|
|
|
|
<p>However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and
|
|
Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function.
|
|
</p>
|
|
|
|
<p>Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU).
|
|
We will be using the sigmoid function \( \sigma(x) \):
|
|
</p>
|
|
|
|
<p>$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$</p>
|
|
|
|
<p>which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.</p>
|
|
|
|
<!-- !split -->
|
|
<h2 id="layers">Layers </h2>
|
|
|
|
<ul>
|
|
<li> Input</li>
|
|
</ul>
|
|
<p>Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. </p>
|
|
|
|
<ul>
|
|
<li> Hidden layer</li>
|
|
</ul>
|
|
<p>We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer.
|
|
Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer.
|
|
</p>
|
|
|
|
<ul>
|
|
<li> Output</li>
|
|
</ul>
|
|
<p>If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,
|
|
which could output 0 or 1 according to the Heaviside function. This would be an example of a <em>hard</em> classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a <em>soft</em> classifier, which outputs the probability of being in class 0 or 1.
|
|
</p>
|
|
|
|
<p>For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. </p>
|
|
|
|
<p>Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the <em>softmax</em> function: </p>
|
|
|
|
<p>$$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}}
|
|
{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$
|
|
</p>
|
|
|
|
<p>i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs.
|
|
The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1.
|
|
The exponent is just the weighted sum of inputs as before:
|
|
</p>
|
|
|
|
<p>$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ </p>
|
|
|
|
<p>Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500
|
|
weights to the output layer.
|
|
</p>
|
|
|
|
<!-- !split -->
|
|
<h2 id="weights-and-biases">Weights and biases </h2>
|
|
|
|
<p>Typically weights are initialized with small values distributed around zero, drawn from a uniform
|
|
or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless.
|
|
</p>
|
|
|
|
<p>Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range
|
|
of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \):
|
|
</p>
|
|
|
|
<p>$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ </p>
|
|
|
|
<p>The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.</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"># building our neural network</span>
|
|
|
|
n_inputs, n_features <span style="color: #666666">=</span> X_train<span style="color: #666666">.</span>shape
|
|
n_hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">50</span>
|
|
n_categories <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># we make the weights normally distributed using numpy.random.randn</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># weights and bias in the hidden layer</span>
|
|
hidden_weights <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(n_features, n_hidden_neurons)
|
|
hidden_bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n_hidden_neurons) <span style="color: #666666">+</span> <span style="color: #666666">0.01</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># weights and bias in the output layer</span>
|
|
output_weights <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(n_hidden_neurons, n_categories)
|
|
output_bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n_categories) <span style="color: #666666">+</span> <span style="color: #666666">0.01</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="feed-forward-pass">Feed-forward pass </h2>
|
|
|
|
<p>Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories.
|
|
For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \):
|
|
</p>
|
|
|
|
<p>$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$</p>
|
|
|
|
<p>this is then passed through our activation function </p>
|
|
|
|
<p>$$ a_{j}^{l} = f(z_{j}^{l}) .$$ </p>
|
|
|
|
<p>We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer: </p>
|
|
|
|
<p>$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ </p>
|
|
|
|
<p>Finally we calculate the output of neuron \( j \) in the output layer using the softmax function: </p>
|
|
|
|
<p>$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}}
|
|
{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$
|
|
</p>
|
|
|
|
<!-- !split -->
|
|
<h2 id="matrix-multiplications">Matrix multiplications </h2>
|
|
|
|
<p>Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden
|
|
layer have the dimensions
|
|
\( W_{hidden} = (n_{features}, n_{hidden}) \),
|
|
we can easily feed the network all our training data in one go by taking the matrix product
|
|
</p>
|
|
|
|
<p>$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ </p>
|
|
|
|
<p>and obtain a matrix that holds the weighted sum of inputs to the hidden layer
|
|
for each input image and each hidden neuron.
|
|
We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \):
|
|
</p>
|
|
|
|
<p>$$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$</p>
|
|
|
|
<p>meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image.
|
|
This is then passed through the activation:
|
|
</p>
|
|
|
|
<p>$$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$ </p>
|
|
|
|
<p>This is fed to the output layer: </p>
|
|
|
|
<p>$$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$</p>
|
|
|
|
<p>Finally we receive our output values for each image and each category by passing it through the softmax function: </p>
|
|
|
|
<p>$$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$</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"># setup the feed-forward pass, subscript h = hidden layer</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(x):
|
|
<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>x))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">feed_forward</span>(X):
|
|
<span style="color: #408080; font-style: italic"># weighted sum of inputs to the hidden layer</span>
|
|
z_h <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(X, hidden_weights) <span style="color: #666666">+</span> hidden_bias
|
|
<span style="color: #408080; font-style: italic"># activation in the hidden layer</span>
|
|
a_h <span style="color: #666666">=</span> sigmoid(z_h)
|
|
|
|
<span style="color: #408080; font-style: italic"># weighted sum of inputs to the output layer</span>
|
|
z_o <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(a_h, output_weights) <span style="color: #666666">+</span> output_bias
|
|
<span style="color: #408080; font-style: italic"># softmax output</span>
|
|
<span style="color: #408080; font-style: italic"># axis 0 holds each input and axis 1 the probabilities of each category</span>
|
|
exp_term <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(z_o)
|
|
probabilities <span style="color: #666666">=</span> exp_term <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum(exp_term, 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: #008000; font-weight: bold">return</span> probabilities
|
|
|
|
probabilities <span style="color: #666666">=</span> feed_forward(X_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"probabilities = (n_inputs, n_categories) = "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(probabilities<span style="color: #666666">.</span>shape))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"probability that image 0 is in category 0,1,2,...,9 = </span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">"</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(probabilities[<span style="color: #666666">0</span>]))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"probabilities sum up to: "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(probabilities[<span style="color: #666666">0</span>]<span style="color: #666666">.</span>sum()))
|
|
<span style="color: #008000">print</span>()
|
|
|
|
<span style="color: #408080; font-style: italic"># we obtain a prediction by taking the class with the highest likelihood</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">predict</span>(X):
|
|
probabilities <span style="color: #666666">=</span> feed_forward(X)
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>argmax(probabilities, axis<span style="color: #666666">=1</span>)
|
|
|
|
predictions <span style="color: #666666">=</span> predict(X_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"predictions = (n_inputs) = "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(predictions<span style="color: #666666">.</span>shape))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"prediction for image 0: "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(predictions[<span style="color: #666666">0</span>]))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"correct label for image 0: "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(Y_train[<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="choose-cost-function-and-optimizer">Choose cost function and optimizer </h2>
|
|
|
|
<p>To measure how well our neural network is doing we need to introduce a cost function.
|
|
We will call the function that gives the error of a single sample output the <em>loss</em> function, and the function
|
|
that gives the total error of our network across all samples the <em>cost</em> function.
|
|
A typical choice for multiclass classification is the <em>cross-entropy</em> loss, also known as the negative log likelihood.
|
|
</p>
|
|
|
|
<p>In <em>multiclass</em> classification it is common to treat each integer label as a so called <em>one-hot</em> vector: </p>
|
|
|
|
<p>$$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ </p>
|
|
|
|
<p>$$ y = 1 \quad \rightarrow \quad \boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ </p>
|
|
|
|
<p>i.e. a binary bit string of length \( C \), where \( C = 10 \) is the number of classes in the MNIST dataset. </p>
|
|
|
|
<p>Let \( y_{ic} \) denote the \( c \)-th component of the \( i \)-th one-hot vector.
|
|
We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset.
|
|
</p>
|
|
|
|
<p>In the one-hot representation only one of the terms in the loss function is non-zero, namely the
|
|
probability of the correct category \( c' \)
|
|
(i.e. the category \( c' \) such that \( y_{ic'} = 1 \)). This means that the cross entropy loss only punishes you for how wrong
|
|
you got the correct label. The probability of category \( c \) is given by the softmax function. The vector \( \boldsymbol{\theta} \) represents the parameters of our network, i.e. all the weights and biases.
|
|
</p>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="optimizing-the-cost-function">Optimizing the cost function </h2>
|
|
|
|
<p>The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is <em>gradient descent</em> and its generalizations. The idea behind gradient descent
|
|
is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a <em>local</em> minimum of the cost function.
|
|
Each parameter \( \theta \) is iteratively adjusted according to the rule
|
|
</p>
|
|
|
|
<p>$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$</p>
|
|
|
|
<p>where \( \eta \) is known as the <em>learning rate</em>, which controls how big a step we take towards the minimum.
|
|
This update can be repeated for any number of iterations, or until we are satisfied with the result.
|
|
</p>
|
|
|
|
<p>A simple and effective improvement is a variant called <em>Batch Gradient Descent</em>.
|
|
Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient
|
|
on a subset of the data called a <em>minibatch</em>.
|
|
If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches
|
|
is \( N/M \).
|
|
We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes:
|
|
</p>
|
|
|
|
<p>$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad
|
|
\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$
|
|
</p>
|
|
|
|
<p>i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. </p>
|
|
|
|
<p>This has two important benefits: </p>
|
|
<ol>
|
|
<li> Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.</li>
|
|
<li> It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.</li>
|
|
</ol>
|
|
<p>The various optmization methods, with codes and algorithms, are discussed in our lectures on <a href="https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html" target="_blank">Gradient descent approaches</a>.</p>
|
|
|
|
<!-- !split -->
|
|
<h2 id="regularization">Regularization </h2>
|
|
|
|
<p>It is common to add an extra term to the cost function, proportional
|
|
to the size of the weights. This is equivalent to constraining the
|
|
size of the weights, so that they do not grow out of control.
|
|
Constraining the size of the weights means that the weights cannot
|
|
grow arbitrarily large to fit the training data, and in this way
|
|
reduces <em>overfitting</em>.
|
|
</p>
|
|
|
|
<p>We will measure the size of the weights using the so called <em>L2-norm</em>, meaning our cost function becomes: </p>
|
|
|
|
<p>$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad
|
|
\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2
|
|
= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$
|
|
</p>
|
|
|
|
<p>i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter.</p>
|
|
|
|
<p>In order to train the model, we need to calculate the derivative of
|
|
the cost function with respect to every bias and weight in the
|
|
network. In total our network has \( (64 + 1)\times 50=3250 \) weights in
|
|
the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output
|
|
layer (\( +1 \) for the bias), and the gradient must be calculated for
|
|
every parameter. We use the <em>backpropagation</em> algorithm discussed
|
|
above. This is a clever use of the chain rule that allows us to
|
|
calculate the gradient efficently.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="matrix-multiplication">Matrix multiplication </h2>
|
|
|
|
<p>To more efficently train our network these equations are implemented using matrix operations.
|
|
The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets,
|
|
</p>
|
|
|
|
<p>$$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ </p>
|
|
|
|
<p>The gradient for the output weights is calculated as </p>
|
|
|
|
<p>$$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$</p>
|
|
|
|
<p>where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input.
|
|
Since we are going backwards we have to transpose the activation matrix.
|
|
</p>
|
|
|
|
<p>The gradient with respect to the output bias is then </p>
|
|
|
|
<p>$$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ </p>
|
|
|
|
<p>The error in the hidden layer is </p>
|
|
|
|
<p>$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ </p>
|
|
|
|
<p>where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean
|
|
that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes
|
|
the <em>Hadamard product</em>, meaning element-wise multiplication.
|
|
</p>
|
|
|
|
<p>This again gives us the gradients in the hidden layer: </p>
|
|
|
|
<p>$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ </p>
|
|
|
|
<p>$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$</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"># to categorical turns our integer vector into a onehot representation</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
|
|
|
|
<span style="color: #408080; font-style: italic"># one-hot in numpy</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">to_categorical_numpy</span>(integer_vector):
|
|
n_inputs <span style="color: #666666">=</span> <span style="color: #008000">len</span>(integer_vector)
|
|
n_categories <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(integer_vector) <span style="color: #666666">+</span> <span style="color: #666666">1</span>
|
|
onehot_vector <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n_inputs, n_categories))
|
|
onehot_vector[<span style="color: #008000">range</span>(n_inputs), integer_vector] <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> onehot_vector
|
|
|
|
<span style="color: #408080; font-style: italic">#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)</span>
|
|
Y_train_onehot, Y_test_onehot <span style="color: #666666">=</span> to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">feed_forward_train</span>(X):
|
|
<span style="color: #408080; font-style: italic"># weighted sum of inputs to the hidden layer</span>
|
|
z_h <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(X, hidden_weights) <span style="color: #666666">+</span> hidden_bias
|
|
<span style="color: #408080; font-style: italic"># activation in the hidden layer</span>
|
|
a_h <span style="color: #666666">=</span> sigmoid(z_h)
|
|
|
|
<span style="color: #408080; font-style: italic"># weighted sum of inputs to the output layer</span>
|
|
z_o <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(a_h, output_weights) <span style="color: #666666">+</span> output_bias
|
|
<span style="color: #408080; font-style: italic"># softmax output</span>
|
|
<span style="color: #408080; font-style: italic"># axis 0 holds each input and axis 1 the probabilities of each category</span>
|
|
exp_term <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(z_o)
|
|
probabilities <span style="color: #666666">=</span> exp_term <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum(exp_term, 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: #408080; font-style: italic"># for backpropagation need activations in hidden and output layers</span>
|
|
<span style="color: #008000; font-weight: bold">return</span> a_h, probabilities
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">backpropagation</span>(X, Y):
|
|
a_h, probabilities <span style="color: #666666">=</span> feed_forward_train(X)
|
|
|
|
<span style="color: #408080; font-style: italic"># error in the output layer</span>
|
|
error_output <span style="color: #666666">=</span> probabilities <span style="color: #666666">-</span> Y
|
|
<span style="color: #408080; font-style: italic"># error in the hidden layer</span>
|
|
error_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(error_output, output_weights<span style="color: #666666">.</span>T) <span style="color: #666666">*</span> a_h <span style="color: #666666">*</span> (<span style="color: #666666">1</span> <span style="color: #666666">-</span> a_h)
|
|
|
|
<span style="color: #408080; font-style: italic"># gradients for the output layer</span>
|
|
output_weights_gradient <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(a_h<span style="color: #666666">.</span>T, error_output)
|
|
output_bias_gradient <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(error_output, axis<span style="color: #666666">=0</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># gradient for the hidden layer</span>
|
|
hidden_weights_gradient <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(X<span style="color: #666666">.</span>T, error_hidden)
|
|
hidden_bias_gradient <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(error_hidden, axis<span style="color: #666666">=0</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Old accuracy on training data: "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(accuracy_score(predict(X_train), Y_train)))
|
|
|
|
eta <span style="color: #666666">=</span> <span style="color: #666666">0.01</span>
|
|
lmbd <span style="color: #666666">=</span> <span style="color: #666666">0.01</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">1000</span>):
|
|
<span style="color: #408080; font-style: italic"># calculate gradients</span>
|
|
dWo, dBo, dWh, dBh <span style="color: #666666">=</span> backpropagation(X_train, Y_train_onehot)
|
|
|
|
<span style="color: #408080; font-style: italic"># regularization term gradients</span>
|
|
dWo <span style="color: #666666">+=</span> lmbd <span style="color: #666666">*</span> output_weights
|
|
dWh <span style="color: #666666">+=</span> lmbd <span style="color: #666666">*</span> hidden_weights
|
|
|
|
<span style="color: #408080; font-style: italic"># update weights and biases</span>
|
|
output_weights <span style="color: #666666">-=</span> eta <span style="color: #666666">*</span> dWo
|
|
output_bias <span style="color: #666666">-=</span> eta <span style="color: #666666">*</span> dBo
|
|
hidden_weights <span style="color: #666666">-=</span> eta <span style="color: #666666">*</span> dWh
|
|
hidden_bias <span style="color: #666666">-=</span> eta <span style="color: #666666">*</span> dBh
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"New accuracy on training data: "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(accuracy_score(predict(X_train), Y_train)))
|
|
</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="improving-performance">Improving performance </h2>
|
|
|
|
<p>As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image.
|
|
In order to obtain a network that does something useful, we will have to do a bit more work.
|
|
</p>
|
|
|
|
<p>The choice of <em>hyperparameters</em> such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a <em>grid-search</em> is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \). </p>
|
|
|
|
<p>Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an <em>iteration</em>, and a full training period
|
|
going through the entire dataset (\( n/M \) batches) an <em>epoch</em>.
|
|
</p>
|
|
|
|
<p>If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers.
|
|
Andrew Ng goes through some of these considerations in this <a href="https://youtu.be/F1ka6a13S9I" target="_blank">video</a>. You can find a summary of the video <a href="https://kevinzakka.github.io/2016/09/26/applying-deep-learning/" target="_blank">here</a>.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="full-object-oriented-implementation">Full object-oriented implementation </h2>
|
|
|
|
<p>It is very natural to think of the network as an object, with specific instances of the network
|
|
being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below.
|
|
</p>
|
|
|
|
|
|
<!-- 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">class</span> <span style="color: #0000FF; font-weight: bold">NeuralNetwork</span>:
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(
|
|
<span style="color: #008000">self</span>,
|
|
X_data,
|
|
Y_data,
|
|
n_hidden_neurons<span style="color: #666666">=50</span>,
|
|
n_categories<span style="color: #666666">=10</span>,
|
|
epochs<span style="color: #666666">=10</span>,
|
|
batch_size<span style="color: #666666">=100</span>,
|
|
eta<span style="color: #666666">=0.1</span>,
|
|
lmbd<span style="color: #666666">=0.0</span>):
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>X_data_full <span style="color: #666666">=</span> X_data
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>Y_data_full <span style="color: #666666">=</span> Y_data
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>n_inputs <span style="color: #666666">=</span> X_data<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>]
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>n_features <span style="color: #666666">=</span> X_data<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>n_hidden_neurons <span style="color: #666666">=</span> n_hidden_neurons
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>n_categories <span style="color: #666666">=</span> n_categories
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>epochs <span style="color: #666666">=</span> epochs
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>batch_size <span style="color: #666666">=</span> batch_size
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>iterations <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>n_inputs <span style="color: #666666">//</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>batch_size
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">=</span> eta
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>lmbd <span style="color: #666666">=</span> lmbd
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>create_biases_and_weights()
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">create_biases_and_weights</span>(<span style="color: #008000">self</span>):
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_weights <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>n_features, <span style="color: #008000">self</span><span style="color: #666666">.</span>n_hidden_neurons)
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(<span style="color: #008000">self</span><span style="color: #666666">.</span>n_hidden_neurons) <span style="color: #666666">+</span> <span style="color: #666666">0.01</span>
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>output_weights <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>n_hidden_neurons, <span style="color: #008000">self</span><span style="color: #666666">.</span>n_categories)
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>output_bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(<span style="color: #008000">self</span><span style="color: #666666">.</span>n_categories) <span style="color: #666666">+</span> <span style="color: #666666">0.01</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">feed_forward</span>(<span style="color: #008000">self</span>):
|
|
<span style="color: #408080; font-style: italic"># feed-forward for training</span>
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>z_h <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(<span style="color: #008000">self</span><span style="color: #666666">.</span>X_data, <span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_weights) <span style="color: #666666">+</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_bias
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>a_h <span style="color: #666666">=</span> sigmoid(<span style="color: #008000">self</span><span style="color: #666666">.</span>z_h)
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>z_o <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(<span style="color: #008000">self</span><span style="color: #666666">.</span>a_h, <span style="color: #008000">self</span><span style="color: #666666">.</span>output_weights) <span style="color: #666666">+</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>output_bias
|
|
|
|
exp_term <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(<span style="color: #008000">self</span><span style="color: #666666">.</span>z_o)
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>probabilities <span style="color: #666666">=</span> exp_term <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum(exp_term, 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: #008000; font-weight: bold">def</span> <span style="color: #0000FF">feed_forward_out</span>(<span style="color: #008000">self</span>, X):
|
|
<span style="color: #408080; font-style: italic"># feed-forward for output</span>
|
|
z_h <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(X, <span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_weights) <span style="color: #666666">+</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_bias
|
|
a_h <span style="color: #666666">=</span> sigmoid(z_h)
|
|
|
|
z_o <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(a_h, <span style="color: #008000">self</span><span style="color: #666666">.</span>output_weights) <span style="color: #666666">+</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>output_bias
|
|
|
|
exp_term <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(z_o)
|
|
probabilities <span style="color: #666666">=</span> exp_term <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum(exp_term, 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: #008000; font-weight: bold">return</span> probabilities
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">backpropagation</span>(<span style="color: #008000">self</span>):
|
|
error_output <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>probabilities <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>Y_data
|
|
error_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(error_output, <span style="color: #008000">self</span><span style="color: #666666">.</span>output_weights<span style="color: #666666">.</span>T) <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>a_h <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>a_h)
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>output_weights_gradient <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(<span style="color: #008000">self</span><span style="color: #666666">.</span>a_h<span style="color: #666666">.</span>T, error_output)
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>output_bias_gradient <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(error_output, axis<span style="color: #666666">=0</span>)
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_weights_gradient <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(<span style="color: #008000">self</span><span style="color: #666666">.</span>X_data<span style="color: #666666">.</span>T, error_hidden)
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_bias_gradient <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(error_hidden, axis<span style="color: #666666">=0</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>lmbd <span style="color: #666666">></span> <span style="color: #666666">0.0</span>:
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>output_weights_gradient <span style="color: #666666">+=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>lmbd <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>output_weights
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_weights_gradient <span style="color: #666666">+=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>lmbd <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_weights
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>output_weights <span style="color: #666666">-=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>output_weights_gradient
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>output_bias <span style="color: #666666">-=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>output_bias_gradient
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_weights <span style="color: #666666">-=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_weights_gradient
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_bias <span style="color: #666666">-=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>eta <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>hidden_bias_gradient
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">predict</span>(<span style="color: #008000">self</span>, X):
|
|
probabilities <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>feed_forward_out(X)
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>argmax(probabilities, axis<span style="color: #666666">=1</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">predict_probabilities</span>(<span style="color: #008000">self</span>, X):
|
|
probabilities <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>feed_forward_out(X)
|
|
<span style="color: #008000; font-weight: bold">return</span> probabilities
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">train</span>(<span style="color: #008000">self</span>):
|
|
data_indices <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #008000">self</span><span style="color: #666666">.</span>n_inputs)
|
|
|
|
<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">self</span><span style="color: #666666">.</span>epochs):
|
|
<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">self</span><span style="color: #666666">.</span>iterations):
|
|
<span style="color: #408080; font-style: italic"># pick datapoints with replacement</span>
|
|
chosen_datapoints <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>choice(
|
|
data_indices, size<span style="color: #666666">=</span><span style="color: #008000">self</span><span style="color: #666666">.</span>batch_size, replace<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>
|
|
)
|
|
|
|
<span style="color: #408080; font-style: italic"># minibatch training data</span>
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>X_data <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>X_data_full[chosen_datapoints]
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>Y_data <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>Y_data_full[chosen_datapoints]
|
|
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>feed_forward()
|
|
<span style="color: #008000">self</span><span style="color: #666666">.</span>backpropagation()
|
|
</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="evaluate-model-performance-on-test-data">Evaluate model performance on test data </h2>
|
|
|
|
<p>To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data.
|
|
We measure the performance of the network using the <em>accuracy</em> score.
|
|
The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of \( 1 \).
|
|
</p>
|
|
|
|
<p>$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ </p>
|
|
|
|
<p>where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.</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%;">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>
|
|
|
|
dnn <span style="color: #666666">=</span> NeuralNetwork(X_train, Y_train_onehot, eta<span style="color: #666666">=</span>eta, lmbd<span style="color: #666666">=</span>lmbd, epochs<span style="color: #666666">=</span>epochs, batch_size<span style="color: #666666">=</span>batch_size,
|
|
n_hidden_neurons<span style="color: #666666">=</span>n_hidden_neurons, n_categories<span style="color: #666666">=</span>n_categories)
|
|
dnn<span style="color: #666666">.</span>train()
|
|
test_predict <span style="color: #666666">=</span> dnn<span style="color: #666666">.</span>predict(X_test)
|
|
|
|
<span style="color: #408080; font-style: italic"># accuracy score from scikit library</span>
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Accuracy score on test set: "</span>, accuracy_score(Y_test, test_predict))
|
|
|
|
<span style="color: #408080; font-style: italic"># equivalent in numpy</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">accuracy_score_numpy</span>(Y_test, Y_pred):
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum(Y_test <span style="color: #666666">==</span> Y_pred) <span style="color: #666666">/</span> <span style="color: #008000">len</span>(Y_test)
|
|
|
|
<span style="color: #408080; font-style: italic">#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))</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="adjust-hyperparameters">Adjust hyperparameters </h2>
|
|
|
|
<p>We now perform a grid search to find the optimal hyperparameters for the network.
|
|
Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate).
|
|
</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%;">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: #408080; font-style: italic"># store the models for later use</span>
|
|
DNN_numpy <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: #408080; font-style: italic"># grid search</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> NeuralNetwork(X_train, Y_train_onehot, eta<span style="color: #666666">=</span>eta, lmbd<span style="color: #666666">=</span>lmbd, epochs<span style="color: #666666">=</span>epochs, batch_size<span style="color: #666666">=</span>batch_size,
|
|
n_hidden_neurons<span style="color: #666666">=</span>n_hidden_neurons, n_categories<span style="color: #666666">=</span>n_categories)
|
|
dnn<span style="color: #666666">.</span>train()
|
|
|
|
DNN_numpy[i][j] <span style="color: #666666">=</span> dnn
|
|
|
|
test_predict <span style="color: #666666">=</span> dnn<span style="color: #666666">.</span>predict(X_test)
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Learning rate = "</span>, eta)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Lambda = "</span>, lmbd)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Accuracy score on test set: "</span>, accuracy_score(Y_test, test_predict))
|
|
<span style="color: #008000">print</span>()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="visualization">Visualization </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># visual representation of grid search</span>
|
|
<span style="color: #408080; font-style: italic"># uses seaborn heatmap, you can also do this with matplotlib imshow</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_numpy[i][j]
|
|
|
|
train_pred <span style="color: #666666">=</span> dnn<span style="color: #666666">.</span>predict(X_train)
|
|
test_pred <span style="color: #666666">=</span> dnn<span style="color: #666666">.</span>predict(X_test)
|
|
|
|
train_accuracy[i][j] <span style="color: #666666">=</span> accuracy_score(Y_train, train_pred)
|
|
test_accuracy[i][j] <span style="color: #666666">=</span> accuracy_score(Y_test, test_pred)
|
|
|
|
|
|
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">"viridis"</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">"Training Accuracy"</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"$\eta$"</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"$\lambda$"</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">"viridis"</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">"Test Accuracy"</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"$\eta$"</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"$\lambda$"</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="scikit-learn-implementation">scikit-learn implementation </h2>
|
|
|
|
<p><b>scikit-learn</b> focuses more
|
|
on traditional machine learning methods, such as regression,
|
|
clustering, decision trees, etc. As such, it has only two types of
|
|
neural networks: Multi Layer Perceptron outputting continuous values,
|
|
<em>MPLRegressor</em>, and Multi Layer Perceptron outputting labels,
|
|
<em>MLPClassifier</em>. We will see how simple it is to use these classes.
|
|
</p>
|
|
|
|
<p><b>scikit-learn</b> implements a few improvements from our neural network,
|
|
such as early stopping, a varying learning rate, different
|
|
optimization methods, etc. We would therefore expect a better
|
|
performance overall.
|
|
</p>
|
|
|
|
|
|
<!-- 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.neural_network</span> <span style="color: #008000; font-weight: bold">import</span> MLPClassifier
|
|
<span style="color: #408080; font-style: italic"># store models for later use</span>
|
|
DNN_scikit <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> MLPClassifier(hidden_layer_sizes<span style="color: #666666">=</span>(n_hidden_neurons), activation<span style="color: #666666">=</span><span style="color: #BA2121">'logistic'</span>,
|
|
alpha<span style="color: #666666">=</span>lmbd, learning_rate_init<span style="color: #666666">=</span>eta, max_iter<span style="color: #666666">=</span>epochs)
|
|
dnn<span style="color: #666666">.</span>fit(X_train, Y_train)
|
|
|
|
DNN_scikit[i][j] <span style="color: #666666">=</span> dnn
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Learning rate = "</span>, eta)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Lambda = "</span>, lmbd)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Accuracy score on test set: "</span>, dnn<span style="color: #666666">.</span>score(X_test, Y_test))
|
|
<span style="color: #008000">print</span>()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="visualization">Visualization </h2>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># 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_scikit[i][j]
|
|
|
|
train_pred <span style="color: #666666">=</span> dnn<span style="color: #666666">.</span>predict(X_train)
|
|
test_pred <span style="color: #666666">=</span> dnn<span style="color: #666666">.</span>predict(X_test)
|
|
|
|
train_accuracy[i][j] <span style="color: #666666">=</span> accuracy_score(Y_train, train_pred)
|
|
test_accuracy[i][j] <span style="color: #666666">=</span> accuracy_score(Y_test, test_pred)
|
|
|
|
|
|
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">"viridis"</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">"Training Accuracy"</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"$\eta$"</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"$\lambda$"</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">"viridis"</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">"Test Accuracy"</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"$\eta$"</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"$\lambda$"</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="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 our examples.. </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">'figure.figsize'</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">"inputs = (n_inputs, pixel_width, pixel_height) = "</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">"labels = (n_inputs) = "</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">"X = (n_inputs, n_features) = "</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">'off'</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">'nearest'</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Label: </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121">"</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">'sigmoid'</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">'sigmoid'</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">'softmax'</span>))
|
|
|
|
sgd <span style="color: #666666">=</span> optimizers<span style="color: #666666">.</span>SGD(lr<span style="color: #666666">=</span>eta)
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">'categorical_crossentropy'</span>, optimizer<span style="color: #666666">=</span>sgd, metrics<span style="color: #666666">=</span>[<span style="color: #BA2121">'accuracy'</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">"Learning rate = "</span>, eta)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Lambda = "</span>, lmbd)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test accuracy: </span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121">"</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">"viridis"</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">"Training Accuracy"</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"$\eta$"</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"$\lambda$"</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">"viridis"</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">"Test Accuracy"</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"$\eta$"</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"$\lambda$"</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-breast-cancer-data-now-with-keras">The Breast Cancer Data, now 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.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">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">seaborn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">sns</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">as</span> splitter
|
|
<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">import</span> <span style="color: #0000FF; font-weight: bold">pickle</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
|
|
|
|
|
|
<span style="color: #BA2121; font-style: italic">"""Load breast cancer dataset"""</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">#create same seed for random number every time</span>
|
|
|
|
cancer<span style="color: #666666">=</span>load_breast_cancer() <span style="color: #408080; font-style: italic">#Download breast cancer dataset</span>
|
|
|
|
inputs<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>data <span style="color: #408080; font-style: italic">#Feature matrix of 569 rows (samples) and 30 columns (parameters)</span>
|
|
outputs<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>target <span style="color: #408080; font-style: italic">#Label array of 569 rows (0 for benign and 1 for malignant)</span>
|
|
labels<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>feature_names[<span style="color: #666666">0</span>:<span style="color: #666666">30</span>]
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'The content of the breast cancer dataset is:'</span>) <span style="color: #408080; font-style: italic">#Print information about the datasets</span>
|
|
<span style="color: #008000">print</span>(labels)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'-------------------------'</span>)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"inputs = "</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">"outputs = "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(outputs<span style="color: #666666">.</span>shape))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"labels = "</span><span style="color: #666666">+</span> <span style="color: #008000">str</span>(labels<span style="color: #666666">.</span>shape))
|
|
|
|
x<span style="color: #666666">=</span>inputs <span style="color: #408080; font-style: italic">#Reassign the Feature and Label matrices to other variables</span>
|
|
y<span style="color: #666666">=</span>outputs
|
|
|
|
<span style="color: #408080; font-style: italic">#%% </span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Visualisation of dataset (for correlation analysis)</span>
|
|
|
|
plt<span style="color: #666666">.</span>figure()
|
|
plt<span style="color: #666666">.</span>scatter(x[:,<span style="color: #666666">0</span>],x[:,<span style="color: #666666">2</span>],s<span style="color: #666666">=40</span>,c<span style="color: #666666">=</span>y,cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>Spectral)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'Mean radius'</span>,fontweight<span style="color: #666666">=</span><span style="color: #BA2121">'bold'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'Mean perimeter'</span>,fontweight<span style="color: #666666">=</span><span style="color: #BA2121">'bold'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
plt<span style="color: #666666">.</span>figure()
|
|
plt<span style="color: #666666">.</span>scatter(x[:,<span style="color: #666666">5</span>],x[:,<span style="color: #666666">6</span>],s<span style="color: #666666">=40</span>,c<span style="color: #666666">=</span>y, cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>Spectral)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'Mean compactness'</span>,fontweight<span style="color: #666666">=</span><span style="color: #BA2121">'bold'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'Mean concavity'</span>,fontweight<span style="color: #666666">=</span><span style="color: #BA2121">'bold'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
|
|
plt<span style="color: #666666">.</span>figure()
|
|
plt<span style="color: #666666">.</span>scatter(x[:,<span style="color: #666666">0</span>],x[:,<span style="color: #666666">1</span>],s<span style="color: #666666">=40</span>,c<span style="color: #666666">=</span>y,cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>Spectral)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'Mean radius'</span>,fontweight<span style="color: #666666">=</span><span style="color: #BA2121">'bold'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'Mean texture'</span>,fontweight<span style="color: #666666">=</span><span style="color: #BA2121">'bold'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
plt<span style="color: #666666">.</span>figure()
|
|
plt<span style="color: #666666">.</span>scatter(x[:,<span style="color: #666666">2</span>],x[:,<span style="color: #666666">1</span>],s<span style="color: #666666">=40</span>,c<span style="color: #666666">=</span>y,cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>Spectral)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'Mean perimeter'</span>,fontweight<span style="color: #666666">=</span><span style="color: #BA2121">'bold'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'Mean compactness'</span>,fontweight<span style="color: #666666">=</span><span style="color: #BA2121">'bold'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Generate training and testing datasets</span>
|
|
|
|
<span style="color: #408080; font-style: italic">#Select features relevant to classification (texture,perimeter,compactness and symmetery) </span>
|
|
<span style="color: #408080; font-style: italic">#and add to input matrix</span>
|
|
|
|
temp1<span style="color: #666666">=</span>np<span style="color: #666666">.</span>reshape(x[:,<span style="color: #666666">1</span>],(<span style="color: #008000">len</span>(x[:,<span style="color: #666666">1</span>]),<span style="color: #666666">1</span>))
|
|
temp2<span style="color: #666666">=</span>np<span style="color: #666666">.</span>reshape(x[:,<span style="color: #666666">2</span>],(<span style="color: #008000">len</span>(x[:,<span style="color: #666666">2</span>]),<span style="color: #666666">1</span>))
|
|
X<span style="color: #666666">=</span>np<span style="color: #666666">.</span>hstack((temp1,temp2))
|
|
temp<span style="color: #666666">=</span>np<span style="color: #666666">.</span>reshape(x[:,<span style="color: #666666">5</span>],(<span style="color: #008000">len</span>(x[:,<span style="color: #666666">5</span>]),<span style="color: #666666">1</span>))
|
|
X<span style="color: #666666">=</span>np<span style="color: #666666">.</span>hstack((X,temp))
|
|
temp<span style="color: #666666">=</span>np<span style="color: #666666">.</span>reshape(x[:,<span style="color: #666666">8</span>],(<span style="color: #008000">len</span>(x[:,<span style="color: #666666">8</span>]),<span style="color: #666666">1</span>))
|
|
X<span style="color: #666666">=</span>np<span style="color: #666666">.</span>hstack((X,temp))
|
|
|
|
X_train,X_test,y_train,y_test<span style="color: #666666">=</span>splitter(X,y,test_size<span style="color: #666666">=0.1</span>) <span style="color: #408080; font-style: italic">#Split datasets into training and testing</span>
|
|
|
|
y_train<span style="color: #666666">=</span>to_categorical(y_train) <span style="color: #408080; font-style: italic">#Convert labels to categorical when using categorical cross entropy</span>
|
|
y_test<span style="color: #666666">=</span>to_categorical(y_test)
|
|
|
|
<span style="color: #008000; font-weight: bold">del</span> temp1,temp2,temp
|
|
|
|
<span style="color: #408080; font-style: italic"># %%</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Define tunable parameters"</span>
|
|
|
|
eta<span style="color: #666666">=</span>np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-3</span>,<span style="color: #666666">-1</span>,<span style="color: #666666">3</span>) <span style="color: #408080; font-style: italic">#Define vector of learning rates (parameter to SGD optimiser)</span>
|
|
lamda<span style="color: #666666">=0.01</span> <span style="color: #408080; font-style: italic">#Define hyperparameter</span>
|
|
n_layers<span style="color: #666666">=2</span> <span style="color: #408080; font-style: italic">#Define number of hidden layers in the model</span>
|
|
n_neuron<span style="color: #666666">=</span>np<span style="color: #666666">.</span>logspace(<span style="color: #666666">0</span>,<span style="color: #666666">3</span>,<span style="color: #666666">4</span>,dtype<span style="color: #666666">=</span><span style="color: #008000">int</span>) <span style="color: #408080; font-style: italic">#Define number of neurons per layer</span>
|
|
epochs<span style="color: #666666">=100</span> <span style="color: #408080; font-style: italic">#Number of reiterations over the input data</span>
|
|
batch_size<span style="color: #666666">=100</span> <span style="color: #408080; font-style: italic">#Number of samples per gradient update</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># %%</span>
|
|
|
|
<span style="color: #BA2121; font-style: italic">"""Define function to return Deep Neural Network model"""</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">NN_model</span>(inputsize,n_layers,n_neuron,eta,lamda):
|
|
model<span style="color: #666666">=</span>Sequential()
|
|
<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>(n_layers): <span style="color: #408080; font-style: italic">#Run loop to add hidden layers to the model</span>
|
|
<span style="color: #008000; font-weight: bold">if</span> (i<span style="color: #666666">==0</span>): <span style="color: #408080; font-style: italic">#First layer requires input dimensions</span>
|
|
model<span style="color: #666666">.</span>add(Dense(n_neuron,activation<span style="color: #666666">=</span><span style="color: #BA2121">'relu'</span>,kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lamda),input_dim<span style="color: #666666">=</span>inputsize))
|
|
<span style="color: #008000; font-weight: bold">else</span>: <span style="color: #408080; font-style: italic">#Subsequent layers are capable of automatic shape inferencing</span>
|
|
model<span style="color: #666666">.</span>add(Dense(n_neuron,activation<span style="color: #666666">=</span><span style="color: #BA2121">'relu'</span>,kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lamda)))
|
|
model<span style="color: #666666">.</span>add(Dense(<span style="color: #666666">2</span>,activation<span style="color: #666666">=</span><span style="color: #BA2121">'softmax'</span>)) <span style="color: #408080; font-style: italic">#2 outputs - ordered and disordered (softmax for prob)</span>
|
|
sgd<span style="color: #666666">=</span>optimizers<span style="color: #666666">.</span>SGD(lr<span style="color: #666666">=</span>eta)
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">'categorical_crossentropy'</span>,optimizer<span style="color: #666666">=</span>sgd,metrics<span style="color: #666666">=</span>[<span style="color: #BA2121">'accuracy'</span>])
|
|
<span style="color: #008000; font-weight: bold">return</span> model
|
|
|
|
|
|
Train_accuracy<span style="color: #666666">=</span>np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(n_neuron),<span style="color: #008000">len</span>(eta))) <span style="color: #408080; font-style: italic">#Define matrices to store accuracy scores as a function</span>
|
|
Test_accuracy<span style="color: #666666">=</span>np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(n_neuron),<span style="color: #008000">len</span>(eta))) <span style="color: #408080; font-style: italic">#of learning rate and number of hidden neurons for </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>(n_neuron)): <span style="color: #408080; font-style: italic">#run loops over hidden neurons and learning rates to calculate </span>
|
|
<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>(eta)): <span style="color: #408080; font-style: italic">#accuracy scores </span>
|
|
DNN_model<span style="color: #666666">=</span>NN_model(X_train<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>],n_layers,n_neuron[i],eta[j],lamda)
|
|
DNN_model<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">=1</span>)
|
|
Train_accuracy[i,j]<span style="color: #666666">=</span>DNN_model<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_model<span style="color: #666666">.</span>evaluate(X_test,y_test)[<span style="color: #666666">1</span>]
|
|
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plot_data</span>(x,y,data,title<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>):
|
|
|
|
<span style="color: #408080; font-style: italic"># plot results</span>
|
|
fontsize<span style="color: #666666">=16</span>
|
|
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot(<span style="color: #666666">111</span>)
|
|
cax <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>matshow(data, interpolation<span style="color: #666666">=</span><span style="color: #BA2121">'nearest'</span>, vmin<span style="color: #666666">=0</span>, vmax<span style="color: #666666">=1</span>)
|
|
|
|
cbar<span style="color: #666666">=</span>fig<span style="color: #666666">.</span>colorbar(cax)
|
|
cbar<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'accuracy (%)'</span>,rotation<span style="color: #666666">=90</span>,fontsize<span style="color: #666666">=</span>fontsize)
|
|
cbar<span style="color: #666666">.</span>set_ticks([<span style="color: #666666">0</span>,<span style="color: #666666">.2</span>,<span style="color: #666666">.4</span>,<span style="color: #666666">0.6</span>,<span style="color: #666666">0.8</span>,<span style="color: #666666">1.0</span>])
|
|
cbar<span style="color: #666666">.</span>set_ticklabels([<span style="color: #BA2121">'0%'</span>,<span style="color: #BA2121">'20%'</span>,<span style="color: #BA2121">'40%'</span>,<span style="color: #BA2121">'60%'</span>,<span style="color: #BA2121">'80%'</span>,<span style="color: #BA2121">'100%'</span>])
|
|
|
|
<span style="color: #408080; font-style: italic"># put text on matrix elements</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> i, x_val <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(np<span style="color: #666666">.</span>arange(<span style="color: #008000">len</span>(x))):
|
|
<span style="color: #008000; font-weight: bold">for</span> j, y_val <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(np<span style="color: #666666">.</span>arange(<span style="color: #008000">len</span>(y))):
|
|
c <span style="color: #666666">=</span> <span style="color: #BA2121">"$</span><span style="color: #BB6688; font-weight: bold">{0:.1f}</span><span style="color: #BB6622; font-weight: bold">\\</span><span style="color: #BA2121">%$"</span><span style="color: #666666">.</span>format( <span style="color: #666666">100*</span>data[j,i])
|
|
ax<span style="color: #666666">.</span>text(x_val, y_val, c, va<span style="color: #666666">=</span><span style="color: #BA2121">'center'</span>, ha<span style="color: #666666">=</span><span style="color: #BA2121">'center'</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># convert axis vaues to to string labels</span>
|
|
x<span style="color: #666666">=</span>[<span style="color: #008000">str</span>(i) <span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> x]
|
|
y<span style="color: #666666">=</span>[<span style="color: #008000">str</span>(i) <span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> y]
|
|
|
|
|
|
ax<span style="color: #666666">.</span>set_xticklabels([<span style="color: #BA2121">''</span>]<span style="color: #666666">+</span>x)
|
|
ax<span style="color: #666666">.</span>set_yticklabels([<span style="color: #BA2121">''</span>]<span style="color: #666666">+</span>y)
|
|
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'$</span><span style="color: #BB6622; font-weight: bold">\\</span><span style="color: #BA2121">mathrm{learning</span><span style="color: #BB6622; font-weight: bold">\\</span><span style="color: #BA2121"> rate}$'</span>,fontsize<span style="color: #666666">=</span>fontsize)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'$</span><span style="color: #BB6622; font-weight: bold">\\</span><span style="color: #BA2121">mathrm{hidden</span><span style="color: #BB6622; font-weight: bold">\\</span><span style="color: #BA2121"> neurons}$'</span>,fontsize<span style="color: #666666">=</span>fontsize)
|
|
<span style="color: #008000; font-weight: bold">if</span> title <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>:
|
|
ax<span style="color: #666666">.</span>set_title(title)
|
|
|
|
plt<span style="color: #666666">.</span>tight_layout()
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
plot_data(eta,n_neuron,Train_accuracy, <span style="color: #BA2121">'training'</span>)
|
|
plot_data(eta,n_neuron,Test_accuracy, <span style="color: #BA2121">'testing'</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="fine-tuning-neural-network-hyperparameters">Fine-tuning neural network hyperparameters </h2>
|
|
|
|
<p>The flexibility of neural networks is also one of their main
|
|
drawbacks: there are many hyperparameters to tweak. Not only can you
|
|
use any imaginable network topology (how neurons/nodes are interconnected),
|
|
but even in a simple FFNN you can change the number of layers, the
|
|
number of neurons per layer, the type of activation function to use in
|
|
each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you
|
|
know what combination of hyperparameters is the best for your task?
|
|
</p>
|
|
|
|
<ul>
|
|
<li> You can use grid search with cross-validation to find the right hyperparameters.</li>
|
|
</ul>
|
|
<p>However,since there are many hyperparameters to tune, and since
|
|
training a neural network on a large dataset takes a lot of time, you
|
|
will only be able to explore a tiny part of the hyperparameter space.
|
|
</p>
|
|
|
|
<ul>
|
|
<li> You can use randomized search.</li>
|
|
<li> Or use tools like <a href="http://oscar.calldesk.ai/" target="_blank">Oscar</a>, which implements more complex algorithms to help you find a good set of hyperparameters quickly.</li>
|
|
</ul>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="hidden-layers">Hidden layers </h2>
|
|
|
|
<p>For many problems you can start with just one or two hidden layers and it will work just fine.
|
|
For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a
|
|
few hundred neurons.
|
|
You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of
|
|
neurons, in roughly the same amount of training time.
|
|
</p>
|
|
|
|
<p>For more complex problems, you can gradually
|
|
ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such
|
|
as large image classification or speech recognition, typically require networks with dozens of layers
|
|
and they need a huge amount
|
|
of training data. However, you will rarely have to train such networks from scratch: it is much more
|
|
common to reuse parts of a pretrained state-of-the-art network that performs a similar task.
|
|
</p>
|
|
|
|
<!-- !split -->
|
|
<h2 id="which-activation-function-should-i-use">Which activation function should I use? </h2>
|
|
|
|
<p>The Back propagation algorithm we derived above works by going from
|
|
the output layer to the input layer, propagating the error gradient on
|
|
the way. Once the algorithm has computed the gradient of the cost
|
|
function with regards to each parameter in the network, it uses these
|
|
gradients to update each parameter with a Gradient Descent (GD) step.
|
|
</p>
|
|
|
|
<p>Unfortunately for us, the gradients often get smaller and smaller as the
|
|
algorithm progresses down to the first hidden layers. As a result, the
|
|
GD update leaves the lower layer connection weights
|
|
virtually unchanged, and training never converges to a good
|
|
solution. This is known in the literature as
|
|
<b>the vanishing gradients problem</b>.
|
|
</p>
|
|
|
|
<p>In other cases, the opposite can happen, namely the the gradients can grow bigger and
|
|
bigger. The result is that many of the layers get large updates of the
|
|
weights the
|
|
algorithm diverges. This is the <b>exploding gradients problem</b>, which is
|
|
mostly encountered in recurrent neural networks. More generally, deep
|
|
neural networks suffer from unstable gradients, different layers may
|
|
learn at widely different speeds
|
|
</p>
|
|
|
|
<!-- !split -->
|
|
<h2 id="is-the-logistic-activation-function-sigmoid-our-choice">Is the Logistic activation function (Sigmoid) our choice? </h2>
|
|
|
|
<p>Although this unfortunate behavior has been empirically observed for
|
|
quite a while (it was one of the reasons why deep neural networks were
|
|
mostly abandoned for a long time), it is only around 2010 that
|
|
significant progress was made in understanding it.
|
|
</p>
|
|
|
|
<p>A paper titled <a href="http://proceedings.mlr.press/v9/glorot10a.html" target="_blank">Understanding the Difficulty of Training Deep
|
|
Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio</a> found that
|
|
the problems with the popular logistic
|
|
sigmoid activation function and the weight initialization technique
|
|
that was most popular at the time, namely random initialization using
|
|
a normal distribution with a mean of 0 and a standard deviation of
|
|
1.
|
|
</p>
|
|
|
|
<p>They showed that with this activation function and this
|
|
initialization scheme, the variance of the outputs of each layer is
|
|
much greater than the variance of its inputs. Going forward in the
|
|
network, the variance keeps increasing after each layer until the
|
|
activation function saturates at the top layers. This is actually made
|
|
worse by the fact that the logistic function has a mean of 0.5, not 0
|
|
(the hyperbolic tangent function has a mean of 0 and behaves slightly
|
|
better than the logistic function in deep networks).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-derivative-of-the-logistic-funtion">The derivative of the Logistic funtion </h2>
|
|
|
|
<p>Looking at the logistic activation function, when inputs become large
|
|
(negative or positive), the function saturates at 0 or 1, with a
|
|
derivative extremely close to 0. Thus when backpropagation kicks in,
|
|
it has virtually no gradient to propagate back through the network,
|
|
and what little gradient exists keeps getting diluted as
|
|
backpropagation progresses down through the top layers, so there is
|
|
really nothing left for the lower layers.
|
|
</p>
|
|
|
|
<p>In their paper, Glorot and Bengio propose a way to significantly
|
|
alleviate this problem. We need the signal to flow properly in both
|
|
directions: in the forward direction when making predictions, and in
|
|
the reverse direction when backpropagating gradients. We don’t want
|
|
the signal to die out, nor do we want it to explode and saturate. For
|
|
the signal to flow properly, the authors argue that we need the
|
|
variance of the outputs of each layer to be equal to the variance of
|
|
its inputs, and we also need the gradients to have equal variance
|
|
before and after flowing through a layer in the reverse direction.
|
|
</p>
|
|
|
|
<p>One of the insights in the 2010 paper by Glorot and Bengio was that
|
|
the vanishing/exploding gradients problems were in part due to a poor
|
|
choice of activation function. Until then most people had assumed that
|
|
if Nature had chosen to use roughly sigmoid activation functions in
|
|
biological neurons, they must be an excellent choice. But it turns out
|
|
that other activation functions behave much better in deep neural
|
|
networks, in particular the ReLU activation function, mostly because
|
|
it does not saturate for positive values (and also because it is quite
|
|
fast to compute).
|
|
</p>
|
|
|
|
<!-- !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’s neurons are
|
|
dead, especially if you used a large learning rate. During training,
|
|
if a neuron’s weights get updated such that the weighted sum of the
|
|
neuron’s inputs is negative, it will start outputting 0. When this
|
|
happen, the neuron is unlikely to come back to life since the gradient
|
|
of the ReLU function is 0 when its input is negative.
|
|
</p>
|
|
|
|
<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’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="batch-normalization">Batch Normalization </h2>
|
|
|
|
<p>Batch Normalization
|
|
aims to address the vanishing/exploding gradients problems, and more generally the problem that the
|
|
distribution of each layer’s inputs changes during training, as the parameters of the previous layers change.
|
|
</p>
|
|
|
|
<p>The technique consists of adding an operation in the model just before the activation function of each
|
|
layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new
|
|
parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model
|
|
learn the optimal scale and mean of the inputs for each layer.
|
|
In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and
|
|
standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current
|
|
mini-batch, from this the name batch normalization.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="dropout">Dropout </h2>
|
|
|
|
<p>It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but
|
|
excluding the output neurons) has a probability \( p \) of being temporarily dropped out, meaning it will be
|
|
entirely ignored during this training step, but it may be active during the next step.
|
|
</p>
|
|
|
|
<p>The
|
|
hyperparameter \( p \) is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore.
|
|
It is viewed as one of the most popular regularization techniques.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="gradient-clipping">Gradient Clipping </h2>
|
|
|
|
<p>A popular technique to lessen the exploding gradients problem is to simply clip the gradients during
|
|
backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural
|
|
networks).
|
|
</p>
|
|
|
|
<p>This technique is called Gradient Clipping.</p>
|
|
|
|
<p>In general however, Batch
|
|
Normalization is preferred.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="a-very-nice-website-on-neural-networks">A very nice website on Neural Networks </h2>
|
|
|
|
<p>You may find this <a href="https://playground.tensorflow.org/#activation=tanh&batchSize=10&dataset=circle®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=4,2&seed=0.29243&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false" target="_blank">website</a> very useful. </p>
|
|
|
|
<!-- !split -->
|
|
<h2 id="a-top-down-perspective-on-neural-networks">A top-down perspective on Neural networks </h2>
|
|
|
|
<p>The first thing we would like to do is divide the data into two or three
|
|
parts. A training set, a validation or dev (development) set, and a
|
|
test set. The test set is the data on which we want to make
|
|
predictions. The dev set is a subset of the training data we use to
|
|
check how well we are doing out-of-sample, after training the model on
|
|
the training dataset. We use the validation error as a proxy for the
|
|
test error in order to make tweaks to our model. It is crucial that we
|
|
do not use any of the test data to train the algorithm. This is a
|
|
cardinal sin in ML. Then:
|
|
</p>
|
|
|
|
<ul>
|
|
<li> Estimate optimal error rate</li>
|
|
<li> Minimize underfitting (bias) on training data set.</li>
|
|
<li> Make sure you are not overfitting.</li>
|
|
</ul>
|
|
<p>If the validation and test sets are drawn from the same distributions,
|
|
then a good performance on the validation set should lead to similarly
|
|
good performance on the test set.
|
|
</p>
|
|
|
|
<p>However, sometimes
|
|
the training data and test data differ in subtle ways because, for
|
|
example, they are collected using slightly different methods, or
|
|
because it is cheaper to collect data in one way versus another. In
|
|
this case, there can be a mismatch between the training and test
|
|
data. This can lead to the neural network overfitting these small
|
|
differences between the test and training sets, and a poor performance
|
|
on the test set despite having a good performance on the validation
|
|
set. To rectify this, Andrew Ng suggests making two validation or dev
|
|
sets, one constructed from the training data and one constructed from
|
|
the test data. The difference between the performance of the algorithm
|
|
on these two validation sets quantifies the train-test mismatch. This
|
|
can serve as another important diagnostic when using DNNs for
|
|
supervised learning.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="limitations-of-supervised-learning-with-deep-networks">Limitations of supervised learning with deep networks </h2>
|
|
|
|
<p>Like all statistical methods, supervised learning using neural
|
|
networks has important limitations. This is especially important when
|
|
one seeks to apply these methods, especially to physics problems. Like
|
|
all tools, DNNs are not a universal solution. Often, the same or
|
|
better performance on a task can be achieved by using a few
|
|
hand-engineered features (or even a collection of random
|
|
features).
|
|
</p>
|
|
|
|
<p>Here we list some of the important limitations of supervised neural network based models. </p>
|
|
|
|
<ul>
|
|
<li> <b>Need labeled data</b>. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).</li>
|
|
<li> <b>Supervised neural networks are extremely data intensive.</b> DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.</li>
|
|
<li> <b>Homogeneous data.</b> Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.</li>
|
|
<li> <b>Many problems are not about prediction.</b> In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a <em>wrong</em> model. The model might or might not be useful for understanding the underlying science.</li>
|
|
</ul>
|
|
<p>Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="solving-odes-with-deep-learning">Solving ODEs with Deep Learning </h2>
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b></b>
|
|
<p>
|
|
<p>The Universal Approximation Theorem states that a neural network can
|
|
approximate any function at a single hidden layer along with one input
|
|
and output layer to any given precision.
|
|
</p>
|
|
</div>
|
|
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Book on solving differential equations with ML methods</b>
|
|
<p>
|
|
<p><a href="https://www.springer.com/gp/book/9789401798150" target="_blank">An Introduction to Neural Network Methods for Differential Equations</a>, by Yadav and Kumar.</p>
|
|
</div>
|
|
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Master thesis on applying deep learning to problems in mechanics</b>
|
|
<p>
|
|
<p><a href="https://www.duo.uio.no/handle/10852/79212" target="_blank">Using Deep Reinforcement Learning for Active Flow Control</a>, by Marius Holm</p>
|
|
</div>
|
|
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Thanks to Kristine Baluka Hein</b>
|
|
<p>
|
|
<p>The lectures on differential equations were developed by Kristine Baluka Hein, now PhD student at IFI.
|
|
A great thanks to Kristine.
|
|
</p>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="ordinary-differential-equations">Ordinary Differential Equations </h2>
|
|
|
|
<p>An ordinary differential equation (ODE) is an equation involving functions having one variable.</p>
|
|
|
|
<p>In general, an ordinary differential equation looks like</p>
|
|
|
|
$$
|
|
\begin{equation} \label{ode}
|
|
f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) = 0
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>where \( g(x) \) is the function to find, and \( g^{(n)}(x) \) is the \( n \)-th derivative of \( g(x) \).</p>
|
|
|
|
<p>The \( f\left(x, g(x), g'(x), g''(x), \, \dots \, , g^{(n)}(x)\right) \) is just a way to write that there is an expression involving \( x \) and \( g(x), \ g'(x), \ g''(x), \, \dots \, , \text{ and } g^{(n)}(x) \) on the left side of the equality sign in \eqref{ode}.
|
|
The highest order of derivative, that is the value of \( n \), determines to the order of the equation.
|
|
The equation is referred to as a \( n \)-th order ODE.
|
|
Along with \eqref{ode}, some additional conditions of the function \( g(x) \) are typically given
|
|
for the solution to be unique.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-trial-solution">The trial solution </h2>
|
|
|
|
<p>Let the trial solution \( g_t(x) \) be</p>
|
|
|
|
$$
|
|
\begin{equation}
|
|
g_t(x) = h_1(x) + h_2(x,N(x,P))
|
|
\label{_auto1}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>where \( h_1(x) \) is a function that makes \( g_t(x) \) satisfy a given set
|
|
of conditions, \( N(x,P) \) a neural network with weights and biases
|
|
described by \( P \) and \( h_2(x, N(x,P)) \) some expression involving the
|
|
neural network. The role of the function \( h_2(x, N(x,P)) \), is to
|
|
ensure that the output from \( N(x,P) \) is zero when \( g_t(x) \) is
|
|
evaluated at the values of \( x \) where the given conditions must be
|
|
satisfied. The function \( h_1(x) \) should alone make \( g_t(x) \) satisfy
|
|
the conditions.
|
|
</p>
|
|
|
|
<p>But what about the network \( N(x,P) \)?</p>
|
|
|
|
<p>As described previously, an optimization method could be used to minimize the parameters of a neural network, that being its weights and biases, through backward propagation.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="minimization-process">Minimization process </h2>
|
|
|
|
<p>For the minimization to be defined, we need to have a cost function at hand to minimize.</p>
|
|
|
|
<p>It is given that \( f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) \) should be equal to zero in \eqref{ode}.
|
|
We can choose to consider the mean squared error as the cost function for an input \( x \).
|
|
Since we are looking at one input, the cost function is just \( f \) squared.
|
|
The cost function \( c\left(x, P \right) \) can therefore be expressed as
|
|
</p>
|
|
|
|
$$
|
|
C\left(x, P\right) = \big(f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right)\big)^2
|
|
$$
|
|
|
|
<p>If \( N \) inputs are given as a vector \( \boldsymbol{x} \) with elements \( x_i \) for \( i = 1,\dots,N \),
|
|
the cost function becomes
|
|
</p>
|
|
|
|
$$
|
|
\begin{equation} \label{cost}
|
|
C\left(\boldsymbol{x}, P\right) = \frac{1}{N} \sum_{i=1}^N \big(f\left(x_i, \, g(x_i), \, g'(x_i), \, g''(x_i), \, \dots \, , \, g^{(n)}(x_i)\right)\big)^2
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>The neural net should then find the parameters \( P \) that minimizes the cost function in
|
|
\eqref{cost} for a set of \( N \) training samples \( x_i \).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="minimizing-the-cost-function-using-gradient-descent-and-automatic-differentiation">Minimizing the cost function using gradient descent and automatic differentiation </h2>
|
|
|
|
<p>To perform the minimization using gradient descent, the gradient of \( C\left(\boldsymbol{x}, P\right) \) is needed.
|
|
It might happen so that finding an analytical expression of the gradient of \( C(\boldsymbol{x}, P) \) from \eqref{cost} gets too messy, depending on which cost function one desires to use.
|
|
</p>
|
|
|
|
<p>Luckily, there exists libraries that makes the job for us through automatic differentiation.
|
|
Automatic differentiation is a method of finding the derivatives numerically with very high precision.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="example-exponential-decay">Example: Exponential decay </h2>
|
|
|
|
<p>An exponential decay of a quantity \( g(x) \) is described by the equation</p>
|
|
|
|
$$
|
|
\begin{equation} \label{solve_expdec}
|
|
g'(x) = -\gamma g(x)
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>with \( g(0) = g_0 \) for some chosen initial value \( g_0 \).</p>
|
|
|
|
<p>The analytical solution of \eqref{solve_expdec} is</p>
|
|
|
|
$$
|
|
\begin{equation}
|
|
g(x) = g_0 \exp\left(-\gamma x\right)
|
|
\label{_auto2}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of \eqref{solve_expdec}.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-function-to-solve-for">The function to solve for </h2>
|
|
|
|
<p>The program will use a neural network to solve</p>
|
|
|
|
$$
|
|
\begin{equation} \label{solveode}
|
|
g'(x) = -\gamma g(x)
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>where \( g(0) = g_0 \) with \( \gamma \) and \( g_0 \) being some chosen values.</p>
|
|
|
|
<p>In this example, \( \gamma = 2 \) and \( g_0 = 10 \).</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-trial-solution">The trial solution </h2>
|
|
<p>To begin with, a trial solution \( g_t(t) \) must be chosen. A general trial solution for ordinary differential equations could be</p>
|
|
|
|
$$
|
|
g_t(x, P) = h_1(x) + h_2(x, N(x, P))
|
|
$$
|
|
|
|
<p>with \( h_1(x) \) ensuring that \( g_t(x) \) satisfies some conditions and \( h_2(x,N(x, P)) \) an expression involving \( x \) and the output from the neural network \( N(x,P) \) with \( P \) being the collection of the weights and biases for each layer. For now, it is assumed that the network consists of one input layer, one hidden layer, and one output layer.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="setup-of-network">Setup of Network </h2>
|
|
|
|
<p>In this network, there are no weights and bias at the input layer, so \( P = \{ P_{\text{hidden}}, P_{\text{output}} \} \).
|
|
If there are \( N_{\text{hidden} } \) neurons in the hidden layer, then \( P_{\text{hidden}} \) is a \( N_{\text{hidden} } \times (1 + N_{\text{input}}) \) matrix, given that there are \( N_{\text{input}} \) neurons in the input layer.
|
|
</p>
|
|
|
|
<p>The first column in \( P_{\text{hidden} } \) represents the bias for each neuron in the hidden layer and the second column represents the weights for each neuron in the hidden layer from the input layer.
|
|
If there are \( N_{\text{output} } \) neurons in the output layer, then \( P_{\text{output}} \) is a \( N_{\text{output} } \times (1 + N_{\text{hidden} }) \) matrix.
|
|
</p>
|
|
|
|
<p>Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron.</p>
|
|
|
|
<p>It is given that \( g(0) = g_0 \). The trial solution must fulfill this condition to be a proper solution of \eqref{solveode}. A possible way to ensure that \( g_t(0, P) = g_0 \), is to let \( F(N(x,P)) = x \cdot N(x,P) \) and \( A(x) = g_0 \). This gives the following trial solution:</p>
|
|
|
|
$$
|
|
\begin{equation} \label{trial}
|
|
g_t(x, P) = g_0 + x \cdot N(x, P)
|
|
\end{equation}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="reformulating-the-problem">Reformulating the problem </h2>
|
|
|
|
<p>We wish that our neural network manages to minimize a given cost function.</p>
|
|
|
|
<p>A reformulation of out equation, \eqref{solveode}, must therefore be done,
|
|
such that it describes the problem a neural network can solve for.
|
|
</p>
|
|
|
|
<p>The neural network must find the set of weights and biases \( P \) such that the trial solution in \eqref{trial} satisfies \eqref{solveode}.</p>
|
|
|
|
<p>The trial solution</p>
|
|
|
|
$$
|
|
g_t(x, P) = g_0 + x \cdot N(x, P)
|
|
$$
|
|
|
|
<p>has been chosen such that it already solves the condition \( g(0) = g_0 \). What remains, is to find \( P \) such that</p>
|
|
|
|
$$
|
|
\begin{equation} \label{nnmin}
|
|
g_t'(x, P) = - \gamma g_t(x, P)
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>is fulfilled as <em>best as possible</em>.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="more-technicalities">More technicalities </h2>
|
|
|
|
<p>The left hand side and right hand side of \eqref{nnmin} must be computed separately, and then the neural network must choose weights and biases, contained in \( P \), such that the sides are equal as best as possible.
|
|
This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero.
|
|
In this case, the difference squared shows to be an appropriate measurement of how erroneous the trial solution is with respect to \( P \) of the neural network.
|
|
</p>
|
|
|
|
<p>This gives the following cost function our neural network must solve for:</p>
|
|
|
|
$$
|
|
\min_{P}\Big\{ \big(g_t'(x, P) - ( -\gamma g_t(x, P) \big)^2 \Big\}
|
|
$$
|
|
|
|
<p>(the notation \( \min_{P}\{ f(x, P) \} \) means that we desire to find \( P \) that yields the minimum of \( f(x, P) \))</p>
|
|
|
|
<p>or, in terms of weights and biases for the hidden and output layer in our network:</p>
|
|
|
|
$$
|
|
\min_{P_{\text{hidden} }, \ P_{\text{output} }}\Big\{ \big(g_t'(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) - ( -\gamma g_t(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) \big)^2 \Big\}
|
|
$$
|
|
|
|
<p>for an input value \( x \).</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="more-details">More details </h2>
|
|
|
|
<p>If the neural network evaluates \( g_t(x, P) \) at more values for \( x \), say \( N \) values \( x_i \) for \( i = 1, \dots, N \), then the <em>total</em> error to minimize becomes</p>
|
|
|
|
$$
|
|
\begin{equation} \label{min}
|
|
\min_{P}\Big\{\frac{1}{N} \sum_{i=1}^N \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \Big\}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>Letting \( \boldsymbol{x} \) be a vector with elements \( x_i \) and \( C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \) denote the cost function, the minimization problem that our network must solve, becomes</p>
|
|
|
|
$$
|
|
\min_{P} C(\boldsymbol{x}, P)
|
|
$$
|
|
|
|
<p>In terms of \( P_{\text{hidden} } \) and \( P_{\text{output} } \), this could also be expressed as</p>
|
|
|
|
<p>$$
|
|
\min_{P_{\text{hidden} }, \ P_{\text{output} }} C(\boldsymbol{x}, \{P_{\text{hidden} }, P_{\text{output} }\})
|
|
$$
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="a-possible-implementation-of-a-neural-network">A possible implementation of a neural network </h2>
|
|
|
|
<p>For simplicity, it is assumed that the input is an array \( \boldsymbol{x} = (x_1, \dots, x_N) \) with \( N \) elements. It is at these points the neural network should find \( P \) such that it fulfills \eqref{min}.</p>
|
|
|
|
<p>First, the neural network must feed forward the inputs.
|
|
This means that \( \boldsymbol{x}s \) must be passed through an input layer, a hidden layer and a output layer. The input layer in this case, does not need to process the data any further.
|
|
The input layer will consist of \( N_{\text{input} } \) neurons, passing its element to each neuron in the hidden layer. The number of neurons in the hidden layer will be \( N_{\text{hidden} } \).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="technicalities">Technicalities </h2>
|
|
|
|
<p>For the \( i \)-th in the hidden layer with weight \( w_i^{\text{hidden} } \) and bias \( b_i^{\text{hidden} } \), the weighting from the \( j \)-th neuron at the input layer is:</p>
|
|
|
|
$$
|
|
\begin{aligned}
|
|
z_{i,j}^{\text{hidden}} &= b_i^{\text{hidden}} + w_i^{\text{hidden}}x_j \\
|
|
&=
|
|
\begin{pmatrix}
|
|
b_i^{\text{hidden}} & w_i^{\text{hidden}}
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
1 \\
|
|
x_j
|
|
\end{pmatrix}
|
|
\end{aligned}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="final-technicalities-i">Final technicalities I </h2>
|
|
|
|
<p>The result after weighting the inputs at the \( i \)-th hidden neuron can be written as a vector:</p>
|
|
|
|
$$
|
|
\begin{aligned}
|
|
\boldsymbol{z}_{i}^{\text{hidden}} &= \Big( b_i^{\text{hidden}} + w_i^{\text{hidden}}x_1 , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_2, \ \dots \, , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_N\Big) \\
|
|
&=
|
|
\begin{pmatrix}
|
|
b_i^{\text{hidden}} & w_i^{\text{hidden}}
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
1 & 1 & \dots & 1 \\
|
|
x_1 & x_2 & \dots & x_N
|
|
\end{pmatrix} \\
|
|
&= \boldsymbol{p}_{i, \text{hidden}}^T X
|
|
\end{aligned}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="final-technicalities-ii">Final technicalities II </h2>
|
|
|
|
<p>The vector \( \boldsymbol{p}_{i, \text{hidden}}^T \) constitutes each row in \( P_{\text{hidden} } \), which contains the weights for the neural network to minimize according to \eqref{min}.</p>
|
|
|
|
<p>After having found \( \boldsymbol{z}_{i}^{\text{hidden}} \) for every \( i \)-th neuron within the hidden layer, the vector will be sent to an activation function \( a_i(\boldsymbol{z}) \).</p>
|
|
|
|
<p>In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron:</p>
|
|
|
|
$$
|
|
f(z) = \frac{1}{1 + \exp{(-z)}}
|
|
$$
|
|
|
|
<p>It is possible to use other activations functions for the hidden layer also.</p>
|
|
|
|
<p>The output \( \boldsymbol{x}_i^{\text{hidden}} \) from each \( i \)-th hidden neuron is:</p>
|
|
|
|
<p>$$
|
|
\boldsymbol{x}_i^{\text{hidden} } = f\big( \boldsymbol{z}_{i}^{\text{hidden}} \big)
|
|
$$
|
|
</p>
|
|
|
|
<p>The outputs \( \boldsymbol{x}_i^{\text{hidden} } \) are then sent to the output layer.</p>
|
|
|
|
<p>The output layer consists of one neuron in this case, and combines the
|
|
output from each of the neurons in the hidden layers. The output layer
|
|
combines the results from the hidden layer using some weights \( w_i^{\text{output}} \)
|
|
and biases \( b_i^{\text{output}} \). In this case,
|
|
it is assumes that the number of neurons in the output layer is one.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="final-technicalities-iii">Final technicalities III </h2>
|
|
|
|
<p>The procedure of weighting the output neuron \( j \) in the hidden layer to the \( i \)-th neuron in the output layer is similar as for the hidden layer described previously.</p>
|
|
|
|
$$
|
|
\begin{aligned}
|
|
z_{1,j}^{\text{output}} & =
|
|
\begin{pmatrix}
|
|
b_1^{\text{output}} & \boldsymbol{w}_1^{\text{output}}
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
1 \\
|
|
\boldsymbol{x}_j^{\text{hidden}}
|
|
\end{pmatrix}
|
|
\end{aligned}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="final-technicalities-iv">Final technicalities IV </h2>
|
|
|
|
<p>Expressing \( z_{1,j}^{\text{output}} \) as a vector gives the following way of weighting the inputs from the hidden layer:</p>
|
|
|
|
$$
|
|
\boldsymbol{z}_{1}^{\text{output}} =
|
|
\begin{pmatrix}
|
|
b_1^{\text{output}} & \boldsymbol{w}_1^{\text{output}}
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
1 & 1 & \dots & 1 \\
|
|
\boldsymbol{x}_1^{\text{hidden}} & \boldsymbol{x}_2^{\text{hidden}} & \dots & \boldsymbol{x}_N^{\text{hidden}}
|
|
\end{pmatrix}
|
|
$$
|
|
|
|
<p>In this case we seek a continuous range of values since we are approximating a function. This means that after computing \( \boldsymbol{z}_{1}^{\text{output}} \) the neural network has finished its feed forward step, and \( \boldsymbol{z}_{1}^{\text{output}} \) is the final output of the network.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="back-propagation">Back propagation </h2>
|
|
|
|
<p>The next step is to decide how the parameters should be changed such that they minimize the cost function.</p>
|
|
|
|
<p>The chosen cost function for this problem is</p>
|
|
|
|
$$
|
|
C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2
|
|
$$
|
|
|
|
<p>In order to minimize the cost function, an optimization method must be chosen.</p>
|
|
|
|
<p>Here, gradient descent with a constant step size has been chosen.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="gradient-descent">Gradient descent </h2>
|
|
|
|
<p>The idea of the gradient descent algorithm is to update parameters in
|
|
a direction where the cost function decreases goes to a minimum.
|
|
</p>
|
|
|
|
<p>In general, the update of some parameters \( \boldsymbol{\omega} \) given a cost
|
|
function defined by some weights \( \boldsymbol{\omega} \), \( C(\boldsymbol{x},
|
|
\boldsymbol{\omega}) \), goes as follows:
|
|
</p>
|
|
|
|
$$
|
|
\boldsymbol{\omega}_{\text{new} } = \boldsymbol{\omega} - \lambda \nabla_{\boldsymbol{\omega}} C(\boldsymbol{x}, \boldsymbol{\omega})
|
|
$$
|
|
|
|
<p>for a number of iterations or until $ \big|\big| \boldsymbol{\omega}_{\text{new} } - \boldsymbol{\omega} \big|\big|$ becomes smaller than some given tolerance.</p>
|
|
|
|
<p>The value of \( \lambda \) decides how large steps the algorithm must take
|
|
in the direction of $ \nabla_{\boldsymbol{\omega}} C(\boldsymbol{x}, \boldsymbol{\omega})$.
|
|
The notation \( \nabla_{\boldsymbol{\omega}} \) express the gradient with respect
|
|
to the elements in \( \boldsymbol{\omega} \).
|
|
</p>
|
|
|
|
<p>In our case, we have to minimize the cost function \( C(\boldsymbol{x}, P) \) with
|
|
respect to the two sets of weights and biases, that is for the hidden
|
|
layer \( P_{\text{hidden} } \) and for the output layer \( P_{\text{output}
|
|
} \) .
|
|
</p>
|
|
|
|
<p>This means that \( P_{\text{hidden} } \) and \( P_{\text{output} } \) is updated by</p>
|
|
|
|
$$
|
|
\begin{aligned}
|
|
P_{\text{hidden},\text{new}} &= P_{\text{hidden}} - \lambda \nabla_{P_{\text{hidden}}} C(\boldsymbol{x}, P) \\
|
|
P_{\text{output},\text{new}} &= P_{\text{output}} - \lambda \nabla_{P_{\text{output}}} C(\boldsymbol{x}, P)
|
|
\end{aligned}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-code-for-solving-the-ode">The code for solving the ODE </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #408080; font-style: italic"># Assuming one input, hidden, and output layer</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">neural_network</span>(params, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the weights (including and biases) for the hidden and output layer.</span>
|
|
<span style="color: #408080; font-style: italic"># Assume that params is a list of parameters for each layer.</span>
|
|
<span style="color: #408080; font-style: italic"># The biases are the first element for each array in params,</span>
|
|
<span style="color: #408080; font-style: italic"># and the weights are the remaning elements in each array in params.</span>
|
|
|
|
w_hidden <span style="color: #666666">=</span> params[<span style="color: #666666">0</span>]
|
|
w_output <span style="color: #666666">=</span> params[<span style="color: #666666">1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_input <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_input ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_input)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_hidden ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_hidden)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
<span style="color: #408080; font-style: italic"># The trial solution using the deep neural network:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(x,params, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> g0 <span style="color: #666666">+</span> x<span style="color: #666666">*</span>neural_network(params,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g</span>(x, g_trial, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>g_trial
|
|
|
|
<span style="color: #408080; font-style: italic"># The cost function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
|
|
g_t <span style="color: #666666">=</span> g_trial(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the neural network</span>
|
|
d_net_out <span style="color: #666666">=</span> elementwise_grad(neural_network,<span style="color: #666666">1</span>)(P,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
|
|
d_g_t <span style="color: #666666">=</span> elementwise_grad(g_trial,<span style="color: #666666">0</span>)(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
|
|
func <span style="color: #666666">=</span> g(x, g_t)
|
|
|
|
err_sqr <span style="color: #666666">=</span> (d_g_t <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> np<span style="color: #666666">.</span>size(err_sqr)
|
|
|
|
<span style="color: #408080; font-style: italic"># Solve the exponential decay ODE using neural network with one input, hidden, and output layer</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_neural_network</span>(x, num_neurons_hidden, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic">## Set up initial weights and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the hidden layer</span>
|
|
p0 <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons_hidden, <span style="color: #666666">2</span> )
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
p1 <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
P <span style="color: #666666">=</span> [p0, p1]
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'__main__'</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">'Max absolute difference: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'Performance of neural network solving an ODE compared to the analytical solution'</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">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'x'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(x)'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-network-with-one-input-layer-specified-number-of-hidden-layers-and-one-output-layer">The network with one input layer, specified number of hidden layers, and one output layer </h2>
|
|
|
|
<p>It is also possible to extend the construction of our network into a more general one, allowing the network to contain more than one hidden layers.</p>
|
|
|
|
<p>The number of neurons within each hidden layer are given as a list of integers in the program below.</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #408080; font-style: italic"># The neural network with one input layer and one output layer,</span>
|
|
<span style="color: #408080; font-style: italic"># but with number of hidden layers specified by the user.</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consists of</span>
|
|
<span style="color: #408080; font-style: italic"># parameters to all the hidden</span>
|
|
<span style="color: #408080; font-style: italic"># layers AND the output layer.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
|
|
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
<span style="color: #408080; font-style: italic"># The trial solution using the deep neural network:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x,params, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> g0 <span style="color: #666666">+</span> x<span style="color: #666666">*</span>deep_neural_network(params, x)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g</span>(x, g_trial, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>g_trial
|
|
|
|
<span style="color: #408080; font-style: italic"># The same cost function as before, but calls deep_neural_network instead.</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
|
|
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the neural network</span>
|
|
d_net_out <span style="color: #666666">=</span> elementwise_grad(deep_neural_network,<span style="color: #666666">1</span>)(P,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
|
|
d_g_t <span style="color: #666666">=</span> elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>)(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
|
|
func <span style="color: #666666">=</span> g(x, g_t)
|
|
|
|
err_sqr <span style="color: #666666">=</span> (d_g_t <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> np<span style="color: #666666">.</span>size(err_sqr)
|
|
|
|
<span style="color: #408080; font-style: italic"># Solve the exponential decay ODE using neural network with one input and one output layer,</span>
|
|
<span style="color: #408080; font-style: italic"># but with specified number of hidden layers from the user.</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># The number of elements in the list num_hidden_neurons thus represents</span>
|
|
<span style="color: #408080; font-style: italic"># the number of hidden layers.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weights and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'__main__'</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">'Performance of a deep neural network solving an ODE compared to the analytical solution'</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">'analytical'</span>,<span style="color: #BA2121">'dnn'</span>])
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(x)'</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's liking.</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">get_parameters</span>():
|
|
alpha <span style="color: #666666">=</span> <span style="color: #666666">2</span>
|
|
A <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
g0 <span style="color: #666666">=</span> <span style="color: #666666">1.2</span>
|
|
<span style="color: #008000; font-weight: bold">return</span> alpha, A, g0
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(P, x):
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(P) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
|
|
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> P[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> P[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
|
|
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
|
|
d_g_t <span style="color: #666666">=</span> elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>)(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
|
|
func <span style="color: #666666">=</span> f(x, g_t)
|
|
|
|
err_sqr <span style="color: #666666">=</span> (d_g_t <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> np<span style="color: #666666">.</span>size(err_sqr)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(x, g_trial):
|
|
alpha,A, g0 <span style="color: #666666">=</span> get_parameters()
|
|
<span style="color: #008000; font-weight: bold">return</span> alpha<span style="color: #666666">*</span>g_trial<span style="color: #666666">*</span>(A <span style="color: #666666">-</span> g_trial)
|
|
|
|
<span style="color: #408080; font-style: italic"># The trial solution using the deep neural network:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x, params):
|
|
alpha,A, g0 <span style="color: #666666">=</span> get_parameters()
|
|
<span style="color: #008000; font-weight: bold">return</span> g0 <span style="color: #666666">+</span> x<span style="color: #666666">*</span>deep_neural_network(params,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># The analytical solution:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(t):
|
|
alpha,A, g0 <span style="color: #666666">=</span> get_parameters()
|
|
<span style="color: #008000; font-weight: bold">return</span> A<span style="color: #666666">*</span>g0<span style="color: #666666">/</span>(g0 <span style="color: #666666">+</span> (A <span style="color: #666666">-</span> g0)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>alpha<span style="color: #666666">*</span>A<span style="color: #666666">*</span>t))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'__main__'</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">"The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</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">'Performance of neural network solving an ODE compared to the analytical solution'</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">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'t'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(t)'</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">'__main__'</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">"The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</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">'Performance of neural network solving an ODE compared to the analytical solution'</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">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'t'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(t)'</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">'Max absolute difference between Euler method and analytical: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>diff1)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Max absolute difference between deep neural network and analytical: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'euler'</span>,<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'dnn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'Time t'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(t)'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="example-solving-the-one-dimensional-poisson-equation">Example: Solving the one dimensional Poisson equation </h2>
|
|
|
|
<p>The Poisson equation for \( g(x) \) in one dimension is</p>
|
|
|
|
$$
|
|
\begin{equation} \label{poisson}
|
|
-g''(x) = f(x)
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>where \( f(x) \) is a given function for \( x \in (0,1) \).</p>
|
|
|
|
<p>The conditions that \( g(x) \) is chosen to fulfill, are</p>
|
|
$$
|
|
\begin{align*}
|
|
g(0) &= 0 \\
|
|
g(1) &= 0
|
|
\end{align*}
|
|
$$
|
|
|
|
<p>This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used.
|
|
The results from the networks can then be compared to the analytical solution.
|
|
In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-specific-equation-to-solve-for">The specific equation to solve for </h2>
|
|
|
|
<p>Here, the function \( g(x) \) to solve for follows the equation</p>
|
|
|
|
$$
|
|
-g''(x) = f(x),\qquad x \in (0,1)
|
|
$$
|
|
|
|
<p>where \( f(x) \) is a given function, along with the chosen conditions</p>
|
|
|
|
$$
|
|
\begin{aligned}
|
|
g(0) = g(1) = 0
|
|
\end{aligned}\label{cond}
|
|
$$
|
|
|
|
<p>In this example, we consider the case when \( f(x) = (3x + x^2)\exp(x) \).</p>
|
|
|
|
<p>For this case, a possible trial solution satisfying the conditions could be</p>
|
|
|
|
$$
|
|
g_t(x) = x \cdot (1-x) \cdot N(P,x)
|
|
$$
|
|
|
|
<p>The analytical solution for this problem is</p>
|
|
|
|
$$
|
|
g(x) = x(1 - x)\exp(x)
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="solving-the-equation-using-autograd">Solving the equation using Autograd </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
|
|
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'__main__'</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">"The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</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">'Performance of neural network solving an ODE compared to the analytical solution'</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">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'x'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(x)'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="comparing-with-a-numerical-scheme">Comparing with a numerical scheme </h2>
|
|
|
|
<p>The Poisson equation is possible to solve using Taylor series to approximate the second derivative.</p>
|
|
|
|
<p>Using Taylor series, the second derivative can be expressed as</p>
|
|
|
|
<p>$$
|
|
g''(x) = \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2} + E_{\Delta x}(x)
|
|
$$
|
|
</p>
|
|
|
|
<p>where \( \Delta x \) is a small step size and \( E_{\Delta x}(x) \) being the error term.</p>
|
|
|
|
<p>Looking away from the error terms gives an approximation to the second derivative:</p>
|
|
|
|
$$
|
|
\begin{equation} \label{approx}
|
|
g''(x) \approx \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>If \( x_i = i \Delta x = x_{i-1} + \Delta x \) and \( g_i = g(x_i) \) for \( i = 1,\dots N_x - 2 \) with \( N_x \) being the number of values for \( x \), \eqref{approx} becomes</p>
|
|
|
|
$$
|
|
\begin{aligned}
|
|
g''(x_i) &\approx \frac{g(x_i + \Delta x) - 2g(x_i) + g(x_i -\Delta x)}{\Delta x^2} \\
|
|
&= \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2}
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>Since we know from our problem that</p>
|
|
|
|
$$
|
|
\begin{aligned}
|
|
-g''(x) &= f(x) \\
|
|
&= (3x + x^2)\exp(x)
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>along with the conditions \( g(0) = g(1) = 0 \),
|
|
the following scheme can be used to find an approximate solution for \( g(x) \) numerically:
|
|
</p>
|
|
|
|
$$
|
|
\begin{equation}
|
|
\begin{aligned}
|
|
-\Big( \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2} \Big) &= f(x_i) \\
|
|
-g_{i+1} + 2g_i - g_{i-1} &= \Delta x^2 f(x_i)
|
|
\end{aligned}
|
|
\end{equation} \label{odesys}
|
|
$$
|
|
|
|
<p>for \( i = 1, \dots, N_x - 2 \) where \( g_0 = g_{N_x - 1} = 0 \) and \( f(x_i) = (3x_i + x_i^2)\exp(x_i) \), which is given for our specific problem.</p>
|
|
|
|
<p>The equation can be rewritten into a matrix equation:</p>
|
|
|
|
$$
|
|
\begin{aligned}
|
|
\begin{pmatrix}
|
|
2 & -1 & 0 & \dots & 0 \\
|
|
-1 & 2 & -1 & \dots & 0 \\
|
|
\vdots & & \ddots & & \vdots \\
|
|
0 & \dots & -1 & 2 & -1 \\
|
|
0 & \dots & 0 & -1 & 2\\
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
g_1 \\
|
|
g_2 \\
|
|
\vdots \\
|
|
g_{N_x - 3} \\
|
|
g_{N_x - 2}
|
|
\end{pmatrix}
|
|
&=
|
|
\Delta x^2
|
|
\begin{pmatrix}
|
|
f(x_1) \\
|
|
f(x_2) \\
|
|
\vdots \\
|
|
f(x_{N_x - 3}) \\
|
|
f(x_{N_x - 2})
|
|
\end{pmatrix} \\
|
|
\boldsymbol{A}\boldsymbol{g} &= \boldsymbol{f},
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>which makes it possible to solve for the vector \( \boldsymbol{g} \).</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="setting-up-the-code">Setting up the code </h2>
|
|
|
|
<p>We can then compare the result from this numerical scheme with the output from our network using Autograd:</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
|
|
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</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">'__main__'</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">'Performance of neural network solving an ODE compared to the analytical solution'</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">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'x'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(x)'</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">"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">"</span><span style="color: #666666">%</span>max_diff1)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"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">"</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">'numerical scheme'</span>,<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'dnn'</span>])
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="partial-differential-equations">Partial Differential Equations </h2>
|
|
|
|
<p>A partial differential equation (PDE) has a solution here the function
|
|
is defined by multiple variables. The equation may involve all kinds
|
|
of combinations of which variables the function is differentiated with
|
|
respect to.
|
|
</p>
|
|
|
|
<p>In general, a partial differential equation for a function \( g(x_1,\dots,x_N) \) with \( N \) variables may be expressed as</p>
|
|
|
|
$$
|
|
\begin{equation} \label{PDE}
|
|
f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) = 0
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>where \( f \) is an expression involving all kinds of possible mixed derivatives of \( g(x_1,\dots,x_N) \) up to an order \( n \). In order for the solution to be unique, some additional conditions must also be given.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="type-of-problem">Type of problem </h2>
|
|
|
|
<p>The problem our network must solve for, is similar to the ODE case.
|
|
We must have a trial solution \( g_t \) at hand.
|
|
</p>
|
|
|
|
<p>For instance, the trial solution could be expressed as</p>
|
|
$$
|
|
\begin{align*}
|
|
g_t(x_1,\dots,x_N) = h_1(x_1,\dots,x_N) + h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P))
|
|
\end{align*}
|
|
$$
|
|
|
|
<p>where \( h_1(x_1,\dots,x_N) \) is a function that ensures \( g_t(x_1,\dots,x_N) \) satisfies some given conditions.
|
|
The neural network \( N(x_1,\dots,x_N,P) \) has weights and biases described by \( P \) and \( h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P)) \) is an expression using the output from the neural network in some way.
|
|
</p>
|
|
|
|
<p>The role of the function \( h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P)) \), is to ensure that the output of \( N(x_1,\dots,x_N,P) \) is zero when \( g_t(x_1,\dots,x_N) \) is evaluated at the values of \( x_1,\dots,x_N \) where the given conditions must be satisfied. The function \( h_1(x_1,\dots,x_N) \) should alone make \( g_t(x_1,\dots,x_N) \) satisfy the conditions.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="network-requirements">Network requirements </h2>
|
|
|
|
<p>The network tries then the minimize the cost function following the
|
|
same ideas as described for the ODE case, but now with more than one
|
|
variables to consider. The concept still remains the same; find a set
|
|
of parameters \( P \) such that the expression \( f \) in \eqref{PDE} is as
|
|
close to zero as possible.
|
|
</p>
|
|
|
|
<p>As for the ODE case, the cost function is the mean squared error that
|
|
the network must try to minimize. The cost function for the network to
|
|
minimize is
|
|
</p>
|
|
|
|
$$
|
|
\begin{equation*}
|
|
C\left(x_1, \dots, x_N, P\right) = \left( f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) \right)^2
|
|
\end{equation*}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="more-details">More details </h2>
|
|
|
|
<p>If we let \( \boldsymbol{x} = \big( x_1, \dots, x_N \big) \) be an array containing the values for \( x_1, \dots, x_N \) respectively, the cost function can be reformulated into the following:</p>
|
|
$$
|
|
C\left(\boldsymbol{x}, P\right) = f\left( \left( \boldsymbol{x}, \frac{\partial g(\boldsymbol{x}) }{\partial x_1}, \dots , \frac{\partial g(\boldsymbol{x}) }{\partial x_N}, \frac{\partial g(\boldsymbol{x}) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\boldsymbol{x}) }{\partial x_N^n} \right) \right)^2
|
|
$$
|
|
|
|
<p>If we also have \( M \) different sets of values for \( x_1, \dots, x_N \), that is \( \boldsymbol{x}_i = \big(x_1^{(i)}, \dots, x_N^{(i)}\big) \) for \( i = 1,\dots,M \) being the rows in matrix \( X \), the cost function can be generalized into</p>
|
|
$$
|
|
\begin{equation*}
|
|
C\left(X, P \right) = \sum_{i=1}^M f\left( \left( \boldsymbol{x}_i, \frac{\partial g(\boldsymbol{x}_i) }{\partial x_1}, \dots , \frac{\partial g(\boldsymbol{x}_i) }{\partial x_N}, \frac{\partial g(\boldsymbol{x}_i) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\boldsymbol{x}_i) }{\partial x_N^n} \right) \right)^2.
|
|
\end{equation*}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="example-the-diffusion-equation">Example: The diffusion equation </h2>
|
|
|
|
<p>In one spatial dimension, the equation reads</p>
|
|
$$
|
|
\begin{equation*}
|
|
\frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2}
|
|
\end{equation*}
|
|
$$
|
|
|
|
<p>where a possible choice of conditions are</p>
|
|
$$
|
|
\begin{align*}
|
|
g(0,t) &= 0 ,\qquad t \geq 0 \\
|
|
g(1,t) &= 0, \qquad t \geq 0 \\
|
|
g(x,0) &= u(x),\qquad x\in [0,1]
|
|
\end{align*}
|
|
$$
|
|
|
|
<p>with \( u(x) \) being some given function.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="defining-the-problem">Defining the problem </h2>
|
|
|
|
<p>For this case, we want to find \( g(x,t) \) such that</p>
|
|
|
|
$$
|
|
\begin{equation}
|
|
\frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2}
|
|
\end{equation} \label{diffonedim}
|
|
$$
|
|
|
|
<p>and</p>
|
|
|
|
$$
|
|
\begin{align*}
|
|
g(0,t) &= 0 ,\qquad t \geq 0 \\
|
|
g(1,t) &= 0, \qquad t \geq 0 \\
|
|
g(x,0) &= u(x),\qquad x\in [0,1]
|
|
\end{align*}
|
|
$$
|
|
|
|
<p>with \( u(x) = \sin(\pi x) \).</p>
|
|
|
|
<p>First, let us set up the deep neural network.
|
|
The deep neural network will follow the same structure as discussed in the examples solving the ODEs.
|
|
First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="setting-up-the-network-using-autograd">Setting up the network using Autograd </h2>
|
|
|
|
<p>The only change to do here, is to extend our network such that
|
|
functions of multiple parameters are correctly handled. In this case
|
|
we have two variables in our function to solve for, that is time \( t \)
|
|
and position \( x \). The variables will be represented by a
|
|
one-dimensional array in the program. The program will evaluate the
|
|
network at each possible pair \( (x,t) \), given an array for the desired
|
|
\( x \)-values and \( t \)-values to approximate the solution at.
|
|
</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># x is now a point and a 1D numpy array; make it a column vector</span>
|
|
num_coordinates <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">0</span>)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(num_coordinates,<span style="color: #666666">-1</span>)
|
|
|
|
num_points <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="setting-up-the-network-using-autograd-the-trial-solution">Setting up the network using Autograd; The trial solution </h2>
|
|
|
|
<p>The cost function must then iterate through the given arrays
|
|
containing values for \( x \) and \( t \), defines a point \( (x,t) \) the deep
|
|
neural network and the trial solution is evaluated at, and then finds
|
|
the Jacobian of the trial solution.
|
|
</p>
|
|
|
|
<p>A possible trial solution for this PDE is</p>
|
|
|
|
<p>$$
|
|
g_t(x,t) = h_1(x,t) + x(1-x)tN(x,t,P)
|
|
$$
|
|
</p>
|
|
|
|
<p>with \( A(x,t) \) being a function ensuring that \( g_t(x,t) \) satisfies our given conditions, and \( N(x,t,P) \) being the output from the deep neural network using weights and biases for each layer from \( P \).</p>
|
|
|
|
<p>To fulfill the conditions, \( A(x,t) \) could be:</p>
|
|
|
|
<p>$$
|
|
h_1(x,t) = (1-t)\Big(u(x) - \big((1-x)u(0) + x u(1)\big)\Big) = (1-t)u(x) = (1-t)\sin(\pi x)
|
|
$$
|
|
since \( (0) = u(1) = 0 \) and \( u(x) = \sin(\pi x) \).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="why-the-jacobian">Why the jacobian? </h2>
|
|
|
|
<p>The Jacobian is used because the program must find the derivative of
|
|
the trial solution with respect to \( x \) and \( t \).
|
|
</p>
|
|
|
|
<p>This gives the necessity of computing the Jacobian matrix, as we want
|
|
to evaluate the gradient with respect to \( x \) and \( t \) (note that the
|
|
Jacobian of a scalar-valued multivariate function is simply its
|
|
gradient).
|
|
</p>
|
|
|
|
<p>In Autograd, the differentiation is by default done with respect to
|
|
the first input argument of your Python function. Since the points is
|
|
an array representing \( x \) and \( t \), the Jacobian is calculated using
|
|
the values of \( x \) and \( t \).
|
|
</p>
|
|
|
|
<p>To find the second derivative with respect to \( x \) and \( t \), the
|
|
Jacobian can be found for the second time. The result is a Hessian
|
|
matrix, which is the matrix containing all the possible second order
|
|
mixed derivatives of \( g(x,t) \).
|
|
</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Set up the trial function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">u</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(point,P):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1-</span>t)<span style="color: #666666">*</span>u(x) <span style="color: #666666">+</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>t<span style="color: #666666">*</span>deep_neural_network(P,point)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(point):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">0.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># The cost function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x, t):
|
|
cost_sum <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
|
|
g_t_jacobian_func <span style="color: #666666">=</span> jacobian(g_trial)
|
|
g_t_hessian_func <span style="color: #666666">=</span> hessian(g_trial)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> x_ <span style="color: #AA22FF; font-weight: bold">in</span> x:
|
|
<span style="color: #008000; font-weight: bold">for</span> t_ <span style="color: #AA22FF; font-weight: bold">in</span> t:
|
|
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_,t_])
|
|
|
|
g_t <span style="color: #666666">=</span> g_trial(point,P)
|
|
g_t_jacobian <span style="color: #666666">=</span> g_t_jacobian_func(point,P)
|
|
g_t_hessian <span style="color: #666666">=</span> g_t_hessian_func(point,P)
|
|
|
|
g_t_dt <span style="color: #666666">=</span> g_t_jacobian[<span style="color: #666666">1</span>]
|
|
g_t_d2x <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
|
|
func <span style="color: #666666">=</span> f(point)
|
|
|
|
err_sqr <span style="color: #666666">=</span> ( (g_t_dt <span style="color: #666666">-</span> g_t_d2x) <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">+=</span> err_sqr
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="setting-up-the-network-using-autograd-the-full-program">Setting up the network using Autograd; The full program </h2>
|
|
|
|
<p>Having set up the network, along with the trial solution and cost function, we can now see how the deep neural network performs by comparing the results to the analytical solution.</p>
|
|
|
|
<p>The analytical solution of our problem is</p>
|
|
|
|
<p>$$
|
|
g(x,t) = \exp(-\pi^2 t)\sin(\pi x)
|
|
$$
|
|
</p>
|
|
|
|
<p>A possible way to implement a neural network solving the PDE, is given below.
|
|
Be aware, though, that it is fairly slow for the parameters used.
|
|
A better result is possible, but requires more iterations, and thus longer time to complete.
|
|
</p>
|
|
|
|
<p>Indeed, the program below is not optimal in its implementation, but rather serves as an example on how to implement and use a neural network to solve a PDE.
|
|
Using TensorFlow results in a much better execution time. Try it!
|
|
</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> jacobian,hessian,grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> axes3d
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the network</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># x is now a point and a 1D numpy array; make it a column vector</span>
|
|
num_coordinates <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">0</span>)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(num_coordinates,<span style="color: #666666">-1</span>)
|
|
|
|
num_points <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
|
|
<span style="color: #408080; font-style: italic">## Define the trial solution and cost function</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">u</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(point,P):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1-</span>t)<span style="color: #666666">*</span>u(x) <span style="color: #666666">+</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>t<span style="color: #666666">*</span>deep_neural_network(P,point)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(point):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">0.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># The cost function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x, t):
|
|
cost_sum <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
|
|
g_t_jacobian_func <span style="color: #666666">=</span> jacobian(g_trial)
|
|
g_t_hessian_func <span style="color: #666666">=</span> hessian(g_trial)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> x_ <span style="color: #AA22FF; font-weight: bold">in</span> x:
|
|
<span style="color: #008000; font-weight: bold">for</span> t_ <span style="color: #AA22FF; font-weight: bold">in</span> t:
|
|
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_,t_])
|
|
|
|
g_t <span style="color: #666666">=</span> g_trial(point,P)
|
|
g_t_jacobian <span style="color: #666666">=</span> g_t_jacobian_func(point,P)
|
|
g_t_hessian <span style="color: #666666">=</span> g_t_hessian_func(point,P)
|
|
|
|
g_t_dt <span style="color: #666666">=</span> g_t_jacobian[<span style="color: #666666">1</span>]
|
|
g_t_d2x <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
|
|
func <span style="color: #666666">=</span> f(point)
|
|
|
|
err_sqr <span style="color: #666666">=</span> ( (g_t_dt <span style="color: #666666">-</span> g_t_d2x) <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">+=</span> err_sqr
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span>( np<span style="color: #666666">.</span>size(x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>size(t) )
|
|
|
|
<span style="color: #408080; font-style: italic">## For comparison, define the analytical solution</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(point):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">**2*</span>t)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up a function for training the network to solve for the equation</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_pde_deep_neural_network</span>(x,t, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># 2 since we have two points, +1 to include bias</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: '</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">'Final cost: '</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">'__main__'</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">'Max absolute difference between the analytical solution and the network: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(diff_ag))
|
|
|
|
<span style="color: #408080; font-style: italic">## Plot the solutions in two dimensions, that being in position and time</span>
|
|
|
|
T,X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(t,x)
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Solution from the deep neural network w/ </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> layer'</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">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Analytical solution'</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">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Difference'</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">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</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">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</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">'dnn'</span>,<span style="color: #BA2121">'analytical'</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">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</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">'dnn'</span>,<span style="color: #BA2121">'analytical'</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">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</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">'dnn'</span>,<span style="color: #BA2121">'analytical'</span>])
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="example-solving-the-wave-equation-with-neural-networks">Example: Solving the wave equation with Neural Networks </h2>
|
|
|
|
<p>The wave equation is</p>
|
|
$$
|
|
\begin{equation*}
|
|
\frac{\partial^2 g(x,t)}{\partial t^2} = c^2\frac{\partial^2 g(x,t)}{\partial x^2}
|
|
\end{equation*}
|
|
$$
|
|
|
|
<p>with \( c \) being the specified wave speed.</p>
|
|
|
|
<p>Here, the chosen conditions are</p>
|
|
$$
|
|
\begin{align*}
|
|
g(0,t) &= 0 \\
|
|
g(1,t) &= 0 \\
|
|
g(x,0) &= u(x) \\
|
|
\frac{\partial g(x,t)}{\partial t} \Big |_{t = 0} &= v(x)
|
|
\end{align*}
|
|
$$
|
|
|
|
<p>where \( \frac{\partial g(x,t)}{\partial t} \Big |_{t = 0} \) means the derivative of \( g(x,t) \) with respect to \( t \) is evaluated at \( t = 0 \), and \( u(x) \) and \( v(x) \) being given functions.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-problem-to-solve-for">The problem to solve for </h2>
|
|
|
|
<p>The wave equation to solve for, is</p>
|
|
|
|
$$
|
|
\begin{equation} \label{wave}
|
|
\frac{\partial^2 g(x,t)}{\partial t^2} = c^2 \frac{\partial^2 g(x,t)}{\partial x^2}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>where \( c \) is the given wave speed.
|
|
The chosen conditions for this equation are
|
|
</p>
|
|
|
|
$$
|
|
\begin{aligned}
|
|
g(0,t) &= 0, &t \geq 0 \\
|
|
g(1,t) &= 0, &t \geq 0 \\
|
|
g(x,0) &= u(x), &x\in[0,1] \\
|
|
\frac{\partial g(x,t)}{\partial t}\Big |_{t = 0} &= v(x), &x \in [0,1]
|
|
\end{aligned} \label{condwave}
|
|
$$
|
|
|
|
<p>In this example, let \( c = 1 \) and \( u(x) = \sin(\pi x) \) and \( v(x) = -\pi\sin(\pi x) \).</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-trial-solution">The trial solution </h2>
|
|
<p>Setting up the network is done in similar matter as for the example of solving the diffusion equation.
|
|
The only things we have to change, is the trial solution such that it satisfies the conditions from \eqref{condwave} and the cost function.
|
|
</p>
|
|
|
|
<p>The trial solution becomes slightly different since we have other conditions than in the example of solving the diffusion equation. Here, a possible trial solution \( g_t(x,t) \) is</p>
|
|
|
|
<p>$$
|
|
g_t(x,t) = h_1(x,t) + x(1-x)t^2N(x,t,P)
|
|
$$
|
|
</p>
|
|
|
|
<p>where</p>
|
|
|
|
<p>$$
|
|
h_1(x,t) = (1-t^2)u(x) + tv(x)
|
|
$$
|
|
</p>
|
|
|
|
<p>Note that this trial solution satisfies the conditions only if \( u(0) = v(0) = u(1) = v(1) = 0 \), which is the case in this example.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-analytical-solution">The analytical solution </h2>
|
|
|
|
<p>The analytical solution for our specific problem, is</p>
|
|
|
|
<p>$$
|
|
g(x,t) = \sin(\pi x)\cos(\pi t) - \sin(\pi x)\sin(\pi t)
|
|
$$
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="solving-the-wave-equation-the-full-program-using-autograd">Solving the wave equation - the full program using Autograd </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> hessian,grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> axes3d
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the trial function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">u</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">v</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">h1</span>(point):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1</span> <span style="color: #666666">-</span> t<span style="color: #666666">**2</span>)<span style="color: #666666">*</span>u(x) <span style="color: #666666">+</span> t<span style="color: #666666">*</span>v(x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(point,P):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> h1(point) <span style="color: #666666">+</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>t<span style="color: #666666">**2*</span>deep_neural_network(P,point)
|
|
|
|
<span style="color: #408080; font-style: italic">## Define the cost function</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x, t):
|
|
cost_sum <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
|
|
g_t_hessian_func <span style="color: #666666">=</span> hessian(g_trial)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> x_ <span style="color: #AA22FF; font-weight: bold">in</span> x:
|
|
<span style="color: #008000; font-weight: bold">for</span> t_ <span style="color: #AA22FF; font-weight: bold">in</span> t:
|
|
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_,t_])
|
|
|
|
g_t_hessian <span style="color: #666666">=</span> g_t_hessian_func(point,P)
|
|
|
|
g_t_d2x <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
g_t_d2t <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">1</span>][<span style="color: #666666">1</span>]
|
|
|
|
err_sqr <span style="color: #666666">=</span> ( (g_t_d2t <span style="color: #666666">-</span> g_t_d2x) )<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">+=</span> err_sqr
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> (np<span style="color: #666666">.</span>size(t) <span style="color: #666666">*</span> np<span style="color: #666666">.</span>size(x))
|
|
|
|
<span style="color: #408080; font-style: italic">## The neural network</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># x is now a point and a 1D numpy array; make it a column vector</span>
|
|
num_coordinates <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">0</span>)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(num_coordinates,<span style="color: #666666">-1</span>)
|
|
|
|
num_points <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
|
|
<span style="color: #408080; font-style: italic">## The analytical solution</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(point):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>cos(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>t) <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>t)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_pde_deep_neural_network</span>(x,t, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># 2 since we have two points, +1 to include bias</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: '</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">'Final cost: '</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">'__main__'</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">"Max difference between analytical and solution from nn: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(diff))
|
|
|
|
<span style="color: #408080; font-style: italic">## Plot the solutions in two dimensions, that being in position and time</span>
|
|
|
|
T,X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(t,x)
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Solution from the deep neural network w/ </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> layer'</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">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Analytical solution'</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">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Difference'</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">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</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">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</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">'dnn'</span>,<span style="color: #BA2121">'analytical'</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">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</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">'dnn'</span>,<span style="color: #BA2121">'analytical'</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">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</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">'dnn'</span>,<span style="color: #BA2121">'analytical'</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 --> © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
|
</center>
|
|
</body>
|
|
</html>
|
|
|