854 lines
73 KiB
HTML
854 lines
73 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: Convolutional Neural Networks and Recurrent Neural Networks">
|
|
|
|
<title>Week 43: Convolutional Neural Networks and Recurrent Neural Networks</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'),
|
|
('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')]}
|
|
end of tocinfo -->
|
|
|
|
<body>
|
|
|
|
|
|
<!-- ------------------- main content ---------------------- -->
|
|
|
|
|
|
|
|
<center><h1>Week 43: Convolutional Neural Networks and Recurrent Neural Networks</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 23, 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</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>
|
|
</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>
|
|
</ul>
|
|
|
|
<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>
|
|
</div>
|
|
|
|
|
|
<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>
|
|
Text to come.
|
|
|
|
<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">"relu"</span>))
|
|
model<span style="color: #666666">.</span>add(Dense(<span style="color: #666666">8</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">"relu"</span>))
|
|
model<span style="color: #666666">.</span>add(Dense(<span style="color: #666666">1</span>))
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">'mean_squared_error'</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">'rmsprop'</span>)
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
model<span style="color: #666666">.</span>fit(trainX,trainY, epochs<span style="color: #666666">=100</span>, batch_size<span style="color: #666666">=16</span>, verbose<span style="color: #666666">=2</span>)
|
|
trainPredict <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(trainX)
|
|
testPredict<span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(testX)
|
|
predicted<span style="color: #666666">=</span>np<span style="color: #666666">.</span>concatenate((trainPredict,testPredict),axis<span style="color: #666666">=0</span>)
|
|
|
|
trainScore <span style="color: #666666">=</span> model<span style="color: #666666">.</span>evaluate(trainX, trainY, verbose<span style="color: #666666">=0</span>)
|
|
<span style="color: #008000">print</span>(trainScore)
|
|
|
|
index <span style="color: #666666">=</span> df<span style="color: #666666">.</span>index<span style="color: #666666">.</span>values
|
|
plt<span style="color: #666666">.</span>plot(index,df)
|
|
plt<span style="color: #666666">.</span>plot(index,predicted)
|
|
plt<span style="color: #666666">.</span>axvline(df<span style="color: #666666">.</span>index[Tp], c<span style="color: #666666">=</span><span style="color: #BA2121">"r"</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<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">'VaryDimension'</span>
|
|
X_tot <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">2</span>, <span style="color: #666666">42</span>, <span style="color: #666666">2</span>)
|
|
y_tot <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">-0.03077640549</span>, <span style="color: #666666">-0.08336233266</span>, <span style="color: #666666">-0.1446729567</span>, <span style="color: #666666">-0.2116753732</span>, <span style="color: #666666">-0.2830637392</span>, <span style="color: #666666">-0.3581341341</span>, <span style="color: #666666">-0.436462435</span>, <span style="color: #666666">-0.5177783846</span>,
|
|
<span style="color: #666666">-0.6019067271</span>, <span style="color: #666666">-0.6887363571</span>, <span style="color: #666666">-0.7782028952</span>, <span style="color: #666666">-0.8702784034</span>, <span style="color: #666666">-0.9649652536</span>, <span style="color: #666666">-1.062292565</span>, <span style="color: #666666">-1.16231451</span>,
|
|
<span style="color: #666666">-1.265109911</span>, <span style="color: #666666">-1.370782966</span>, <span style="color: #666666">-1.479465113</span>, <span style="color: #666666">-1.591317992</span>, <span style="color: #666666">-1.70653767</span>])
|
|
</pre></div>
|
|
<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">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> data(a numpy array): the data that will be the inputs to the recurrent neural</span>
|
|
<span style="color: #BA2121; font-style: italic"> network</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequence (an int): the number of elements in one iteration of the</span>
|
|
<span style="color: #BA2121; font-style: italic"> sequence patter. For a function approximator use length_of_sequence = 2.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its</span>
|
|
<span style="color: #BA2121; font-style: italic"> dimensions are length of data - length of sequence, length of sequence, </span>
|
|
<span style="color: #BA2121; font-style: italic"> dimnsion of data</span>
|
|
<span style="color: #BA2121; font-style: italic"> rnn_output (a numpy array): the training data for the neural network</span>
|
|
<span style="color: #BA2121; font-style: italic"> Formats data to be used in a recurrent neural network.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
|
|
X, Y <span style="color: #666666">=</span> [], []
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">len</span>(data)<span style="color: #666666">-</span>length_of_sequence):
|
|
<span style="color: #408080; font-style: italic"># Get the next length_of_sequence elements</span>
|
|
a <span style="color: #666666">=</span> data[i:i<span style="color: #666666">+</span>length_of_sequence]
|
|
<span style="color: #408080; font-style: italic"># Get the element that immediately follows that</span>
|
|
b <span style="color: #666666">=</span> data[i<span style="color: #666666">+</span>length_of_sequence]
|
|
<span style="color: #408080; font-style: italic"># Reshape so that each data point is contained in its own array</span>
|
|
a <span style="color: #666666">=</span> np<span style="color: #666666">.</span>reshape (a, (<span style="color: #008000">len</span>(a), <span style="color: #666666">1</span>))
|
|
X<span style="color: #666666">.</span>append(a)
|
|
Y<span style="color: #666666">.</span>append(b)
|
|
rnn_input <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array(X)
|
|
rnn_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array(Y)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> rnn_input, rnn_output
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># ## Defining the Recurrent Neural Network Using Keras</span>
|
|
<span style="color: #408080; font-style: italic"># </span>
|
|
<span style="color: #408080; font-style: italic"># The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">rnn</span>(length_of_sequences, batch_size <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>, stateful <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">False</span>):
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequences (an int): the number of y values in "x data". This is determined</span>
|
|
<span style="color: #BA2121; font-style: italic"> when the data is formatted</span>
|
|
<span style="color: #BA2121; font-style: italic"> batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> model (a Keras model): The recurrent neural network that is built and compiled by this</span>
|
|
<span style="color: #BA2121; font-style: italic"> method</span>
|
|
<span style="color: #BA2121; font-style: italic"> Builds and compiles a recurrent neural network with one hidden layer and returns the model.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons in the input and output layers</span>
|
|
in_out_neurons <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons in the hidden layer</span>
|
|
hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">200</span>
|
|
<span style="color: #408080; font-style: italic"># Define the input layer</span>
|
|
inp <span style="color: #666666">=</span> Input(batch_shape<span style="color: #666666">=</span>(batch_size,
|
|
length_of_sequences,
|
|
in_out_neurons))
|
|
<span style="color: #408080; font-style: italic"># Define the hidden layer as a simple RNN layer with a set number of neurons and add it to </span>
|
|
<span style="color: #408080; font-style: italic"># the network immediately after the input layer</span>
|
|
rnn <span style="color: #666666">=</span> SimpleRNN(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN"</span>)(inp)
|
|
<span style="color: #408080; font-style: italic"># Define the output layer as a dense neural network layer (standard neural network layer)</span>
|
|
<span style="color: #408080; font-style: italic">#and add it to the network immediately after the hidden layer.</span>
|
|
dens <span style="color: #666666">=</span> Dense(in_out_neurons,name<span style="color: #666666">=</span><span style="color: #BA2121">"dense"</span>)(rnn)
|
|
<span style="color: #408080; font-style: italic"># Create the machine learning model starting with the input layer and ending with the </span>
|
|
<span style="color: #408080; font-style: italic"># output layer</span>
|
|
model <span style="color: #666666">=</span> Model(inputs<span style="color: #666666">=</span>[inp],outputs<span style="color: #666666">=</span>[dens])
|
|
<span style="color: #408080; font-style: italic"># Compile the machine learning model using the mean squared error function as the loss </span>
|
|
<span style="color: #408080; font-style: italic"># function and an Adams optimizer.</span>
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">"mean_squared_error"</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">"adam"</span>)
|
|
<span style="color: #008000; font-weight: bold">return</span> model
|
|
</pre></div>
|
|
<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">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> x1 (a list or numpy array): The complete x component of the data set</span>
|
|
<span style="color: #BA2121; font-style: italic"> y_test (a list or numpy array): The complete y component of the data set</span>
|
|
<span style="color: #BA2121; font-style: italic"> plot_min (an int or float): the smallest x value used in the training data</span>
|
|
<span style="color: #BA2121; font-style: italic"> plot_max (an int or float): the largest x valye used in the training data</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> None.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Uses a trained recurrent neural network model to predict future points in the </span>
|
|
<span style="color: #BA2121; font-style: italic"> series. Computes the MSE of the predicted data set from the true data set, saves</span>
|
|
<span style="color: #BA2121; font-style: italic"> the predicted data set to a csv file, and plots the predicted and true data sets w</span>
|
|
<span style="color: #BA2121; font-style: italic"> while also displaying the data range used for training.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Add the training data as the first dim points in the predicted data array as these</span>
|
|
<span style="color: #408080; font-style: italic"># are known values.</span>
|
|
y_pred <span style="color: #666666">=</span> y_test[:dim]<span style="color: #666666">.</span>tolist()
|
|
<span style="color: #408080; font-style: italic"># Generate the first input to the trained recurrent neural network using the last two </span>
|
|
<span style="color: #408080; font-style: italic"># points of the training data. Based on how the network was trained this means that it</span>
|
|
<span style="color: #408080; font-style: italic"># will predict the first point in the data set after the training data. All of the </span>
|
|
<span style="color: #408080; font-style: italic"># brackets are necessary for Tensorflow.</span>
|
|
next_input <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[[y_test[dim<span style="color: #666666">-2</span>]], [y_test[dim<span style="color: #666666">-1</span>]]]])
|
|
<span style="color: #408080; font-style: italic"># Save the very last point in the training data set. This will be used later.</span>
|
|
last <span style="color: #666666">=</span> [y_test[dim<span style="color: #666666">-1</span>]]
|
|
|
|
<span style="color: #408080; font-style: italic"># Iterate until the complete data set is created.</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span> (dim, <span style="color: #008000">len</span>(y_test)):
|
|
<span style="color: #408080; font-style: italic"># Predict the next point in the data set using the previous two points.</span>
|
|
<span style="color: #008000">next</span> <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(next_input)
|
|
<span style="color: #408080; font-style: italic"># Append just the number of the predicted data set</span>
|
|
y_pred<span style="color: #666666">.</span>append(<span style="color: #008000">next</span>[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>])
|
|
<span style="color: #408080; font-style: italic"># Create the input that will be used to predict the next data point in the data set.</span>
|
|
next_input <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[last, <span style="color: #008000">next</span>[<span style="color: #666666">0</span>]]], dtype<span style="color: #666666">=</span>np<span style="color: #666666">.</span>float64)
|
|
last <span style="color: #666666">=</span> <span style="color: #008000">next</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Print the mean squared error between the known data set and the predicted data set.</span>
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'MSE: '</span>, np<span style="color: #666666">.</span>square(np<span style="color: #666666">.</span>subtract(y_test, y_pred))<span style="color: #666666">.</span>mean())
|
|
<span style="color: #408080; font-style: italic"># Save the predicted data set as a csv file for later use</span>
|
|
name <span style="color: #666666">=</span> datatype <span style="color: #666666">+</span> <span style="color: #BA2121">'Predicted'</span><span style="color: #666666">+</span><span style="color: #008000">str</span>(dim)<span style="color: #666666">+</span><span style="color: #BA2121">'.csv'</span>
|
|
np<span style="color: #666666">.</span>savetxt(name, y_pred, delimiter<span style="color: #666666">=</span><span style="color: #BA2121">','</span>)
|
|
<span style="color: #408080; font-style: italic"># Plot the known data set and the predicted data set. The red box represents the region that was used</span>
|
|
<span style="color: #408080; font-style: italic"># for the training data.</span>
|
|
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots()
|
|
ax<span style="color: #666666">.</span>plot(x1, y_test, label<span style="color: #666666">=</span><span style="color: #BA2121">"true"</span>, linewidth<span style="color: #666666">=3</span>)
|
|
ax<span style="color: #666666">.</span>plot(x1, y_pred, <span style="color: #BA2121">'g-.'</span>,label<span style="color: #666666">=</span><span style="color: #BA2121">"predicted"</span>, linewidth<span style="color: #666666">=4</span>)
|
|
ax<span style="color: #666666">.</span>legend()
|
|
<span style="color: #408080; font-style: italic"># Created a red region to represent the points used in the training data.</span>
|
|
ax<span style="color: #666666">.</span>axvspan(plot_min, plot_max, alpha<span style="color: #666666">=0.25</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">'red'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Check to make sure the data set is complete</span>
|
|
<span style="color: #008000; font-weight: bold">assert</span> <span style="color: #008000">len</span>(X_tot) <span style="color: #666666">==</span> <span style="color: #008000">len</span>(y_tot)
|
|
|
|
<span style="color: #408080; font-style: italic"># This is the number of points that will be used in as the training data</span>
|
|
dim<span style="color: #666666">=12</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Separate the training data from the whole data set</span>
|
|
X_train <span style="color: #666666">=</span> X_tot[:dim]
|
|
y_train <span style="color: #666666">=</span> y_tot[:dim]
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Generate the training data for the RNN, using a sequence of 2</span>
|
|
rnn_input, rnn_training <span style="color: #666666">=</span> format_data(y_train, <span style="color: #666666">2</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Create a recurrent neural network in Keras and produce a summary of the </span>
|
|
<span style="color: #408080; font-style: italic"># machine learning model</span>
|
|
model <span style="color: #666666">=</span> rnn(length_of_sequences <span style="color: #666666">=</span> rnn_input<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>])
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
<span style="color: #408080; font-style: italic"># Start the timer. Want to time training+testing</span>
|
|
start <span style="color: #666666">=</span> timer()
|
|
<span style="color: #408080; font-style: italic"># Fit the model using the training data genenerated above using 150 training iterations and a 5%</span>
|
|
<span style="color: #408080; font-style: italic"># validation split. Setting verbose to True prints information about each training iteration.</span>
|
|
hist <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(rnn_input, rnn_training, batch_size<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>, epochs<span style="color: #666666">=150</span>,
|
|
verbose<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,validation_split<span style="color: #666666">=0.05</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> label <span style="color: #AA22FF; font-weight: bold">in</span> [<span style="color: #BA2121">"loss"</span>,<span style="color: #BA2121">"val_loss"</span>]:
|
|
plt<span style="color: #666666">.</span>plot(hist<span style="color: #666666">.</span>history[label],label<span style="color: #666666">=</span>label)
|
|
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"loss"</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"epoch"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">"val_loss"</span>][<span style="color: #666666">-1</span>]))
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Use the trained neural network to predict more points of the data set</span>
|
|
test_rnn(X_tot, y_tot, X_tot[<span style="color: #666666">0</span>], X_tot[dim<span style="color: #666666">-1</span>])
|
|
<span style="color: #408080; font-style: italic"># Stop the timer and calculate the total time needed.</span>
|
|
end <span style="color: #666666">=</span> timer()
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Time: '</span>, end<span style="color: #666666">-</span>start)
|
|
</pre></div>
|
|
<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">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequences (an int): the number of y values in "x data". This is determined</span>
|
|
<span style="color: #BA2121; font-style: italic"> when the data is formatted</span>
|
|
<span style="color: #BA2121; font-style: italic"> batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> model (a Keras model): The recurrent neural network that is built and compiled by this</span>
|
|
<span style="color: #BA2121; font-style: italic"> method</span>
|
|
<span style="color: #BA2121; font-style: italic"> Builds and compiles a recurrent neural network with two hidden layers and returns the model.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons in the input and output layers</span>
|
|
in_out_neurons <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons in the hidden layer, increased from the first network</span>
|
|
hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">500</span>
|
|
<span style="color: #408080; font-style: italic"># Define the input layer</span>
|
|
inp <span style="color: #666666">=</span> Input(batch_shape<span style="color: #666666">=</span>(batch_size,
|
|
length_of_sequences,
|
|
in_out_neurons))
|
|
<span style="color: #408080; font-style: italic"># Create two hidden layers instead of one hidden layer. Explicitly set the activation</span>
|
|
<span style="color: #408080; font-style: italic"># function to be the sigmoid function (the default value is hyperbolic tangent)</span>
|
|
rnn1 <span style="color: #666666">=</span> SimpleRNN(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, <span style="color: #408080; font-style: italic"># This needs to be True if another hidden layer is to follow</span>
|
|
stateful <span style="color: #666666">=</span> stateful, activation <span style="color: #666666">=</span> <span style="color: #BA2121">'sigmoid'</span>,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN1"</span>)(inp)
|
|
rnn2 <span style="color: #666666">=</span> SimpleRNN(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>, activation <span style="color: #666666">=</span> <span style="color: #BA2121">'sigmoid'</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN2"</span>)(rnn1)
|
|
<span style="color: #408080; font-style: italic"># Define the output layer as a dense neural network layer (standard neural network layer)</span>
|
|
<span style="color: #408080; font-style: italic">#and add it to the network immediately after the hidden layer.</span>
|
|
dens <span style="color: #666666">=</span> Dense(in_out_neurons,name<span style="color: #666666">=</span><span style="color: #BA2121">"dense"</span>)(rnn2)
|
|
<span style="color: #408080; font-style: italic"># Create the machine learning model starting with the input layer and ending with the </span>
|
|
<span style="color: #408080; font-style: italic"># output layer</span>
|
|
model <span style="color: #666666">=</span> Model(inputs<span style="color: #666666">=</span>[inp],outputs<span style="color: #666666">=</span>[dens])
|
|
<span style="color: #408080; font-style: italic"># Compile the machine learning model using the mean squared error function as the loss </span>
|
|
<span style="color: #408080; font-style: italic"># function and an Adams optimizer.</span>
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">"mean_squared_error"</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">"adam"</span>)
|
|
<span style="color: #008000; font-weight: bold">return</span> model
|
|
|
|
<span style="color: #408080; font-style: italic"># Check to make sure the data set is complete</span>
|
|
<span style="color: #008000; font-weight: bold">assert</span> <span style="color: #008000">len</span>(X_tot) <span style="color: #666666">==</span> <span style="color: #008000">len</span>(y_tot)
|
|
|
|
<span style="color: #408080; font-style: italic"># This is the number of points that will be used in as the training data</span>
|
|
dim<span style="color: #666666">=12</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Separate the training data from the whole data set</span>
|
|
X_train <span style="color: #666666">=</span> X_tot[:dim]
|
|
y_train <span style="color: #666666">=</span> y_tot[:dim]
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Generate the training data for the RNN, using a sequence of 2</span>
|
|
rnn_input, rnn_training <span style="color: #666666">=</span> format_data(y_train, <span style="color: #666666">2</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Create a recurrent neural network in Keras and produce a summary of the </span>
|
|
<span style="color: #408080; font-style: italic"># machine learning model</span>
|
|
model <span style="color: #666666">=</span> rnn_2layers(length_of_sequences <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
<span style="color: #408080; font-style: italic"># Start the timer. Want to time training+testing</span>
|
|
start <span style="color: #666666">=</span> timer()
|
|
<span style="color: #408080; font-style: italic"># Fit the model using the training data genenerated above using 150 training iterations and a 5%</span>
|
|
<span style="color: #408080; font-style: italic"># validation split. Setting verbose to True prints information about each training iteration.</span>
|
|
hist <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(rnn_input, rnn_training, batch_size<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>, epochs<span style="color: #666666">=150</span>,
|
|
verbose<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,validation_split<span style="color: #666666">=0.05</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># This section plots the training loss and the validation loss as a function of training iteration.</span>
|
|
<span style="color: #408080; font-style: italic"># This is not required for analyzing the couple cluster data but can help determine if the network is</span>
|
|
<span style="color: #408080; font-style: italic"># being overtrained.</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> label <span style="color: #AA22FF; font-weight: bold">in</span> [<span style="color: #BA2121">"loss"</span>,<span style="color: #BA2121">"val_loss"</span>]:
|
|
plt<span style="color: #666666">.</span>plot(hist<span style="color: #666666">.</span>history[label],label<span style="color: #666666">=</span>label)
|
|
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"loss"</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"epoch"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">"val_loss"</span>][<span style="color: #666666">-1</span>]))
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Use the trained neural network to predict more points of the data set</span>
|
|
test_rnn(X_tot, y_tot, X_tot[<span style="color: #666666">0</span>], X_tot[dim<span style="color: #666666">-1</span>])
|
|
<span style="color: #408080; font-style: italic"># Stop the timer and calculate the total time needed.</span>
|
|
end <span style="color: #666666">=</span> timer()
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Time: '</span>, end<span style="color: #666666">-</span>start)
|
|
</pre></div>
|
|
<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">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequences (an int): the number of y values in "x data". This is determined</span>
|
|
<span style="color: #BA2121; font-style: italic"> when the data is formatted</span>
|
|
<span style="color: #BA2121; font-style: italic"> batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> model (a Keras model): The recurrent neural network that is built and compiled by this</span>
|
|
<span style="color: #BA2121; font-style: italic"> method</span>
|
|
<span style="color: #BA2121; font-style: italic"> Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons on the input/output layer and the number of neurons in the hidden layer</span>
|
|
in_out_neurons <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">250</span>
|
|
<span style="color: #408080; font-style: italic"># Input Layer</span>
|
|
inp <span style="color: #666666">=</span> Input(batch_shape<span style="color: #666666">=</span>(batch_size,
|
|
length_of_sequences,
|
|
in_out_neurons))
|
|
<span style="color: #408080; font-style: italic"># Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)</span>
|
|
rnn<span style="color: #666666">=</span> LSTM(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN"</span>, use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">'tanh'</span>)(inp)
|
|
rnn1 <span style="color: #666666">=</span> LSTM(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN1"</span>, use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">'tanh'</span>)(rnn)
|
|
<span style="color: #408080; font-style: italic"># Output layer</span>
|
|
dens <span style="color: #666666">=</span> Dense(in_out_neurons,name<span style="color: #666666">=</span><span style="color: #BA2121">"dense"</span>)(rnn1)
|
|
<span style="color: #408080; font-style: italic"># Define the midel</span>
|
|
model <span style="color: #666666">=</span> Model(inputs<span style="color: #666666">=</span>[inp],outputs<span style="color: #666666">=</span>[dens])
|
|
<span style="color: #408080; font-style: italic"># Compile the model</span>
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">'mean_squared_error'</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">'adam'</span>)
|
|
<span style="color: #408080; font-style: italic"># Return the model</span>
|
|
<span style="color: #008000; font-weight: bold">return</span> model
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">dnn2_gru2</span>(length_of_sequences, batch_size <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>, stateful <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">False</span>):
|
|
<span style="color: #BA2121; font-style: italic">"""</span>
|
|
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
|
|
<span style="color: #BA2121; font-style: italic"> length_of_sequences (an int): the number of y values in "x data". This is determined</span>
|
|
<span style="color: #BA2121; font-style: italic"> when the data is formatted</span>
|
|
<span style="color: #BA2121; font-style: italic"> batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.</span>
|
|
<span style="color: #BA2121; font-style: italic"> Returns:</span>
|
|
<span style="color: #BA2121; font-style: italic"> model (a Keras model): The recurrent neural network that is built and compiled by this</span>
|
|
<span style="color: #BA2121; font-style: italic"> method</span>
|
|
<span style="color: #BA2121; font-style: italic"> Builds and compiles a recurrent neural network with four hidden layers (two dense followed by</span>
|
|
<span style="color: #BA2121; font-style: italic"> two GRU layers) and returns the model.</span>
|
|
<span style="color: #BA2121; font-style: italic"> """</span>
|
|
<span style="color: #408080; font-style: italic"># Number of neurons on the input/output layers and hidden layers</span>
|
|
in_out_neurons <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">250</span>
|
|
<span style="color: #408080; font-style: italic"># Input layer</span>
|
|
inp <span style="color: #666666">=</span> Input(batch_shape<span style="color: #666666">=</span>(batch_size,
|
|
length_of_sequences,
|
|
in_out_neurons))
|
|
<span style="color: #408080; font-style: italic"># Hidden Dense (feedforward) layers</span>
|
|
dnn <span style="color: #666666">=</span> Dense(hidden_neurons<span style="color: #666666">/2</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">'relu'</span>, name<span style="color: #666666">=</span><span style="color: #BA2121">'dnn'</span>)(inp)
|
|
dnn1 <span style="color: #666666">=</span> Dense(hidden_neurons<span style="color: #666666">/2</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">'relu'</span>, name<span style="color: #666666">=</span><span style="color: #BA2121">'dnn1'</span>)(dnn)
|
|
<span style="color: #408080; font-style: italic"># Hidden GRU layers</span>
|
|
rnn1 <span style="color: #666666">=</span> GRU(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN1"</span>, use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)(dnn1)
|
|
rnn <span style="color: #666666">=</span> GRU(hidden_neurons,
|
|
return_sequences<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,
|
|
stateful <span style="color: #666666">=</span> stateful,
|
|
name<span style="color: #666666">=</span><span style="color: #BA2121">"RNN"</span>, use_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)(rnn1)
|
|
<span style="color: #408080; font-style: italic"># Output layer</span>
|
|
dens <span style="color: #666666">=</span> Dense(in_out_neurons,name<span style="color: #666666">=</span><span style="color: #BA2121">"dense"</span>)(rnn)
|
|
<span style="color: #408080; font-style: italic"># Define the model</span>
|
|
model <span style="color: #666666">=</span> Model(inputs<span style="color: #666666">=</span>[inp],outputs<span style="color: #666666">=</span>[dens])
|
|
<span style="color: #408080; font-style: italic"># Compile the mdoel</span>
|
|
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">'mean_squared_error'</span>, optimizer<span style="color: #666666">=</span><span style="color: #BA2121">'adam'</span>)
|
|
<span style="color: #408080; font-style: italic"># Return the model</span>
|
|
<span style="color: #008000; font-weight: bold">return</span> model
|
|
|
|
<span style="color: #408080; font-style: italic"># Check to make sure the data set is complete</span>
|
|
<span style="color: #008000; font-weight: bold">assert</span> <span style="color: #008000">len</span>(X_tot) <span style="color: #666666">==</span> <span style="color: #008000">len</span>(y_tot)
|
|
|
|
<span style="color: #408080; font-style: italic"># This is the number of points that will be used in as the training data</span>
|
|
dim<span style="color: #666666">=12</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Separate the training data from the whole data set</span>
|
|
X_train <span style="color: #666666">=</span> X_tot[:dim]
|
|
y_train <span style="color: #666666">=</span> y_tot[:dim]
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Generate the training data for the RNN, using a sequence of 2</span>
|
|
rnn_input, rnn_training <span style="color: #666666">=</span> format_data(y_train, <span style="color: #666666">2</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Create a recurrent neural network in Keras and produce a summary of the </span>
|
|
<span style="color: #408080; font-style: italic"># machine learning model</span>
|
|
<span style="color: #408080; font-style: italic"># Change the method name to reflect which network you want to use</span>
|
|
model <span style="color: #666666">=</span> dnn2_gru2(length_of_sequences <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
<span style="color: #408080; font-style: italic"># Start the timer. Want to time training+testing</span>
|
|
start <span style="color: #666666">=</span> timer()
|
|
<span style="color: #408080; font-style: italic"># Fit the model using the training data genenerated above using 150 training iterations and a 5%</span>
|
|
<span style="color: #408080; font-style: italic"># validation split. Setting verbose to True prints information about each training iteration.</span>
|
|
hist <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(rnn_input, rnn_training, batch_size<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>, epochs<span style="color: #666666">=150</span>,
|
|
verbose<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,validation_split<span style="color: #666666">=0.05</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># This section plots the training loss and the validation loss as a function of training iteration.</span>
|
|
<span style="color: #408080; font-style: italic"># This is not required for analyzing the couple cluster data but can help determine if the network is</span>
|
|
<span style="color: #408080; font-style: italic"># being overtrained.</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> label <span style="color: #AA22FF; font-weight: bold">in</span> [<span style="color: #BA2121">"loss"</span>,<span style="color: #BA2121">"val_loss"</span>]:
|
|
plt<span style="color: #666666">.</span>plot(hist<span style="color: #666666">.</span>history[label],label<span style="color: #666666">=</span>label)
|
|
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"loss"</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"epoch"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">"val_loss"</span>][<span style="color: #666666">-1</span>]))
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Use the trained neural network to predict more points of the data set</span>
|
|
test_rnn(X_tot, y_tot, X_tot[<span style="color: #666666">0</span>], X_tot[dim<span style="color: #666666">-1</span>])
|
|
<span style="color: #408080; font-style: italic"># Stop the timer and calculate the total time needed.</span>
|
|
end <span style="color: #666666">=</span> timer()
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Time: '</span>, end<span style="color: #666666">-</span>start)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)</span>
|
|
<span style="color: #408080; font-style: italic"># </span>
|
|
<span style="color: #408080; font-style: italic"># Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Check to make sure the data set is complete</span>
|
|
<span style="color: #008000; font-weight: bold">assert</span> <span style="color: #008000">len</span>(X_tot) <span style="color: #666666">==</span> <span style="color: #008000">len</span>(y_tot)
|
|
|
|
<span style="color: #408080; font-style: italic"># This is the number of points that will be used in as the training data</span>
|
|
dim<span style="color: #666666">=12</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Separate the training data from the whole data set</span>
|
|
X_train <span style="color: #666666">=</span> X_tot[:dim]
|
|
y_train <span style="color: #666666">=</span> y_tot[:dim]
|
|
|
|
<span style="color: #408080; font-style: italic"># Reshape the data for Keras specifications</span>
|
|
X_train <span style="color: #666666">=</span> X_train<span style="color: #666666">.</span>reshape((dim, <span style="color: #666666">1</span>))
|
|
y_train <span style="color: #666666">=</span> y_train<span style="color: #666666">.</span>reshape((dim, <span style="color: #666666">1</span>))
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Create a recurrent neural network in Keras and produce a summary of the </span>
|
|
<span style="color: #408080; font-style: italic"># machine learning model</span>
|
|
<span style="color: #408080; font-style: italic"># Set the sequence length to 1 for regular data formatting </span>
|
|
model <span style="color: #666666">=</span> rnn(length_of_sequences <span style="color: #666666">=</span> <span style="color: #666666">1</span>)
|
|
model<span style="color: #666666">.</span>summary()
|
|
|
|
<span style="color: #408080; font-style: italic"># Start the timer. Want to time training+testing</span>
|
|
start <span style="color: #666666">=</span> timer()
|
|
<span style="color: #408080; font-style: italic"># Fit the model using the training data genenerated above using 150 training iterations and a 5%</span>
|
|
<span style="color: #408080; font-style: italic"># validation split. Setting verbose to True prints information about each training iteration.</span>
|
|
hist <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(X_train, y_train, batch_size<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>, epochs<span style="color: #666666">=150</span>,
|
|
verbose<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,validation_split<span style="color: #666666">=0.05</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># This section plots the training loss and the validation loss as a function of training iteration.</span>
|
|
<span style="color: #408080; font-style: italic"># This is not required for analyzing the couple cluster data but can help determine if the network is</span>
|
|
<span style="color: #408080; font-style: italic"># being overtrained.</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> label <span style="color: #AA22FF; font-weight: bold">in</span> [<span style="color: #BA2121">"loss"</span>,<span style="color: #BA2121">"val_loss"</span>]:
|
|
plt<span style="color: #666666">.</span>plot(hist<span style="color: #666666">.</span>history[label],label<span style="color: #666666">=</span>label)
|
|
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"loss"</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"epoch"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"The final validation loss: </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(hist<span style="color: #666666">.</span>history[<span style="color: #BA2121">"val_loss"</span>][<span style="color: #666666">-1</span>]))
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Use the trained neural network to predict the remaining data points</span>
|
|
X_pred <span style="color: #666666">=</span> X_tot[dim:]
|
|
X_pred <span style="color: #666666">=</span> X_pred<span style="color: #666666">.</span>reshape((<span style="color: #008000">len</span>(X_pred), <span style="color: #666666">1</span>))
|
|
y_model <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(X_pred)
|
|
y_pred <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((y_tot[:dim], y_model<span style="color: #666666">.</span>flatten()))
|
|
|
|
<span style="color: #408080; font-style: italic"># Plot the known data set and the predicted data set. The red box represents the region that was used</span>
|
|
<span style="color: #408080; font-style: italic"># for the training data.</span>
|
|
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots()
|
|
ax<span style="color: #666666">.</span>plot(X_tot, y_tot, label<span style="color: #666666">=</span><span style="color: #BA2121">"true"</span>, linewidth<span style="color: #666666">=3</span>)
|
|
ax<span style="color: #666666">.</span>plot(X_tot, y_pred, <span style="color: #BA2121">'g-.'</span>,label<span style="color: #666666">=</span><span style="color: #BA2121">"predicted"</span>, linewidth<span style="color: #666666">=4</span>)
|
|
ax<span style="color: #666666">.</span>legend()
|
|
<span style="color: #408080; font-style: italic"># Created a red region to represent the points used in the training data.</span>
|
|
ax<span style="color: #666666">.</span>axvspan(X_tot[<span style="color: #666666">0</span>], X_tot[dim], alpha<span style="color: #666666">=0.25</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">'red'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #408080; font-style: italic"># Stop the timer and calculate the total time needed.</span>
|
|
end <span style="color: #666666">=</span> timer()
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Time: '</span>, end<span style="color: #666666">-</span>start)
|
|
</pre></div>
|
|
<p>
|
|
|
|
<!-- ------------------- end of main content --------------- -->
|
|
|
|
|
|
<center style="font-size:80%">
|
|
<!-- copyright --> © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
|
</center>
|
|
|
|
|
|
</body>
|
|
</html>
|
|
|
|
|