3446 lines
214 KiB
HTML
3446 lines
214 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: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis">
|
|
<title>Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis</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'),
|
|
('Reading Recommendations', 2, None, 'reading-recommendations'),
|
|
('Summary on Deep Learning Methods',
|
|
2,
|
|
None,
|
|
'summary-on-deep-learning-methods'),
|
|
('CNNs in brief', 2, None, 'cnns-in-brief'),
|
|
('Recurrent neural networks: Overarching view',
|
|
2,
|
|
None,
|
|
'recurrent-neural-networks-overarching-view'),
|
|
('Set up of an RNN', 2, None, 'set-up-of-an-rnn'),
|
|
('A simple example', 2, None, 'a-simple-example'),
|
|
('An extrapolation example', 2, None, 'an-extrapolation-example'),
|
|
('Formatting the Data', 2, None, 'formatting-the-data'),
|
|
('Predicting New Points With A Trained Recurrent Neural Network',
|
|
2,
|
|
None,
|
|
'predicting-new-points-with-a-trained-recurrent-neural-network'),
|
|
('Other Things to Try', 2, None, 'other-things-to-try'),
|
|
('Other Types of Recurrent Neural Networks',
|
|
2,
|
|
None,
|
|
'other-types-of-recurrent-neural-networks'),
|
|
('Generative Models', 2, None, 'generative-models'),
|
|
('Generative Adversarial Networks',
|
|
2,
|
|
None,
|
|
'generative-adversarial-networks'),
|
|
('Discriminator', 2, None, 'discriminator'),
|
|
('Learning Process', 2, None, 'learning-process'),
|
|
('More about the Learning Process',
|
|
2,
|
|
None,
|
|
'more-about-the-learning-process'),
|
|
('Additional References', 2, None, 'additional-references'),
|
|
('Writing Our First Generative Adversarial Network',
|
|
2,
|
|
None,
|
|
'writing-our-first-generative-adversarial-network'),
|
|
('MNIST and GANs', 2, None, 'mnist-and-gans'),
|
|
('Other Models', 2, None, 'other-models'),
|
|
('Training Step', 2, None, 'training-step'),
|
|
('Checkpoints', 2, None, 'checkpoints'),
|
|
('Exploring the Latent Space',
|
|
2,
|
|
None,
|
|
'exploring-the-latent-space'),
|
|
('Getting Results', 2, None, 'getting-results'),
|
|
('Interpolating Between MNIST Digits',
|
|
2,
|
|
None,
|
|
'interpolating-between-mnist-digits'),
|
|
('Basic ideas of the Principal Component Analysis (PCA)',
|
|
2,
|
|
None,
|
|
'basic-ideas-of-the-principal-component-analysis-pca'),
|
|
('Introducing the Covariance and Correlation functions',
|
|
2,
|
|
None,
|
|
'introducing-the-covariance-and-correlation-functions'),
|
|
('More on the covariance', 2, None, 'more-on-the-covariance'),
|
|
('Reminding ourselves about Linear Regression',
|
|
2,
|
|
None,
|
|
'reminding-ourselves-about-linear-regression'),
|
|
('Simple Example', 2, None, 'simple-example'),
|
|
('The Correlation Matrix', 2, None, 'the-correlation-matrix'),
|
|
('Numpy Functionality', 2, None, 'numpy-functionality'),
|
|
('Correlation Matrix again', 2, None, 'correlation-matrix-again'),
|
|
('Using Pandas', 2, None, 'using-pandas'),
|
|
('And then the Franke Function',
|
|
2,
|
|
None,
|
|
'and-then-the-franke-function'),
|
|
('Lnks with the Design Matrix',
|
|
2,
|
|
None,
|
|
'lnks-with-the-design-matrix'),
|
|
('Computing the Expectation Values',
|
|
2,
|
|
None,
|
|
'computing-the-expectation-values'),
|
|
('Towards the PCA theorem', 2, None, 'towards-the-pca-theorem'),
|
|
('More on the PCA Theorem', 2, None, 'more-on-the-pca-theorem'),
|
|
('The Algorithm before the Theorem',
|
|
2,
|
|
None,
|
|
'the-algorithm-before-the-theorem'),
|
|
('Writing our own PCA code', 2, None, 'writing-our-own-pca-code'),
|
|
('Implementing it', 2, None, 'implementing-it'),
|
|
('First Step', 2, None, 'first-step'),
|
|
('Scaling', 2, None, 'scaling'),
|
|
('Centered Data', 2, None, 'centered-data'),
|
|
('Exploring', 2, None, 'exploring'),
|
|
('Diagonalize the sample covariance matrix to obtain the '
|
|
'principal components',
|
|
2,
|
|
None,
|
|
'diagonalize-the-sample-covariance-matrix-to-obtain-the-principal-components'),
|
|
('Collecting all Steps', 2, None, 'collecting-all-steps'),
|
|
('Classical PCA Theorem', 2, None, 'classical-pca-theorem'),
|
|
('The PCA Theorem', 2, None, 'the-pca-theorem'),
|
|
('Geometric Interpretation and link with Singular Value '
|
|
'Decomposition',
|
|
2,
|
|
None,
|
|
'geometric-interpretation-and-link-with-singular-value-decomposition'),
|
|
('PCA and scikit-learn', 2, None, 'pca-and-scikit-learn'),
|
|
('Back to the Cancer Data', 2, None, 'back-to-the-cancer-data'),
|
|
('Incremental PCA', 2, None, 'incremental-pca'),
|
|
('Randomized PCA', 3, None, 'randomized-pca'),
|
|
('Kernel PCA', 3, None, 'kernel-pca'),
|
|
('Other techniques', 2, None, 'other-techniques')]}
|
|
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: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis</h1>
|
|
</center> <!-- document title -->
|
|
|
|
<!-- author(s): Morten Hjorth-Jensen -->
|
|
<center>
|
|
<b>Morten Hjorth-Jensen</b> [1, 2]
|
|
</center>
|
|
<!-- institution(s) -->
|
|
<center>
|
|
[1] <b>Department of Physics, University of Oslo</b>
|
|
</center>
|
|
<center>
|
|
[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b>
|
|
</center>
|
|
<br>
|
|
<center>
|
|
<h4>Aug 23, 2022</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>
|
|
|
|
<ul>
|
|
<li> Thursday: Summary of Convolutional Neural Networks from week 42 and Recurrent Neural Networks</li>
|
|
<li> Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis</li>
|
|
</ul>
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Excellent lectures on CNNs and RNNs</b>
|
|
<p>
|
|
<ul>
|
|
<li> <a href="https://www.youtube.com/watch?v=iaSUYvmCekI&ab_channel=AlexanderAmini" target="_blank">Video on Convolutional Neural Networks from MIT</a></li>
|
|
<li> <a href="https://www.youtube.com/watch?v=SEnXr6v2ifU&ab_channel=AlexanderAmini" target="_blank">Video on Recurrent Neural Networks from MIT</a></li>
|
|
<li> <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi" target="_blank">Video on Deep Learning</a></li>
|
|
</ul>
|
|
</div>
|
|
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>More resources</b>
|
|
<p>
|
|
<ul>
|
|
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/v20/material/week10/in5400_2020_week10_recurrent_neural_network.pdf" target="_blank">IN5400 at UiO Lecture</a></li>
|
|
<li> <a href="https://www.youtube.com/watch?v=6niqTuYFZLQ&list=PLzUTmXVwsnXod6WNdg57Yc3zFx_f-RYsq&index=10&ab_channel=StanfordUniversitySchoolofEngineering" target="_blank">CS231 at Stanford Lecture</a></li>
|
|
</ul>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="reading-recommendations">Reading Recommendations </h2>
|
|
|
|
<ul>
|
|
<li> Goodfellow et al, chapter 10 on Recurrent NNs, chapters 11 and 12 on various practicalities around deep learning are also recommended.</li>
|
|
<li> Aurelien Geron, chapter 14 on RNNs.</li>
|
|
</ul>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="summary-on-deep-learning-methods">Summary on Deep Learning Methods </h2>
|
|
|
|
<p>We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs).</p>
|
|
|
|
<p>The first type of deep learning networks work very well on homogeneous and structured input data while CCNs are normally tailored to recognizing images.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="cnns-in-brief">CNNs in brief </h2>
|
|
|
|
<p>In summary:</p>
|
|
|
|
<ul>
|
|
<li> A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)</li>
|
|
<li> There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)</li>
|
|
<li> Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function</li>
|
|
<li> Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)</li>
|
|
<li> Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)</li>
|
|
</ul>
|
|
<p>For more material on convolutional networks, we strongly recommend
|
|
the course
|
|
<a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" target="_blank">IN5400 – Machine Learning for Image Analysis</a>
|
|
and the slides of <a href="http://cs231n.github.io/convolutional-networks/" target="_blank">CS231</a> which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). <a href="http://neuralnetworksanddeeplearning.com/chap6.html" target="_blank">Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs</a>.
|
|
</p>
|
|
|
|
<p>However, both standard feed forwards networks and CNNs perform well on data with unknown length.</p>
|
|
|
|
<p>This is where recurrent nueral networks (RNNs) come to our rescue.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="recurrent-neural-networks-overarching-view">Recurrent neural networks: Overarching view </h2>
|
|
|
|
<p>Till now our focus has been, including convolutional neural networks
|
|
as well, on feedforward neural networks. The output or the activations
|
|
flow only in one direction, from the input layer to the output layer.
|
|
</p>
|
|
|
|
<p>A recurrent neural network (RNN) looks very much like a feedforward
|
|
neural network, except that it also has connections pointing
|
|
backward.
|
|
</p>
|
|
|
|
<p>RNNs are used to analyze time series data such as stock prices, and
|
|
tell you when to buy or sell. In autonomous driving systems, they can
|
|
anticipate car trajectories and help avoid accidents. More generally,
|
|
they can work on sequences of arbitrary lengths, rather than on
|
|
fixed-sized inputs like all the nets we have discussed so far. For
|
|
example, they can take sentences, documents, or audio samples as
|
|
input, making them extremely useful for natural language processing
|
|
systems such as automatic translation and speech-to-text.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="set-up-of-an-rnn">Set up of an RNN </h2>
|
|
|
|
<p>More to text to be added</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="a-simple-example">A simple example </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"># Start importing packages</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</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">tensorflow.keras</span> <span style="color: #008000; font-weight: bold">import</span> datasets, layers, models
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras.layers</span> <span style="color: #008000; font-weight: bold">import</span> Input
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras.models</span> <span style="color: #008000; font-weight: bold">import</span> Model, Sequential
|
|
<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, SimpleRNN, LSTM, GRU
|
|
<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: #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: #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"># convert into dataset matrix</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">convertToMatrix</span>(data, step):
|
|
X, Y <span style="color: #666666">=</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>(data)<span style="color: #666666">-</span>step):
|
|
d<span style="color: #666666">=</span>i<span style="color: #666666">+</span>step
|
|
X<span style="color: #666666">.</span>append(data[i:d,])
|
|
Y<span style="color: #666666">.</span>append(data[d,])
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>array(X), np<span style="color: #666666">.</span>array(Y)
|
|
|
|
step <span style="color: #666666">=</span> <span style="color: #666666">4</span>
|
|
N <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
|
|
Tp <span style="color: #666666">=</span> <span style="color: #666666">800</span>
|
|
|
|
t<span style="color: #666666">=</span>np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>,N)
|
|
x<span style="color: #666666">=</span>np<span style="color: #666666">.</span>sin(<span style="color: #666666">0.02*</span>t)<span style="color: #666666">+2*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(N)
|
|
df <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(x)
|
|
df<span style="color: #666666">.</span>head()
|
|
|
|
plt<span style="color: #666666">.</span>plot(df)
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
values<span style="color: #666666">=</span>df<span style="color: #666666">.</span>values
|
|
train,test <span style="color: #666666">=</span> values[<span style="color: #666666">0</span>:Tp,:], values[Tp:N,:]
|
|
|
|
<span style="color: #408080; font-style: italic"># add step elements into train and test</span>
|
|
test <span style="color: #666666">=</span> np<span style="color: #666666">.</span>append(test,np<span style="color: #666666">.</span>repeat(test[<span style="color: #666666">-1</span>,],step))
|
|
train <span style="color: #666666">=</span> np<span style="color: #666666">.</span>append(train,np<span style="color: #666666">.</span>repeat(train[<span style="color: #666666">-1</span>,],step))
|
|
|
|
trainX,trainY <span style="color: #666666">=</span>convertToMatrix(train,step)
|
|
testX,testY <span style="color: #666666">=</span>convertToMatrix(test,step)
|
|
trainX <span style="color: #666666">=</span> np<span style="color: #666666">.</span>reshape(trainX, (trainX<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], <span style="color: #666666">1</span>, trainX<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]))
|
|
testX <span style="color: #666666">=</span> np<span style="color: #666666">.</span>reshape(testX, (testX<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], <span style="color: #666666">1</span>, testX<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]))
|
|
|
|
model <span style="color: #666666">=</span> Sequential()
|
|
model<span style="color: #666666">.</span>add(SimpleRNN(units<span style="color: #666666">=32</span>, input_shape<span style="color: #666666">=</span>(<span style="color: #666666">1</span>,step), activation<span style="color: #666666">=</span><span style="color: #BA2121">"relu"</span>))
|
|
model<span style="color: #666666">.</span>add(Dense(<span style="color: #666666">8</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">"relu"</span>))
|
|
model<span style="color: #666666">.</span>add(Dense(<span style="color: #666666">1</span>))
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">'mean_squared_error'</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">'rmsprop'</span>)
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
model<span style="color: #666666">.</span>fit(trainX,trainY, epochs<span style="color: #666666">=100</span>, batch_size<span style="color: #666666">=16</span>, verbose<span style="color: #666666">=2</span>)
|
|
trainPredict <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(trainX)
|
|
testPredict<span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(testX)
|
|
predicted<span style="color: #666666">=</span>np<span style="color: #666666">.</span>concatenate((trainPredict,testPredict),axis<span style="color: #666666">=0</span>)
|
|
|
|
trainScore <span style="color: #666666">=</span> model<span style="color: #666666">.</span>evaluate(trainX, trainY, verbose<span style="color: #666666">=0</span>)
|
|
<span style="color: #008000">print</span>(trainScore)
|
|
|
|
index <span style="color: #666666">=</span> df<span style="color: #666666">.</span>index<span style="color: #666666">.</span>values
|
|
plt<span style="color: #666666">.</span>plot(index,df)
|
|
plt<span style="color: #666666">.</span>plot(index,predicted)
|
|
plt<span style="color: #666666">.</span>axvline(df<span style="color: #666666">.</span>index[Tp], c<span style="color: #666666">=</span><span style="color: #BA2121">"r"</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="an-extrapolation-example">An extrapolation example </h2>
|
|
|
|
<p>The following code provides an example of how recurrent neural
|
|
networks can be used to extrapolate to unknown values of physics data
|
|
sets. Specifically, the data sets used in this program come from
|
|
a quantum mechanical many-body calculation of energies as functions of the number of particles.
|
|
</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"># For matrices and calculations</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: #408080; font-style: italic"># For machine learning (backend for keras)</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: #408080; font-style: italic"># User-friendly machine learning library</span>
|
|
<span style="color: #408080; font-style: italic"># Front end for TensorFlow</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras</span>
|
|
<span style="color: #408080; font-style: italic"># Different methods from Keras needed to create an RNN</span>
|
|
<span style="color: #408080; font-style: italic"># This is not necessary but it shortened function calls </span>
|
|
<span style="color: #408080; font-style: italic"># that need to be used in the code.</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras</span> <span style="color: #008000; font-weight: bold">import</span> datasets, layers, models
|
|
<span style="color: #008000; font-weight: bold">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</span> <span style="color: #008000; font-weight: bold">import</span> regularizers
|
|
<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> Model, Sequential
|
|
<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, SimpleRNN, LSTM, GRU
|
|
<span style="color: #408080; font-style: italic"># For timing the code</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">timeit</span> <span style="color: #008000; font-weight: bold">import</span> default_timer <span style="color: #008000; font-weight: bold">as</span> timer
|
|
<span style="color: #408080; font-style: italic"># For plotting</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: #408080; font-style: italic"># The data set</span>
|
|
datatype<span style="color: #666666">=</span><span style="color: #BA2121">'VaryDimension'</span>
|
|
X_tot <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">2</span>, <span style="color: #666666">42</span>, <span style="color: #666666">2</span>)
|
|
y_tot <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">-0.03077640549</span>, <span style="color: #666666">-0.08336233266</span>, <span style="color: #666666">-0.1446729567</span>, <span style="color: #666666">-0.2116753732</span>, <span style="color: #666666">-0.2830637392</span>, <span style="color: #666666">-0.3581341341</span>, <span style="color: #666666">-0.436462435</span>, <span style="color: #666666">-0.5177783846</span>,
|
|
<span style="color: #666666">-0.6019067271</span>, <span style="color: #666666">-0.6887363571</span>, <span style="color: #666666">-0.7782028952</span>, <span style="color: #666666">-0.8702784034</span>, <span style="color: #666666">-0.9649652536</span>, <span style="color: #666666">-1.062292565</span>, <span style="color: #666666">-1.16231451</span>,
|
|
<span style="color: #666666">-1.265109911</span>, <span style="color: #666666">-1.370782966</span>, <span style="color: #666666">-1.479465113</span>, <span style="color: #666666">-1.591317992</span>, <span style="color: #666666">-1.70653767</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="formatting-the-data">Formatting the Data </h2>
|
|
|
|
<p>The way the recurrent neural networks are trained in this program
|
|
differs from how machine learning algorithms are usually trained.
|
|
Typically a machine learning algorithm is trained by learning the
|
|
relationship between the x data and the y data. In this program, the
|
|
recurrent neural network will be trained to recognize the relationship
|
|
in a sequence of y values. This is type of data formatting is
|
|
typically used time series forcasting, but it can also be used in any
|
|
extrapolation (time series forecasting is just a specific type of
|
|
extrapolation along the time axis). This method of data formatting
|
|
does not use the x data and assumes that the y data are evenly spaced.
|
|
</p>
|
|
|
|
<p>For a standard machine learning algorithm, the training data has the
|
|
form of (x,y) so the machine learning algorithm learns to assiciate a
|
|
y value with a given x value. This is useful when the test data has x
|
|
values within the same range as the training data. However, for this
|
|
application, the x values of the test data are outside of the x values
|
|
of the training data and the traditional method of training a machine
|
|
learning algorithm does not work as well. For this reason, the
|
|
recurrent neural network is trained on sequences of y values of the
|
|
form ((y1, y2), y3), so that the network is concerned with learning
|
|
the pattern of the y data and not the relation between the x and y
|
|
data. As long as the pattern of y data outside of the training region
|
|
stays relatively stable compared to what was inside the training
|
|
region, this method of training can produce accurate extrapolations to
|
|
y values far removed from the training data set.
|
|
</p>
|
|
|
|
<!-- -->
|
|
<!-- The idea behind formatting the data in this way comes from [this resource](https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/) and [this one](https://fairyonice.github.io/Understand-Keras%27s-RNN-behind-the-scenes-with-a-sin-wave-example.html). -->
|
|
<!-- -->
|
|
<!-- The following method takes in a y data set and formats it so the "x data" are of the form (y1, y2) and the "y data" are of the form y3, with extra brackets added in to make the resulting arrays compatable with both Keras and Tensorflow. -->
|
|
<!-- -->
|
|
<!-- Note: Using a sequence length of two is not required for time series forecasting so any lenght of sequence could be used (for example instead of ((y1, y2) y3) you could change the length of sequence to be 4 and the resulting data points would have the form ((y1, y2, y3, y4), y5)). While the following method can be used to create a data set of any sequence length, the remainder of the code expects the length of sequence to be 2. This is because the data sets are very small and the higher the lenght of the sequence the less resulting data points. -->
|
|
|
|
|
|
<!-- 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"># FORMAT_DATA</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">format_data</span>(data, length_of_sequence <span style="color: #666666">=</span> <span style="color: #666666">2</span>):
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> data(a numpy array): the data that will be the inputs to the recurrent neural</span>
|
|
<span style="color: #BA2121; font-style: italic"> network</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequence (an int): the number of elements in one iteration of the</span>
|
|
<span style="color: #BA2121; font-style: italic"> sequence patter. For a function approximator use length_of_sequence = 2.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its</span>
|
|
<span style="color: #BA2121; font-style: italic"> dimensions are length of data - length of sequence, length of sequence, </span>
|
|
<span style="color: #BA2121; font-style: italic"> dimnsion of data</span>
|
|
<span style="color: #BA2121; font-style: italic"> rnn_output (a numpy array): the training data for the neural network</span>
|
|
<span style="color: #BA2121; font-style: italic"> Formats data to be used in a recurrent neural network.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
|
|
X, Y <span style="color: #666666">=</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>(data)<span style="color: #666666">-</span>length_of_sequence):
|
|
<span style="color: #408080; font-style: italic"># Get the next length_of_sequence elements</span>
|
|
a <span style="color: #666666">=</span> data[i:i<span style="color: #666666">+</span>length_of_sequence]
|
|
<span style="color: #408080; font-style: italic"># Get the element that immediately follows that</span>
|
|
b <span style="color: #666666">=</span> data[i<span style="color: #666666">+</span>length_of_sequence]
|
|
<span style="color: #408080; font-style: italic"># Reshape so that each data point is contained in its own array</span>
|
|
a <span style="color: #666666">=</span> np<span style="color: #666666">.</span>reshape (a, (<span style="color: #008000">len</span>(a), <span style="color: #666666">1</span>))
|
|
X<span style="color: #666666">.</span>append(a)
|
|
Y<span style="color: #666666">.</span>append(b)
|
|
rnn_input <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array(X)
|
|
rnn_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array(Y)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> rnn_input, rnn_output
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># ## Defining the Recurrent Neural Network Using Keras</span>
|
|
<span style="color: #408080; font-style: italic"># </span>
|
|
<span style="color: #408080; font-style: italic"># The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">rnn</span>(length_of_sequences, batch_size <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>, stateful <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">False</span>):
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequences (an int): the number of y values in "x data". This is determined</span>
|
|
<span style="color: #BA2121; font-style: italic"> when the data is formatted</span>
|
|
<span style="color: #BA2121; font-style: italic"> batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> model (a Keras model): The recurrent neural network that is built and compiled by this</span>
|
|
<span style="color: #BA2121; font-style: italic"> method</span>
|
|
<span style="color: #BA2121; font-style: italic"> Builds and compiles a recurrent neural network with one hidden layer and returns the model.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons in the input and output layers</span>
|
|
in_out_neurons <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons in the hidden layer</span>
|
|
hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">200</span>
|
|
<span style="color: #408080; font-style: italic"># Define the input layer</span>
|
|
inp <span style="color: #666666">=</span> Input(batch_shape<span style="color: #666666">=</span>(batch_size,
|
|
length_of_sequences,
|
|
in_out_neurons))
|
|
<span style="color: #408080; font-style: italic"># Define the hidden layer as a simple RNN layer with a set number of neurons and add it to </span>
|
|
<span style="color: #408080; font-style: italic"># the network immediately after the input layer</span>
|
|
rnn <span style="color: #666666">=</span> SimpleRNN(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN"</span>)(inp)
|
|
<span style="color: #408080; font-style: italic"># Define the output layer as a dense neural network layer (standard neural network layer)</span>
|
|
<span style="color: #408080; font-style: italic">#and add it to the network immediately after the hidden layer.</span>
|
|
dens <span style="color: #666666">=</span> Dense(in_out_neurons,name<span style="color: #666666">=</span><span style="color: #BA2121">"dense"</span>)(rnn)
|
|
<span style="color: #408080; font-style: italic"># Create the machine learning model starting with the input layer and ending with the </span>
|
|
<span style="color: #408080; font-style: italic"># output layer</span>
|
|
model <span style="color: #666666">=</span> Model(inputs<span style="color: #666666">=</span>[inp],outputs<span style="color: #666666">=</span>[dens])
|
|
<span style="color: #408080; font-style: italic"># Compile the machine learning model using the mean squared error function as the loss </span>
|
|
<span style="color: #408080; font-style: italic"># function and an Adams optimizer.</span>
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">"mean_squared_error"</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">"adam"</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>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="predicting-new-points-with-a-trained-recurrent-neural-network">Predicting New Points With A Trained Recurrent Neural Network </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">test_rnn</span> (x1, y_test, plot_min, plot_max):
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> x1 (a list or numpy array): The complete x component of the data set</span>
|
|
<span style="color: #BA2121; font-style: italic"> y_test (a list or numpy array): The complete y component of the data set</span>
|
|
<span style="color: #BA2121; font-style: italic"> plot_min (an int or float): the smallest x value used in the training data</span>
|
|
<span style="color: #BA2121; font-style: italic"> plot_max (an int or float): the largest x valye used in the training data</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> None.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Uses a trained recurrent neural network model to predict future points in the </span>
|
|
<span style="color: #BA2121; font-style: italic"> series. Computes the MSE of the predicted data set from the true data set, saves</span>
|
|
<span style="color: #BA2121; font-style: italic"> the predicted data set to a csv file, and plots the predicted and true data sets w</span>
|
|
<span style="color: #BA2121; font-style: italic"> while also displaying the data range used for training.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Add the training data as the first dim points in the predicted data array as these</span>
|
|
<span style="color: #408080; font-style: italic"># are known values.</span>
|
|
y_pred <span style="color: #666666">=</span> y_test[:dim]<span style="color: #666666">.</span>tolist()
|
|
<span style="color: #408080; font-style: italic"># Generate the first input to the trained recurrent neural network using the last two </span>
|
|
<span style="color: #408080; font-style: italic"># points of the training data. Based on how the network was trained this means that it</span>
|
|
<span style="color: #408080; font-style: italic"># will predict the first point in the data set after the training data. All of the </span>
|
|
<span style="color: #408080; font-style: italic"># brackets are necessary for Tensorflow.</span>
|
|
next_input <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[[y_test[dim<span style="color: #666666">-2</span>]], [y_test[dim<span style="color: #666666">-1</span>]]]])
|
|
<span style="color: #408080; font-style: italic"># Save the very last point in the training data set. This will be used later.</span>
|
|
last <span style="color: #666666">=</span> [y_test[dim<span style="color: #666666">-1</span>]]
|
|
|
|
<span style="color: #408080; font-style: italic"># Iterate until the complete data set is created.</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> (dim, <span style="color: #008000">len</span>(y_test)):
|
|
<span style="color: #408080; font-style: italic"># Predict the next point in the data set using the previous two points.</span>
|
|
<span style="color: #008000">next</span> <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(next_input)
|
|
<span style="color: #408080; font-style: italic"># Append just the number of the predicted data set</span>
|
|
y_pred<span style="color: #666666">.</span>append(<span style="color: #008000">next</span>[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>])
|
|
<span style="color: #408080; font-style: italic"># Create the input that will be used to predict the next data point in the data set.</span>
|
|
next_input <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[last, <span style="color: #008000">next</span>[<span style="color: #666666">0</span>]]], dtype<span style="color: #666666">=</span>np<span style="color: #666666">.</span>float64)
|
|
last <span style="color: #666666">=</span> <span style="color: #008000">next</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Print the mean squared error between the known data set and the predicted data set.</span>
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'MSE: '</span>, np<span style="color: #666666">.</span>square(np<span style="color: #666666">.</span>subtract(y_test, y_pred))<span style="color: #666666">.</span>mean())
|
|
<span style="color: #408080; font-style: italic"># Save the predicted data set as a csv file for later use</span>
|
|
name <span style="color: #666666">=</span> datatype <span style="color: #666666">+</span> <span style="color: #BA2121">'Predicted'</span><span style="color: #666666">+</span><span style="color: #008000">str</span>(dim)<span style="color: #666666">+</span><span style="color: #BA2121">'.csv'</span>
|
|
np<span style="color: #666666">.</span>savetxt(name, y_pred, delimiter<span style="color: #666666">=</span><span style="color: #BA2121">','</span>)
|
|
<span style="color: #408080; font-style: italic"># Plot the known data set and the predicted data set. The red box represents the region that was used</span>
|
|
<span style="color: #408080; font-style: italic"># for the training data.</span>
|
|
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots()
|
|
ax<span style="color: #666666">.</span>plot(x1, y_test, label<span style="color: #666666">=</span><span style="color: #BA2121">"true"</span>, linewidth<span style="color: #666666">=3</span>)
|
|
ax<span style="color: #666666">.</span>plot(x1, y_pred, <span style="color: #BA2121">'g-.'</span>,label<span style="color: #666666">=</span><span style="color: #BA2121">"predicted"</span>, linewidth<span style="color: #666666">=4</span>)
|
|
ax<span style="color: #666666">.</span>legend()
|
|
<span style="color: #408080; font-style: italic"># Created a red region to represent the points used in the training data.</span>
|
|
ax<span style="color: #666666">.</span>axvspan(plot_min, plot_max, alpha<span style="color: #666666">=0.25</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">'red'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Check to make sure the data set is complete</span>
|
|
<span style="color: #008000; font-weight: bold">assert</span> <span style="color: #008000">len</span>(X_tot) <span style="color: #666666">==</span> <span style="color: #008000">len</span>(y_tot)
|
|
|
|
<span style="color: #408080; font-style: italic"># This is the number of points that will be used in as the training data</span>
|
|
dim<span style="color: #666666">=12</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Separate the training data from the whole data set</span>
|
|
X_train <span style="color: #666666">=</span> X_tot[:dim]
|
|
y_train <span style="color: #666666">=</span> y_tot[:dim]
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Generate the training data for the RNN, using a sequence of 2</span>
|
|
rnn_input, rnn_training <span style="color: #666666">=</span> format_data(y_train, <span style="color: #666666">2</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Create a recurrent neural network in Keras and produce a summary of the </span>
|
|
<span style="color: #408080; font-style: italic"># machine learning model</span>
|
|
model <span style="color: #666666">=</span> rnn(length_of_sequences <span style="color: #666666">=</span> rnn_input<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>])
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
<span style="color: #408080; font-style: italic"># Start the timer. Want to time training+testing</span>
|
|
start <span style="color: #666666">=</span> timer()
|
|
<span style="color: #408080; font-style: italic"># Fit the model using the training data genenerated above using 150 training iterations and a 5%</span>
|
|
<span style="color: #408080; font-style: italic"># validation split. Setting verbose to True prints information about each training iteration.</span>
|
|
hist <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(rnn_input, rnn_training, batch_size<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>, epochs<span style="color: #666666">=150</span>,
|
|
verbose<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,validation_split<span style="color: #666666">=0.05</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> label <span style="color: #AA22FF; font-weight: bold">in</span> [<span style="color: #BA2121">"loss"</span>,<span style="color: #BA2121">"val_loss"</span>]:
|
|
plt<span style="color: #666666">.</span>plot(hist<span style="color: #666666">.</span>history[label],label<span style="color: #666666">=</span>label)
|
|
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"loss"</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"epoch"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">"val_loss"</span>][<span style="color: #666666">-1</span>]))
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Use the trained neural network to predict more points of the data set</span>
|
|
test_rnn(X_tot, y_tot, X_tot[<span style="color: #666666">0</span>], X_tot[dim<span style="color: #666666">-1</span>])
|
|
<span style="color: #408080; font-style: italic"># Stop the timer and calculate the total time needed.</span>
|
|
end <span style="color: #666666">=</span> timer()
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Time: '</span>, end<span style="color: #666666">-</span>start)
|
|
</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="other-things-to-try">Other Things to Try </h2>
|
|
|
|
<p>Changing the size of the recurrent neural network and its parameters
|
|
can drastically change the results you get from the model. The below
|
|
code takes the simple recurrent neural network from above and adds a
|
|
second hidden layer, changes the number of neurons in the hidden
|
|
layer, and explicitly declares the activation function of the hidden
|
|
layers to be a sigmoid function. The loss function and optimizer can
|
|
also be changed but are kept the same as the above network. These
|
|
parameters can be tuned to provide the optimal result from the
|
|
network. For some ideas on how to improve the performance of a
|
|
<a href="https://danijar.com/tips-for-training-recurrent-neural-networks" target="_blank">recurrent neural network</a>.
|
|
</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">rnn_2layers</span>(length_of_sequences, batch_size <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>, stateful <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">False</span>):
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequences (an int): the number of y values in "x data". This is determined</span>
|
|
<span style="color: #BA2121; font-style: italic"> when the data is formatted</span>
|
|
<span style="color: #BA2121; font-style: italic"> batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> model (a Keras model): The recurrent neural network that is built and compiled by this</span>
|
|
<span style="color: #BA2121; font-style: italic"> method</span>
|
|
<span style="color: #BA2121; font-style: italic"> Builds and compiles a recurrent neural network with two hidden layers and returns the model.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons in the input and output layers</span>
|
|
in_out_neurons <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons in the hidden layer, increased from the first network</span>
|
|
hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">500</span>
|
|
<span style="color: #408080; font-style: italic"># Define the input layer</span>
|
|
inp <span style="color: #666666">=</span> Input(batch_shape<span style="color: #666666">=</span>(batch_size,
|
|
length_of_sequences,
|
|
in_out_neurons))
|
|
<span style="color: #408080; font-style: italic"># Create two hidden layers instead of one hidden layer. Explicitly set the activation</span>
|
|
<span style="color: #408080; font-style: italic"># function to be the sigmoid function (the default value is hyperbolic tangent)</span>
|
|
rnn1 <span style="color: #666666">=</span> SimpleRNN(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, <span style="color: #408080; font-style: italic"># This needs to be True if another hidden layer is to follow</span>
|
|
stateful <span style="color: #666666">=</span> stateful, activation <span style="color: #666666">=</span> <span style="color: #BA2121">'sigmoid'</span>,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN1"</span>)(inp)
|
|
rnn2 <span style="color: #666666">=</span> SimpleRNN(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>, activation <span style="color: #666666">=</span> <span style="color: #BA2121">'sigmoid'</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN2"</span>)(rnn1)
|
|
<span style="color: #408080; font-style: italic"># Define the output layer as a dense neural network layer (standard neural network layer)</span>
|
|
<span style="color: #408080; font-style: italic">#and add it to the network immediately after the hidden layer.</span>
|
|
dens <span style="color: #666666">=</span> Dense(in_out_neurons,name<span style="color: #666666">=</span><span style="color: #BA2121">"dense"</span>)(rnn2)
|
|
<span style="color: #408080; font-style: italic"># Create the machine learning model starting with the input layer and ending with the </span>
|
|
<span style="color: #408080; font-style: italic"># output layer</span>
|
|
model <span style="color: #666666">=</span> Model(inputs<span style="color: #666666">=</span>[inp],outputs<span style="color: #666666">=</span>[dens])
|
|
<span style="color: #408080; font-style: italic"># Compile the machine learning model using the mean squared error function as the loss </span>
|
|
<span style="color: #408080; font-style: italic"># function and an Adams optimizer.</span>
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">"mean_squared_error"</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">"adam"</span>)
|
|
<span style="color: #008000; font-weight: bold">return</span> model
|
|
|
|
<span style="color: #408080; font-style: italic"># Check to make sure the data set is complete</span>
|
|
<span style="color: #008000; font-weight: bold">assert</span> <span style="color: #008000">len</span>(X_tot) <span style="color: #666666">==</span> <span style="color: #008000">len</span>(y_tot)
|
|
|
|
<span style="color: #408080; font-style: italic"># This is the number of points that will be used in as the training data</span>
|
|
dim<span style="color: #666666">=12</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Separate the training data from the whole data set</span>
|
|
X_train <span style="color: #666666">=</span> X_tot[:dim]
|
|
y_train <span style="color: #666666">=</span> y_tot[:dim]
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Generate the training data for the RNN, using a sequence of 2</span>
|
|
rnn_input, rnn_training <span style="color: #666666">=</span> format_data(y_train, <span style="color: #666666">2</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Create a recurrent neural network in Keras and produce a summary of the </span>
|
|
<span style="color: #408080; font-style: italic"># machine learning model</span>
|
|
model <span style="color: #666666">=</span> rnn_2layers(length_of_sequences <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
<span style="color: #408080; font-style: italic"># Start the timer. Want to time training+testing</span>
|
|
start <span style="color: #666666">=</span> timer()
|
|
<span style="color: #408080; font-style: italic"># Fit the model using the training data genenerated above using 150 training iterations and a 5%</span>
|
|
<span style="color: #408080; font-style: italic"># validation split. Setting verbose to True prints information about each training iteration.</span>
|
|
hist <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(rnn_input, rnn_training, batch_size<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>, epochs<span style="color: #666666">=150</span>,
|
|
verbose<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,validation_split<span style="color: #666666">=0.05</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># This section plots the training loss and the validation loss as a function of training iteration.</span>
|
|
<span style="color: #408080; font-style: italic"># This is not required for analyzing the couple cluster data but can help determine if the network is</span>
|
|
<span style="color: #408080; font-style: italic"># being overtrained.</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> label <span style="color: #AA22FF; font-weight: bold">in</span> [<span style="color: #BA2121">"loss"</span>,<span style="color: #BA2121">"val_loss"</span>]:
|
|
plt<span style="color: #666666">.</span>plot(hist<span style="color: #666666">.</span>history[label],label<span style="color: #666666">=</span>label)
|
|
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"loss"</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"epoch"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">"val_loss"</span>][<span style="color: #666666">-1</span>]))
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Use the trained neural network to predict more points of the data set</span>
|
|
test_rnn(X_tot, y_tot, X_tot[<span style="color: #666666">0</span>], X_tot[dim<span style="color: #666666">-1</span>])
|
|
<span style="color: #408080; font-style: italic"># Stop the timer and calculate the total time needed.</span>
|
|
end <span style="color: #666666">=</span> timer()
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Time: '</span>, end<span style="color: #666666">-</span>start)
|
|
</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="other-types-of-recurrent-neural-networks">Other Types of Recurrent Neural Networks </h2>
|
|
|
|
<p>Besides a simple recurrent neural network layer, there are two other
|
|
commonly used types of recurrent neural network layers: Long Short
|
|
Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short
|
|
introduction to these layers see <a href="https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b" target="_blank"><tt>https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b</tt></a>
|
|
and <a href="https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b" target="_blank"><tt>https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b</tt></a>.
|
|
</p>
|
|
|
|
<p>The first network created below is similar to the previous network,
|
|
but it replaces the SimpleRNN layers with LSTM layers. The second
|
|
network below has two hidden layers made up of GRUs, which are
|
|
preceeded by two dense (feeddorward) neural network layers. These
|
|
dense layers "preprocess" the data before it reaches the recurrent
|
|
layers. This architecture has been shown to improve the performance
|
|
of recurrent neural networks (see the link above and also
|
|
<a href="https://arxiv.org/pdf/1807.02857.pdf" target="_blank"><tt>https://arxiv.org/pdf/1807.02857.pdf</tt></a>.
|
|
</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">lstm_2layers</span>(length_of_sequences, batch_size <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>, stateful <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">False</span>):
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequences (an int): the number of y values in "x data". This is determined</span>
|
|
<span style="color: #BA2121; font-style: italic"> when the data is formatted</span>
|
|
<span style="color: #BA2121; font-style: italic"> batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> model (a Keras model): The recurrent neural network that is built and compiled by this</span>
|
|
<span style="color: #BA2121; font-style: italic"> method</span>
|
|
<span style="color: #BA2121; font-style: italic"> Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons on the input/output layer and the number of neurons in the hidden layer</span>
|
|
in_out_neurons <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">250</span>
|
|
<span style="color: #408080; font-style: italic"># Input Layer</span>
|
|
inp <span style="color: #666666">=</span> Input(batch_shape<span style="color: #666666">=</span>(batch_size,
|
|
length_of_sequences,
|
|
in_out_neurons))
|
|
<span style="color: #408080; font-style: italic"># Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)</span>
|
|
rnn<span style="color: #666666">=</span> LSTM(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN"</span>, use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">'tanh'</span>)(inp)
|
|
rnn1 <span style="color: #666666">=</span> LSTM(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN1"</span>, use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">'tanh'</span>)(rnn)
|
|
<span style="color: #408080; font-style: italic"># Output layer</span>
|
|
dens <span style="color: #666666">=</span> Dense(in_out_neurons,name<span style="color: #666666">=</span><span style="color: #BA2121">"dense"</span>)(rnn1)
|
|
<span style="color: #408080; font-style: italic"># Define the midel</span>
|
|
model <span style="color: #666666">=</span> Model(inputs<span style="color: #666666">=</span>[inp],outputs<span style="color: #666666">=</span>[dens])
|
|
<span style="color: #408080; font-style: italic"># Compile the model</span>
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">'mean_squared_error'</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">'adam'</span>)
|
|
<span style="color: #408080; font-style: italic"># Return the model</span>
|
|
<span style="color: #008000; font-weight: bold">return</span> model
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">dnn2_gru2</span>(length_of_sequences, batch_size <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>, stateful <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">False</span>):
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequences (an int): the number of y values in "x data". This is determined</span>
|
|
<span style="color: #BA2121; font-style: italic"> when the data is formatted</span>
|
|
<span style="color: #BA2121; font-style: italic"> batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> model (a Keras model): The recurrent neural network that is built and compiled by this</span>
|
|
<span style="color: #BA2121; font-style: italic"> method</span>
|
|
<span style="color: #BA2121; font-style: italic"> Builds and compiles a recurrent neural network with four hidden layers (two dense followed by</span>
|
|
<span style="color: #BA2121; font-style: italic"> two GRU layers) and returns the model.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons on the input/output layers and hidden layers</span>
|
|
in_out_neurons <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">250</span>
|
|
<span style="color: #408080; font-style: italic"># Input layer</span>
|
|
inp <span style="color: #666666">=</span> Input(batch_shape<span style="color: #666666">=</span>(batch_size,
|
|
length_of_sequences,
|
|
in_out_neurons))
|
|
<span style="color: #408080; font-style: italic"># Hidden Dense (feedforward) layers</span>
|
|
dnn <span style="color: #666666">=</span> Dense(hidden_neurons<span style="color: #666666">/2</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">'relu'</span>, name<span style="color: #666666">=</span><span style="color: #BA2121">'dnn'</span>)(inp)
|
|
dnn1 <span style="color: #666666">=</span> Dense(hidden_neurons<span style="color: #666666">/2</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">'relu'</span>, name<span style="color: #666666">=</span><span style="color: #BA2121">'dnn1'</span>)(dnn)
|
|
<span style="color: #408080; font-style: italic"># Hidden GRU layers</span>
|
|
rnn1 <span style="color: #666666">=</span> GRU(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN1"</span>, use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)(dnn1)
|
|
rnn <span style="color: #666666">=</span> GRU(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN"</span>, use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)(rnn1)
|
|
<span style="color: #408080; font-style: italic"># Output layer</span>
|
|
dens <span style="color: #666666">=</span> Dense(in_out_neurons,name<span style="color: #666666">=</span><span style="color: #BA2121">"dense"</span>)(rnn)
|
|
<span style="color: #408080; font-style: italic"># Define the model</span>
|
|
model <span style="color: #666666">=</span> Model(inputs<span style="color: #666666">=</span>[inp],outputs<span style="color: #666666">=</span>[dens])
|
|
<span style="color: #408080; font-style: italic"># Compile the mdoel</span>
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">'mean_squared_error'</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">'adam'</span>)
|
|
<span style="color: #408080; font-style: italic"># Return the model</span>
|
|
<span style="color: #008000; font-weight: bold">return</span> model
|
|
|
|
<span style="color: #408080; font-style: italic"># Check to make sure the data set is complete</span>
|
|
<span style="color: #008000; font-weight: bold">assert</span> <span style="color: #008000">len</span>(X_tot) <span style="color: #666666">==</span> <span style="color: #008000">len</span>(y_tot)
|
|
|
|
<span style="color: #408080; font-style: italic"># This is the number of points that will be used in as the training data</span>
|
|
dim<span style="color: #666666">=12</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Separate the training data from the whole data set</span>
|
|
X_train <span style="color: #666666">=</span> X_tot[:dim]
|
|
y_train <span style="color: #666666">=</span> y_tot[:dim]
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Generate the training data for the RNN, using a sequence of 2</span>
|
|
rnn_input, rnn_training <span style="color: #666666">=</span> format_data(y_train, <span style="color: #666666">2</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Create a recurrent neural network in Keras and produce a summary of the </span>
|
|
<span style="color: #408080; font-style: italic"># machine learning model</span>
|
|
<span style="color: #408080; font-style: italic"># Change the method name to reflect which network you want to use</span>
|
|
model <span style="color: #666666">=</span> dnn2_gru2(length_of_sequences <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
<span style="color: #408080; font-style: italic"># Start the timer. Want to time training+testing</span>
|
|
start <span style="color: #666666">=</span> timer()
|
|
<span style="color: #408080; font-style: italic"># Fit the model using the training data genenerated above using 150 training iterations and a 5%</span>
|
|
<span style="color: #408080; font-style: italic"># validation split. Setting verbose to True prints information about each training iteration.</span>
|
|
hist <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(rnn_input, rnn_training, batch_size<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>, epochs<span style="color: #666666">=150</span>,
|
|
verbose<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,validation_split<span style="color: #666666">=0.05</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># This section plots the training loss and the validation loss as a function of training iteration.</span>
|
|
<span style="color: #408080; font-style: italic"># This is not required for analyzing the couple cluster data but can help determine if the network is</span>
|
|
<span style="color: #408080; font-style: italic"># being overtrained.</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> label <span style="color: #AA22FF; font-weight: bold">in</span> [<span style="color: #BA2121">"loss"</span>,<span style="color: #BA2121">"val_loss"</span>]:
|
|
plt<span style="color: #666666">.</span>plot(hist<span style="color: #666666">.</span>history[label],label<span style="color: #666666">=</span>label)
|
|
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"loss"</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"epoch"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">"val_loss"</span>][<span style="color: #666666">-1</span>]))
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Use the trained neural network to predict more points of the data set</span>
|
|
test_rnn(X_tot, y_tot, X_tot[<span style="color: #666666">0</span>], X_tot[dim<span style="color: #666666">-1</span>])
|
|
<span style="color: #408080; font-style: italic"># Stop the timer and calculate the total time needed.</span>
|
|
end <span style="color: #666666">=</span> timer()
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Time: '</span>, end<span style="color: #666666">-</span>start)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)</span>
|
|
<span style="color: #408080; font-style: italic"># </span>
|
|
<span style="color: #408080; font-style: italic"># Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Check to make sure the data set is complete</span>
|
|
<span style="color: #008000; font-weight: bold">assert</span> <span style="color: #008000">len</span>(X_tot) <span style="color: #666666">==</span> <span style="color: #008000">len</span>(y_tot)
|
|
|
|
<span style="color: #408080; font-style: italic"># This is the number of points that will be used in as the training data</span>
|
|
dim<span style="color: #666666">=12</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Separate the training data from the whole data set</span>
|
|
X_train <span style="color: #666666">=</span> X_tot[:dim]
|
|
y_train <span style="color: #666666">=</span> y_tot[:dim]
|
|
|
|
<span style="color: #408080; font-style: italic"># Reshape the data for Keras specifications</span>
|
|
X_train <span style="color: #666666">=</span> X_train<span style="color: #666666">.</span>reshape((dim, <span style="color: #666666">1</span>))
|
|
y_train <span style="color: #666666">=</span> y_train<span style="color: #666666">.</span>reshape((dim, <span style="color: #666666">1</span>))
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Create a recurrent neural network in Keras and produce a summary of the </span>
|
|
<span style="color: #408080; font-style: italic"># machine learning model</span>
|
|
<span style="color: #408080; font-style: italic"># Set the sequence length to 1 for regular data formatting </span>
|
|
model <span style="color: #666666">=</span> rnn(length_of_sequences <span style="color: #666666">=</span> <span style="color: #666666">1</span>)
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
<span style="color: #408080; font-style: italic"># Start the timer. Want to time training+testing</span>
|
|
start <span style="color: #666666">=</span> timer()
|
|
<span style="color: #408080; font-style: italic"># Fit the model using the training data genenerated above using 150 training iterations and a 5%</span>
|
|
<span style="color: #408080; font-style: italic"># validation split. Setting verbose to True prints information about each training iteration.</span>
|
|
hist <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(X_train, y_train, batch_size<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>, epochs<span style="color: #666666">=150</span>,
|
|
verbose<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,validation_split<span style="color: #666666">=0.05</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># This section plots the training loss and the validation loss as a function of training iteration.</span>
|
|
<span style="color: #408080; font-style: italic"># This is not required for analyzing the couple cluster data but can help determine if the network is</span>
|
|
<span style="color: #408080; font-style: italic"># being overtrained.</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> label <span style="color: #AA22FF; font-weight: bold">in</span> [<span style="color: #BA2121">"loss"</span>,<span style="color: #BA2121">"val_loss"</span>]:
|
|
plt<span style="color: #666666">.</span>plot(hist<span style="color: #666666">.</span>history[label],label<span style="color: #666666">=</span>label)
|
|
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"loss"</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"epoch"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">"val_loss"</span>][<span style="color: #666666">-1</span>]))
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Use the trained neural network to predict the remaining data points</span>
|
|
X_pred <span style="color: #666666">=</span> X_tot[dim:]
|
|
X_pred <span style="color: #666666">=</span> X_pred<span style="color: #666666">.</span>reshape((<span style="color: #008000">len</span>(X_pred), <span style="color: #666666">1</span>))
|
|
y_model <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(X_pred)
|
|
y_pred <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((y_tot[:dim], y_model<span style="color: #666666">.</span>flatten()))
|
|
|
|
<span style="color: #408080; font-style: italic"># Plot the known data set and the predicted data set. The red box represents the region that was used</span>
|
|
<span style="color: #408080; font-style: italic"># for the training data.</span>
|
|
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots()
|
|
ax<span style="color: #666666">.</span>plot(X_tot, y_tot, label<span style="color: #666666">=</span><span style="color: #BA2121">"true"</span>, linewidth<span style="color: #666666">=3</span>)
|
|
ax<span style="color: #666666">.</span>plot(X_tot, y_pred, <span style="color: #BA2121">'g-.'</span>,label<span style="color: #666666">=</span><span style="color: #BA2121">"predicted"</span>, linewidth<span style="color: #666666">=4</span>)
|
|
ax<span style="color: #666666">.</span>legend()
|
|
<span style="color: #408080; font-style: italic"># Created a red region to represent the points used in the training data.</span>
|
|
ax<span style="color: #666666">.</span>axvspan(X_tot[<span style="color: #666666">0</span>], X_tot[dim], alpha<span style="color: #666666">=0.25</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">'red'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Stop the timer and calculate the total time needed.</span>
|
|
end <span style="color: #666666">=</span> timer()
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Time: '</span>, end<span style="color: #666666">-</span>start)
|
|
</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="generative-models">Generative Models </h2>
|
|
|
|
<p><b>Generative models</b> describe a class of statistical models that are a contrast
|
|
to <b>discriminative models</b>. Informally we say that generative models can
|
|
generate new data instances while discriminative models discriminate between
|
|
different kinds of data instances. A generative model could generate new photos
|
|
of animals that look like 'real' animals while a discriminative model could tell
|
|
a dog from a cat. More formally, given a data set \( x \) and a set of labels /
|
|
targets \( y \). Generative models capture the joint probability \( p(x, y) \), or
|
|
just \( p(x) \) if there are no labels, while discriminative models capture the
|
|
conditional probability \( p(y | x) \). Discriminative models generally try to draw
|
|
boundaries in the data space (often high dimensional), while generative models
|
|
try to model how data is placed throughout the space.
|
|
</p>
|
|
|
|
<p><b>Note</b>: this material is thanks to Linus Ekstrøm. </p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="generative-adversarial-networks">Generative Adversarial Networks </h2>
|
|
|
|
<p><b>Generative Adversarial Networks</b> are a type of unsupervised machine learning
|
|
algorithm proposed by <a href="https://arxiv.org/pdf/1406.2661.pdf" target="_blank">Goodfellow et. al</a>
|
|
in 2014 (short and good article).
|
|
</p>
|
|
|
|
<p>The simplest formulation of
|
|
the model is based on a game theoretic approach, <em>zero sum game</em>, where we pit
|
|
two neural networks against one another. We define two rival networks, one
|
|
generator \( g \), and one discriminator \( d \). The generator directly produces
|
|
samples
|
|
</p>
|
|
$$
|
|
\begin{equation}
|
|
x = g(z; \theta^{(g)})
|
|
\label{_auto1}
|
|
\end{equation}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="discriminator">Discriminator </h2>
|
|
<p>The discriminator attempts to distinguish between samples drawn from the
|
|
training data and samples drawn from the generator. In other words, it tries to
|
|
tell the difference between the fake data produced by \( g \) and the actual data
|
|
samples we want to do prediction on. The discriminator outputs a probability
|
|
value given by
|
|
</p>
|
|
|
|
$$
|
|
\begin{equation}
|
|
d(x; \theta^{(d)})
|
|
\label{_auto2}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>indicating the probability that \( x \) is a real training example rather than a
|
|
fake sample the generator has generated. The simplest way to formulate the
|
|
learning process in a generative adversarial network is a zero-sum game, in
|
|
which a function
|
|
</p>
|
|
|
|
$$
|
|
\begin{equation}
|
|
v(\theta^{(g)}, \theta^{(d)})
|
|
\label{_auto3}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>determines the reward for the discriminator, while the generator gets the
|
|
conjugate reward
|
|
</p>
|
|
|
|
$$
|
|
\begin{equation}
|
|
-v(\theta^{(g)}, \theta^{(d)})
|
|
\label{_auto4}
|
|
\end{equation}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="learning-process">Learning Process </h2>
|
|
|
|
<p>During learning both of the networks maximize their own reward function, so that
|
|
the generator gets better and better at tricking the discriminator, while the
|
|
discriminator gets better and better at telling the difference between the fake
|
|
and real data. The generator and discriminator alternate on which one trains at
|
|
one time (i.e. for one epoch). In other words, we keep the generator constant
|
|
and train the discriminator, then we keep the discriminator constant to train
|
|
the generator and repeat. It is this back and forth dynamic which lets GANs
|
|
tackle otherwise intractable generative problems. As the generator improves with
|
|
training, the discriminator's performance gets worse because it cannot easily
|
|
tell the difference between real and fake. If the generator ends up succeeding
|
|
perfectly, the the discriminator will do no better than random guessing i.e.
|
|
50\%. This progression in the training poses a problem for the convergence
|
|
criteria for GANs. The discriminator feedback gets less meaningful over time,
|
|
if we continue training after this point then the generator is effectively
|
|
training on junk data which can undo the learning up to that point. Therefore,
|
|
we stop training when the discriminator starts outputting \( 1/2 \) everywhere.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="more-about-the-learning-process">More about the Learning Process </h2>
|
|
|
|
<p>At convergence we have</p>
|
|
|
|
$$
|
|
\begin{equation}
|
|
g^* = \underset{g}{\mathrm{argmin}}\hspace{2pt}
|
|
\underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)})
|
|
\label{_auto5}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>The default choice for \( v \) is</p>
|
|
$$
|
|
\begin{equation}
|
|
v(\theta^{(g)}, \theta^{(d)}) = \mathbb{E}_{x\sim p_\mathrm{data}}\log d(x)
|
|
+ \mathbb{E}_{x\sim p_\mathrm{model}}
|
|
\log (1 - d(x))
|
|
\label{_auto6}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>The main motivation for the design of GANs is that the learning process requires
|
|
neither approximate inference (variational autoencoders for example) nor
|
|
approximation of a partition function. In the case where
|
|
</p>
|
|
$$
|
|
\begin{equation}
|
|
\underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)})
|
|
\label{_auto7}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is
|
|
asymptotically consistent
|
|
( <a href="https://arxiv.org/pdf/1804.09139.pdf" target="_blank">Seth Lloyd on QuGANs</a> ).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="additional-references">Additional References </h2>
|
|
<p>This is in
|
|
general not the case and it is possible to get situations where the training
|
|
process never converges because the generator and discriminator chase one
|
|
another around in the parameter space indefinitely. A much deeper discussion on
|
|
the currently open research problem of GAN convergence is available
|
|
<a href="https://www.deeplearningbook.org/contents/generative_models.html" target="_blank">here</a>. To
|
|
anyone interested in learning more about GANs it is a highly recommended read.
|
|
Direct quote: "In this best-performing formulation, the generator aims to
|
|
increase the log probability that the discriminator makes a mistake, rather than
|
|
aiming to decrease the log probability that the discriminator makes the correct
|
|
prediction." <a href="https://arxiv.org/abs/1701.00160" target="_blank">Another interesting read</a>
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="writing-our-first-generative-adversarial-network">Writing Our First Generative Adversarial Network </h2>
|
|
<p>Let us now move on to actually implementing a GAN in tensorflow. We will study
|
|
the performance of our GAN on the MNIST dataset. This code is based on and
|
|
adapted from the
|
|
<a href="https://www.tensorflow.org/tutorials/generative/dcgan" target="_blank">google tutorial</a>
|
|
</p>
|
|
|
|
<p>First we import our libraries</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">os</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">time</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">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">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">tensorflow.keras</span> <span style="color: #008000; font-weight: bold">import</span> layers
|
|
<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> plot_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>
|
|
</div>
|
|
|
|
<p>Next we define our hyperparameters and import our data the usual way</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%;">BUFFER_SIZE <span style="color: #666666">=</span> <span style="color: #666666">60000</span>
|
|
BATCH_SIZE <span style="color: #666666">=</span> <span style="color: #666666">256</span>
|
|
EPOCHS <span style="color: #666666">=</span> <span style="color: #666666">30</span>
|
|
|
|
data <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>keras<span style="color: #666666">.</span>datasets<span style="color: #666666">.</span>mnist<span style="color: #666666">.</span>load_data()
|
|
(train_images, train_labels), (test_images, test_labels) <span style="color: #666666">=</span> data
|
|
train_images <span style="color: #666666">=</span> np<span style="color: #666666">.</span>reshape(train_images, (train_images<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>],
|
|
<span style="color: #666666">28</span>,
|
|
<span style="color: #666666">28</span>,
|
|
<span style="color: #666666">1</span>))<span style="color: #666666">.</span>astype(<span style="color: #BA2121">'float32'</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># we normalize between -1 and 1</span>
|
|
train_images <span style="color: #666666">=</span> (train_images <span style="color: #666666">-</span> <span style="color: #666666">127.5</span>) <span style="color: #666666">/</span> <span style="color: #666666">127.5</span>
|
|
training_dataset <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>data<span style="color: #666666">.</span>Dataset<span style="color: #666666">.</span>from_tensor_slices(
|
|
train_images)<span style="color: #666666">.</span>shuffle(BUFFER_SIZE)<span style="color: #666666">.</span>batch(BATCH_SIZE)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="mnist-and-gans">MNIST and GANs </h2>
|
|
|
|
<p>Let's have a quick look</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%;">plt<span style="color: #666666">.</span>imshow(train_images[<span style="color: #666666">0</span>], cmap<span style="color: #666666">=</span><span style="color: #BA2121">'Greys'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<p>Now we define our two models. This is where the 'magic' happens. There are a
|
|
huge amount of possible formulations for both models. A lot of engineering and
|
|
trial and error can be done here to try to produce better performing models. For
|
|
more advanced GANs this is by far the step where you can 'make or break' a
|
|
model.
|
|
</p>
|
|
|
|
<p>We start with the generator. As stated in the introductory text the generator
|
|
\( g \) upsamples from a random sample to the shape of what we want to predict. In
|
|
our case we are trying to predict MNIST images (\( 28\times 28 \) pixels).
|
|
</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">generator_model</span>():
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to</span>
|
|
<span style="color: #BA2121; font-style: italic"> produce an image from a random seed. We start with a Dense layer taking this</span>
|
|
<span style="color: #BA2121; font-style: italic"> random sample as an input and subsequently upsample through multiple</span>
|
|
<span style="color: #BA2121; font-style: italic"> convolutional layers.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># we define our model</span>
|
|
model <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>keras<span style="color: #666666">.</span>Sequential()
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># adding our input layer. Dense means that every neuron is connected and</span>
|
|
<span style="color: #408080; font-style: italic"># the input shape is the shape of our random noise. The units need to match</span>
|
|
<span style="color: #408080; font-style: italic"># in some sense the upsampling strides to reach our desired output shape.</span>
|
|
<span style="color: #408080; font-style: italic"># we are using 100 random numbers as our seed</span>
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dense(units<span style="color: #666666">=7*7*</span>BATCH_SIZE,
|
|
use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,
|
|
input_shape<span style="color: #666666">=</span>(<span style="color: #666666">100</span>, )))
|
|
<span style="color: #408080; font-style: italic"># we normalize the output form the Dense layer</span>
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>BatchNormalization())
|
|
<span style="color: #408080; font-style: italic"># and add an activation function to our 'layer'. LeakyReLU avoids vanishing</span>
|
|
<span style="color: #408080; font-style: italic"># gradient problem</span>
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>LeakyReLU())
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Reshape((<span style="color: #666666">7</span>, <span style="color: #666666">7</span>, BATCH_SIZE)))
|
|
<span style="color: #008000; font-weight: bold">assert</span> model<span style="color: #666666">.</span>output_shape <span style="color: #666666">==</span> (<span style="color: #008000; font-weight: bold">None</span>, <span style="color: #666666">7</span>, <span style="color: #666666">7</span>, BATCH_SIZE)
|
|
<span style="color: #408080; font-style: italic"># even though we just added four keras layers we think of everything above</span>
|
|
<span style="color: #408080; font-style: italic"># as 'one' layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># next we add our upscaling convolutional layers</span>
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2DTranspose(filters<span style="color: #666666">=128</span>,
|
|
kernel_size<span style="color: #666666">=</span>(<span style="color: #666666">5</span>, <span style="color: #666666">5</span>),
|
|
strides<span style="color: #666666">=</span>(<span style="color: #666666">1</span>, <span style="color: #666666">1</span>),
|
|
padding<span style="color: #666666">=</span><span style="color: #BA2121">'same'</span>,
|
|
use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>))
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>BatchNormalization())
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>LeakyReLU())
|
|
<span style="color: #008000; font-weight: bold">assert</span> model<span style="color: #666666">.</span>output_shape <span style="color: #666666">==</span> (<span style="color: #008000; font-weight: bold">None</span>, <span style="color: #666666">7</span>, <span style="color: #666666">7</span>, <span style="color: #666666">128</span>)
|
|
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2DTranspose(filters<span style="color: #666666">=64</span>,
|
|
kernel_size<span style="color: #666666">=</span>(<span style="color: #666666">5</span>, <span style="color: #666666">5</span>),
|
|
strides<span style="color: #666666">=</span>(<span style="color: #666666">2</span>, <span style="color: #666666">2</span>),
|
|
padding<span style="color: #666666">=</span><span style="color: #BA2121">'same'</span>,
|
|
use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>))
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>BatchNormalization())
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>LeakyReLU())
|
|
<span style="color: #008000; font-weight: bold">assert</span> model<span style="color: #666666">.</span>output_shape <span style="color: #666666">==</span> (<span style="color: #008000; font-weight: bold">None</span>, <span style="color: #666666">14</span>, <span style="color: #666666">14</span>, <span style="color: #666666">64</span>)
|
|
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2DTranspose(filters<span style="color: #666666">=1</span>,
|
|
kernel_size<span style="color: #666666">=</span>(<span style="color: #666666">5</span>, <span style="color: #666666">5</span>),
|
|
strides<span style="color: #666666">=</span>(<span style="color: #666666">2</span>, <span style="color: #666666">2</span>),
|
|
padding<span style="color: #666666">=</span><span style="color: #BA2121">'same'</span>,
|
|
use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,
|
|
activation<span style="color: #666666">=</span><span style="color: #BA2121">'tanh'</span>))
|
|
<span style="color: #008000; font-weight: bold">assert</span> model<span style="color: #666666">.</span>output_shape <span style="color: #666666">==</span> (<span style="color: #008000; font-weight: bold">None</span>, <span style="color: #666666">28</span>, <span style="color: #666666">28</span>, <span style="color: #666666">1</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>
|
|
</div>
|
|
|
|
<p>And there we have our 'simple' generator model. Now we move on to defining our
|
|
discriminator model \( d \), which is a convolutional neural network based image
|
|
classifier.
|
|
</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">discriminator_model</span>():
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> The discriminator is a convolutional neural network based image classifier</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># we define our model</span>
|
|
model <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>keras<span style="color: #666666">.</span>Sequential()
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(filters<span style="color: #666666">=64</span>,
|
|
kernel_size<span style="color: #666666">=</span>(<span style="color: #666666">5</span>, <span style="color: #666666">5</span>),
|
|
strides<span style="color: #666666">=</span>(<span style="color: #666666">2</span>, <span style="color: #666666">2</span>),
|
|
padding<span style="color: #666666">=</span><span style="color: #BA2121">'same'</span>,
|
|
input_shape<span style="color: #666666">=</span>[<span style="color: #666666">28</span>, <span style="color: #666666">28</span>, <span style="color: #666666">1</span>]))
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>LeakyReLU())
|
|
<span style="color: #408080; font-style: italic"># adding a dropout layer as you do in conv-nets</span>
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dropout(<span style="color: #666666">0.3</span>))
|
|
|
|
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(filters<span style="color: #666666">=128</span>,
|
|
kernel_size<span style="color: #666666">=</span>(<span style="color: #666666">5</span>, <span style="color: #666666">5</span>),
|
|
strides<span style="color: #666666">=</span>(<span style="color: #666666">2</span>, <span style="color: #666666">2</span>),
|
|
padding<span style="color: #666666">=</span><span style="color: #BA2121">'same'</span>))
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>LeakyReLU())
|
|
<span style="color: #408080; font-style: italic"># adding a dropout layer as you do in conv-nets</span>
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dropout(<span style="color: #666666">0.3</span>))
|
|
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Flatten())
|
|
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dense(<span style="color: #666666">1</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>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="other-models">Other Models </h2>
|
|
<p>Let us take a look at our models. <b>Note</b>: double click images for bigger view.</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%;">generator <span style="color: #666666">=</span> generator_model()
|
|
plot_model(generator, show_shapes<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, rankdir<span style="color: #666666">=</span><span style="color: #BA2121">'LR'</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%;">discriminator <span style="color: #666666">=</span> discriminator_model()
|
|
plot_model(discriminator, show_shapes<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, rankdir<span style="color: #666666">=</span><span style="color: #BA2121">'LR'</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>Next we need a few helper objects we will use in training</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%;">cross_entropy <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>keras<span style="color: #666666">.</span>losses<span style="color: #666666">.</span>BinaryCrossentropy(from_logits<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
generator_optimizer <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>keras<span style="color: #666666">.</span>optimizers<span style="color: #666666">.</span>Adam(<span style="color: #666666">1e-4</span>)
|
|
discriminator_optimizer <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>keras<span style="color: #666666">.</span>optimizers<span style="color: #666666">.</span>Adam(<span style="color: #666666">1e-4</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>The first object, <em>cross_entropy</em> is our loss function and the two others are
|
|
our optimizers. Notice we use the same learning rate for both \( g \) and \( d \). This
|
|
is because they need to improve their accuracy at approximately equal speeds to
|
|
get convergence (not necessarily exactly equal). Now we define our loss
|
|
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%;"><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">generator_loss</span>(fake_output):
|
|
loss <span style="color: #666666">=</span> cross_entropy(tf<span style="color: #666666">.</span>ones_like(fake_output), fake_output)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> loss
|
|
</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">def</span> <span style="color: #0000FF">discriminator_loss</span>(real_output, fake_output):
|
|
real_loss <span style="color: #666666">=</span> cross_entropy(tf<span style="color: #666666">.</span>ones_like(real_output), real_output)
|
|
fake_loss <span style="color: #666666">=</span> cross_entropy(tf<span style="color: #666666">.</span>zeros_liks(fake_output), fake_output)
|
|
total_loss <span style="color: #666666">=</span> real_loss <span style="color: #666666">+</span> fake_loss
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> total_loss
|
|
</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>Next we define a kind of seed to help us compare the learning process over
|
|
multiple training epochs.
|
|
</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%;">noise_dimension <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
n_examples_to_generate <span style="color: #666666">=</span> <span style="color: #666666">16</span>
|
|
seed_images <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal([n_examples_to_generate, noise_dimension])
|
|
</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="training-step">Training Step </h2>
|
|
|
|
<p>Now we have everything we need to define our training step, which we will apply
|
|
for every step in our training loop. Notice the @tf.function flag signifying
|
|
that the function is tensorflow 'compiled'. Removing this flag doubles the
|
|
computation time.
|
|
</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: #AA22FF">@tf</span><span style="color: #666666">.</span>function
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">train_step</span>(images):
|
|
noise <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal([BATCH_SIZE, noise_dimension])
|
|
|
|
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>GradientTape() <span style="color: #008000; font-weight: bold">as</span> gen_tape, tf<span style="color: #666666">.</span>GradientTape() <span style="color: #008000; font-weight: bold">as</span> disc_tape:
|
|
generated_images <span style="color: #666666">=</span> generator(noise, training<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
|
|
real_output <span style="color: #666666">=</span> discriminator(images, training<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
fake_output <span style="color: #666666">=</span> discriminator(generated_images, training<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
|
|
gen_loss <span style="color: #666666">=</span> generator_loss(fake_output)
|
|
disc_loss <span style="color: #666666">=</span> discriminator_loss(real_output, fake_output)
|
|
|
|
gradients_of_generator <span style="color: #666666">=</span> gen_tape<span style="color: #666666">.</span>gradient(gen_loss,
|
|
generator<span style="color: #666666">.</span>trainable_variables)
|
|
gradients_of_discriminator <span style="color: #666666">=</span> disc_tape<span style="color: #666666">.</span>gradient(disc_loss,
|
|
discriminator<span style="color: #666666">.</span>trainable_variables)
|
|
generator_optimizer<span style="color: #666666">.</span>apply_gradients(<span style="color: #008000">zip</span>(gradients_of_generator,
|
|
generator<span style="color: #666666">.</span>trainable_variables))
|
|
discriminator_optimizer<span style="color: #666666">.</span>apply_gradients(<span style="color: #008000">zip</span>(gradients_of_discriminator,
|
|
discriminator<span style="color: #666666">.</span>trainable_variables))
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> gen_loss, disc_loss
|
|
</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>Next we define a helper function to produce an output over our training epochs
|
|
to see the predictive progression of our generator model. <b>Note</b>: I am including
|
|
this code here, but comment it out in the training loop.
|
|
</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">generate_and_save_images</span>(model, epoch, test_input):
|
|
<span style="color: #408080; font-style: italic"># we're making inferences here</span>
|
|
predictions <span style="color: #666666">=</span> model(test_input, training<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">4</span>, <span style="color: #666666">4</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>(predictions<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>]):
|
|
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">4</span>, <span style="color: #666666">4</span>, i<span style="color: #666666">+1</span>)
|
|
plt<span style="color: #666666">.</span>imshow(predictions[i, :, :, <span style="color: #666666">0</span>] <span style="color: #666666">*</span> <span style="color: #666666">127.5</span> <span style="color: #666666">+</span> <span style="color: #666666">127.5</span>, cmap<span style="color: #666666">=</span><span style="color: #BA2121">'gray'</span>)
|
|
plt<span style="color: #666666">.</span>axis(<span style="color: #BA2121">'off'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">f'./images_from_seed_images/image_at_epoch_</span><span style="color: #BB6688; font-weight: bold">{</span><span style="color: #008000">str</span>(epoch)<span style="color: #666666">.</span>zfill(<span style="color: #666666">3</span>)<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">.png'</span>)
|
|
plt<span style="color: #666666">.</span>close()
|
|
<span style="color: #408080; font-style: italic">#plt.show()</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="checkpoints">Checkpoints </h2>
|
|
<p>Setting up checkpoints to periodically save our model during training so that
|
|
everything is not lost even if the program were to somehow terminate while
|
|
training.
|
|
</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"># Setting up checkpoints to save model during training</span>
|
|
checkpoint_dir <span style="color: #666666">=</span> <span style="color: #BA2121">'./training_checkpoints'</span>
|
|
checkpoint_prefix <span style="color: #666666">=</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(checkpoint_dir, <span style="color: #BA2121">'ckpt'</span>)
|
|
checkpoint <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>train<span style="color: #666666">.</span>Checkpoint(generator_optimizer<span style="color: #666666">=</span>generator_optimizer,
|
|
discriminator_optimizer<span style="color: #666666">=</span>discriminator_optimizer,
|
|
generator<span style="color: #666666">=</span>generator,
|
|
discriminator<span style="color: #666666">=</span>discriminator)
|
|
</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 we define our training loop</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">train</span>(dataset, epochs):
|
|
generator_loss_list <span style="color: #666666">=</span> []
|
|
discriminator_loss_list <span style="color: #666666">=</span> []
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> epoch <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(epochs):
|
|
start <span style="color: #666666">=</span> time<span style="color: #666666">.</span>time()
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> image_batch <span style="color: #AA22FF; font-weight: bold">in</span> dataset:
|
|
gen_loss, disc_loss <span style="color: #666666">=</span> train_step(image_batch)
|
|
generator_loss_list<span style="color: #666666">.</span>append(gen_loss<span style="color: #666666">.</span>numpy())
|
|
discriminator_loss_list<span style="color: #666666">.</span>append(disc_loss<span style="color: #666666">.</span>numpy())
|
|
|
|
<span style="color: #408080; font-style: italic">#generate_and_save_images(generator, epoch + 1, seed_images)</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> (epoch <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #666666">%</span> <span style="color: #666666">15</span> <span style="color: #666666">==</span> <span style="color: #666666">0</span>:
|
|
checkpoint<span style="color: #666666">.</span>save(file_prefix<span style="color: #666666">=</span>checkpoint_prefix)
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f'Time for epoch </span><span style="color: #BB6688; font-weight: bold">{</span>epoch<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> is </span><span style="color: #BB6688; font-weight: bold">{</span>time<span style="color: #666666">.</span>time() <span style="color: #666666">-</span> start<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">'</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">#generate_and_save_images(generator, epochs, seed_images)</span>
|
|
|
|
loss_file <span style="color: #666666">=</span> <span style="color: #BA2121">'./data/lossfile.txt'</span>
|
|
<span style="color: #008000; font-weight: bold">with</span> <span style="color: #008000">open</span>(loss_file, <span style="color: #BA2121">'w'</span>) <span style="color: #008000; font-weight: bold">as</span> outfile:
|
|
outfile<span style="color: #666666">.</span>write(<span style="color: #008000">str</span>(generator_loss_list))
|
|
outfile<span style="color: #666666">.</span>write(<span style="color: #BA2121">'</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">'</span>)
|
|
outfile<span style="color: #666666">.</span>write(<span style="color: #BA2121">'</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">'</span>)
|
|
outfile<span style="color: #666666">.</span>write(<span style="color: #008000">str</span>(discriminator_loss_list))
|
|
outfile<span style="color: #666666">.</span>write(<span style="color: #BA2121">'</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">'</span>)
|
|
outfile<span style="color: #666666">.</span>write(<span style="color: #BA2121">'</span><span style="color: #BB6622; font-weight: bold">\n</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>To train simply call this function. <b>Warning</b>: this might take a long time so
|
|
there is a folder of a pretrained network already included in the repository.
|
|
</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%;">train(train_dataset, EPOCHS)
|
|
</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 here is the result of training our model for 100 epochs</p>
|
|
|
|
<embed src="images_from_seed_images/generation.gif" autoplay="false" loop="true"></embed>
|
|
<p><em></em></p>
|
|
|
|
<p>Now to avoid having to train and everything, which will take a while depending
|
|
on your computer setup we now load in the model which produced the above gif.
|
|
</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%;">checkpoint<span style="color: #666666">.</span>restore(tf<span style="color: #666666">.</span>train<span style="color: #666666">.</span>latest_checkpoint(checkpoint_dir))
|
|
restored_generator <span style="color: #666666">=</span> checkpoint<span style="color: #666666">.</span>generator
|
|
restored_discriminator <span style="color: #666666">=</span> checkpoint<span style="color: #666666">.</span>discriminator
|
|
|
|
<span style="color: #008000">print</span>(restored_generator)
|
|
<span style="color: #008000">print</span>(restored_discriminator)
|
|
</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="exploring-the-latent-space">Exploring the Latent Space </h2>
|
|
|
|
<p>We have successfully loaded in our latest model. Let us now play around a bit
|
|
and see what kind of things we can learn about this model. Our generator takes
|
|
an array of 100 numbers. One idea can be to try to systematically change our
|
|
input. Let us try and see what we get
|
|
</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">generate_latent_points</span>(number<span style="color: #666666">=100</span>, scale_means<span style="color: #666666">=1</span>, scale_stds<span style="color: #666666">=1</span>):
|
|
latent_dim <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
means <span style="color: #666666">=</span> scale_means <span style="color: #666666">*</span> tf<span style="color: #666666">.</span>linspace(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>, num<span style="color: #666666">=</span>latent_dim)
|
|
stds <span style="color: #666666">=</span> scale_stds <span style="color: #666666">*</span> tf<span style="color: #666666">.</span>linspace(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>, num<span style="color: #666666">=</span>latent_dim)
|
|
latent_space_value_range <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal([number, latent_dim],
|
|
means,
|
|
stds,
|
|
dtype<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>float64)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> latent_space_value_range
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">generate_images</span>(latent_points):
|
|
<span style="color: #408080; font-style: italic"># notice we set training to false because we are making inferences</span>
|
|
generated_images <span style="color: #666666">=</span> restored_generator<span style="color: #666666">.</span>predict(latent_points)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> generated_images
|
|
</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">def</span> <span style="color: #0000FF">plot_result</span>(generated_images, number<span style="color: #666666">=100</span>):
|
|
<span style="color: #408080; font-style: italic"># obviously this assumes sqrt number is an int</span>
|
|
fig, axs <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots(<span style="color: #008000">int</span>(np<span style="color: #666666">.</span>sqrt(number)), <span style="color: #008000">int</span>(np<span style="color: #666666">.</span>sqrt(number)),
|
|
figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>, <span style="color: #666666">10</span>))
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">int</span>(np<span style="color: #666666">.</span>sqrt(number))):
|
|
<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">int</span>(np<span style="color: #666666">.</span>sqrt(number))):
|
|
axs[i, j]<span style="color: #666666">.</span>imshow(generated_images[i<span style="color: #666666">*</span>j], cmap<span style="color: #666666">=</span><span style="color: #BA2121">'Greys'</span>)
|
|
axs[i, j]<span style="color: #666666">.</span>axis(<span style="color: #BA2121">'off'</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>
|
|
<!-- 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%;">generated_images <span style="color: #666666">=</span> generate_images(generate_latent_points())
|
|
plot_result(generated_images)
|
|
</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="getting-results">Getting Results </h2>
|
|
<p>We see that the generator generates images that look like MNIST
|
|
numbers: \( 1, 4, 7, 9 \). Let's try to tweak it a bit more to see if we are able
|
|
to generate a similar plot where we generate every MNIST number. Let us now try
|
|
to 'move' a bit around in the latent space. <b>Note</b>: decrease the plot number if
|
|
these following cells take too long to run on your computer.
|
|
</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%;">plot_number <span style="color: #666666">=</span> <span style="color: #666666">225</span>
|
|
|
|
generated_images <span style="color: #666666">=</span> generate_images(generate_latent_points(number<span style="color: #666666">=</span>plot_number,
|
|
scale_means<span style="color: #666666">=5</span>,
|
|
scale_stds<span style="color: #666666">=1</span>))
|
|
plot_result(generated_images, number<span style="color: #666666">=</span>plot_number)
|
|
|
|
generated_images <span style="color: #666666">=</span> generate_images(generate_latent_points(number<span style="color: #666666">=</span>plot_number,
|
|
scale_means<span style="color: #666666">=-5</span>,
|
|
scale_stds<span style="color: #666666">=1</span>))
|
|
plot_result(generated_images, number<span style="color: #666666">=</span>plot_number)
|
|
|
|
generated_images <span style="color: #666666">=</span> generate_images(generate_latent_points(number<span style="color: #666666">=</span>plot_number,
|
|
scale_means<span style="color: #666666">=1</span>,
|
|
scale_stds<span style="color: #666666">=5</span>))
|
|
plot_result(generated_images, number<span style="color: #666666">=</span>plot_number)
|
|
</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>Again, we have found something interesting. <em>Moving</em> around using our means
|
|
takes us from digit to digit, while <em>moving</em> around using our standard
|
|
deviations seem to increase the number of different digits! In the last image
|
|
above, we can barely make out every MNIST digit. Let us make on last plot using
|
|
this information by upping the standard deviation of our Gaussian noises.
|
|
</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%;">plot_number <span style="color: #666666">=</span> <span style="color: #666666">400</span>
|
|
generated_images <span style="color: #666666">=</span> generate_images(generate_latent_points(number<span style="color: #666666">=</span>plot_number,
|
|
scale_means<span style="color: #666666">=1</span>,
|
|
scale_stds<span style="color: #666666">=10</span>))
|
|
plot_result(generated_images, number<span style="color: #666666">=</span>plot_number)
|
|
</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>A pretty cool result! We see that our generator indeed has learned a
|
|
distribution which qualitatively looks a whole lot like the MNIST dataset.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="interpolating-between-mnist-digits">Interpolating Between MNIST Digits </h2>
|
|
<p>Another interesting way to explore the latent space of our generator model is by
|
|
interpolating between the MNIST digits. This section is largely based on
|
|
<a href="https://machinelearningmastery.com/how-to-interpolate-and-perform-vector-arithmetic-with-faces-using-a-generative-adversarial-network/" target="_blank">this excellent blogpost</a>
|
|
by Jason Brownlee.
|
|
</p>
|
|
|
|
<p>So let us start by defining a function to interpolate between two points in the
|
|
latent space.
|
|
</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">interpolation</span>(point_1, point_2, n_steps<span style="color: #666666">=10</span>):
|
|
ratios <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, num<span style="color: #666666">=</span>n_steps)
|
|
vectors <span style="color: #666666">=</span> []
|
|
<span style="color: #008000; font-weight: bold">for</span> i, ratio <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(ratios):
|
|
vectors<span style="color: #666666">.</span>append(((<span style="color: #666666">1.0</span> <span style="color: #666666">-</span> ratio) <span style="color: #666666">*</span> point_1 <span style="color: #666666">+</span> ratio <span style="color: #666666">*</span> point_2))
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> tf<span style="color: #666666">.</span>stack(vectors)
|
|
</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 we have all we need to do our interpolation analysis.</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%;">plot_number <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
latent_points <span style="color: #666666">=</span> generate_latent_points(number<span style="color: #666666">=</span>plot_number)
|
|
results <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</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">0</span>, <span style="color: #666666">2*</span>np<span style="color: #666666">.</span>sqrt(plot_number), <span style="color: #666666">2</span>):
|
|
interpolated <span style="color: #666666">=</span> interpolation(latent_points[i], latent_points[i<span style="color: #666666">+1</span>])
|
|
generated_images <span style="color: #666666">=</span> generate_images(interpolated)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> results <span style="color: #AA22FF; font-weight: bold">is</span> <span style="color: #008000; font-weight: bold">None</span>:
|
|
results <span style="color: #666666">=</span> generated_images
|
|
<span style="color: #008000; font-weight: bold">else</span>:
|
|
results <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>stack((results, generated_images))
|
|
|
|
plot_results(results, plot_number)
|
|
</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="basic-ideas-of-the-principal-component-analysis-pca">Basic ideas of the Principal Component Analysis (PCA) </h2>
|
|
|
|
<p>The principal component analysis deals with the problem of fitting a
|
|
low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than
|
|
the total dimension \( D \) of the problem at hand (our data
|
|
set). Mathematically it can be formulated as a statistical problem or
|
|
a geometric problem. In our discussion of the theorem for the
|
|
classical PCA, we will stay with a statistical approach.
|
|
Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable.
|
|
</p>
|
|
|
|
<p>We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) </p>
|
|
<ul>
|
|
<li> Each data point is determined by \( p \) extrinsic (measurement) variables</li>
|
|
<li> We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?</li>
|
|
<li> If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.</li>
|
|
</ul>
|
|
<p>A good read is for example <a href="https://www.springer.com/gp/book/9780387878102" target="_blank">Vidal, Ma and Sastry</a>.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="introducing-the-covariance-and-correlation-functions">Introducing the Covariance and Correlation functions </h2>
|
|
|
|
<p>Before we discuss the PCA theorem, we need to remind ourselves about
|
|
the definition of the covariance and the correlation function. These are quantities
|
|
</p>
|
|
|
|
<p>Suppose we have defined two vectors
|
|
\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as
|
|
</p>
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
|
|
\mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<p>where for example</p>
|
|
$$
|
|
\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
|
|
$$
|
|
|
|
<p>With this definition and recalling that the variance is defined as</p>
|
|
$$
|
|
\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
|
|
$$
|
|
|
|
<p>we can rewrite the covariance matrix as </p>
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
|
|
\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\
|
|
\end{bmatrix}.
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="more-on-the-covariance">More on the covariance </h2>
|
|
<p>The covariance takes values between zero and infinity and may thus
|
|
lead to problems with loss of numerical precision for particularly
|
|
large values. It is common to scale the covariance matrix by
|
|
introducing instead the correlation matrix defined via the so-called
|
|
correlation function
|
|
</p>
|
|
|
|
$$
|
|
\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}.
|
|
$$
|
|
|
|
<p>The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]
|
|
\in [-1,1] \). This avoids eventual problems with too large values. We
|
|
can then define the correlation matrix for the two vectors \( \boldsymbol{x} \)
|
|
and \( \boldsymbol{y} \) as
|
|
</p>
|
|
|
|
$$
|
|
\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\
|
|
\mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<p>In the above example this is the function we constructed using <b>pandas</b>.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="reminding-ourselves-about-linear-regression">Reminding ourselves about Linear Regression </h2>
|
|
<p>In our derivation of the various regression algorithms like <b>Ordinary Least Squares</b> or <b>Ridge regression</b>
|
|
we defined the design/feature matrix \( \boldsymbol{X} \) as
|
|
</p>
|
|
|
|
$$
|
|
\boldsymbol{X}=\begin{bmatrix}
|
|
x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
|
|
x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
|
|
x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
|
|
\dots & \dots & \dots & \dots \dots & \dots \\
|
|
x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
|
|
x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<p>with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the
|
|
entries \( n \) being the row elements.
|
|
We can rewrite the design/feature matrix in terms of its column vectors as
|
|
</p>
|
|
$$
|
|
\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix},
|
|
$$
|
|
|
|
<p>with a given vector</p>
|
|
$$
|
|
\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="simple-example">Simple Example </h2>
|
|
<p>With these definitions, we can now rewrite our \( 2\times 2 \)
|
|
correlation/covariance matrix in terms of a moe general design/feature
|
|
matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \)
|
|
covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \)
|
|
</p>
|
|
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix}
|
|
\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
|
|
\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
|
|
\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
|
|
\dots & \dots & \dots & \dots & \dots & \dots \\
|
|
\dots & \dots & \dots & \dots & \dots & \dots \\
|
|
\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-correlation-matrix">The Correlation Matrix </h2>
|
|
|
|
<p>and the correlation matrix</p>
|
|
$$
|
|
\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix}
|
|
1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
|
|
\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
|
|
\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
|
|
\dots & \dots & \dots & \dots & \dots & \dots \\
|
|
\dots & \dots & \dots & \dots & \dots & \dots \\
|
|
\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="numpy-functionality">Numpy Functionality </h2>
|
|
|
|
<p>The Numpy function <b>np.cov</b> calculates the covariance elements using
|
|
the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have
|
|
the exact mean values. The following simple function uses the
|
|
<b>np.vstack</b> function which takes each vector of dimension \( 1\times n \)
|
|
and produces a \( 2\times n \) matrix \( \boldsymbol{W} \)
|
|
</p>
|
|
|
|
$$
|
|
\boldsymbol{W}^T = \begin{bmatrix} x_0 & y_0 \\
|
|
x_1 & y_1 \\
|
|
x_2 & y_2\\
|
|
\dots & \dots \\
|
|
x_{n-2} & y_{n-2}\\
|
|
x_{n-1} & y_{n-1} &
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<p>which in turn is converted into into the \( 2\times 2 \) covariance matrix
|
|
\( \boldsymbol{C} \) via the Numpy function <b>np.cov()</b>. We note that we can also calculate
|
|
the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy
|
|
function <b>np.mean(x)</b>. We can also extract the eigenvalues of the
|
|
covariance matrix through the <b>np.linalg.eig()</b> function.
|
|
</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"># Importing various 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>
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
<span style="color: #008000">print</span>(np<span style="color: #666666">.</span>mean(x))
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
<span style="color: #008000">print</span>(np<span style="color: #666666">.</span>mean(y))
|
|
W <span style="color: #666666">=</span> np<span style="color: #666666">.</span>vstack((x, y))
|
|
C <span style="color: #666666">=</span> np<span style="color: #666666">.</span>cov(W)
|
|
<span style="color: #008000">print</span>(C)
|
|
</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="correlation-matrix-again">Correlation Matrix again </h2>
|
|
|
|
<p>The previous example can be converted into the correlation matrix by
|
|
simply scaling the matrix elements with the variances. We should also
|
|
subtract the mean values for each column. This leads to the following
|
|
code which sets up the correlations matrix for the previous example in
|
|
a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors).
|
|
</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
<span style="color: #408080; font-style: italic"># define two vectors </span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>random(size<span style="color: #666666">=</span>n)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
<span style="color: #408080; font-style: italic">#scaling the x and y vectors </span>
|
|
x <span style="color: #666666">=</span> x <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(x)
|
|
y <span style="color: #666666">=</span> y <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y)
|
|
variance_x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #AA22FF">@x</span>)<span style="color: #666666">/</span>n
|
|
variance_y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(y<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>n
|
|
<span style="color: #008000">print</span>(variance_x)
|
|
<span style="color: #008000">print</span>(variance_y)
|
|
cov_xy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>n
|
|
cov_xx <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #AA22FF">@x</span>)<span style="color: #666666">/</span>n
|
|
cov_yy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(y<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>n
|
|
C <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #666666">2</span>,<span style="color: #666666">2</span>))
|
|
C[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>]<span style="color: #666666">=</span> cov_xx<span style="color: #666666">/</span>variance_x
|
|
C[<span style="color: #666666">1</span>,<span style="color: #666666">1</span>]<span style="color: #666666">=</span> cov_yy<span style="color: #666666">/</span>variance_y
|
|
C[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>]<span style="color: #666666">=</span> cov_xy<span style="color: #666666">/</span>np<span style="color: #666666">.</span>sqrt(variance_y<span style="color: #666666">*</span>variance_x)
|
|
C[<span style="color: #666666">1</span>,<span style="color: #666666">0</span>]<span style="color: #666666">=</span> C[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>]
|
|
<span style="color: #008000">print</span>(C)
|
|
</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 the matrix elements along the diagonal are one as they
|
|
should be and that the matrix is symmetric. Furthermore, diagonalizing
|
|
this matrix we easily see that it is a positive definite matrix.
|
|
</p>
|
|
|
|
<p>The above procedure with <b>numpy</b> can be made more compact if we use <b>pandas</b>.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="using-pandas">Using Pandas </h2>
|
|
|
|
<p>We whow here how we can set up the correlation matrix using <b>pandas</b>, as done in this simple code</p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</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>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
x <span style="color: #666666">=</span> x <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(x)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
y <span style="color: #666666">=</span> y <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y)
|
|
X <span style="color: #666666">=</span> (np<span style="color: #666666">.</span>vstack((x, y)))<span style="color: #666666">.</span>T
|
|
<span style="color: #008000">print</span>(X)
|
|
Xpd <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(X)
|
|
<span style="color: #008000">print</span>(Xpd)
|
|
correlation_matrix <span style="color: #666666">=</span> Xpd<span style="color: #666666">.</span>corr()
|
|
<span style="color: #008000">print</span>(correlation_matrix)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="and-then-the-franke-function">And then the Franke Function </h2>
|
|
|
|
<p>We expand this model to the Franke function discussed above.</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"># Common imports</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">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">FrankeFunction</span>(x,y):
|
|
term1 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">0.25*</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>) <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>))
|
|
term2 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>((<span style="color: #666666">9*</span>x<span style="color: #666666">+1</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">/49.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.1*</span>(<span style="color: #666666">9*</span>y<span style="color: #666666">+1</span>))
|
|
term3 <span style="color: #666666">=</span> <span style="color: #666666">0.5*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-7</span>)<span style="color: #666666">**2/4.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-3</span>)<span style="color: #666666">**2</span>))
|
|
term4 <span style="color: #666666">=</span> <span style="color: #666666">-0.2*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-4</span>)<span style="color: #666666">**2</span> <span style="color: #666666">-</span> (<span style="color: #666666">9*</span>y<span style="color: #666666">-7</span>)<span style="color: #666666">**2</span>)
|
|
<span style="color: #008000; font-weight: bold">return</span> term1 <span style="color: #666666">+</span> term2 <span style="color: #666666">+</span> term3 <span style="color: #666666">+</span> term4
|
|
|
|
|
|
<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">+1</span>)<span style="color: #666666">*</span>(n<span style="color: #666666">+2</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">+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">+1</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">+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
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Making meshgrid of datapoints and compute Franke's function</span>
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">4</span>
|
|
N <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sort(np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>uniform(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, N))
|
|
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sort(np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>uniform(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, N))
|
|
z <span style="color: #666666">=</span> FrankeFunction(x, y)
|
|
X <span style="color: #666666">=</span> create_X(x, y, n<span style="color: #666666">=</span>n)
|
|
|
|
Xpd <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(X)
|
|
<span style="color: #408080; font-style: italic"># subtract the mean values and set up the covariance matrix</span>
|
|
Xpd <span style="color: #666666">=</span> Xpd <span style="color: #666666">-</span> Xpd<span style="color: #666666">.</span>mean()
|
|
covariance_matrix <span style="color: #666666">=</span> Xpd<span style="color: #666666">.</span>cov()
|
|
<span style="color: #008000">print</span>(covariance_matrix)
|
|
</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 note here that the covariance is zero for the first rows and
|
|
columns since all matrix elements in the design matrix were set to one
|
|
(we are fitting the function in terms of a polynomial of degree \( n \)). We would however not include the intercept
|
|
and wee can simply
|
|
drop these elements and construct a correlation
|
|
matrix without them by centering our matrix elements by subtracting the mean of each column.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="lnks-with-the-design-matrix">Lnks with the Design Matrix </h2>
|
|
|
|
<p>We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as </p>
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}].
|
|
$$
|
|
|
|
<p>To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)</p>
|
|
$$
|
|
\boldsymbol{X}=\begin{bmatrix}
|
|
x_{00} & x_{01}\\
|
|
x_{10} & x_{11}\\
|
|
\end{bmatrix}=\begin{bmatrix}
|
|
\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\
|
|
\end{bmatrix}.
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="computing-the-expectation-values">Computing the Expectation Values </h2>
|
|
|
|
<p>If we then compute the expectation value</p>
|
|
$$
|
|
\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix}
|
|
x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
|
|
x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<p>which is just </p>
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\
|
|
\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<p>where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \).</p>
|
|
|
|
<p>It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="towards-the-pca-theorem">Towards the PCA theorem </h2>
|
|
|
|
<p>We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as</p>
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}].
|
|
$$
|
|
|
|
<p>Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \).
|
|
These matrices are defined as \( \boldsymbol{S}\in {\mathbb{R}}^{p\times p} \) and obey the orthogonality requirements \( \boldsymbol{S}\boldsymbol{S}^T=\boldsymbol{S}^T\boldsymbol{S}=\boldsymbol{I} \). The matrix can be written out in terms of the column vectors \( \boldsymbol{s}_i \) as \( \boldsymbol{S}=[\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \) and \( \boldsymbol{s}_i \in {\mathbb{R}}^{p} \).
|
|
</p>
|
|
|
|
<p>Assume also that there is a transformation \( \boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}=\boldsymbol{C}[\boldsymbol{y}] \) such that the new matrix \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal with elements \( [\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}] \). </p>
|
|
|
|
<p>That is we have</p>
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{y}] = \mathbb{E}[\boldsymbol{S}^T\boldsymbol{X}^T\boldsymbol{X}T\boldsymbol{S}]=\boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S},
|
|
$$
|
|
|
|
<p>since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have</p>
|
|
$$
|
|
\boldsymbol{S}\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S},
|
|
$$
|
|
|
|
<p>and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that</p>
|
|
|
|
$$
|
|
\boldsymbol{S}_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}_i.
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="more-on-the-pca-theorem">More on the PCA Theorem </h2>
|
|
|
|
<p>In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is
|
|
\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \).
|
|
</p>
|
|
|
|
<p>The eigenvalues tell us then how much we need to stretch the
|
|
corresponding eigenvectors. Dimensions with large eigenvalues have
|
|
thus large variations (large variance) and define therefore useful
|
|
dimensions. The data points are more spread out in the direction of
|
|
these eigenvectors. Smaller eigenvalues mean on the other hand that
|
|
the corresponding eigenvectors are shrunk accordingly and the data
|
|
points are tightly bunched together and there is not much variation in
|
|
these specific directions. Hopefully then we could leave it out
|
|
dimensions where the eigenvalues are very small. If \( p \) is very large,
|
|
we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \)
|
|
features/predictors.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-algorithm-before-theorem">The Algorithm before theorem </h2>
|
|
|
|
<p>Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. </p>
|
|
<ul>
|
|
<li> Set up the datapoints for the design/feature matrix \( \boldsymbol{X} \) with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) referring to the column numbers and the entries \( n \) being the row elements.</li>
|
|
</ul>
|
|
$$
|
|
\boldsymbol{X}=\begin{bmatrix}
|
|
x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
|
|
x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
|
|
x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
|
|
\dots & \dots & \dots & \dots \dots & \dots \\
|
|
x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
|
|
x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<ul>
|
|
<li> Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).</li>
|
|
<li> Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}^T\overline{\boldsymbol{X}}] \).</li>
|
|
<li> Find the eigenpairs of \( \boldsymbol{C} \) with eigenvalues \( [\lambda_0,\lambda_1,\dots,\lambda_{p-1}] \) and eigenvectors \( [\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \).</li>
|
|
<li> Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.</li>
|
|
<li> Keep only those \( l \) eigenvalues larger than a selected threshold value, discarding thus \( p-l \) features since we expect small variations in the data here.</li>
|
|
</ul>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="writing-our-own-pca-code">Writing our own PCA code </h2>
|
|
|
|
<p>We will use a simple example first with two-dimensional data
|
|
drawn from a multivariate normal distribution with the following mean and covariance matrix (we have fixed these quantities but will play around with them below):
|
|
</p>
|
|
$$
|
|
\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\
|
|
2 & 2
|
|
\end{bmatrix}
|
|
$$
|
|
|
|
<p>Note that the mean refers to each column of data.
|
|
We will generate \( n = 10000 \) points \( X = \{ x_1, \ldots, x_N \} \) from
|
|
this distribution, and store them in the \( 1000 \times 2 \) matrix \( \boldsymbol{X} \). This is our design matrix where we have forced the covariance and mean values to take specific values.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="implementing-it">Implementing it </h2>
|
|
<p>The following Python code aids in setting up the data and writing out the design matrix.
|
|
Note that the function <b>multivariate</b> returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \).
|
|
</p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</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">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">10000</span>
|
|
mean <span style="color: #666666">=</span> (<span style="color: #666666">-1</span>, <span style="color: #666666">2</span>)
|
|
cov <span style="color: #666666">=</span> [[<span style="color: #666666">4</span>, <span style="color: #666666">2</span>], [<span style="color: #666666">2</span>, <span style="color: #666666">2</span>]]
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>multivariate_normal(mean, cov, n)
|
|
</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 we are going to implement the PCA algorithm. We will break it down into various substeps.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="first-step">First Step </h2>
|
|
|
|
<p>The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is</p>
|
|
$$
|
|
\mu_n = \frac{1}{n} \sum_{i=1}^n x_i
|
|
$$
|
|
|
|
<p>and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form</p>
|
|
$$
|
|
\bar{x}_i = x_i - \mu_n.
|
|
$$
|
|
|
|
<p>When you are done with these steps, print out \( \mu_n \) to verify it is
|
|
close to \( \mu \) and plot your mean centered data to verify it is
|
|
centered at the origin!
|
|
The following code elements perform these operations using <b>pandas</b> or using our own functionality for doing so. The latter, using <b>numpy</b> is rather simple through the <b>mean()</b> function.
|
|
</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%;">df <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(X)
|
|
<span style="color: #408080; font-style: italic"># Pandas does the centering for us</span>
|
|
df <span style="color: #666666">=</span> df <span style="color: #666666">-</span>df<span style="color: #666666">.</span>mean()
|
|
<span style="color: #408080; font-style: italic"># we center it ourselves</span>
|
|
X_centered <span style="color: #666666">=</span> X <span style="color: #666666">-</span> X<span style="color: #666666">.</span>mean(axis<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="scaling">Scaling </h2>
|
|
<p>Alternatively, we could use the functions we discussed
|
|
earlier for scaling the data set. That is, we could have used the
|
|
<b>StandardScaler</b> function in <b>Scikit-Learn</b>, a function which ensures
|
|
that for each feature/predictor we study the mean value is zero and
|
|
the variance is one (every column in the design/feature matrix). You
|
|
would then not get the same results, since we divide by the
|
|
variance. The diagonal covariance matrix elements will then be one,
|
|
while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our
|
|
specific case.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="centered-data">Centered Data </h2>
|
|
|
|
<p>Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation</p>
|
|
$$
|
|
\begin{equation*}
|
|
\Sigma_n = \frac{1}{n-1} \sum_{i=1}^n \bar{x}_i^T \bar{x}_i = \frac{1}{n-1} \sum_{i=1}^n (x_i - \mu_n)^T (x_i - \mu_n)
|
|
\end{equation*}
|
|
$$
|
|
|
|
<p>where the data points \( x_i \in \mathbb{R}^p \) (here in this example \( p = 2 \)) are column vectors and \( x^T \) is the transpose of \( x \).
|
|
We can write our own code or simply use either the functionaly of <b>numpy</b> or that of <b>pandas</b>, as follows
|
|
</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">print</span>(df<span style="color: #666666">.</span>cov())
|
|
<span style="color: #008000">print</span>(np<span style="color: #666666">.</span>cov(X_centered<span style="color: #666666">.</span>T))
|
|
</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>Note that the way we define the covariance matrix here has a factor \( n-1 \) instead of \( n \). This is included in the <b>cov()</b> function by <b>numpy</b> and <b>pandas</b>.
|
|
Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix.
|
|
</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"># extract the relevant columns from the centered design matrix of dim n x 2</span>
|
|
x <span style="color: #666666">=</span> X_centered[:,<span style="color: #666666">0</span>]
|
|
y <span style="color: #666666">=</span> X_centered[:,<span style="color: #666666">1</span>]
|
|
Cov <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #666666">2</span>,<span style="color: #666666">2</span>))
|
|
Cov[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #666666">.</span>T<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>(n<span style="color: #666666">-1.0</span>)
|
|
Cov[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #666666">.</span>T<span style="color: #AA22FF">@x</span>)<span style="color: #666666">/</span>(n<span style="color: #666666">-1.0</span>)
|
|
Cov[<span style="color: #666666">1</span>,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(y<span style="color: #666666">.</span>T<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>(n<span style="color: #666666">-1.0</span>)
|
|
Cov[<span style="color: #666666">1</span>,<span style="color: #666666">0</span>]<span style="color: #666666">=</span> Cov[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>]
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Centered covariance using own code"</span>)
|
|
<span style="color: #008000">print</span>(Cov)
|
|
plt<span style="color: #666666">.</span>plot(x, y, <span style="color: #BA2121">'x'</span>)
|
|
plt<span style="color: #666666">.</span>axis(<span style="color: #BA2121">'equal'</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="exploring">Exploring </h2>
|
|
|
|
<p>Depending on the number of points \( n \), we will get results that are close to the covariance values defined above.
|
|
The plot shows how the data are clustered around a line with slope close to one. Is this expected? Try to change the covariance and the mean values. For example, try to make the variance of the first element much larger than that of the second diagonal element. Try also to shrink the covariance (the non-diagonal elements) and see how the data points are distributed.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="diagonalize-the-sample-covariance-matrix-to-obtain-the-principal-components">Diagonalize the sample covariance matrix to obtain the principal components </h2>
|
|
|
|
<p>Now we are ready to solve for the principal components! To do so we
|
|
diagonalize the sample covariance matrix \( \Sigma \). We can use the
|
|
function <b>np.linalg.eig</b> to do so. It will return the eigenvalues and
|
|
eigenvectors of \( \Sigma \). Once we have these we can perform the
|
|
following tasks:
|
|
</p>
|
|
|
|
<ul>
|
|
<li> We compute the percentage of the total variance captured by the first principal component</li>
|
|
<li> We plot the mean centered data and lines along the first and second principal components</li>
|
|
<li> Then we project the mean centered data onto the first and second principal components, and plot the projected data.</li>
|
|
<li> Finally, we approximate the data as</li>
|
|
</ul>
|
|
$$
|
|
\begin{equation*}
|
|
x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0
|
|
\end{equation*}
|
|
$$
|
|
|
|
<p>where \( v_0 \) is the first principal component. </p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="collecting-all-steps">Collecting all Steps </h2>
|
|
|
|
<p>Collecting all these steps we can write our own PCA function and
|
|
compare this with the functionality included in <b>Scikit-Learn</b>.
|
|
</p>
|
|
|
|
<p>The code here outlines some of the elements we could include in the
|
|
analysis. Feel free to extend upon this in order to address the above
|
|
questions.
|
|
</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"># diagonalize and obtain eigenvalues, not necessarily sorted</span>
|
|
EigValues, EigVectors <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>eig(Cov)
|
|
<span style="color: #408080; font-style: italic"># sort eigenvectors and eigenvalues</span>
|
|
<span style="color: #408080; font-style: italic">#permute = EigValues.argsort()</span>
|
|
<span style="color: #408080; font-style: italic">#EigValues = EigValues[permute]</span>
|
|
<span style="color: #408080; font-style: italic">#EigVectors = EigVectors[:,permute]</span>
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Eigenvalues of Covariance 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: #666666">2</span>):
|
|
<span style="color: #008000">print</span>(EigValues[i])
|
|
FirstEigvector <span style="color: #666666">=</span> EigVectors[:,<span style="color: #666666">0</span>]
|
|
SecondEigvector <span style="color: #666666">=</span> EigVectors[:,<span style="color: #666666">1</span>]
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"First eigenvector"</span>)
|
|
<span style="color: #008000">print</span>(FirstEigvector)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Second eigenvector"</span>)
|
|
<span style="color: #008000">print</span>(SecondEigvector)
|
|
<span style="color: #408080; font-style: italic">#thereafter we do a PCA with Scikit-learn</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.decomposition</span> <span style="color: #008000; font-weight: bold">import</span> PCA
|
|
pca <span style="color: #666666">=</span> PCA(n_components <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
X2Dsl <span style="color: #666666">=</span> pca<span style="color: #666666">.</span>fit_transform(X)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Eigenvector of largest eigenvalue"</span>)
|
|
<span style="color: #008000">print</span>(pca<span style="color: #666666">.</span>components_<span style="color: #666666">.</span>T[:, <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>
|
|
|
|
<p>This code does not contain all the above elements, but it shows how we can use <b>Scikit-Learn</b> to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then? </p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="classical-pca-theorem">Classical PCA Theorem </h2>
|
|
|
|
<p>We assume now that we have a design matrix \( \boldsymbol{X} \) which has been
|
|
centered as discussed above. For the sake of simplicity we skip the
|
|
overline symbol. The matrix is defined in terms of the various column
|
|
vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension
|
|
\( \boldsymbol{x}\in {\mathbb{R}}^{n} \).
|
|
</p>
|
|
|
|
<p>The PCA theorem states that minimizing the above reconstruction error
|
|
corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which
|
|
diagonalizes the empirical covariance(correlation) matrix. The optimal
|
|
low-dimensional encoding of the data is then given by a set of vectors
|
|
\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the
|
|
orthogonal projection of the data onto the columns spanned by the
|
|
eigenvectors of the covariance(correlations matrix).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-pca-theorem">The PCA Theorem </h2>
|
|
|
|
<p>To show the PCA theorem let us start with the assumption that there is one vector \( \boldsymbol{s}_0 \) which corresponds to a solution which minimized the reconstruction error \( J \). This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of \( \boldsymbol{w}_0 \) and \( \boldsymbol{z}_0 \) as</p>
|
|
|
|
<p>We are almost there, we have obtained a relation between minimizing
|
|
the reconstruction error and the variance and the covariance
|
|
matrix. Minimizing the error is equivalent to maximizing the variance
|
|
of the projected data.
|
|
</p>
|
|
|
|
<p>We could trivially maximize the variance of the projection (and
|
|
thereby minimize the error in the reconstruction function) by letting
|
|
the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we
|
|
want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by
|
|
\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a
|
|
Lagrange multiplier we can then in turn maximize
|
|
</p>
|
|
|
|
$$
|
|
J(\boldsymbol{w}_0)= \boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0+\lambda_0(1-\boldsymbol{w}_0^T\boldsymbol{w}_0).
|
|
$$
|
|
|
|
<p>Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain</p>
|
|
|
|
$$
|
|
\frac{\partial J(\boldsymbol{w}_0)}{\partial \boldsymbol{w}_0}= 2\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0-2\lambda_0\boldsymbol{w}_0=0,
|
|
$$
|
|
|
|
<p>meaning that</p>
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0.
|
|
$$
|
|
|
|
<p><b>The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix</b>! If we left multiply with \( \boldsymbol{w}_0^T \) we have the variance of the projected data is</p>
|
|
$$
|
|
\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0.
|
|
$$
|
|
|
|
<p>If we want to maximize the variance (minimize the construction error)
|
|
we simply pick the eigenvector of the covariance matrix with the
|
|
largest eigenvalue. This establishes the link between the minimization
|
|
of the reconstruction function \( J \) in terms of an orthogonal matrix
|
|
and the maximization of the variance and thereby the covariance of our
|
|
observations encoded in the design/feature matrix \( \boldsymbol{X} \).
|
|
</p>
|
|
|
|
<p>The proof
|
|
for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be
|
|
established by applying the above arguments and using the fact that
|
|
our basis of eigenvectors is orthogonal, see <a href="https://mitpress.mit.edu/books/machine-learning-1" target="_blank">Murphy chapter
|
|
12.2</a>. The
|
|
discussion in chapter 12.2 of Murphy's text has also a nice link with
|
|
the Singular Value Decomposition theorem. For categorical data, see
|
|
chapter 12.4 and discussion therein.
|
|
</p>
|
|
|
|
<p>For more details, see for example <a href="https://www.springer.com/gp/book/9780387878102" target="_blank">Vidal, Ma and Sastry, chapter 2</a>.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="geometric-interpretation-and-link-with-singular-value-decomposition">Geometric Interpretation and link with Singular Value Decomposition </h2>
|
|
|
|
<p>For a detailed demonstration of the geometric interpretation, see <a href="https://www.springer.com/gp/book/9780387878102" target="_blank">Vidal, Ma and Sastry, section 2.1.2</a>.</p>
|
|
|
|
<p>Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.
|
|
First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.
|
|
</p>
|
|
|
|
<p>The following Python code uses NumPy’s <b>svd()</b> function to obtain all the principal components of the
|
|
training set, then extracts the first two principal components. First we center the data using either <b>pandas</b> or our own code
|
|
</p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
|
|
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">100</span>)
|
|
<span style="color: #408080; font-style: italic"># setting up a 10 x 5 vanilla matrix </span>
|
|
rows <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
cols <span style="color: #666666">=</span> <span style="color: #666666">5</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(rows,cols)
|
|
df <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(X)
|
|
<span style="color: #408080; font-style: italic"># Pandas does the centering for us</span>
|
|
df <span style="color: #666666">=</span> df <span style="color: #666666">-</span>df<span style="color: #666666">.</span>mean()
|
|
display(df)
|
|
|
|
<span style="color: #408080; font-style: italic"># we center it ourselves</span>
|
|
X_centered <span style="color: #666666">=</span> X <span style="color: #666666">-</span> X<span style="color: #666666">.</span>mean(axis<span style="color: #666666">=0</span>)
|
|
<span style="color: #408080; font-style: italic"># Then check the difference between pandas and our own set up</span>
|
|
<span style="color: #008000">print</span>(X_centered<span style="color: #666666">-</span>df)
|
|
<span style="color: #408080; font-style: italic">#Now we do an SVD</span>
|
|
U, s, V <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>svd(X_centered)
|
|
c1 <span style="color: #666666">=</span> V<span style="color: #666666">.</span>T[:, <span style="color: #666666">0</span>]
|
|
c2 <span style="color: #666666">=</span> V<span style="color: #666666">.</span>T[:, <span style="color: #666666">1</span>]
|
|
W2 <span style="color: #666666">=</span> V<span style="color: #666666">.</span>T[:, :<span style="color: #666666">2</span>]
|
|
X2D <span style="color: #666666">=</span> X_centered<span style="color: #666666">.</span>dot(W2)
|
|
<span style="color: #008000">print</span>(X2D)
|
|
</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>PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering
|
|
the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t
|
|
forget to center the data first.
|
|
</p>
|
|
|
|
<p>Once you have identified all the principal components, you can reduce the dimensionality of the dataset
|
|
down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components.
|
|
Selecting this hyperplane ensures that the projection will preserve as much variance as possible.
|
|
</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%;">W2 <span style="color: #666666">=</span> V<span style="color: #666666">.</span>T[:, :<span style="color: #666666">2</span>]
|
|
X2D <span style="color: #666666">=</span> X_centered<span style="color: #666666">.</span>dot(W2)
|
|
</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="pca-and-scikit-learn">PCA and scikit-learn </h2>
|
|
|
|
<p>Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
|
|
following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note
|
|
that it automatically takes care of centering the data):
|
|
</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">#thereafter we do a PCA with Scikit-learn</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.decomposition</span> <span style="color: #008000; font-weight: bold">import</span> PCA
|
|
pca <span style="color: #666666">=</span> PCA(n_components <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
X2D <span style="color: #666666">=</span> pca<span style="color: #666666">.</span>fit_transform(X)
|
|
<span style="color: #008000">print</span>(X2D)
|
|
</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>After fitting the PCA transformer to the dataset, you can access the principal components using the
|
|
components variable (note that it contains the PCs as horizontal vectors, so, for example, the first
|
|
principal component is equal to
|
|
</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%;">pca<span style="color: #666666">.</span>components_<span style="color: #666666">.</span>T[:, <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>
|
|
|
|
<p>Another very useful piece of information is the explained variance ratio of each principal component,
|
|
available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s
|
|
variance that lies along the axis of each principal component.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="back-to-the-cancer-data">Back to the Cancer Data </h2>
|
|
<p>We can now repeat the above but applied to real data, in this case our breast cancer data.
|
|
Here we compute performance scores on the training data using logistic regression.
|
|
</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">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">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">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.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
|
|
cancer <span style="color: #666666">=</span> load_breast_cancer()
|
|
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(cancer<span style="color: #666666">.</span>data,cancer<span style="color: #666666">.</span>target,random_state<span style="color: #666666">=0</span>)
|
|
|
|
logreg <span style="color: #666666">=</span> LogisticRegression()
|
|
logreg<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Train set accuracy from Logistic Regression: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_train,y_train)))
|
|
<span style="color: #408080; font-style: italic"># We scale the data</span>
|
|
<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> StandardScaler
|
|
scaler <span style="color: #666666">=</span> StandardScaler()
|
|
scaler<span style="color: #666666">.</span>fit(X_train)
|
|
X_train_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_train)
|
|
X_test_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_test)
|
|
<span style="color: #408080; font-style: italic"># Then perform again a log reg fit</span>
|
|
logreg<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Train set accuracy scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_train_scaled,y_train)))
|
|
<span style="color: #408080; font-style: italic">#thereafter we do a PCA with Scikit-learn</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.decomposition</span> <span style="color: #008000; font-weight: bold">import</span> PCA
|
|
pca <span style="color: #666666">=</span> PCA(n_components <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
X2D_train <span style="color: #666666">=</span> pca<span style="color: #666666">.</span>fit_transform(X_train_scaled)
|
|
<span style="color: #408080; font-style: italic"># and finally compute the log reg fit and the score on the training data </span>
|
|
logreg<span style="color: #666666">.</span>fit(X2D_train,y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Train set accuracy scaled and PCA data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X2D_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>
|
|
|
|
<p>We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. </p>
|
|
|
|
<p>Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to
|
|
choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).
|
|
Unless, of course, you are reducing dimensionality for data visualization — in that case you will
|
|
generally want to reduce the dimensionality down to 2 or 3.
|
|
The following code computes PCA without reducing dimensionality, then computes the minimum number
|
|
of dimensions required to preserve 95% of the training set’s variance:
|
|
</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%;">pca <span style="color: #666666">=</span> PCA()
|
|
pca<span style="color: #666666">.</span>fit(X)
|
|
cumsum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>cumsum(pca<span style="color: #666666">.</span>explained_variance_ratio_)
|
|
d <span style="color: #666666">=</span> np<span style="color: #666666">.</span>argmax(cumsum <span style="color: #666666">>=</span> <span style="color: #666666">0.95</span>) <span style="color: #666666">+</span> <span style="color: #666666">1</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>You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead
|
|
of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be
|
|
a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:
|
|
</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%;">pca <span style="color: #666666">=</span> PCA(n_components<span style="color: #666666">=0.95</span>)
|
|
X_reduced <span style="color: #666666">=</span> pca<span style="color: #666666">.</span>fit_transform(X)
|
|
</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="incremental-pca">Incremental PCA </h2>
|
|
|
|
<p>One problem with the preceding implementation of PCA is that it requires the whole training set to fit in
|
|
memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have
|
|
been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch
|
|
at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new
|
|
instances arrive).
|
|
</p>
|
|
<h3 id="randomized-pca">Randomized PCA </h3>
|
|
|
|
<p>Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic
|
|
algorithm that quickly finds an approximation of the first d principal components. Its computational
|
|
complexity is \( O(m \times d^2)+O(d^3) \), instead of \( O(m \times n^2) + O(n^3) \), so it is dramatically faster than the
|
|
previous algorithms when \( d \) is much smaller than \( n \).
|
|
</p>
|
|
<h3 id="kernel-pca">Kernel PCA </h3>
|
|
|
|
<p>The kernel trick is a mathematical technique that implicitly maps instances into a
|
|
very high-dimensional space (called the feature space), enabling nonlinear classification and regression
|
|
with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature
|
|
space corresponds to a complex nonlinear decision boundary in the original space.
|
|
It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear
|
|
projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at
|
|
preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a
|
|
twisted manifold.
|
|
For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an
|
|
</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.decomposition</span> <span style="color: #008000; font-weight: bold">import</span> KernelPCA
|
|
rbf_pca <span style="color: #666666">=</span> KernelPCA(n_components <span style="color: #666666">=</span> <span style="color: #666666">2</span>, kernel<span style="color: #666666">=</span><span style="color: #BA2121">"rbf"</span>, gamma<span style="color: #666666">=0.04</span>)
|
|
X_reduced <span style="color: #666666">=</span> rbf_pca<span style="color: #666666">.</span>fit_transform(X)
|
|
</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="other-techniques">Other techniques </h2>
|
|
|
|
<p>There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.</p>
|
|
|
|
<p>Here are some of the most popular:</p>
|
|
<ul>
|
|
<li> <b>Multidimensional Scaling (MDS)</b> reduces dimensionality while trying to preserve the distances between the instances.</li>
|
|
<li> <b>Isomap</b> creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.</li>
|
|
<li> <b>t-Distributed Stochastic Neighbor Embedding</b> (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).</li>
|
|
<li> Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures.</li>
|
|
</ul>
|
|
<!-- ------------------- end of main content --------------- -->
|
|
<center style="font-size:80%">
|
|
<!-- copyright --> © 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
|
</center>
|
|
</body>
|
|
</html>
|
|
|