Files
FYS-STK4155/doc/pub/week43/html/week43.html
T
Morten Hjorth-Jensen bddecbcb9e added material
2021-10-26 12:00:58 +02:00

1642 lines
127 KiB
HTML

<!--
Automatically generated HTML file from DocOnce source
(https://github.com/doconce/doconce/)
-->
<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 methods">
<title>Week 43: Deep Learning: Recurrent Neural Networks and other methods</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 { color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
/* pre style removed because it will interfer with pygments */
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}
.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; }
</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')]}
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 methods</h1></center> <!-- document title -->
<p>
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<p>
<!-- 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>
<p>
<center><h4>Oct 26, 2021</h4></center> <!-- date -->
<br>
<p>
<!-- !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</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>
<p>
<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>
<p>
<!-- !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>
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:
<ul>
<li> A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)</li>
<li> There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)</li>
<li> Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function</li>
<li> Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don&#8217;t)</li>
<li> Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn&#8217;t)</li>
</ul>
For more material on convolutional networks, we strongly recommend
the course
<a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" target="_blank">IN5400 &#8211; Machine Learning for Image Analysis</a>
and the slides of <a href="http://cs231n.github.io/convolutional-networks/" target="_blank">CS231</a> which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). <a href="http://neuralnetworksanddeeplearning.com/chap6.html" target="_blank">Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs</a>.
<p>
However, both standard feed forwards networks and CNNs perform well on data with unknown length.
<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>
A recurrent neural network (RNN) looks very much like a feedforward
neural network, except that it also has connections pointing
backward.
<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 by Wednesday October 27.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-simple-example">A simple example </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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">&quot;relu&quot;</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">&quot;relu&quot;</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">&#39;mean_squared_error&#39;</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">&#39;rmsprop&#39;</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">&quot;r&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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">&#39;VaryDimension&#39;</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>
<p>
<!-- !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>
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. -->
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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">&quot;&quot;&quot;</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"> &quot;&quot;&quot;</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">&quot;&quot;&quot;</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 &quot;x data&quot;. 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"> &quot;&quot;&quot;</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">&quot;RNN&quot;</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">&quot;dense&quot;</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">&quot;mean_squared_error&quot;</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">&quot;adam&quot;</span>)
<span style="color: #008000; font-weight: bold">return</span> model
</pre></div>
<p>
<!-- !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>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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">&quot;&quot;&quot;</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"> &quot;&quot;&quot;</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">&#39;MSE: &#39;</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">&#39;Predicted&#39;</span><span style="color: #666666">+</span><span style="color: #008000">str</span>(dim)<span style="color: #666666">+</span><span style="color: #BA2121">&#39;.csv&#39;</span>
np<span style="color: #666666">.</span>savetxt(name, y_pred, delimiter<span style="color: #666666">=</span><span style="color: #BA2121">&#39;,&#39;</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">&quot;true&quot;</span>, linewidth<span style="color: #666666">=3</span>)
ax<span style="color: #666666">.</span>plot(x1, y_pred, <span style="color: #BA2121">&#39;g-.&#39;</span>,label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;predicted&quot;</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">&#39;red&#39;</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">&quot;loss&quot;</span>,<span style="color: #BA2121">&quot;val_loss&quot;</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">&quot;loss&quot;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;epoch&quot;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">&quot;val_loss&quot;</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">&#39;Time: &#39;</span>, end<span style="color: #666666">-</span>start)
</pre></div>
<p>
<!-- !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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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">&quot;&quot;&quot;</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 &quot;x data&quot;. 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"> &quot;&quot;&quot;</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">&#39;sigmoid&#39;</span>,
name<span style="color: #666666">=</span><span style="color: #BA2121">&quot;RNN1&quot;</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">&#39;sigmoid&#39;</span>,
stateful <span style="color: #666666">=</span> stateful,
name<span style="color: #666666">=</span><span style="color: #BA2121">&quot;RNN2&quot;</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">&quot;dense&quot;</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">&quot;mean_squared_error&quot;</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">&quot;adam&quot;</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">&quot;loss&quot;</span>,<span style="color: #BA2121">&quot;val_loss&quot;</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">&quot;loss&quot;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;epoch&quot;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">&quot;val_loss&quot;</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">&#39;Time: &#39;</span>, end<span style="color: #666666">-</span>start)
</pre></div>
<p>
<!-- !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>
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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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">&quot;&quot;&quot;</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 &quot;x data&quot;. 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"> &quot;&quot;&quot;</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">&quot;RNN&quot;</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">&#39;tanh&#39;</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">&quot;RNN1&quot;</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">&#39;tanh&#39;</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">&quot;dense&quot;</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">&#39;mean_squared_error&#39;</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">&#39;adam&#39;</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">&quot;&quot;&quot;</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 &quot;x data&quot;. 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"> &quot;&quot;&quot;</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">&#39;relu&#39;</span>, name<span style="color: #666666">=</span><span style="color: #BA2121">&#39;dnn&#39;</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">&#39;relu&#39;</span>, name<span style="color: #666666">=</span><span style="color: #BA2121">&#39;dnn1&#39;</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">&quot;RNN1&quot;</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">&quot;RNN&quot;</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">&quot;dense&quot;</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">&#39;mean_squared_error&#39;</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">&#39;adam&#39;</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">&quot;loss&quot;</span>,<span style="color: #BA2121">&quot;val_loss&quot;</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">&quot;loss&quot;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;epoch&quot;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">&quot;val_loss&quot;</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">&#39;Time: &#39;</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">&quot;loss&quot;</span>,<span style="color: #BA2121">&quot;val_loss&quot;</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">&quot;loss&quot;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;epoch&quot;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">&quot;val_loss&quot;</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">&quot;true&quot;</span>, linewidth<span style="color: #666666">=3</span>)
ax<span style="color: #666666">.</span>plot(X_tot, y_pred, <span style="color: #BA2121">&#39;g-.&#39;</span>,label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;predicted&quot;</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">&#39;red&#39;</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">&#39;Time: &#39;</span>, end<span style="color: #666666">-</span>start)
</pre></div>
<p>
<!-- !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>
<b>Note</b>: this material is thanks to Linus Ekstr&#248;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>
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
$$
\begin{equation}
x = g(z; \theta^{(g)})
\label{_auto1}
\end{equation}
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="discriminator">Discriminator </h2>
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
$$
\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
$$
\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
$$
\begin{equation}
-v(\theta^{(g)}, \theta^{(d)})
\label{_auto4}
\end{equation}
$$
<p>
<!-- !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
$$
\begin{equation}
g^* = \underset{g}{\mathrm{argmin}}\hspace{2pt}
\underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)})
\label{_auto5}
\end{equation}
$$
The default choice for \( v \) is
$$
\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}
$$
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
$$
\begin{equation}
\underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)})
\label{_auto7}
\end{equation}
$$
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>
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>
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>
First we import our libraries
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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>
<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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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">&#39;float32&#39;</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>
<p>
<!-- !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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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">&#39;Greys&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></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>
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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">generator_model</span>():
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</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"> &quot;&quot;&quot;</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 &#39;layer&#39;. 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 &#39;one&#39; 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">&#39;same&#39;</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">&#39;same&#39;</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">&#39;same&#39;</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">&#39;tanh&#39;</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>
<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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">discriminator_model</span>():
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</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"> &quot;&quot;&quot;</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">&#39;same&#39;</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">&#39;same&#39;</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>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="other-models">Other Models </h2>
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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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">&#39;LR&#39;</span>)
</pre></div>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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">&#39;LR&#39;</span>)
</pre></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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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>
<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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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>
<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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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>
<p>
<!-- !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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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>
<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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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&#39;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">&#39;gray&#39;</span>)
plt<span style="color: #666666">.</span>axis(<span style="color: #BA2121">&#39;off&#39;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">f&#39;./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&#39;</span>)
plt<span style="color: #666666">.</span>close()
<span style="color: #408080; font-style: italic">#plt.show()</span>
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="checkpoints">Checkpoints </h2>
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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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">&#39;./training_checkpoints&#39;</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">&#39;ckpt&#39;</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>
<p>
Now we define our training loop
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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&#39;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">&#39;</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">&#39;./data/lossfile.txt&#39;</span>
<span style="color: #008000; font-weight: bold">with</span> <span style="color: #008000">open</span>(loss_file, <span style="color: #BA2121">&#39;w&#39;</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">&#39;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span>)
outfile<span style="color: #666666">.</span>write(<span style="color: #BA2121">&#39;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</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">&#39;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span>)
outfile<span style="color: #666666">.</span>write(<span style="color: #BA2121">&#39;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span>)
</pre></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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>train(train_dataset, EPOCHS)
</pre></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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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>
<p>
<!-- !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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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">&#39;Greys&#39;</span>)
axs[i, j]<span style="color: #666666">.</span>axis(<span style="color: #BA2121">&#39;off&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>generated_images <span style="color: #666666">=</span> generate_images(generate_latent_points())
plot_result(generated_images)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="getting-results">Getting Results </h2>
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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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>
<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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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>
<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>
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>
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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><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>
<p>
Now we have all we need to do our interpolation analysis.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>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>
<p>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>