udating week43

This commit is contained in:
Morten Hjorth-Jensen
2021-10-23 21:52:26 +02:00
parent b16f2c0ddb
commit b590e8fad5
17 changed files with 729 additions and 4664 deletions
+9 -106
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -218,7 +123,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Oct 19, 2021</h4></center> <!-- date -->
<center><h4>Oct 23, 2021</h4></center> <!-- date -->
<br>
<p>
@@ -241,8 +146,6 @@ MathJax.Hub.Config({
<li><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs001.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+9 -107
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -202,7 +107,7 @@ MathJax.Hub.Config({
<h2 id="plans-for-week-43" class="anchor">Plans for week 43 </h2>
<ul>
<li> Thursday: Convolutional Neural Networks and Recurrent Neural Networks</li>
<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>
@@ -247,9 +152,6 @@ MathJax.Hub.Config({
<li><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="._week43-bs010.html">11</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs002.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+23 -136
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -199,41 +104,27 @@ MathJax.Hub.Config({
<a name="part0002"></a>
<!-- !split -->
<h2 id="convolutional-neural-networks-recognizing-images" class="anchor">Convolutional Neural Networks (recognizing images) </h2>
<h2 id="recurrent-neural-networks-overarching-view" class="anchor">Recurrent neural networks: Overarching view </h2>
<p>
Convolutional neural networks (CNNs) were developed during the last
decade of the previous century, with a focus on character recognition
tasks. Nowadays, CNNs are a central element in the spectacular success
of deep learning methods. The success in for example image
classifications have made them a central tool for most machine
learning practitioners.
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>
CNNs are very similar to ordinary Neural Networks.
They are made up of neurons that have learnable weights and
biases. Each neuron receives some inputs, performs a dot product and
optionally follows it with a non-linearity. The whole network still
expresses a single differentiable score function: from the raw image
pixels on one end to class scores at the other. And they still have a
loss function (for example Softmax) on the last (fully-connected) layer
and all the tips/tricks we developed for learning regular Neural
Networks still apply (back propagation, gradient descent etc etc).
A recurrent neural network (RNN) looks very much like a feedforward
neural network, except that it also has connections pointing
backward.
<p>
What is the difference? <b>CNN architectures make the explicit assumption that
the inputs are images, which allows us to encode certain properties
into the architecture. These then make the forward function more
efficient to implement and vastly reduce the amount of parameters in
the network.</b>
<p>
Here we provide only a superficial overview, for the more interested, we recommend highly the course
<a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" target="_self">IN5400 &#8211; Machine Learning for Image Analysis</a>
and the slides of <a href="http://cs231n.github.io/convolutional-networks/" target="_self">CS231</a>.
<p>
Another good read is the article here <a href="https://arxiv.org/pdf/1603.07285.pdf" target="_self"><tt>https://arxiv.org/pdf/1603.07285.pdf</tt></a>.
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>
<p>
@@ -250,10 +141,6 @@ Another good read is the article here <a href="https://arxiv.org/pdf/1603.07285.
<li><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="._week43-bs010.html">11</a></li>
<li><a href="._week43-bs011.html">12</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs003.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+10 -116
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -199,16 +104,10 @@ MathJax.Hub.Config({
<a name="part0003"></a>
<!-- !split -->
<h2 id="neural-networks-vs-cnns" class="anchor">Neural Networks vs CNNs </h2>
<h2 id="set-up-of-an-rnn" class="anchor">Set up of an RNN </h2>
<p>
Neural networks are defined as <b>affine transformations</b>, that is
a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an
output (to which a bias vector is usually added before passing the result
through a nonlinear activation function). This is applicable to any type of input, be it an
image, a sound clip or an unordered collection of features: whatever their
dimensionality, their representation can always be flattened into a vector
before the transformation.
Text to come.
<p>
<p>
@@ -225,11 +124,6 @@ before the transformation.
<li><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="._week43-bs010.html">11</a></li>
<li><a href="._week43-bs011.html">12</a></li>
<li><a href="._week43-bs012.html">13</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs004.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+76 -128
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -199,31 +104,80 @@ MathJax.Hub.Config({
<a name="part0004"></a>
<!-- !split -->
<h2 id="why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" class="anchor">Why CNNS for images, sound files, medical images from CT scans etc? </h2>
<h2 id="a-simple-example" class="anchor">A simple example </h2>
<p>
However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic
structure. More formally, they share these important properties:</li>
<ul>
<li> They are stored as multi-dimensional arrays (think of the pixels of a figure) .</li>
<li> They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).</li>
<li> One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).</li>
</ul>
<!-- 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
These properties are not exploited when an affine transformation is applied; in
fact, all the axes are treated in the same way and the topological information
is not taken into account. Still, taking advantage of the implicit structure of
the data may prove very handy in solving some tasks, like computer vision and
speech recognition, and in these cases it would be best to preserve it. This is
where discrete convolutions come into play.
<p>
A discrete convolution is a linear transformation that preserves this notion of
ordering. It is sparse (only a few input units contribute to a given output
unit) and reuses parameters (the same weights are applied to multiple locations
in the input).
<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>
<p>
<!-- navigation buttons at the bottom of the page -->
@@ -239,12 +193,6 @@ in the input).
<li><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="._week43-bs010.html">11</a></li>
<li><a href="._week43-bs011.html">12</a></li>
<li><a href="._week43-bs012.html">13</a></li>
<li><a href="._week43-bs013.html">14</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs005.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+41 -129
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -199,31 +104,45 @@ MathJax.Hub.Config({
<a name="part0005"></a>
<!-- !split -->
<h2 id="regular-nns-don-t-scale-well-to-full-images" class="anchor">Regular NNs don&#8217;t scale well to full images </h2>
<h2 id="an-extrapolation-example" class="anchor">An extrapolation example </h2>
<p>
As an example, consider
an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a
single fully-connected neuron in a first hidden layer of a regular
Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still
seems manageable, but clearly this fully-connected structure does not
scale to larger images. For example, an image of more respectable
size, say \( 200\times 200\times 3 \), would lead to neurons that have
\( 200\times 200\times 3 = 120,000 \) weights.
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>
We could have
several such neurons, and the parameters would add up quickly! Clearly,
this full connectivity is wasteful and the huge number of parameters
would quickly lead to possible overfitting.
<p>
<center> <!-- FIGURE -->
<hr class="figure">
<center><p class="caption">Figure 1: A regular 3-layer Neural Network. </p></center>
<p><img src="figslides/nn.jpeg" align="bottom" width=500></p>
</center>
<!-- 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>
<p>
<!-- navigation buttons at the bottom of the page -->
@@ -239,13 +158,6 @@ would quickly lead to possible overfitting.
<li><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="._week43-bs010.html">11</a></li>
<li><a href="._week43-bs011.html">12</a></li>
<li><a href="._week43-bs012.html">13</a></li>
<li><a href="._week43-bs013.html">14</a></li>
<li><a href="._week43-bs014.html">15</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs006.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+112 -138
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -199,43 +104,120 @@ MathJax.Hub.Config({
<a name="part0006"></a>
<!-- !split -->
<h2 id="3d-volumes-of-neurons" class="anchor">3D volumes of neurons </h2>
<h2 id="formatting-the-data" class="anchor">Formatting the Data </h2>
<p>
Convolutional Neural Networks take advantage of the fact that the
input consists of images and they constrain the architecture in a more
sensible way.
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>
In particular, unlike a regular Neural Network, the
layers of a CNN have neurons arranged in 3 dimensions: width,
height, depth. (Note that the word depth here refers to the third
dimension of an activation volume, not to the depth of a full Neural
Network, which can refer to the total number of layers in a network.)
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>
To understand it better, the above example of an image
with an input volume of
activations has dimensions \( 32\times 32\times 3 \) (width, height,
depth respectively).
<!-- -->
<!-- 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>
The neurons in a layer will
only be connected to a small region of the layer before it, instead of
all of the neurons in a fully-connected manner. Moreover, the final
output layer could for this specific image have dimensions \( 1\times 1 \times 10 \),
because by the
end of the CNN architecture we will reduce the full image into a
single vector of class scores, arranged along the depth
dimension.
<p>
<center> <!-- FIGURE -->
<hr class="figure">
<center><p class="caption">Figure 2: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). </p></center>
<p><img src="figslides/cnn.jpeg" align="bottom" width=500></p>
</center>
<!-- 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>
<p>
<!-- navigation buttons at the bottom of the page -->
@@ -251,14 +233,6 @@ dimension.
<li><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="._week43-bs010.html">11</a></li>
<li><a href="._week43-bs011.html">12</a></li>
<li><a href="._week43-bs012.html">13</a></li>
<li><a href="._week43-bs013.html">14</a></li>
<li><a href="._week43-bs014.html">15</a></li>
<li><a href="._week43-bs015.html">16</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs007.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+103 -130
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -197,29 +102,106 @@ MathJax.Hub.Config({
<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p> <!-- add vertical space -->
<a name="part0007"></a>
<!-- !split -->
<!-- !split -->
<h2 id="layers-used-to-build-cnns" class="anchor">Layers used to build CNNs </h2>
<h2 id="predicting-new-points-with-a-trained-recurrent-neural-network" class="anchor">Predicting New Points With A Trained Recurrent Neural Network </h2>
<p>
A simple CNN is a sequence of layers, and every layer of a CNN
transforms one volume of activations to another through a
differentiable function. We use three main types of layers to build
CNN architectures: Convolutional Layer, Pooling Layer, and
Fully-Connected Layer (exactly as seen in regular Neural Networks). We
will stack these layers to form a full CNN architecture.
<!-- 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>
A simple CNN for image classification could have the architecture:
<ul>
<li> <b>INPUT</b> (\( 32\times 32 \times 3 \)) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.</li>
<li> <b>CONV</b> (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as \( [32\times 32\times 12] \) if we decided to use 12 filters.</li>
<li> <b>RELU</b> layer will apply an elementwise activation function, such as the \( max(0,x) \) thresholding at zero. This leaves the size of the volume unchanged (\( [32\times 32\times 12] \)).</li>
<li> <b>POOL</b> (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as \( [16\times 16\times 12] \).</li>
<li> <b>FC</b> (i.e. fully-connected) layer will compute the class scores, resulting in volume of size \( [1\times 1\times 10] \), where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.</li>
</ul>
<p>
<!-- navigation buttons at the bottom of the page -->
<ul class="pagination">
@@ -234,15 +216,6 @@ A simple CNN for image classification could have the architecture:
<li class="active"><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="._week43-bs010.html">11</a></li>
<li><a href="._week43-bs011.html">12</a></li>
<li><a href="._week43-bs012.html">13</a></li>
<li><a href="._week43-bs013.html">14</a></li>
<li><a href="._week43-bs014.html">15</a></li>
<li><a href="._week43-bs015.html">16</a></li>
<li><a href="._week43-bs016.html">17</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs008.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+107 -124
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -199,22 +104,110 @@ MathJax.Hub.Config({
<a name="part0008"></a>
<!-- !split -->
<h2 id="transforming-images" class="anchor">Transforming images </h2>
<h2 id="other-things-to-try" class="anchor">Other Things to Try </h2>
<p>
CNNs transform the original image layer by layer from the original
pixel values to the final class scores.
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="_self">recurrent neural network</a>.
<p>
Observe that some layers contain
parameters and other don&#8217;t. In particular, the CNN layers perform
transformations that are a function of not only the activations in the
input volume, but also of the parameters (the weights and biases of
the neurons). On the other hand, the RELU/POOL layers will implement a
fixed function. The parameters in the CONV/FC layers will be trained
with gradient descent so that the class scores that the CNN computes
are consistent with the labels in the training set for each image.
<!-- 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>
<p>
<!-- navigation buttons at the bottom of the page -->
@@ -230,16 +223,6 @@ are consistent with the labels in the training set for each image.
<li><a href="._week43-bs007.html">8</a></li>
<li class="active"><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="._week43-bs010.html">11</a></li>
<li><a href="._week43-bs011.html">12</a></li>
<li><a href="._week43-bs012.html">13</a></li>
<li><a href="._week43-bs013.html">14</a></li>
<li><a href="._week43-bs014.html">15</a></li>
<li><a href="._week43-bs015.html">16</a></li>
<li><a href="._week43-bs016.html">17</a></li>
<li><a href="._week43-bs017.html">18</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs009.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+219 -130
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -199,25 +104,221 @@ MathJax.Hub.Config({
<a name="part0009"></a>
<!-- !split -->
<h2 id="cnns-in-brief" class="anchor">CNNs in brief </h2>
<h2 id="other-types-of-recurrent-neural-networks" class="anchor">Other Types of Recurrent Neural Networks </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="_self">IN5400 &#8211; Machine Learning for Image Analysis</a>
and the slides of <a href="http://cs231n.github.io/convolutional-networks/" target="_self">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="_self">Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs</a>.
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="_self"><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="_self"><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="_self"><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>
<p>
<!-- navigation buttons at the bottom of the page -->
<ul class="pagination">
@@ -232,18 +333,6 @@ and the slides of <a href="http://cs231n.github.io/convolutional-networks/" targ
<li><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li class="active"><a href="._week43-bs009.html">10</a></li>
<li><a href="._week43-bs010.html">11</a></li>
<li><a href="._week43-bs011.html">12</a></li>
<li><a href="._week43-bs012.html">13</a></li>
<li><a href="._week43-bs013.html">14</a></li>
<li><a href="._week43-bs014.html">15</a></li>
<li><a href="._week43-bs015.html">16</a></li>
<li><a href="._week43-bs016.html">17</a></li>
<li><a href="._week43-bs017.html">18</a></li>
<li><a href="._week43-bs018.html">19</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs010.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+9 -106
View File
@@ -42,60 +42,6 @@ Automatically generated HTML file from DocOnce source
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -117,22 +63,6 @@ end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
@@ -151,39 +81,14 @@ MathJax.Hub.Config({
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week43-bs001.html#plans-for-week-43" style="font-size: 80%;">Plans for week 43</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#convolutional-neural-networks-recognizing-images" style="font-size: 80%;">Convolutional Neural Networks (recognizing images)</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#neural-networks-vs-cnns" style="font-size: 80%;">Neural Networks vs CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc" style="font-size: 80%;">Why CNNS for images, sound files, medical images from CT scans etc?</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#regular-nns-don-t-scale-well-to-full-images" style="font-size: 80%;">Regular NNs dont scale well to full images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#3d-volumes-of-neurons" style="font-size: 80%;">3D volumes of neurons</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#layers-used-to-build-cnns" style="font-size: 80%;">Layers used to build CNNs</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#transforming-images" style="font-size: 80%;">Transforming images</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#cnns-in-brief" style="font-size: 80%;">CNNs in brief</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs010.html#cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras" style="font-size: 80%;">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs011.html#setting-it-up" style="font-size: 80%;">Setting it up</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs012.html#the-mnist-dataset-again" style="font-size: 80%;">The MNIST dataset again</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs013.html#strong-correlations" style="font-size: 80%;">Strong correlations</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs014.html#layers-of-a-cnn" style="font-size: 80%;">Layers of a CNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs015.html#systematic-reduction" style="font-size: 80%;">Systematic reduction</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs016.html#prerequisites-collect-and-pre-process-data" style="font-size: 80%;">Prerequisites: Collect and pre-process data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs017.html#importing-keras-and-tensorflow" style="font-size: 80%;">Importing Keras and Tensorflow</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs018.html#running-with-keras" style="font-size: 80%;">Running with Keras</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs019.html#final-part" style="font-size: 80%;">Final part</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs020.html#final-visualization" style="font-size: 80%;">Final visualization</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs021.html#the-cifar01-data-set" style="font-size: 80%;">The CIFAR01 data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs022.html#verifying-the-data-set" style="font-size: 80%;">Verifying the data set</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs023.html#set-up-the-model" style="font-size: 80%;">Set up the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs024.html#add-dense-layers-on-top" style="font-size: 80%;">Add Dense layers on top</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs025.html#compile-and-train-the-model" style="font-size: 80%;">Compile and train the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs026.html#finally-evaluate-the-model" style="font-size: 80%;">Finally, evaluate the model</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs027.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs028.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs029.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs030.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs031.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs032.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs033.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs034.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs002.html#recurrent-neural-networks-overarching-view" style="font-size: 80%;">Recurrent neural networks: Overarching view</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs003.html#set-up-of-an-rnn" style="font-size: 80%;">Set up of an RNN</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs004.html#a-simple-example" style="font-size: 80%;">A simple example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs005.html#an-extrapolation-example" style="font-size: 80%;">An extrapolation example</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs006.html#formatting-the-data" style="font-size: 80%;">Formatting the Data</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs007.html#predicting-new-points-with-a-trained-recurrent-neural-network" style="font-size: 80%;">Predicting New Points With A Trained Recurrent Neural Network</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs008.html#other-things-to-try" style="font-size: 80%;">Other Things to Try</a></li>
<!-- navigation toc: --> <li><a href="._week43-bs009.html#other-types-of-recurrent-neural-networks" style="font-size: 80%;">Other Types of Recurrent Neural Networks</a></li>
</ul>
</li>
@@ -218,7 +123,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Oct 19, 2021</h4></center> <!-- date -->
<center><h4>Oct 23, 2021</h4></center> <!-- date -->
<br>
<p>
@@ -241,8 +146,6 @@ MathJax.Hub.Config({
<li><a href="._week43-bs007.html">8</a></li>
<li><a href="._week43-bs008.html">9</a></li>
<li><a href="._week43-bs009.html">10</a></li>
<li><a href="">...</a></li>
<li><a href="._week43-bs034.html">35</a></li>
<li><a href="._week43-bs001.html">&raquo;</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
+2 -663
View File
@@ -107,22 +107,6 @@ td.padding {
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
@@ -148,7 +132,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>&nbsp;<br>
<center><h4>Oct 19, 2021</h4></center> <!-- date -->
<center><h4>Oct 23, 2021</h4></center> <!-- date -->
<br>
<p>
@@ -162,7 +146,7 @@ MathJax.Hub.Config({
<h2 id="plans-for-week-43">Plans for week 43 </h2>
<ul>
<p><li> Thursday: Convolutional Neural Networks and Recurrent Neural Networks</li>
<p><li> Thursday: Summary of Convolutional Neural Networks from week 42 and Recurrent Neural Networks</li>
<p><li> Friday: Recurrent Neural Networks and other Deep Learning methods</li>
</ul>
<p>
@@ -186,651 +170,6 @@ MathJax.Hub.Config({
</section>
<section>
<h2 id="convolutional-neural-networks-recognizing-images">Convolutional Neural Networks (recognizing images) </h2>
<p>
Convolutional neural networks (CNNs) were developed during the last
decade of the previous century, with a focus on character recognition
tasks. Nowadays, CNNs are a central element in the spectacular success
of deep learning methods. The success in for example image
classifications have made them a central tool for most machine
learning practitioners.
<p>
CNNs are very similar to ordinary Neural Networks.
They are made up of neurons that have learnable weights and
biases. Each neuron receives some inputs, performs a dot product and
optionally follows it with a non-linearity. The whole network still
expresses a single differentiable score function: from the raw image
pixels on one end to class scores at the other. And they still have a
loss function (for example Softmax) on the last (fully-connected) layer
and all the tips/tricks we developed for learning regular Neural
Networks still apply (back propagation, gradient descent etc etc).
<p>
What is the difference? <b>CNN architectures make the explicit assumption that
the inputs are images, which allows us to encode certain properties
into the architecture. These then make the forward function more
efficient to implement and vastly reduce the amount of parameters in
the network.</b>
<p>
Here we provide only a superficial overview, for the more interested, we recommend highly 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>.
<p>
Another good read is the article here <a href="https://arxiv.org/pdf/1603.07285.pdf" target="_blank"><tt>https://arxiv.org/pdf/1603.07285.pdf</tt></a>.
</section>
<section>
<h2 id="neural-networks-vs-cnns">Neural Networks vs CNNs </h2>
<p>
Neural networks are defined as <b>affine transformations</b>, that is
a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an
output (to which a bias vector is usually added before passing the result
through a nonlinear activation function). This is applicable to any type of input, be it an
image, a sound clip or an unordered collection of features: whatever their
dimensionality, their representation can always be flattened into a vector
before the transformation.
</section>
<section>
<h2 id="why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc">Why CNNS for images, sound files, medical images from CT scans etc? </h2>
<p>
However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic
structure. More formally, they share these important properties:</li>
<ul>
<p><li> They are stored as multi-dimensional arrays (think of the pixels of a figure) .</li>
<p><li> They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).</li>
<p><li> One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).</li>
</ul>
<p>
These properties are not exploited when an affine transformation is applied; in
fact, all the axes are treated in the same way and the topological information
is not taken into account. Still, taking advantage of the implicit structure of
the data may prove very handy in solving some tasks, like computer vision and
speech recognition, and in these cases it would be best to preserve it. This is
where discrete convolutions come into play.
<p>
A discrete convolution is a linear transformation that preserves this notion of
ordering. It is sparse (only a few input units contribute to a given output
unit) and reuses parameters (the same weights are applied to multiple locations
in the input).
</section>
<section>
<h2 id="regular-nns-don-t-scale-well-to-full-images">Regular NNs don&#8217;t scale well to full images </h2>
<p>
As an example, consider
an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a
single fully-connected neuron in a first hidden layer of a regular
Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still
seems manageable, but clearly this fully-connected structure does not
scale to larger images. For example, an image of more respectable
size, say \( 200\times 200\times 3 \), would lead to neurons that have
\( 200\times 200\times 3 = 120,000 \) weights.
<p>
We could have
several such neurons, and the parameters would add up quickly! Clearly,
this full connectivity is wasteful and the huge number of parameters
would quickly lead to possible overfitting.
<p>
<center> <!-- FIGURE -->
<hr class="figure">
<center><p class="caption">Figure 1: A regular 3-layer Neural Network. </p></center>
<p><img src="figslides/nn.jpeg" align="bottom" width=500></p>
</center>
</section>
<section>
<h2 id="3d-volumes-of-neurons">3D volumes of neurons </h2>
<p>
Convolutional Neural Networks take advantage of the fact that the
input consists of images and they constrain the architecture in a more
sensible way.
<p>
In particular, unlike a regular Neural Network, the
layers of a CNN have neurons arranged in 3 dimensions: width,
height, depth. (Note that the word depth here refers to the third
dimension of an activation volume, not to the depth of a full Neural
Network, which can refer to the total number of layers in a network.)
<p>
To understand it better, the above example of an image
with an input volume of
activations has dimensions \( 32\times 32\times 3 \) (width, height,
depth respectively).
<p>
The neurons in a layer will
only be connected to a small region of the layer before it, instead of
all of the neurons in a fully-connected manner. Moreover, the final
output layer could for this specific image have dimensions \( 1\times 1 \times 10 \),
because by the
end of the CNN architecture we will reduce the full image into a
single vector of class scores, arranged along the depth
dimension.
<p>
<center> <!-- FIGURE -->
<hr class="figure">
<center><p class="caption">Figure 2: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). </p></center>
<p><img src="figslides/cnn.jpeg" align="bottom" width=500></p>
</center>
</section>
<section>
<h2 id="layers-used-to-build-cnns">Layers used to build CNNs </h2>
<p>
A simple CNN is a sequence of layers, and every layer of a CNN
transforms one volume of activations to another through a
differentiable function. We use three main types of layers to build
CNN architectures: Convolutional Layer, Pooling Layer, and
Fully-Connected Layer (exactly as seen in regular Neural Networks). We
will stack these layers to form a full CNN architecture.
<p>
A simple CNN for image classification could have the architecture:
<ul>
<p><li> <b>INPUT</b> (\( 32\times 32 \times 3 \)) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.</li>
<p><li> <b>CONV</b> (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as \( [32\times 32\times 12] \) if we decided to use 12 filters.</li>
<p><li> <b>RELU</b> layer will apply an elementwise activation function, such as the \( max(0,x) \) thresholding at zero. This leaves the size of the volume unchanged (\( [32\times 32\times 12] \)).</li>
<p><li> <b>POOL</b> (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as \( [16\times 16\times 12] \).</li>
<p><li> <b>FC</b> (i.e. fully-connected) layer will compute the class scores, resulting in volume of size \( [1\times 1\times 10] \), where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.</li>
</ul>
</section>
<section>
<h2 id="transforming-images">Transforming images </h2>
<p>
CNNs transform the original image layer by layer from the original
pixel values to the final class scores.
<p>
Observe that some layers contain
parameters and other don&#8217;t. In particular, the CNN layers perform
transformations that are a function of not only the activations in the
input volume, but also of the parameters (the weights and biases of
the neurons). On the other hand, the RELU/POOL layers will implement a
fixed function. The parameters in the CONV/FC layers will be trained
with gradient descent so that the class scores that the CNN computes
are consistent with the labels in the training set for each image.
</section>
<section>
<h2 id="cnns-in-brief">CNNs in brief </h2>
<p>
In summary:
<ul>
<p><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>
<p><li> There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)</li>
<p><li> Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function</li>
<p><li> Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don&#8217;t)</li>
<p><li> Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn&#8217;t)</li>
</ul>
<p>
For more material on convolutional networks, we strongly recommend
the course
<a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" target="_blank">IN5400 &#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>.
</section>
<section>
<h2 id="cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras </h2>
<p>
As discussed above, CNNs are neural networks built from the assumption that the inputs
to the network are 2D images. This is important because the number of features or pixels in images
grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
<p>
As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
are the <b>convolutional</b> and <b>pooling</b> layers stacked in pairs between the input and the hidden layer.
In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
matrices, typically 1 for each color dimension (Red, Green, Blue).
</section>
<section>
<h2 id="setting-it-up">Setting it up </h2>
<p>
It means that to represent the entire
dataset of images, we require a 4D matrix or <b>tensor</b>. This tensor has the dimensions:
<p>&nbsp;<br>
$$
(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
$$
<p>&nbsp;<br>
</section>
<section>
<h2 id="the-mnist-dataset-again">The MNIST dataset again </h2>
<p>
The MNIST dataset consists of grayscale images with a pixel size of
\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each
neuron in the first hidden layer.
<p>
If we were to analyze images of size \( 128\times 128 \) we would require
\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were
dealing with color images, as most images are, we have an image matrix
of size \( 128\times 128 \) for each color dimension (Red, Green, Blue),
meaning 3 times the number of weights \( = 49152 \) are required for every
single neuron in the first hidden layer.
</section>
<section>
<h2 id="strong-correlations">Strong correlations </h2>
<p>
Images typically have strong local correlations, meaning that a small
part of the image varies little from its neighboring regions. If for
example we have an image of a blue car, we can roughly assume that a
small blue part of the image is surrounded by other blue regions.
<p>
Therefore, instead of connecting every single pixel to a neuron in the
first hidden layer, as we have previously done with deep neural
networks, we can instead connect each neuron to a small part of the
image (in all 3 RGB depth dimensions). The size of each small area is
fixed, and known as a <a href="https://en.wikipedia.org/wiki/Receptive_field" target="_blank">receptive</a>.
</section>
<section>
<h2 id="layers-of-a-cnn">Layers of a CNN </h2>
The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
The input image is typically a square matrix of depth 3.
<p>
A <b>convolution</b> is performed on the image which outputs
a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as <b>filters</b>.
<p>
Each filter slides along the input image, taking the dot product
between each small part of the image and the filter, in all depth
dimensions. This is then passed through a non-linear function,
typically the <b>Rectified Linear (ReLu)</b> function, which serves as the
activation of the neurons in the first convolutional layer. This is
further passed through a <b>pooling layer</b>, which reduces the size of the
convolutional layer, e.g. by taking the maximum or average across some
small regions, and this serves as input to the next convolutional
layer.
</section>
<section>
<h2 id="systematic-reduction">Systematic reduction </h2>
<p>
By systematically reducing the size of the input volume, through
convolution and pooling, the network should create representations of
small parts of the input, and then from them assemble representations
of larger areas. The final pooling layer is flattened to serve as
input to a hidden layer, such that each neuron in the final pooling
layer is connected to every single neuron in the hidden layer. This
then serves as input to the output layer, e.g. a softmax output for
classification.
</section>
<section>
<h2 id="prerequisites-collect-and-pre-process-data">Prerequisites: Collect and pre-process data </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #228B22"># import necessary packages</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn</span> <span style="color: #8B008B; font-weight: bold">import</span> datasets
<span style="color: #228B22"># ensure the same random numbers appear every time</span>
np.random.seed(<span style="color: #B452CD">0</span>)
<span style="color: #228B22"># display images in notebook</span>
%matplotlib inline
plt.rcParams[<span style="color: #CD5555">&#39;figure.figsize&#39;</span>] = (<span style="color: #B452CD">12</span>,<span style="color: #B452CD">12</span>)
<span style="color: #228B22"># download MNIST dataset</span>
digits = datasets.load_digits()
<span style="color: #228B22"># define inputs and labels</span>
inputs = digits.images
labels = digits.target
<span style="color: #228B22"># RGB images have a depth of 3</span>
<span style="color: #228B22"># our images are grayscale so they should have a depth of 1</span>
inputs = inputs[:,:,:,np.newaxis]
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;inputs = (n_inputs, pixel_width, pixel_height, depth) = &quot;</span> + <span style="color: #658b00">str</span>(inputs.shape))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;labels = (n_inputs) = &quot;</span> + <span style="color: #658b00">str</span>(labels.shape))
<span style="color: #228B22"># choose some random images to display</span>
n_inputs = <span style="color: #658b00">len</span>(inputs)
indices = np.arange(n_inputs)
random_indices = np.random.choice(indices, size=<span style="color: #B452CD">5</span>)
<span style="color: #8B008B; font-weight: bold">for</span> i, image <span style="color: #8B008B">in</span> <span style="color: #658b00">enumerate</span>(digits.images[random_indices]):
plt.subplot(<span style="color: #B452CD">1</span>, <span style="color: #B452CD">5</span>, i+<span style="color: #B452CD">1</span>)
plt.axis(<span style="color: #CD5555">&#39;off&#39;</span>)
plt.imshow(image, cmap=plt.cm.gray_r, interpolation=<span style="color: #CD5555">&#39;nearest&#39;</span>)
plt.title(<span style="color: #CD5555">&quot;Label: %d&quot;</span> % digits.target[random_indices[i]])
plt.show()
</pre></div>
</section>
<section>
<h2 id="importing-keras-and-tensorflow">Importing Keras and Tensorflow </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras</span> <span style="color: #8B008B; font-weight: bold">import</span> datasets, layers, models
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras.layers</span> <span style="color: #8B008B; font-weight: bold">import</span> Input
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras.models</span> <span style="color: #8B008B; font-weight: bold">import</span> Sequential <span style="color: #228B22">#This allows appending layers to existing models</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras.layers</span> <span style="color: #8B008B; font-weight: bold">import</span> Dense <span style="color: #228B22">#This allows defining the characteristics of a particular layer</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras</span> <span style="color: #8B008B; font-weight: bold">import</span> optimizers <span style="color: #228B22">#This allows using whichever optimiser we want (sgd,adam,RMSprop)</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras</span> <span style="color: #8B008B; font-weight: bold">import</span> regularizers <span style="color: #228B22">#This allows using whichever regularizer we want (l1,l2,l1_l2)</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras.utils</span> <span style="color: #8B008B; font-weight: bold">import</span> to_categorical <span style="color: #228B22">#This allows using categorical cross entropy as the cost function</span>
<span style="color: #228B22">#from tensorflow.keras import Conv2D</span>
<span style="color: #228B22">#from tensorflow.keras import MaxPooling2D</span>
<span style="color: #228B22">#from tensorflow.keras import Flatten</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #228B22"># representation of labels</span>
labels = to_categorical(labels)
<span style="color: #228B22"># split into train and test data</span>
<span style="color: #228B22"># one-liner from scikit-learn library</span>
train_size = <span style="color: #B452CD">0.8</span>
test_size = <span style="color: #B452CD">1</span> - train_size
X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
test_size=test_size)
</pre></div>
</section>
<section>
<h2 id="running-with-keras">Running with Keras </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">create_convolutional_neural_network_keras</span>(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd):
model = Sequential()
model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding=<span style="color: #CD5555">&#39;same&#39;</span>,
activation=<span style="color: #CD5555">&#39;relu&#39;</span>, kernel_regularizer=regularizers.l2(lmbd)))
model.add(layers.MaxPooling2D(pool_size=(<span style="color: #B452CD">2</span>, <span style="color: #B452CD">2</span>)))
model.add(layers.Flatten())
model.add(layers.Dense(n_neurons_connected, activation=<span style="color: #CD5555">&#39;relu&#39;</span>, kernel_regularizer=regularizers.l2(lmbd)))
model.add(layers.Dense(n_categories, activation=<span style="color: #CD5555">&#39;softmax&#39;</span>, kernel_regularizer=regularizers.l2(lmbd)))
sgd = optimizers.SGD(lr=eta)
model.compile(loss=<span style="color: #CD5555">&#39;categorical_crossentropy&#39;</span>, optimizer=sgd, metrics=[<span style="color: #CD5555">&#39;accuracy&#39;</span>])
<span style="color: #8B008B; font-weight: bold">return</span> model
epochs = <span style="color: #B452CD">100</span>
batch_size = <span style="color: #B452CD">100</span>
input_shape = X_train.shape[<span style="color: #B452CD">1</span>:<span style="color: #B452CD">4</span>]
receptive_field = <span style="color: #B452CD">3</span>
n_filters = <span style="color: #B452CD">10</span>
n_neurons_connected = <span style="color: #B452CD">50</span>
n_categories = <span style="color: #B452CD">10</span>
eta_vals = np.logspace(-<span style="color: #B452CD">5</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">7</span>)
lmbd_vals = np.logspace(-<span style="color: #B452CD">5</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">7</span>)
</pre></div>
</section>
<section>
<h2 id="final-part">Final part </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span>CNN_keras = np.zeros((<span style="color: #658b00">len</span>(eta_vals), <span style="color: #658b00">len</span>(lmbd_vals)), dtype=<span style="color: #658b00">object</span>)
<span style="color: #8B008B; font-weight: bold">for</span> i, eta <span style="color: #8B008B">in</span> <span style="color: #658b00">enumerate</span>(eta_vals):
<span style="color: #8B008B; font-weight: bold">for</span> j, lmbd <span style="color: #8B008B">in</span> <span style="color: #658b00">enumerate</span>(lmbd_vals):
CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd)
CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=<span style="color: #B452CD">0</span>)
scores = CNN.evaluate(X_test, Y_test)
CNN_keras[i][j] = CNN
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Learning rate = &quot;</span>, eta)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Lambda = &quot;</span>, lmbd)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test accuracy: %.3f&quot;</span> % scores[<span style="color: #B452CD">1</span>])
<span style="color: #658b00">print</span>()
</pre></div>
</section>
<section>
<h2 id="final-visualization">Final visualization </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #228B22"># visual representation of grid search</span>
<span style="color: #228B22"># uses seaborn heatmap, could probably do this in matplotlib</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">seaborn</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">sns</span>
sns.set()
train_accuracy = np.zeros((<span style="color: #658b00">len</span>(eta_vals), <span style="color: #658b00">len</span>(lmbd_vals)))
test_accuracy = np.zeros((<span style="color: #658b00">len</span>(eta_vals), <span style="color: #658b00">len</span>(lmbd_vals)))
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #658b00">len</span>(eta_vals)):
<span style="color: #8B008B; font-weight: bold">for</span> j <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #658b00">len</span>(lmbd_vals)):
CNN = CNN_keras[i][j]
train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[<span style="color: #B452CD">1</span>]
test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[<span style="color: #B452CD">1</span>]
fig, ax = plt.subplots(figsize = (<span style="color: #B452CD">10</span>, <span style="color: #B452CD">10</span>))
sns.heatmap(train_accuracy, annot=<span style="color: #8B008B; font-weight: bold">True</span>, ax=ax, cmap=<span style="color: #CD5555">&quot;viridis&quot;</span>)
ax.set_title(<span style="color: #CD5555">&quot;Training Accuracy&quot;</span>)
ax.set_ylabel(<span style="color: #CD5555">&quot;$\eta$&quot;</span>)
ax.set_xlabel(<span style="color: #CD5555">&quot;$\lambda$&quot;</span>)
plt.show()
fig, ax = plt.subplots(figsize = (<span style="color: #B452CD">10</span>, <span style="color: #B452CD">10</span>))
sns.heatmap(test_accuracy, annot=<span style="color: #8B008B; font-weight: bold">True</span>, ax=ax, cmap=<span style="color: #CD5555">&quot;viridis&quot;</span>)
ax.set_title(<span style="color: #CD5555">&quot;Test Accuracy&quot;</span>)
ax.set_ylabel(<span style="color: #CD5555">&quot;$\eta$&quot;</span>)
ax.set_xlabel(<span style="color: #CD5555">&quot;$\lambda$&quot;</span>)
plt.show()
</pre></div>
</section>
<section>
<h2 id="the-cifar01-data-set">The CIFAR01 data set </h2>
<p>
The CIFAR10 dataset contains 60,000 color images in 10 classes, with
6,000 images in each class. The dataset is divided into 50,000
training images and 10,000 testing images. The classes are mutually
exclusive and there is no overlap between them.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">tensorflow</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">tf</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras</span> <span style="color: #8B008B; font-weight: bold">import</span> datasets, layers, models
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #228B22"># We import the data set</span>
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
<span style="color: #228B22"># Normalize pixel values to be between 0 and 1 by dividing by 255. </span>
train_images, test_images = train_images / <span style="color: #B452CD">255.0</span>, test_images / <span style="color: #B452CD">255.0</span>
</pre></div>
</section>
<section>
<h2 id="verifying-the-data-set">Verifying the data set </h2>
<p>
To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span>class_names = [<span style="color: #CD5555">&#39;airplane&#39;</span>, <span style="color: #CD5555">&#39;automobile&#39;</span>, <span style="color: #CD5555">&#39;bird&#39;</span>, <span style="color: #CD5555">&#39;cat&#39;</span>, <span style="color: #CD5555">&#39;deer&#39;</span>,
<span style="color: #CD5555">&#39;dog&#39;</span>, <span style="color: #CD5555">&#39;frog&#39;</span>, <span style="color: #CD5555">&#39;horse&#39;</span>, <span style="color: #CD5555">&#39;ship&#39;</span>, <span style="color: #CD5555">&#39;truck&#39;</span>]
<span style="color: #a61717; background-color: #e3d2d2"></span>
plt.figure(figsize=(<span style="color: #B452CD">10</span>,<span style="color: #B452CD">10</span>))
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">25</span>):
plt.subplot(<span style="color: #B452CD">5</span>,<span style="color: #B452CD">5</span>,i+<span style="color: #B452CD">1</span>)
plt.xticks([])
plt.yticks([])
plt.grid(<span style="color: #8B008B; font-weight: bold">False</span>)
plt.imshow(train_images[i], cmap=plt.cm.binary)
<span style="color: #228B22"># The CIFAR labels happen to be arrays, </span>
<span style="color: #228B22"># which is why you need the extra index</span>
plt.xlabel(class_names[train_labels[i][<span style="color: #B452CD">0</span>]])
plt.show()
</pre></div>
</section>
<section>
<h2 id="set-up-the-model">Set up the model </h2>
<p>
The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.
<p>
As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span>model = models.Sequential()
model.add(layers.Conv2D(<span style="color: #B452CD">32</span>, (<span style="color: #B452CD">3</span>, <span style="color: #B452CD">3</span>), activation=<span style="color: #CD5555">&#39;relu&#39;</span>, input_shape=(<span style="color: #B452CD">32</span>, <span style="color: #B452CD">32</span>, <span style="color: #B452CD">3</span>)))
model.add(layers.MaxPooling2D((<span style="color: #B452CD">2</span>, <span style="color: #B452CD">2</span>)))
model.add(layers.Conv2D(<span style="color: #B452CD">64</span>, (<span style="color: #B452CD">3</span>, <span style="color: #B452CD">3</span>), activation=<span style="color: #CD5555">&#39;relu&#39;</span>))
model.add(layers.MaxPooling2D((<span style="color: #B452CD">2</span>, <span style="color: #B452CD">2</span>)))
model.add(layers.Conv2D(<span style="color: #B452CD">64</span>, (<span style="color: #B452CD">3</span>, <span style="color: #B452CD">3</span>), activation=<span style="color: #CD5555">&#39;relu&#39;</span>))
<span style="color: #228B22"># Let&#39;s display the architecture of our model so far.</span>
model.summary()
</pre></div>
<p>
You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.
</section>
<section>
<h2 id="add-dense-layers-on-top">Add Dense layers on top </h2>
<p>
To complete our model, you will feed the last output tensor from the
convolutional base (of shape (4, 4, 64)) into one or more Dense layers
to perform classification. Dense layers take vectors as input (which
are 1D), while the current output is a 3D tensor. First, you will
flatten (or unroll) the 3D output to 1D, then add one or more Dense
layers on top. CIFAR has 10 output classes, so you use a final Dense
layer with 10 outputs and a softmax activation.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span>model.add(layers.Flatten())
model.add(layers.Dense(<span style="color: #B452CD">64</span>, activation=<span style="color: #CD5555">&#39;relu&#39;</span>))
model.add(layers.Dense(<span style="color: #B452CD">10</span>))
Here<span style="color: #CD5555">&#39;s the complete architecture of our model.</span>
model.summary()
</pre></div>
<p>
As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.
</section>
<section>
<h2 id="compile-and-train-the-model">Compile and train the model </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span>model.compile(optimizer=<span style="color: #CD5555">&#39;adam&#39;</span>,
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=<span style="color: #8B008B; font-weight: bold">True</span>),
metrics=[<span style="color: #CD5555">&#39;accuracy&#39;</span>])
<span style="color: #a61717; background-color: #e3d2d2"></span>
history = model.fit(train_images, train_labels, epochs=<span style="color: #B452CD">10</span>,
validation_data=(test_images, test_labels))
</pre></div>
</section>
<section>
<h2 id="finally-evaluate-the-model">Finally, evaluate the model </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%;"><span></span>plt.plot(history.history[<span style="color: #CD5555">&#39;accuracy&#39;</span>], label=<span style="color: #CD5555">&#39;accuracy&#39;</span>)
plt.plot(history.history[<span style="color: #CD5555">&#39;val_accuracy&#39;</span>], label = <span style="color: #CD5555">&#39;val_accuracy&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;Epoch&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;Accuracy&#39;</span>)
plt.ylim([<span style="color: #B452CD">0.5</span>, <span style="color: #B452CD">1</span>])
plt.legend(loc=<span style="color: #CD5555">&#39;lower right&#39;</span>)
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=<span style="color: #B452CD">2</span>)
<span style="color: #658b00">print</span>(test_acc)
</pre></div>
</section>
<section>
<h2 id="recurrent-neural-networks-overarching-view">Recurrent neural networks: Overarching view </h2>
+2 -702
View File
@@ -62,60 +62,6 @@ div { text-align: justify; text-justify: inter-word; }
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -137,22 +83,6 @@ 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 ---------------------- -->
@@ -174,7 +104,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Oct 19, 2021</h4></center> <!-- date -->
<center><h4>Oct 23, 2021</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -182,7 +112,7 @@ MathJax.Hub.Config({
<h2 id="plans-for-week-43">Plans for week 43 </h2>
<ul>
<li> Thursday: Convolutional Neural Networks and Recurrent Neural Networks</li>
<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>
@@ -213,636 +143,6 @@ MathJax.Hub.Config({
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="convolutional-neural-networks-recognizing-images">Convolutional Neural Networks (recognizing images) </h2>
<p>
Convolutional neural networks (CNNs) were developed during the last
decade of the previous century, with a focus on character recognition
tasks. Nowadays, CNNs are a central element in the spectacular success
of deep learning methods. The success in for example image
classifications have made them a central tool for most machine
learning practitioners.
<p>
CNNs are very similar to ordinary Neural Networks.
They are made up of neurons that have learnable weights and
biases. Each neuron receives some inputs, performs a dot product and
optionally follows it with a non-linearity. The whole network still
expresses a single differentiable score function: from the raw image
pixels on one end to class scores at the other. And they still have a
loss function (for example Softmax) on the last (fully-connected) layer
and all the tips/tricks we developed for learning regular Neural
Networks still apply (back propagation, gradient descent etc etc).
<p>
What is the difference? <b>CNN architectures make the explicit assumption that
the inputs are images, which allows us to encode certain properties
into the architecture. These then make the forward function more
efficient to implement and vastly reduce the amount of parameters in
the network.</b>
<p>
Here we provide only a superficial overview, for the more interested, we recommend highly 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>.
<p>
Another good read is the article here <a href="https://arxiv.org/pdf/1603.07285.pdf" target="_blank"><tt>https://arxiv.org/pdf/1603.07285.pdf</tt></a>.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="neural-networks-vs-cnns">Neural Networks vs CNNs </h2>
<p>
Neural networks are defined as <b>affine transformations</b>, that is
a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an
output (to which a bias vector is usually added before passing the result
through a nonlinear activation function). This is applicable to any type of input, be it an
image, a sound clip or an unordered collection of features: whatever their
dimensionality, their representation can always be flattened into a vector
before the transformation.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc">Why CNNS for images, sound files, medical images from CT scans etc? </h2>
<p>
However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic
structure. More formally, they share these important properties:</li>
<ul>
<li> They are stored as multi-dimensional arrays (think of the pixels of a figure) .</li>
<li> They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).</li>
<li> One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).</li>
</ul>
These properties are not exploited when an affine transformation is applied; in
fact, all the axes are treated in the same way and the topological information
is not taken into account. Still, taking advantage of the implicit structure of
the data may prove very handy in solving some tasks, like computer vision and
speech recognition, and in these cases it would be best to preserve it. This is
where discrete convolutions come into play.
<p>
A discrete convolution is a linear transformation that preserves this notion of
ordering. It is sparse (only a few input units contribute to a given output
unit) and reuses parameters (the same weights are applied to multiple locations
in the input).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="regular-nns-don-t-scale-well-to-full-images">Regular NNs don&#8217;t scale well to full images </h2>
<p>
As an example, consider
an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a
single fully-connected neuron in a first hidden layer of a regular
Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still
seems manageable, but clearly this fully-connected structure does not
scale to larger images. For example, an image of more respectable
size, say \( 200\times 200\times 3 \), would lead to neurons that have
\( 200\times 200\times 3 = 120,000 \) weights.
<p>
We could have
several such neurons, and the parameters would add up quickly! Clearly,
this full connectivity is wasteful and the huge number of parameters
would quickly lead to possible overfitting.
<p>
<center> <!-- FIGURE -->
<hr class="figure">
<center><p class="caption">Figure 1: A regular 3-layer Neural Network. </p></center>
<p><img src="figslides/nn.jpeg" align="bottom" width=500></p>
</center>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="3d-volumes-of-neurons">3D volumes of neurons </h2>
<p>
Convolutional Neural Networks take advantage of the fact that the
input consists of images and they constrain the architecture in a more
sensible way.
<p>
In particular, unlike a regular Neural Network, the
layers of a CNN have neurons arranged in 3 dimensions: width,
height, depth. (Note that the word depth here refers to the third
dimension of an activation volume, not to the depth of a full Neural
Network, which can refer to the total number of layers in a network.)
<p>
To understand it better, the above example of an image
with an input volume of
activations has dimensions \( 32\times 32\times 3 \) (width, height,
depth respectively).
<p>
The neurons in a layer will
only be connected to a small region of the layer before it, instead of
all of the neurons in a fully-connected manner. Moreover, the final
output layer could for this specific image have dimensions \( 1\times 1 \times 10 \),
because by the
end of the CNN architecture we will reduce the full image into a
single vector of class scores, arranged along the depth
dimension.
<p>
<center> <!-- FIGURE -->
<hr class="figure">
<center><p class="caption">Figure 2: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). </p></center>
<p><img src="figslides/cnn.jpeg" align="bottom" width=500></p>
</center>
<p>
<!-- !split -->
<h2 id="layers-used-to-build-cnns">Layers used to build CNNs </h2>
<p>
A simple CNN is a sequence of layers, and every layer of a CNN
transforms one volume of activations to another through a
differentiable function. We use three main types of layers to build
CNN architectures: Convolutional Layer, Pooling Layer, and
Fully-Connected Layer (exactly as seen in regular Neural Networks). We
will stack these layers to form a full CNN architecture.
<p>
A simple CNN for image classification could have the architecture:
<ul>
<li> <b>INPUT</b> (\( 32\times 32 \times 3 \)) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.</li>
<li> <b>CONV</b> (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as \( [32\times 32\times 12] \) if we decided to use 12 filters.</li>
<li> <b>RELU</b> layer will apply an elementwise activation function, such as the \( max(0,x) \) thresholding at zero. This leaves the size of the volume unchanged (\( [32\times 32\times 12] \)).</li>
<li> <b>POOL</b> (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as \( [16\times 16\times 12] \).</li>
<li> <b>FC</b> (i.e. fully-connected) layer will compute the class scores, resulting in volume of size \( [1\times 1\times 10] \), where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="transforming-images">Transforming images </h2>
<p>
CNNs transform the original image layer by layer from the original
pixel values to the final class scores.
<p>
Observe that some layers contain
parameters and other don&#8217;t. In particular, the CNN layers perform
transformations that are a function of not only the activations in the
input volume, but also of the parameters (the weights and biases of
the neurons). On the other hand, the RELU/POOL layers will implement a
fixed function. The parameters in the CONV/FC layers will be trained
with gradient descent so that the class scores that the CNN computes
are consistent with the labels in the training set for each image.
<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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras </h2>
<p>
As discussed above, CNNs are neural networks built from the assumption that the inputs
to the network are 2D images. This is important because the number of features or pixels in images
grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
<p>
As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
are the <b>convolutional</b> and <b>pooling</b> layers stacked in pairs between the input and the hidden layer.
In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
matrices, typically 1 for each color dimension (Red, Green, Blue).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-it-up">Setting it up </h2>
<p>
It means that to represent the entire
dataset of images, we require a 4D matrix or <b>tensor</b>. This tensor has the dimensions:
$$
(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-mnist-dataset-again">The MNIST dataset again </h2>
<p>
The MNIST dataset consists of grayscale images with a pixel size of
\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each
neuron in the first hidden layer.
<p>
If we were to analyze images of size \( 128\times 128 \) we would require
\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were
dealing with color images, as most images are, we have an image matrix
of size \( 128\times 128 \) for each color dimension (Red, Green, Blue),
meaning 3 times the number of weights \( = 49152 \) are required for every
single neuron in the first hidden layer.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="strong-correlations">Strong correlations </h2>
<p>
Images typically have strong local correlations, meaning that a small
part of the image varies little from its neighboring regions. If for
example we have an image of a blue car, we can roughly assume that a
small blue part of the image is surrounded by other blue regions.
<p>
Therefore, instead of connecting every single pixel to a neuron in the
first hidden layer, as we have previously done with deep neural
networks, we can instead connect each neuron to a small part of the
image (in all 3 RGB depth dimensions). The size of each small area is
fixed, and known as a <a href="https://en.wikipedia.org/wiki/Receptive_field" target="_blank">receptive</a>.
<p>
<!-- !split -->
<h2 id="layers-of-a-cnn">Layers of a CNN </h2>
The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
The input image is typically a square matrix of depth 3.
<p>
A <b>convolution</b> is performed on the image which outputs
a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as <b>filters</b>.
<p>
Each filter slides along the input image, taking the dot product
between each small part of the image and the filter, in all depth
dimensions. This is then passed through a non-linear function,
typically the <b>Rectified Linear (ReLu)</b> function, which serves as the
activation of the neurons in the first convolutional layer. This is
further passed through a <b>pooling layer</b>, which reduces the size of the
convolutional layer, e.g. by taking the maximum or average across some
small regions, and this serves as input to the next convolutional
layer.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="systematic-reduction">Systematic reduction </h2>
<p>
By systematically reducing the size of the input volume, through
convolution and pooling, the network should create representations of
small parts of the input, and then from them assemble representations
of larger areas. The final pooling layer is flattened to serve as
input to a hidden layer, such that each neuron in the final pooling
layer is connected to every single neuron in the hidden layer. This
then serves as input to the output layer, e.g. a softmax output for
classification.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="prerequisites-collect-and-pre-process-data">Prerequisites: Collect and pre-process data </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #228B22"># import necessary packages</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn</span> <span style="color: #8B008B; font-weight: bold">import</span> datasets
<span style="color: #228B22"># ensure the same random numbers appear every time</span>
np.random.seed(<span style="color: #B452CD">0</span>)
<span style="color: #228B22"># display images in notebook</span>
%matplotlib inline
plt.rcParams[<span style="color: #CD5555">&#39;figure.figsize&#39;</span>] = (<span style="color: #B452CD">12</span>,<span style="color: #B452CD">12</span>)
<span style="color: #228B22"># download MNIST dataset</span>
digits = datasets.load_digits()
<span style="color: #228B22"># define inputs and labels</span>
inputs = digits.images
labels = digits.target
<span style="color: #228B22"># RGB images have a depth of 3</span>
<span style="color: #228B22"># our images are grayscale so they should have a depth of 1</span>
inputs = inputs[:,:,:,np.newaxis]
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;inputs = (n_inputs, pixel_width, pixel_height, depth) = &quot;</span> + <span style="color: #658b00">str</span>(inputs.shape))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;labels = (n_inputs) = &quot;</span> + <span style="color: #658b00">str</span>(labels.shape))
<span style="color: #228B22"># choose some random images to display</span>
n_inputs = <span style="color: #658b00">len</span>(inputs)
indices = np.arange(n_inputs)
random_indices = np.random.choice(indices, size=<span style="color: #B452CD">5</span>)
<span style="color: #8B008B; font-weight: bold">for</span> i, image <span style="color: #8B008B">in</span> <span style="color: #658b00">enumerate</span>(digits.images[random_indices]):
plt.subplot(<span style="color: #B452CD">1</span>, <span style="color: #B452CD">5</span>, i+<span style="color: #B452CD">1</span>)
plt.axis(<span style="color: #CD5555">&#39;off&#39;</span>)
plt.imshow(image, cmap=plt.cm.gray_r, interpolation=<span style="color: #CD5555">&#39;nearest&#39;</span>)
plt.title(<span style="color: #CD5555">&quot;Label: %d&quot;</span> % digits.target[random_indices[i]])
plt.show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="importing-keras-and-tensorflow">Importing Keras and Tensorflow </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras</span> <span style="color: #8B008B; font-weight: bold">import</span> datasets, layers, models
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras.layers</span> <span style="color: #8B008B; font-weight: bold">import</span> Input
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras.models</span> <span style="color: #8B008B; font-weight: bold">import</span> Sequential <span style="color: #228B22">#This allows appending layers to existing models</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras.layers</span> <span style="color: #8B008B; font-weight: bold">import</span> Dense <span style="color: #228B22">#This allows defining the characteristics of a particular layer</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras</span> <span style="color: #8B008B; font-weight: bold">import</span> optimizers <span style="color: #228B22">#This allows using whichever optimiser we want (sgd,adam,RMSprop)</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras</span> <span style="color: #8B008B; font-weight: bold">import</span> regularizers <span style="color: #228B22">#This allows using whichever regularizer we want (l1,l2,l1_l2)</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras.utils</span> <span style="color: #8B008B; font-weight: bold">import</span> to_categorical <span style="color: #228B22">#This allows using categorical cross entropy as the cost function</span>
<span style="color: #228B22">#from tensorflow.keras import Conv2D</span>
<span style="color: #228B22">#from tensorflow.keras import MaxPooling2D</span>
<span style="color: #228B22">#from tensorflow.keras import Flatten</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #228B22"># representation of labels</span>
labels = to_categorical(labels)
<span style="color: #228B22"># split into train and test data</span>
<span style="color: #228B22"># one-liner from scikit-learn library</span>
train_size = <span style="color: #B452CD">0.8</span>
test_size = <span style="color: #B452CD">1</span> - train_size
X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
test_size=test_size)
</pre></div>
<p>
<!-- !split -->
<h2 id="running-with-keras">Running with Keras </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">create_convolutional_neural_network_keras</span>(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd):
model = Sequential()
model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding=<span style="color: #CD5555">&#39;same&#39;</span>,
activation=<span style="color: #CD5555">&#39;relu&#39;</span>, kernel_regularizer=regularizers.l2(lmbd)))
model.add(layers.MaxPooling2D(pool_size=(<span style="color: #B452CD">2</span>, <span style="color: #B452CD">2</span>)))
model.add(layers.Flatten())
model.add(layers.Dense(n_neurons_connected, activation=<span style="color: #CD5555">&#39;relu&#39;</span>, kernel_regularizer=regularizers.l2(lmbd)))
model.add(layers.Dense(n_categories, activation=<span style="color: #CD5555">&#39;softmax&#39;</span>, kernel_regularizer=regularizers.l2(lmbd)))
sgd = optimizers.SGD(lr=eta)
model.compile(loss=<span style="color: #CD5555">&#39;categorical_crossentropy&#39;</span>, optimizer=sgd, metrics=[<span style="color: #CD5555">&#39;accuracy&#39;</span>])
<span style="color: #8B008B; font-weight: bold">return</span> model
epochs = <span style="color: #B452CD">100</span>
batch_size = <span style="color: #B452CD">100</span>
input_shape = X_train.shape[<span style="color: #B452CD">1</span>:<span style="color: #B452CD">4</span>]
receptive_field = <span style="color: #B452CD">3</span>
n_filters = <span style="color: #B452CD">10</span>
n_neurons_connected = <span style="color: #B452CD">50</span>
n_categories = <span style="color: #B452CD">10</span>
eta_vals = np.logspace(-<span style="color: #B452CD">5</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">7</span>)
lmbd_vals = np.logspace(-<span style="color: #B452CD">5</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">7</span>)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-part">Final part </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span>CNN_keras = np.zeros((<span style="color: #658b00">len</span>(eta_vals), <span style="color: #658b00">len</span>(lmbd_vals)), dtype=<span style="color: #658b00">object</span>)
<span style="color: #8B008B; font-weight: bold">for</span> i, eta <span style="color: #8B008B">in</span> <span style="color: #658b00">enumerate</span>(eta_vals):
<span style="color: #8B008B; font-weight: bold">for</span> j, lmbd <span style="color: #8B008B">in</span> <span style="color: #658b00">enumerate</span>(lmbd_vals):
CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd)
CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=<span style="color: #B452CD">0</span>)
scores = CNN.evaluate(X_test, Y_test)
CNN_keras[i][j] = CNN
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Learning rate = &quot;</span>, eta)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Lambda = &quot;</span>, lmbd)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test accuracy: %.3f&quot;</span> % scores[<span style="color: #B452CD">1</span>])
<span style="color: #658b00">print</span>()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-visualization">Final visualization </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #228B22"># visual representation of grid search</span>
<span style="color: #228B22"># uses seaborn heatmap, could probably do this in matplotlib</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">seaborn</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">sns</span>
sns.set()
train_accuracy = np.zeros((<span style="color: #658b00">len</span>(eta_vals), <span style="color: #658b00">len</span>(lmbd_vals)))
test_accuracy = np.zeros((<span style="color: #658b00">len</span>(eta_vals), <span style="color: #658b00">len</span>(lmbd_vals)))
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #658b00">len</span>(eta_vals)):
<span style="color: #8B008B; font-weight: bold">for</span> j <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #658b00">len</span>(lmbd_vals)):
CNN = CNN_keras[i][j]
train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[<span style="color: #B452CD">1</span>]
test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[<span style="color: #B452CD">1</span>]
fig, ax = plt.subplots(figsize = (<span style="color: #B452CD">10</span>, <span style="color: #B452CD">10</span>))
sns.heatmap(train_accuracy, annot=<span style="color: #8B008B; font-weight: bold">True</span>, ax=ax, cmap=<span style="color: #CD5555">&quot;viridis&quot;</span>)
ax.set_title(<span style="color: #CD5555">&quot;Training Accuracy&quot;</span>)
ax.set_ylabel(<span style="color: #CD5555">&quot;$\eta$&quot;</span>)
ax.set_xlabel(<span style="color: #CD5555">&quot;$\lambda$&quot;</span>)
plt.show()
fig, ax = plt.subplots(figsize = (<span style="color: #B452CD">10</span>, <span style="color: #B452CD">10</span>))
sns.heatmap(test_accuracy, annot=<span style="color: #8B008B; font-weight: bold">True</span>, ax=ax, cmap=<span style="color: #CD5555">&quot;viridis&quot;</span>)
ax.set_title(<span style="color: #CD5555">&quot;Test Accuracy&quot;</span>)
ax.set_ylabel(<span style="color: #CD5555">&quot;$\eta$&quot;</span>)
ax.set_xlabel(<span style="color: #CD5555">&quot;$\lambda$&quot;</span>)
plt.show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-cifar01-data-set">The CIFAR01 data set </h2>
<p>
The CIFAR10 dataset contains 60,000 color images in 10 classes, with
6,000 images in each class. The dataset is divided into 50,000
training images and 10,000 testing images. The classes are mutually
exclusive and there is no overlap between them.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">tensorflow</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">tf</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">tensorflow.keras</span> <span style="color: #8B008B; font-weight: bold">import</span> datasets, layers, models
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #228B22"># We import the data set</span>
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
<span style="color: #228B22"># Normalize pixel values to be between 0 and 1 by dividing by 255. </span>
train_images, test_images = train_images / <span style="color: #B452CD">255.0</span>, test_images / <span style="color: #B452CD">255.0</span>
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="verifying-the-data-set">Verifying the data set </h2>
<p>
To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span>class_names = [<span style="color: #CD5555">&#39;airplane&#39;</span>, <span style="color: #CD5555">&#39;automobile&#39;</span>, <span style="color: #CD5555">&#39;bird&#39;</span>, <span style="color: #CD5555">&#39;cat&#39;</span>, <span style="color: #CD5555">&#39;deer&#39;</span>,
<span style="color: #CD5555">&#39;dog&#39;</span>, <span style="color: #CD5555">&#39;frog&#39;</span>, <span style="color: #CD5555">&#39;horse&#39;</span>, <span style="color: #CD5555">&#39;ship&#39;</span>, <span style="color: #CD5555">&#39;truck&#39;</span>]
<span style="color: #a61717; background-color: #e3d2d2"></span>
plt.figure(figsize=(<span style="color: #B452CD">10</span>,<span style="color: #B452CD">10</span>))
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">25</span>):
plt.subplot(<span style="color: #B452CD">5</span>,<span style="color: #B452CD">5</span>,i+<span style="color: #B452CD">1</span>)
plt.xticks([])
plt.yticks([])
plt.grid(<span style="color: #8B008B; font-weight: bold">False</span>)
plt.imshow(train_images[i], cmap=plt.cm.binary)
<span style="color: #228B22"># The CIFAR labels happen to be arrays, </span>
<span style="color: #228B22"># which is why you need the extra index</span>
plt.xlabel(class_names[train_labels[i][<span style="color: #B452CD">0</span>]])
plt.show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="set-up-the-model">Set up the model </h2>
<p>
The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.
<p>
As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span>model = models.Sequential()
model.add(layers.Conv2D(<span style="color: #B452CD">32</span>, (<span style="color: #B452CD">3</span>, <span style="color: #B452CD">3</span>), activation=<span style="color: #CD5555">&#39;relu&#39;</span>, input_shape=(<span style="color: #B452CD">32</span>, <span style="color: #B452CD">32</span>, <span style="color: #B452CD">3</span>)))
model.add(layers.MaxPooling2D((<span style="color: #B452CD">2</span>, <span style="color: #B452CD">2</span>)))
model.add(layers.Conv2D(<span style="color: #B452CD">64</span>, (<span style="color: #B452CD">3</span>, <span style="color: #B452CD">3</span>), activation=<span style="color: #CD5555">&#39;relu&#39;</span>))
model.add(layers.MaxPooling2D((<span style="color: #B452CD">2</span>, <span style="color: #B452CD">2</span>)))
model.add(layers.Conv2D(<span style="color: #B452CD">64</span>, (<span style="color: #B452CD">3</span>, <span style="color: #B452CD">3</span>), activation=<span style="color: #CD5555">&#39;relu&#39;</span>))
<span style="color: #228B22"># Let&#39;s display the architecture of our model so far.</span>
model.summary()
</pre></div>
<p>
You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="add-dense-layers-on-top">Add Dense layers on top </h2>
<p>
To complete our model, you will feed the last output tensor from the
convolutional base (of shape (4, 4, 64)) into one or more Dense layers
to perform classification. Dense layers take vectors as input (which
are 1D), while the current output is a 3D tensor. First, you will
flatten (or unroll) the 3D output to 1D, then add one or more Dense
layers on top. CIFAR has 10 output classes, so you use a final Dense
layer with 10 outputs and a softmax activation.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span>model.add(layers.Flatten())
model.add(layers.Dense(<span style="color: #B452CD">64</span>, activation=<span style="color: #CD5555">&#39;relu&#39;</span>))
model.add(layers.Dense(<span style="color: #B452CD">10</span>))
Here<span style="color: #CD5555">&#39;s the complete architecture of our model.</span>
model.summary()
</pre></div>
<p>
As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="compile-and-train-the-model">Compile and train the model </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span>model.compile(optimizer=<span style="color: #CD5555">&#39;adam&#39;</span>,
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=<span style="color: #8B008B; font-weight: bold">True</span>),
metrics=[<span style="color: #CD5555">&#39;accuracy&#39;</span>])
<span style="color: #a61717; background-color: #e3d2d2"></span>
history = model.fit(train_images, train_labels, epochs=<span style="color: #B452CD">10</span>,
validation_data=(test_images, test_labels))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="finally-evaluate-the-model">Finally, evaluate the model </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="line-height: 125%;"><span></span>plt.plot(history.history[<span style="color: #CD5555">&#39;accuracy&#39;</span>], label=<span style="color: #CD5555">&#39;accuracy&#39;</span>)
plt.plot(history.history[<span style="color: #CD5555">&#39;val_accuracy&#39;</span>], label = <span style="color: #CD5555">&#39;val_accuracy&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;Epoch&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;Accuracy&#39;</span>)
plt.ylim([<span style="color: #B452CD">0.5</span>, <span style="color: #B452CD">1</span>])
plt.legend(loc=<span style="color: #CD5555">&#39;lower right&#39;</span>)
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=<span style="color: #B452CD">2</span>)
<span style="color: #658b00">print</span>(test_acc)
</pre></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>
+2 -702
View File
@@ -67,60 +67,6 @@ div { text-align: justify; text-justify: inter-word; }
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 43', 2, None, 'plans-for-week-43'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('Neural Networks vs CNNs', 2, None, 'neural-networks-vs-cnns'),
('Why CNNS for images, sound files, medical images from CT scans '
'etc?',
2,
None,
'why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc'),
('Regular NNs dont scale well to full images',
2,
None,
'regular-nns-don-t-scale-well-to-full-images'),
('3D volumes of neurons', 2, None, '3d-volumes-of-neurons'),
('Layers used to build CNNs',
2,
None,
'layers-used-to-build-cnns'),
('Transforming images', 2, None, 'transforming-images'),
('CNNs in brief', 2, None, 'cnns-in-brief'),
('CNNs in more detail, building convolutional neural networks in '
'Tensorflow and Keras',
2,
None,
'cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras'),
('Setting it up', 2, None, 'setting-it-up'),
('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'),
('Strong correlations', 2, None, 'strong-correlations'),
('Layers of a CNN', 2, None, 'layers-of-a-cnn'),
('Systematic reduction', 2, None, 'systematic-reduction'),
('Prerequisites: Collect and pre-process data',
2,
None,
'prerequisites-collect-and-pre-process-data'),
('Importing Keras and Tensorflow',
2,
None,
'importing-keras-and-tensorflow'),
('Running with Keras', 2, None, 'running-with-keras'),
('Final part', 2, None, 'final-part'),
('Final visualization', 2, None, 'final-visualization'),
('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'),
('Verifying the data set', 2, None, 'verifying-the-data-set'),
('Set up the model', 2, None, 'set-up-the-model'),
('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'),
('Compile and train the model',
2,
None,
'compile-and-train-the-model'),
('Finally, evaluate the model',
2,
None,
'finally-evaluate-the-model'),
('Recurrent neural networks: Overarching view',
2,
None,
@@ -142,22 +88,6 @@ 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 ---------------------- -->
@@ -179,7 +109,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Oct 19, 2021</h4></center> <!-- date -->
<center><h4>Oct 23, 2021</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -187,7 +117,7 @@ MathJax.Hub.Config({
<h2 id="plans-for-week-43">Plans for week 43 </h2>
<ul>
<li> Thursday: Convolutional Neural Networks and Recurrent Neural Networks</li>
<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>
@@ -218,636 +148,6 @@ MathJax.Hub.Config({
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="convolutional-neural-networks-recognizing-images">Convolutional Neural Networks (recognizing images) </h2>
<p>
Convolutional neural networks (CNNs) were developed during the last
decade of the previous century, with a focus on character recognition
tasks. Nowadays, CNNs are a central element in the spectacular success
of deep learning methods. The success in for example image
classifications have made them a central tool for most machine
learning practitioners.
<p>
CNNs are very similar to ordinary Neural Networks.
They are made up of neurons that have learnable weights and
biases. Each neuron receives some inputs, performs a dot product and
optionally follows it with a non-linearity. The whole network still
expresses a single differentiable score function: from the raw image
pixels on one end to class scores at the other. And they still have a
loss function (for example Softmax) on the last (fully-connected) layer
and all the tips/tricks we developed for learning regular Neural
Networks still apply (back propagation, gradient descent etc etc).
<p>
What is the difference? <b>CNN architectures make the explicit assumption that
the inputs are images, which allows us to encode certain properties
into the architecture. These then make the forward function more
efficient to implement and vastly reduce the amount of parameters in
the network.</b>
<p>
Here we provide only a superficial overview, for the more interested, we recommend highly 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>.
<p>
Another good read is the article here <a href="https://arxiv.org/pdf/1603.07285.pdf" target="_blank"><tt>https://arxiv.org/pdf/1603.07285.pdf</tt></a>.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="neural-networks-vs-cnns">Neural Networks vs CNNs </h2>
<p>
Neural networks are defined as <b>affine transformations</b>, that is
a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an
output (to which a bias vector is usually added before passing the result
through a nonlinear activation function). This is applicable to any type of input, be it an
image, a sound clip or an unordered collection of features: whatever their
dimensionality, their representation can always be flattened into a vector
before the transformation.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="why-cnns-for-images-sound-files-medical-images-from-ct-scans-etc">Why CNNS for images, sound files, medical images from CT scans etc? </h2>
<p>
However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic
structure. More formally, they share these important properties:</li>
<ul>
<li> They are stored as multi-dimensional arrays (think of the pixels of a figure) .</li>
<li> They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).</li>
<li> One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).</li>
</ul>
These properties are not exploited when an affine transformation is applied; in
fact, all the axes are treated in the same way and the topological information
is not taken into account. Still, taking advantage of the implicit structure of
the data may prove very handy in solving some tasks, like computer vision and
speech recognition, and in these cases it would be best to preserve it. This is
where discrete convolutions come into play.
<p>
A discrete convolution is a linear transformation that preserves this notion of
ordering. It is sparse (only a few input units contribute to a given output
unit) and reuses parameters (the same weights are applied to multiple locations
in the input).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="regular-nns-don-t-scale-well-to-full-images">Regular NNs don&#8217;t scale well to full images </h2>
<p>
As an example, consider
an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a
single fully-connected neuron in a first hidden layer of a regular
Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still
seems manageable, but clearly this fully-connected structure does not
scale to larger images. For example, an image of more respectable
size, say \( 200\times 200\times 3 \), would lead to neurons that have
\( 200\times 200\times 3 = 120,000 \) weights.
<p>
We could have
several such neurons, and the parameters would add up quickly! Clearly,
this full connectivity is wasteful and the huge number of parameters
would quickly lead to possible overfitting.
<p>
<center> <!-- FIGURE -->
<hr class="figure">
<center><p class="caption">Figure 1: A regular 3-layer Neural Network. </p></center>
<p><img src="figslides/nn.jpeg" align="bottom" width=500></p>
</center>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="3d-volumes-of-neurons">3D volumes of neurons </h2>
<p>
Convolutional Neural Networks take advantage of the fact that the
input consists of images and they constrain the architecture in a more
sensible way.
<p>
In particular, unlike a regular Neural Network, the
layers of a CNN have neurons arranged in 3 dimensions: width,
height, depth. (Note that the word depth here refers to the third
dimension of an activation volume, not to the depth of a full Neural
Network, which can refer to the total number of layers in a network.)
<p>
To understand it better, the above example of an image
with an input volume of
activations has dimensions \( 32\times 32\times 3 \) (width, height,
depth respectively).
<p>
The neurons in a layer will
only be connected to a small region of the layer before it, instead of
all of the neurons in a fully-connected manner. Moreover, the final
output layer could for this specific image have dimensions \( 1\times 1 \times 10 \),
because by the
end of the CNN architecture we will reduce the full image into a
single vector of class scores, arranged along the depth
dimension.
<p>
<center> <!-- FIGURE -->
<hr class="figure">
<center><p class="caption">Figure 2: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). </p></center>
<p><img src="figslides/cnn.jpeg" align="bottom" width=500></p>
</center>
<p>
<!-- !split -->
<h2 id="layers-used-to-build-cnns">Layers used to build CNNs </h2>
<p>
A simple CNN is a sequence of layers, and every layer of a CNN
transforms one volume of activations to another through a
differentiable function. We use three main types of layers to build
CNN architectures: Convolutional Layer, Pooling Layer, and
Fully-Connected Layer (exactly as seen in regular Neural Networks). We
will stack these layers to form a full CNN architecture.
<p>
A simple CNN for image classification could have the architecture:
<ul>
<li> <b>INPUT</b> (\( 32\times 32 \times 3 \)) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.</li>
<li> <b>CONV</b> (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as \( [32\times 32\times 12] \) if we decided to use 12 filters.</li>
<li> <b>RELU</b> layer will apply an elementwise activation function, such as the \( max(0,x) \) thresholding at zero. This leaves the size of the volume unchanged (\( [32\times 32\times 12] \)).</li>
<li> <b>POOL</b> (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as \( [16\times 16\times 12] \).</li>
<li> <b>FC</b> (i.e. fully-connected) layer will compute the class scores, resulting in volume of size \( [1\times 1\times 10] \), where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="transforming-images">Transforming images </h2>
<p>
CNNs transform the original image layer by layer from the original
pixel values to the final class scores.
<p>
Observe that some layers contain
parameters and other don&#8217;t. In particular, the CNN layers perform
transformations that are a function of not only the activations in the
input volume, but also of the parameters (the weights and biases of
the neurons). On the other hand, the RELU/POOL layers will implement a
fixed function. The parameters in the CONV/FC layers will be trained
with gradient descent so that the class scores that the CNN computes
are consistent with the labels in the training set for each image.
<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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cnns-in-more-detail-building-convolutional-neural-networks-in-tensorflow-and-keras">CNNs in more detail, building convolutional neural networks in Tensorflow and Keras </h2>
<p>
As discussed above, CNNs are neural networks built from the assumption that the inputs
to the network are 2D images. This is important because the number of features or pixels in images
grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
<p>
As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
are the <b>convolutional</b> and <b>pooling</b> layers stacked in pairs between the input and the hidden layer.
In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
matrices, typically 1 for each color dimension (Red, Green, Blue).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-it-up">Setting it up </h2>
<p>
It means that to represent the entire
dataset of images, we require a 4D matrix or <b>tensor</b>. This tensor has the dimensions:
$$
(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-mnist-dataset-again">The MNIST dataset again </h2>
<p>
The MNIST dataset consists of grayscale images with a pixel size of
\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each
neuron in the first hidden layer.
<p>
If we were to analyze images of size \( 128\times 128 \) we would require
\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were
dealing with color images, as most images are, we have an image matrix
of size \( 128\times 128 \) for each color dimension (Red, Green, Blue),
meaning 3 times the number of weights \( = 49152 \) are required for every
single neuron in the first hidden layer.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="strong-correlations">Strong correlations </h2>
<p>
Images typically have strong local correlations, meaning that a small
part of the image varies little from its neighboring regions. If for
example we have an image of a blue car, we can roughly assume that a
small blue part of the image is surrounded by other blue regions.
<p>
Therefore, instead of connecting every single pixel to a neuron in the
first hidden layer, as we have previously done with deep neural
networks, we can instead connect each neuron to a small part of the
image (in all 3 RGB depth dimensions). The size of each small area is
fixed, and known as a <a href="https://en.wikipedia.org/wiki/Receptive_field" target="_blank">receptive</a>.
<p>
<!-- !split -->
<h2 id="layers-of-a-cnn">Layers of a CNN </h2>
The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
The input image is typically a square matrix of depth 3.
<p>
A <b>convolution</b> is performed on the image which outputs
a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as <b>filters</b>.
<p>
Each filter slides along the input image, taking the dot product
between each small part of the image and the filter, in all depth
dimensions. This is then passed through a non-linear function,
typically the <b>Rectified Linear (ReLu)</b> function, which serves as the
activation of the neurons in the first convolutional layer. This is
further passed through a <b>pooling layer</b>, which reduces the size of the
convolutional layer, e.g. by taking the maximum or average across some
small regions, and this serves as input to the next convolutional
layer.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="systematic-reduction">Systematic reduction </h2>
<p>
By systematically reducing the size of the input volume, through
convolution and pooling, the network should create representations of
small parts of the input, and then from them assemble representations
of larger areas. The final pooling layer is flattened to serve as
input to a hidden layer, such that each neuron in the final pooling
layer is connected to every single neuron in the hidden layer. This
then serves as input to the output layer, e.g. a softmax output for
classification.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="prerequisites-collect-and-pre-process-data">Prerequisites: Collect and pre-process data </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"># import necessary packages</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> datasets
<span style="color: #408080; font-style: italic"># ensure the same random numbers appear every time</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># display images in notebook</span>
<span style="color: #666666">%</span>matplotlib inline
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;figure.figsize&#39;</span>] <span style="color: #666666">=</span> (<span style="color: #666666">12</span>,<span style="color: #666666">12</span>)
<span style="color: #408080; font-style: italic"># download MNIST dataset</span>
digits <span style="color: #666666">=</span> datasets<span style="color: #666666">.</span>load_digits()
<span style="color: #408080; font-style: italic"># define inputs and labels</span>
inputs <span style="color: #666666">=</span> digits<span style="color: #666666">.</span>images
labels <span style="color: #666666">=</span> digits<span style="color: #666666">.</span>target
<span style="color: #408080; font-style: italic"># RGB images have a depth of 3</span>
<span style="color: #408080; font-style: italic"># our images are grayscale so they should have a depth of 1</span>
inputs <span style="color: #666666">=</span> inputs[:,:,:,np<span style="color: #666666">.</span>newaxis]
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;inputs = (n_inputs, pixel_width, pixel_height, depth) = &quot;</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(inputs<span style="color: #666666">.</span>shape))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;labels = (n_inputs) = &quot;</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(labels<span style="color: #666666">.</span>shape))
<span style="color: #408080; font-style: italic"># choose some random images to display</span>
n_inputs <span style="color: #666666">=</span> <span style="color: #008000">len</span>(inputs)
indices <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(n_inputs)
random_indices <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>choice(indices, size<span style="color: #666666">=5</span>)
<span style="color: #008000; font-weight: bold">for</span> i, image <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(digits<span style="color: #666666">.</span>images[random_indices]):
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">1</span>, <span style="color: #666666">5</span>, i<span style="color: #666666">+1</span>)
plt<span style="color: #666666">.</span>axis(<span style="color: #BA2121">&#39;off&#39;</span>)
plt<span style="color: #666666">.</span>imshow(image, cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>gray_r, interpolation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;nearest&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Label: </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">%</span> digits<span style="color: #666666">.</span>target[random_indices[i]])
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="importing-keras-and-tensorflow">Importing Keras and Tensorflow </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">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> Sequential <span style="color: #408080; font-style: italic">#This allows appending layers to existing models</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras.layers</span> <span style="color: #008000; font-weight: bold">import</span> Dense <span style="color: #408080; font-style: italic">#This allows defining the characteristics of a particular layer</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras</span> <span style="color: #008000; font-weight: bold">import</span> optimizers <span style="color: #408080; font-style: italic">#This allows using whichever optimiser we want (sgd,adam,RMSprop)</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras</span> <span style="color: #008000; font-weight: bold">import</span> regularizers <span style="color: #408080; font-style: italic">#This allows using whichever regularizer we want (l1,l2,l1_l2)</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras.utils</span> <span style="color: #008000; font-weight: bold">import</span> to_categorical <span style="color: #408080; font-style: italic">#This allows using categorical cross entropy as the cost function</span>
<span style="color: #408080; font-style: italic">#from tensorflow.keras import Conv2D</span>
<span style="color: #408080; font-style: italic">#from tensorflow.keras import MaxPooling2D</span>
<span style="color: #408080; font-style: italic">#from tensorflow.keras import Flatten</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #408080; font-style: italic"># representation of labels</span>
labels <span style="color: #666666">=</span> to_categorical(labels)
<span style="color: #408080; font-style: italic"># split into train and test data</span>
<span style="color: #408080; font-style: italic"># one-liner from scikit-learn library</span>
train_size <span style="color: #666666">=</span> <span style="color: #666666">0.8</span>
test_size <span style="color: #666666">=</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> train_size
X_train, X_test, Y_train, Y_test <span style="color: #666666">=</span> train_test_split(inputs, labels, train_size<span style="color: #666666">=</span>train_size,
test_size<span style="color: #666666">=</span>test_size)
</pre></div>
<p>
<!-- !split -->
<h2 id="running-with-keras">Running with Keras </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">create_convolutional_neural_network_keras</span>(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd):
model <span style="color: #666666">=</span> Sequential()
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(n_filters, (receptive_field, receptive_field), input_shape<span style="color: #666666">=</span>input_shape, padding<span style="color: #666666">=</span><span style="color: #BA2121">&#39;same&#39;</span>,
activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>, kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lmbd)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>MaxPooling2D(pool_size<span style="color: #666666">=</span>(<span style="color: #666666">2</span>, <span style="color: #666666">2</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(n_neurons_connected, activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>, kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lmbd)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dense(n_categories, activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;softmax&#39;</span>, kernel_regularizer<span style="color: #666666">=</span>regularizers<span style="color: #666666">.</span>l2(lmbd)))
sgd <span style="color: #666666">=</span> optimizers<span style="color: #666666">.</span>SGD(lr<span style="color: #666666">=</span>eta)
model<span style="color: #666666">.</span>compile(loss<span style="color: #666666">=</span><span style="color: #BA2121">&#39;categorical_crossentropy&#39;</span>, optimizer<span style="color: #666666">=</span>sgd, metrics<span style="color: #666666">=</span>[<span style="color: #BA2121">&#39;accuracy&#39;</span>])
<span style="color: #008000; font-weight: bold">return</span> model
epochs <span style="color: #666666">=</span> <span style="color: #666666">100</span>
batch_size <span style="color: #666666">=</span> <span style="color: #666666">100</span>
input_shape <span style="color: #666666">=</span> X_train<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>:<span style="color: #666666">4</span>]
receptive_field <span style="color: #666666">=</span> <span style="color: #666666">3</span>
n_filters <span style="color: #666666">=</span> <span style="color: #666666">10</span>
n_neurons_connected <span style="color: #666666">=</span> <span style="color: #666666">50</span>
n_categories <span style="color: #666666">=</span> <span style="color: #666666">10</span>
eta_vals <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-5</span>, <span style="color: #666666">1</span>, <span style="color: #666666">7</span>)
lmbd_vals <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-5</span>, <span style="color: #666666">1</span>, <span style="color: #666666">7</span>)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-part">Final part </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>CNN_keras <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)), dtype<span style="color: #666666">=</span><span style="color: #008000">object</span>)
<span style="color: #008000; font-weight: bold">for</span> i, eta <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(eta_vals):
<span style="color: #008000; font-weight: bold">for</span> j, lmbd <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(lmbd_vals):
CNN <span style="color: #666666">=</span> create_convolutional_neural_network_keras(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd)
CNN<span style="color: #666666">.</span>fit(X_train, Y_train, epochs<span style="color: #666666">=</span>epochs, batch_size<span style="color: #666666">=</span>batch_size, verbose<span style="color: #666666">=0</span>)
scores <span style="color: #666666">=</span> CNN<span style="color: #666666">.</span>evaluate(X_test, Y_test)
CNN_keras[i][j] <span style="color: #666666">=</span> CNN
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Learning rate = &quot;</span>, eta)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Lambda = &quot;</span>, lmbd)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test accuracy: </span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">%</span> scores[<span style="color: #666666">1</span>])
<span style="color: #008000">print</span>()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-visualization">Final visualization </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"># visual representation of grid search</span>
<span style="color: #408080; font-style: italic"># uses seaborn heatmap, could probably do this in matplotlib</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">seaborn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">sns</span>
sns<span style="color: #666666">.</span>set()
train_accuracy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)))
test_accuracy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)))
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">len</span>(eta_vals)):
<span style="color: #008000; font-weight: bold">for</span> j <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">len</span>(lmbd_vals)):
CNN <span style="color: #666666">=</span> CNN_keras[i][j]
train_accuracy[i][j] <span style="color: #666666">=</span> CNN<span style="color: #666666">.</span>evaluate(X_train, Y_train)[<span style="color: #666666">1</span>]
test_accuracy[i][j] <span style="color: #666666">=</span> CNN<span style="color: #666666">.</span>evaluate(X_test, Y_test)[<span style="color: #666666">1</span>]
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots(figsize <span style="color: #666666">=</span> (<span style="color: #666666">10</span>, <span style="color: #666666">10</span>))
sns<span style="color: #666666">.</span>heatmap(train_accuracy, annot<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, ax<span style="color: #666666">=</span>ax, cmap<span style="color: #666666">=</span><span style="color: #BA2121">&quot;viridis&quot;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&quot;Training Accuracy&quot;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&quot;$\eta$&quot;</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&quot;$\lambda$&quot;</span>)
plt<span style="color: #666666">.</span>show()
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots(figsize <span style="color: #666666">=</span> (<span style="color: #666666">10</span>, <span style="color: #666666">10</span>))
sns<span style="color: #666666">.</span>heatmap(test_accuracy, annot<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, ax<span style="color: #666666">=</span>ax, cmap<span style="color: #666666">=</span><span style="color: #BA2121">&quot;viridis&quot;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&quot;Test Accuracy&quot;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&quot;$\eta$&quot;</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&quot;$\lambda$&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-cifar01-data-set">The CIFAR01 data set </h2>
<p>
The CIFAR10 dataset contains 60,000 color images in 10 classes, with
6,000 images in each class. The dataset is divided into 50,000
training images and 10,000 testing images. The classes are mutually
exclusive and there is no overlap between them.
<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">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">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"># We import the data set</span>
(train_images, train_labels), (test_images, test_labels) <span style="color: #666666">=</span> datasets<span style="color: #666666">.</span>cifar10<span style="color: #666666">.</span>load_data()
<span style="color: #408080; font-style: italic"># Normalize pixel values to be between 0 and 1 by dividing by 255. </span>
train_images, test_images <span style="color: #666666">=</span> train_images <span style="color: #666666">/</span> <span style="color: #666666">255.0</span>, test_images <span style="color: #666666">/</span> <span style="color: #666666">255.0</span>
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="verifying-the-data-set">Verifying the data set </h2>
<p>
To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>class_names <span style="color: #666666">=</span> [<span style="color: #BA2121">&#39;airplane&#39;</span>, <span style="color: #BA2121">&#39;automobile&#39;</span>, <span style="color: #BA2121">&#39;bird&#39;</span>, <span style="color: #BA2121">&#39;cat&#39;</span>, <span style="color: #BA2121">&#39;deer&#39;</span>,
<span style="color: #BA2121">&#39;dog&#39;</span>, <span style="color: #BA2121">&#39;frog&#39;</span>, <span style="color: #BA2121">&#39;horse&#39;</span>, <span style="color: #BA2121">&#39;ship&#39;</span>, <span style="color: #BA2121">&#39;truck&#39;</span>]
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
<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">25</span>):
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">5</span>,<span style="color: #666666">5</span>,i<span style="color: #666666">+1</span>)
plt<span style="color: #666666">.</span>xticks([])
plt<span style="color: #666666">.</span>yticks([])
plt<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">False</span>)
plt<span style="color: #666666">.</span>imshow(train_images[i], cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>binary)
<span style="color: #408080; font-style: italic"># The CIFAR labels happen to be arrays, </span>
<span style="color: #408080; font-style: italic"># which is why you need the extra index</span>
plt<span style="color: #666666">.</span>xlabel(class_names[train_labels[i][<span style="color: #666666">0</span>]])
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="set-up-the-model">Set up the model </h2>
<p>
The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.
<p>
As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>model <span style="color: #666666">=</span> models<span style="color: #666666">.</span>Sequential()
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(<span style="color: #666666">32</span>, (<span style="color: #666666">3</span>, <span style="color: #666666">3</span>), activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>, input_shape<span style="color: #666666">=</span>(<span style="color: #666666">32</span>, <span style="color: #666666">32</span>, <span style="color: #666666">3</span>)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>MaxPooling2D((<span style="color: #666666">2</span>, <span style="color: #666666">2</span>)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(<span style="color: #666666">64</span>, (<span style="color: #666666">3</span>, <span style="color: #666666">3</span>), activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>MaxPooling2D((<span style="color: #666666">2</span>, <span style="color: #666666">2</span>)))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Conv2D(<span style="color: #666666">64</span>, (<span style="color: #666666">3</span>, <span style="color: #666666">3</span>), activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>))
<span style="color: #408080; font-style: italic"># Let&#39;s display the architecture of our model so far.</span>
model<span style="color: #666666">.</span>summary()
</pre></div>
<p>
You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="add-dense-layers-on-top">Add Dense layers on top </h2>
<p>
To complete our model, you will feed the last output tensor from the
convolutional base (of shape (4, 4, 64)) into one or more Dense layers
to perform classification. Dense layers take vectors as input (which
are 1D), while the current output is a 3D tensor. First, you will
flatten (or unroll) the 3D output to 1D, then add one or more Dense
layers on top. CIFAR has 10 output classes, so you use a final Dense
layer with 10 outputs and a softmax activation.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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">64</span>, activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;relu&#39;</span>))
model<span style="color: #666666">.</span>add(layers<span style="color: #666666">.</span>Dense(<span style="color: #666666">10</span>))
Here<span style="color: #BA2121">&#39;s the complete architecture of our model.</span>
model<span style="color: #666666">.</span>summary()
</pre></div>
<p>
As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="compile-and-train-the-model">Compile and train the model </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>model<span style="color: #666666">.</span>compile(optimizer<span style="color: #666666">=</span><span style="color: #BA2121">&#39;adam&#39;</span>,
loss<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>keras<span style="color: #666666">.</span>losses<span style="color: #666666">.</span>SparseCategoricalCrossentropy(from_logits<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>),
metrics<span style="color: #666666">=</span>[<span style="color: #BA2121">&#39;accuracy&#39;</span>])
history <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(train_images, train_labels, epochs<span style="color: #666666">=10</span>,
validation_data<span style="color: #666666">=</span>(test_images, test_labels))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="finally-evaluate-the-model">Finally, evaluate the model </h2>
<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>plot(history<span style="color: #666666">.</span>history[<span style="color: #BA2121">&#39;accuracy&#39;</span>], label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;accuracy&#39;</span>)
plt<span style="color: #666666">.</span>plot(history<span style="color: #666666">.</span>history[<span style="color: #BA2121">&#39;val_accuracy&#39;</span>], label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;val_accuracy&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Epoch&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;Accuracy&#39;</span>)
plt<span style="color: #666666">.</span>ylim([<span style="color: #666666">0.5</span>, <span style="color: #666666">1</span>])
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&#39;lower right&#39;</span>)
test_loss, test_acc <span style="color: #666666">=</span> model<span style="color: #666666">.</span>evaluate(test_images, test_labels, verbose<span style="color: #666666">=2</span>)
<span style="color: #008000">print</span>(test_acc)
</pre></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>
Binary file not shown.
+4 -694
View File
@@ -10,7 +10,7 @@
"<!-- Author: --> \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
"Date: **Oct 19, 2021**\n",
"Date: **Oct 23, 2021**\n",
"\n",
"Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
@@ -18,7 +18,7 @@
"\n",
"## Plans for week 43\n",
"\n",
"* Thursday: Convolutional Neural Networks and Recurrent Neural Networks\n",
"* Thursday: Summary of Convolutional Neural Networks from week 42 and Recurrent Neural Networks\n",
"\n",
"* Friday: Recurrent Neural Networks and other Deep Learning methods\n",
"\n",
@@ -41,699 +41,7 @@
"\n",
"\n",
"\n",
"## Convolutional Neural Networks (recognizing images)\n",
"\n",
"\n",
"Convolutional neural networks (CNNs) were developed during the last\n",
"decade of the previous century, with a focus on character recognition\n",
"tasks. Nowadays, CNNs are a central element in the spectacular success\n",
"of deep learning methods. The success in for example image\n",
"classifications have made them a central tool for most machine\n",
"learning practitioners.\n",
"\n",
"CNNs are very similar to ordinary Neural Networks.\n",
"They are made up of neurons that have learnable weights and\n",
"biases. Each neuron receives some inputs, performs a dot product and\n",
"optionally follows it with a non-linearity. The whole network still\n",
"expresses a single differentiable score function: from the raw image\n",
"pixels on one end to class scores at the other. And they still have a\n",
"loss function (for example Softmax) on the last (fully-connected) layer\n",
"and all the tips/tricks we developed for learning regular Neural\n",
"Networks still apply (back propagation, gradient descent etc etc).\n",
"\n",
"What is the difference? **CNN architectures make the explicit assumption that\n",
"the inputs are images, which allows us to encode certain properties\n",
"into the architecture. These then make the forward function more\n",
"efficient to implement and vastly reduce the amount of parameters in\n",
"the network.**\n",
"\n",
"Here we provide only a superficial overview, for the more interested, we recommend highly the course\n",
"[IN5400 Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
"and the slides of [CS231](http://cs231n.github.io/convolutional-networks/).\n",
"\n",
"Another good read is the article here <https://arxiv.org/pdf/1603.07285.pdf>. \n",
"\n",
"\n",
"\n",
"\n",
"## Neural Networks vs CNNs\n",
"\n",
"Neural networks are defined as **affine transformations**, that is \n",
"a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an\n",
"output (to which a bias vector is usually added before passing the result\n",
"through a nonlinear activation function). This is applicable to any type of input, be it an\n",
"image, a sound clip or an unordered collection of features: whatever their\n",
"dimensionality, their representation can always be flattened into a vector\n",
"before the transformation.\n",
"\n",
"\n",
"## Why CNNS for images, sound files, medical images from CT scans etc?\n",
"\n",
"However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic\n",
"structure. More formally, they share these important properties:\n",
"* They are stored as multi-dimensional arrays (think of the pixels of a figure) .\n",
"\n",
"* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).\n",
"\n",
"* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).\n",
"\n",
"These properties are not exploited when an affine transformation is applied; in\n",
"fact, all the axes are treated in the same way and the topological information\n",
"is not taken into account. Still, taking advantage of the implicit structure of\n",
"the data may prove very handy in solving some tasks, like computer vision and\n",
"speech recognition, and in these cases it would be best to preserve it. This is\n",
"where discrete convolutions come into play.\n",
"\n",
"A discrete convolution is a linear transformation that preserves this notion of\n",
"ordering. It is sparse (only a few input units contribute to a given output\n",
"unit) and reuses parameters (the same weights are applied to multiple locations\n",
"in the input).\n",
"\n",
"\n",
"\n",
"\n",
"## Regular NNs dont scale well to full images\n",
"\n",
"As an example, consider\n",
"an image of size $32\\times 32\\times 3$ (32 wide, 32 high, 3 color channels), so a\n",
"single fully-connected neuron in a first hidden layer of a regular\n",
"Neural Network would have $32\\times 32\\times 3 = 3072$ weights. This amount still\n",
"seems manageable, but clearly this fully-connected structure does not\n",
"scale to larger images. For example, an image of more respectable\n",
"size, say $200\\times 200\\times 3$, would lead to neurons that have \n",
"$200\\times 200\\times 3 = 120,000$ weights. \n",
"\n",
"We could have\n",
"several such neurons, and the parameters would add up quickly! Clearly,\n",
"this full connectivity is wasteful and the huge number of parameters\n",
"would quickly lead to possible overfitting.\n",
"\n",
"<!-- dom:FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network. -->\n",
"<!-- begin figure -->\n",
"<img src=\"figslides/nn.jpeg\" width=500><p style=\"font-size: 0.9em\"><i>Figure 1: A regular 3-layer Neural Network.</i></p><!-- end figure -->\n",
"\n",
"\n",
"## 3D volumes of neurons\n",
"\n",
"Convolutional Neural Networks take advantage of the fact that the\n",
"input consists of images and they constrain the architecture in a more\n",
"sensible way. \n",
"\n",
"In particular, unlike a regular Neural Network, the\n",
"layers of a CNN have neurons arranged in 3 dimensions: width,\n",
"height, depth. (Note that the word depth here refers to the third\n",
"dimension of an activation volume, not to the depth of a full Neural\n",
"Network, which can refer to the total number of layers in a network.)\n",
"\n",
"To understand it better, the above example of an image \n",
"with an input volume of\n",
"activations has dimensions $32\\times 32\\times 3$ (width, height,\n",
"depth respectively). \n",
"\n",
"The neurons in a layer will\n",
"only be connected to a small region of the layer before it, instead of\n",
"all of the neurons in a fully-connected manner. Moreover, the final\n",
"output layer could for this specific image have dimensions $1\\times 1 \\times 10$, \n",
"because by the\n",
"end of the CNN architecture we will reduce the full image into a\n",
"single vector of class scores, arranged along the depth\n",
"dimension. \n",
"\n",
"<!-- dom:FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). -->\n",
"<!-- begin figure -->\n",
"<img src=\"figslides/cnn.jpeg\" width=500><p style=\"font-size: 0.9em\"><i>Figure 1: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).</i></p><!-- end figure -->\n",
"\n",
"\n",
"\n",
"\n",
"<!-- !split -->\n",
"## Layers used to build CNNs\n",
"\n",
"\n",
"A simple CNN is a sequence of layers, and every layer of a CNN\n",
"transforms one volume of activations to another through a\n",
"differentiable function. We use three main types of layers to build\n",
"CNN architectures: Convolutional Layer, Pooling Layer, and\n",
"Fully-Connected Layer (exactly as seen in regular Neural Networks). We\n",
"will stack these layers to form a full CNN architecture.\n",
"\n",
"A simple CNN for image classification could have the architecture:\n",
"\n",
"* **INPUT** ($32\\times 32 \\times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.\n",
"\n",
"* **CONV** (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\\times 32\\times 12]$ if we decided to use 12 filters.\n",
"\n",
"* **RELU** layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\\times 32\\times 12]$).\n",
"\n",
"* **POOL** (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\\times 16\\times 12]$.\n",
"\n",
"* **FC** (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\\times 1\\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.\n",
"\n",
"## Transforming images\n",
"\n",
"CNNs transform the original image layer by layer from the original\n",
"pixel values to the final class scores. \n",
"\n",
"Observe that some layers contain\n",
"parameters and other dont. In particular, the CNN layers perform\n",
"transformations that are a function of not only the activations in the\n",
"input volume, but also of the parameters (the weights and biases of\n",
"the neurons). On the other hand, the RELU/POOL layers will implement a\n",
"fixed function. The parameters in the CONV/FC layers will be trained\n",
"with gradient descent so that the class scores that the CNN computes\n",
"are consistent with the labels in the training set for each image.\n",
"\n",
"\n",
"## CNNs in brief\n",
"\n",
"In summary:\n",
"\n",
"* 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)\n",
"\n",
"* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n",
"\n",
"* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n",
"\n",
"* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL dont)\n",
"\n",
"* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesnt)\n",
"\n",
"For more material on convolutional networks, we strongly recommend\n",
"the course\n",
"[IN5400 Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
"and the slides of [CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n",
"\n",
"\n",
"\n",
"## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n",
"\n",
"\n",
"As discussed above, CNNs are neural networks built from the assumption that the inputs\n",
"to the network are 2D images. This is important because the number of features or pixels in images\n",
"grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n",
"\n",
"As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n",
"are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n",
"In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n",
"matrices, typically 1 for each color dimension (Red, Green, Blue). \n",
"\n",
"\n",
"## Setting it up\n",
"\n",
"It means that to represent the entire\n",
"dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The MNIST dataset again\n",
"\n",
"The MNIST dataset consists of grayscale images with a pixel size of\n",
"$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n",
"neuron in the first hidden layer.\n",
"\n",
"If we were to analyze images of size $128\\times 128$ we would require\n",
"$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n",
"dealing with color images, as most images are, we have an image matrix\n",
"of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n",
"meaning 3 times the number of weights $= 49152$ are required for every\n",
"single neuron in the first hidden layer.\n",
"\n",
"\n",
"## Strong correlations\n",
"\n",
"Images typically have strong local correlations, meaning that a small\n",
"part of the image varies little from its neighboring regions. If for\n",
"example we have an image of a blue car, we can roughly assume that a\n",
"small blue part of the image is surrounded by other blue regions.\n",
"\n",
"Therefore, instead of connecting every single pixel to a neuron in the\n",
"first hidden layer, as we have previously done with deep neural\n",
"networks, we can instead connect each neuron to a small part of the\n",
"image (in all 3 RGB depth dimensions). The size of each small area is\n",
"fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).\n",
"\n",
"\n",
"<!-- !split -->\n",
"## Layers of a CNN\n",
"The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n",
"The input image is typically a square matrix of depth 3. \n",
"\n",
"A **convolution** is performed on the image which outputs\n",
"a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n",
"\n",
"\n",
"Each filter slides along the input image, taking the dot product\n",
"between each small part of the image and the filter, in all depth\n",
"dimensions. This is then passed through a non-linear function,\n",
"typically the **Rectified Linear (ReLu)** function, which serves as the\n",
"activation of the neurons in the first convolutional layer. This is\n",
"further passed through a **pooling layer**, which reduces the size of the\n",
"convolutional layer, e.g. by taking the maximum or average across some\n",
"small regions, and this serves as input to the next convolutional\n",
"layer.\n",
"\n",
"\n",
"## Systematic reduction\n",
"\n",
"By systematically reducing the size of the input volume, through\n",
"convolution and pooling, the network should create representations of\n",
"small parts of the input, and then from them assemble representations\n",
"of larger areas. The final pooling layer is flattened to serve as\n",
"input to a hidden layer, such that each neuron in the final pooling\n",
"layer is connected to every single neuron in the hidden layer. This\n",
"then serves as input to the output layer, e.g. a softmax output for\n",
"classification.\n",
"\n",
"\n",
"## Prerequisites: Collect and pre-process data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"# import necessary packages\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn import datasets\n",
"\n",
"\n",
"# ensure the same random numbers appear every time\n",
"np.random.seed(0)\n",
"\n",
"# display images in notebook\n",
"%matplotlib inline\n",
"plt.rcParams['figure.figsize'] = (12,12)\n",
"\n",
"\n",
"# download MNIST dataset\n",
"digits = datasets.load_digits()\n",
"\n",
"# define inputs and labels\n",
"inputs = digits.images\n",
"labels = digits.target\n",
"\n",
"# RGB images have a depth of 3\n",
"# our images are grayscale so they should have a depth of 1\n",
"inputs = inputs[:,:,:,np.newaxis]\n",
"\n",
"print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n",
"print(\"labels = (n_inputs) = \" + str(labels.shape))\n",
"\n",
"\n",
"# choose some random images to display\n",
"n_inputs = len(inputs)\n",
"indices = np.arange(n_inputs)\n",
"random_indices = np.random.choice(indices, size=5)\n",
"\n",
"for i, image in enumerate(digits.images[random_indices]):\n",
" plt.subplot(1, 5, i+1)\n",
" plt.axis('off')\n",
" plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n",
" plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Importing Keras and Tensorflow"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from tensorflow.keras import datasets, layers, models\n",
"from tensorflow.keras.layers import Input\n",
"from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n",
"from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n",
"from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n",
"from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n",
"from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n",
"#from tensorflow.keras import Conv2D\n",
"#from tensorflow.keras import MaxPooling2D\n",
"#from tensorflow.keras import Flatten\n",
"\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"# representation of labels\n",
"labels = to_categorical(labels)\n",
"\n",
"# split into train and test data\n",
"# one-liner from scikit-learn library\n",
"train_size = 0.8\n",
"test_size = 1 - train_size\n",
"X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n",
" test_size=test_size)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- !split -->\n",
"## Running with Keras"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"def create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
" n_filters, n_neurons_connected, n_categories,\n",
" eta, lmbd):\n",
" model = Sequential()\n",
" model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n",
" activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
" model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n",
" model.add(layers.Flatten())\n",
" model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
" model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))\n",
" \n",
" sgd = optimizers.SGD(lr=eta)\n",
" model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n",
" \n",
" return model\n",
"\n",
"epochs = 100\n",
"batch_size = 100\n",
"input_shape = X_train.shape[1:4]\n",
"receptive_field = 3\n",
"n_filters = 10\n",
"n_neurons_connected = 50\n",
"n_categories = 10\n",
"\n",
"eta_vals = np.logspace(-5, 1, 7)\n",
"lmbd_vals = np.logspace(-5, 1, 7)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Final part"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
" \n",
"for i, eta in enumerate(eta_vals):\n",
" for j, lmbd in enumerate(lmbd_vals):\n",
" CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
" n_filters, n_neurons_connected, n_categories,\n",
" eta, lmbd)\n",
" CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n",
" scores = CNN.evaluate(X_test, Y_test)\n",
" \n",
" CNN_keras[i][j] = CNN\n",
" \n",
" print(\"Learning rate = \", eta)\n",
" print(\"Lambda = \", lmbd)\n",
" print(\"Test accuracy: %.3f\" % scores[1])\n",
" print()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Final visualization"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# visual representation of grid search\n",
"# uses seaborn heatmap, could probably do this in matplotlib\n",
"import seaborn as sns\n",
"\n",
"sns.set()\n",
"\n",
"train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
"test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
"\n",
"for i in range(len(eta_vals)):\n",
" for j in range(len(lmbd_vals)):\n",
" CNN = CNN_keras[i][j]\n",
"\n",
" train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n",
" test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n",
"\n",
" \n",
"fig, ax = plt.subplots(figsize = (10, 10))\n",
"sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
"ax.set_title(\"Training Accuracy\")\n",
"ax.set_ylabel(\"$\\eta$\")\n",
"ax.set_xlabel(\"$\\lambda$\")\n",
"plt.show()\n",
"\n",
"fig, ax = plt.subplots(figsize = (10, 10))\n",
"sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
"ax.set_title(\"Test Accuracy\")\n",
"ax.set_ylabel(\"$\\eta$\")\n",
"ax.set_xlabel(\"$\\lambda$\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The CIFAR01 data set\n",
"\n",
"The CIFAR10 dataset contains 60,000 color images in 10 classes, with\n",
"6,000 images in each class. The dataset is divided into 50,000\n",
"training images and 10,000 testing images. The classes are mutually\n",
"exclusive and there is no overlap between them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"\n",
"from tensorflow.keras import datasets, layers, models\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# We import the data set\n",
"(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()\n",
"\n",
"# Normalize pixel values to be between 0 and 1 by dividing by 255. \n",
"train_images, test_images = train_images / 255.0, test_images / 255.0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Verifying the data set\n",
"\n",
"To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n",
" 'dog', 'frog', 'horse', 'ship', 'truck']\n",
"\n",
"plt.figure(figsize=(10,10))\n",
"for i in range(25):\n",
" plt.subplot(5,5,i+1)\n",
" plt.xticks([])\n",
" plt.yticks([])\n",
" plt.grid(False)\n",
" plt.imshow(train_images[i], cmap=plt.cm.binary)\n",
" # The CIFAR labels happen to be arrays, \n",
" # which is why you need the extra index\n",
" plt.xlabel(class_names[train_labels[i][0]])\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set up the model\n",
"\n",
"The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.\n",
"\n",
"As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"model = models.Sequential()\n",
"model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\n",
"model.add(layers.MaxPooling2D((2, 2)))\n",
"model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
"model.add(layers.MaxPooling2D((2, 2)))\n",
"model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
"\n",
"# Let's display the architecture of our model so far.\n",
"\n",
"model.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.\n",
"\n",
"\n",
"\n",
"\n",
"## Add Dense layers on top\n",
"\n",
"To complete our model, you will feed the last output tensor from the\n",
"convolutional base (of shape (4, 4, 64)) into one or more Dense layers\n",
"to perform classification. Dense layers take vectors as input (which\n",
"are 1D), while the current output is a 3D tensor. First, you will\n",
"flatten (or unroll) the 3D output to 1D, then add one or more Dense\n",
"layers on top. CIFAR has 10 output classes, so you use a final Dense\n",
"layer with 10 outputs and a softmax activation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"model.add(layers.Flatten())\n",
"model.add(layers.Dense(64, activation='relu'))\n",
"model.add(layers.Dense(10))\n",
"Here's the complete architecture of our model.\n",
"\n",
"model.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.\n",
"\n",
"## Compile and train the model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"model.compile(optimizer='adam',\n",
" loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
" metrics=['accuracy'])\n",
"\n",
"history = model.fit(train_images, train_labels, epochs=10, \n",
" validation_data=(test_images, test_labels))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Finally, evaluate the model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"plt.plot(history.history['accuracy'], label='accuracy')\n",
"plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n",
"plt.xlabel('Epoch')\n",
"plt.ylabel('Accuracy')\n",
"plt.ylim([0.5, 1])\n",
"plt.legend(loc='lower right')\n",
"\n",
"test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n",
"\n",
"print(test_acc)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Recurrent neural networks: Overarching view\n",
"\n",
"Till now our focus has been, including convolutional neural networks\n",
@@ -774,6 +82,8 @@
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"# Start importing packages\n",
"import pandas as pd\n",
"import numpy as np\n",
+1 -553
View File
@@ -5,7 +5,7 @@ DATE: today
!split
===== Plans for week 43 =====
* Thursday: Convolutional Neural Networks and Recurrent Neural Networks
* Thursday: Summary of Convolutional Neural Networks from week 42 and Recurrent Neural Networks
* Friday: Recurrent Neural Networks and other Deep Learning methods
!bblock Excellent lectures on CNNs and RNNs
@@ -21,558 +21,6 @@ DATE: today
!split
===== Convolutional Neural Networks (recognizing images) =====
Convolutional neural networks (CNNs) were developed during the last
decade of the previous century, with a focus on character recognition
tasks. Nowadays, CNNs are a central element in the spectacular success
of deep learning methods. The success in for example image
classifications have made them a central tool for most machine
learning practitioners.
CNNs are very similar to ordinary Neural Networks.
They are made up of neurons that have learnable weights and
biases. Each neuron receives some inputs, performs a dot product and
optionally follows it with a non-linearity. The whole network still
expresses a single differentiable score function: from the raw image
pixels on one end to class scores at the other. And they still have a
loss function (for example Softmax) on the last (fully-connected) layer
and all the tips/tricks we developed for learning regular Neural
Networks still apply (back propagation, gradient descent etc etc).
What is the difference? _CNN architectures make the explicit assumption that
the inputs are images, which allows us to encode certain properties
into the architecture. These then make the forward function more
efficient to implement and vastly reduce the amount of parameters in
the network._
Here we provide only a superficial overview, for the more interested, we recommend highly the course
"IN5400 Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/".
Another good read is the article here URL:"https://arxiv.org/pdf/1603.07285.pdf".
!split
===== Neural Networks vs CNNs =====
Neural networks are defined as _affine transformations_, that is
a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an
output (to which a bias vector is usually added before passing the result
through a nonlinear activation function). This is applicable to any type of input, be it an
image, a sound clip or an unordered collection of features: whatever their
dimensionality, their representation can always be flattened into a vector
before the transformation.
!split
===== Why CNNS for images, sound files, medical images from CT scans etc? =====
However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic
structure. More formally, they share these important properties:
* They are stored as multi-dimensional arrays (think of the pixels of a figure) .
* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).
* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).
These properties are not exploited when an affine transformation is applied; in
fact, all the axes are treated in the same way and the topological information
is not taken into account. Still, taking advantage of the implicit structure of
the data may prove very handy in solving some tasks, like computer vision and
speech recognition, and in these cases it would be best to preserve it. This is
where discrete convolutions come into play.
A discrete convolution is a linear transformation that preserves this notion of
ordering. It is sparse (only a few input units contribute to a given output
unit) and reuses parameters (the same weights are applied to multiple locations
in the input).
!split
===== Regular NNs dont scale well to full images =====
As an example, consider
an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a
single fully-connected neuron in a first hidden layer of a regular
Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still
seems manageable, but clearly this fully-connected structure does not
scale to larger images. For example, an image of more respectable
size, say $200\times 200\times 3$, would lead to neurons that have
$200\times 200\times 3 = 120,000$ weights.
We could have
several such neurons, and the parameters would add up quickly! Clearly,
this full connectivity is wasteful and the huge number of parameters
would quickly lead to possible overfitting.
FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network.
!split
===== 3D volumes of neurons =====
Convolutional Neural Networks take advantage of the fact that the
input consists of images and they constrain the architecture in a more
sensible way.
In particular, unlike a regular Neural Network, the
layers of a CNN have neurons arranged in 3 dimensions: width,
height, depth. (Note that the word depth here refers to the third
dimension of an activation volume, not to the depth of a full Neural
Network, which can refer to the total number of layers in a network.)
To understand it better, the above example of an image
with an input volume of
activations has dimensions $32\times 32\times 3$ (width, height,
depth respectively).
The neurons in a layer will
only be connected to a small region of the layer before it, instead of
all of the neurons in a fully-connected manner. Moreover, the final
output layer could for this specific image have dimensions $1\times 1 \times 10$,
because by the
end of the CNN architecture we will reduce the full image into a
single vector of class scores, arranged along the depth
dimension.
FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).
!split
===== Layers used to build CNNs =====
A simple CNN is a sequence of layers, and every layer of a CNN
transforms one volume of activations to another through a
differentiable function. We use three main types of layers to build
CNN architectures: Convolutional Layer, Pooling Layer, and
Fully-Connected Layer (exactly as seen in regular Neural Networks). We
will stack these layers to form a full CNN architecture.
A simple CNN for image classification could have the architecture:
* _INPUT_ ($32\times 32 \times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.
* _CONV_ (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters.
* _RELU_ layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\times 32\times 12]$).
* _POOL_ (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$.
* _FC_ (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\times 1\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
!split
===== Transforming images =====
CNNs transform the original image layer by layer from the original
pixel values to the final class scores.
Observe that some layers contain
parameters and other dont. In particular, the CNN layers perform
transformations that are a function of not only the activations in the
input volume, but also of the parameters (the weights and biases of
the neurons). On the other hand, the RELU/POOL layers will implement a
fixed function. The parameters in the CONV/FC layers will be trained
with gradient descent so that the class scores that the CNN computes
are consistent with the labels in the training set for each image.
!split
===== CNNs in brief =====
In summary:
* 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)
* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL dont)
* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesnt)
For more material on convolutional networks, we strongly recommend
the course
"IN5400 Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/" which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). "Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs":"http://neuralnetworksanddeeplearning.com/chap6.html".
!split
===== CNNs in more detail, building convolutional neural networks in Tensorflow and Keras =====
As discussed above, CNNs are neural networks built from the assumption that the inputs
to the network are 2D images. This is important because the number of features or pixels in images
grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
are the _convolutional_ and _pooling_ layers stacked in pairs between the input and the hidden layer.
In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
matrices, typically 1 for each color dimension (Red, Green, Blue).
!split
===== Setting it up =====
It means that to represent the entire
dataset of images, we require a 4D matrix or _tensor_. This tensor has the dimensions:
!bt
\[
(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
\]
!et
!split
===== The MNIST dataset again =====
The MNIST dataset consists of grayscale images with a pixel size of
$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each
neuron in the first hidden layer.
If we were to analyze images of size $128\times 128$ we would require
$128 \times 128 = 16384$ weights to each neuron. Even worse if we were
dealing with color images, as most images are, we have an image matrix
of size $128\times 128$ for each color dimension (Red, Green, Blue),
meaning 3 times the number of weights $= 49152$ are required for every
single neuron in the first hidden layer.
!split
===== Strong correlations =====
Images typically have strong local correlations, meaning that a small
part of the image varies little from its neighboring regions. If for
example we have an image of a blue car, we can roughly assume that a
small blue part of the image is surrounded by other blue regions.
Therefore, instead of connecting every single pixel to a neuron in the
first hidden layer, as we have previously done with deep neural
networks, we can instead connect each neuron to a small part of the
image (in all 3 RGB depth dimensions). The size of each small area is
fixed, and known as a "receptive":"https://en.wikipedia.org/wiki/Receptive_field".
!split
===== Layers of a CNN =====
The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
The input image is typically a square matrix of depth 3.
A _convolution_ is performed on the image which outputs
a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as _filters_.
Each filter slides along the input image, taking the dot product
between each small part of the image and the filter, in all depth
dimensions. This is then passed through a non-linear function,
typically the _Rectified Linear (ReLu)_ function, which serves as the
activation of the neurons in the first convolutional layer. This is
further passed through a _pooling layer_, which reduces the size of the
convolutional layer, e.g. by taking the maximum or average across some
small regions, and this serves as input to the next convolutional
layer.
!split
===== Systematic reduction =====
By systematically reducing the size of the input volume, through
convolution and pooling, the network should create representations of
small parts of the input, and then from them assemble representations
of larger areas. The final pooling layer is flattened to serve as
input to a hidden layer, such that each neuron in the final pooling
layer is connected to every single neuron in the hidden layer. This
then serves as input to the output layer, e.g. a softmax output for
classification.
!split
===== Prerequisites: Collect and pre-process data =====
!bc pycod
# import necessary packages
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
# ensure the same random numbers appear every time
np.random.seed(0)
# display images in notebook
%matplotlib inline
plt.rcParams['figure.figsize'] = (12,12)
# download MNIST dataset
digits = datasets.load_digits()
# define inputs and labels
inputs = digits.images
labels = digits.target
# RGB images have a depth of 3
# our images are grayscale so they should have a depth of 1
inputs = inputs[:,:,:,np.newaxis]
print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
print("labels = (n_inputs) = " + str(labels.shape))
# choose some random images to display
n_inputs = len(inputs)
indices = np.arange(n_inputs)
random_indices = np.random.choice(indices, size=5)
for i, image in enumerate(digits.images[random_indices]):
plt.subplot(1, 5, i+1)
plt.axis('off')
plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
plt.title("Label: %d" % digits.target[random_indices[i]])
plt.show()
!ec
!split
===== Importing Keras and Tensorflow =====
!bc pycod
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Sequential #This allows appending layers to existing models
from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer
from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)
from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)
from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function
#from tensorflow.keras import Conv2D
#from tensorflow.keras import MaxPooling2D
#from tensorflow.keras import Flatten
from sklearn.model_selection import train_test_split
# representation of labels
labels = to_categorical(labels)
# split into train and test data
# one-liner from scikit-learn library
train_size = 0.8
test_size = 1 - train_size
X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
test_size=test_size)
!ec
!split
===== Running with Keras =====
!bc pycod
def create_convolutional_neural_network_keras(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd):
model = Sequential()
model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
sgd = optimizers.SGD(lr=eta)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
return model
epochs = 100
batch_size = 100
input_shape = X_train.shape[1:4]
receptive_field = 3
n_filters = 10
n_neurons_connected = 50
n_categories = 10
eta_vals = np.logspace(-5, 1, 7)
lmbd_vals = np.logspace(-5, 1, 7)
!ec
!split
===== Final part =====
!bc pycod
CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
for i, eta in enumerate(eta_vals):
for j, lmbd in enumerate(lmbd_vals):
CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd)
CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
scores = CNN.evaluate(X_test, Y_test)
CNN_keras[i][j] = CNN
print("Learning rate = ", eta)
print("Lambda = ", lmbd)
print("Test accuracy: %.3f" % scores[1])
print()
!ec
!split
===== Final visualization =====
!bc pycod
# visual representation of grid search
# uses seaborn heatmap, could probably do this in matplotlib
import seaborn as sns
sns.set()
train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
for i in range(len(eta_vals)):
for j in range(len(lmbd_vals)):
CNN = CNN_keras[i][j]
train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
ax.set_title("Training Accuracy")
ax.set_ylabel("$\eta$")
ax.set_xlabel("$\lambda$")
plt.show()
fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
ax.set_title("Test Accuracy")
ax.set_ylabel("$\eta$")
ax.set_xlabel("$\lambda$")
plt.show()
!ec
!split
===== The CIFAR01 data set =====
The CIFAR10 dataset contains 60,000 color images in 10 classes, with
6,000 images in each class. The dataset is divided into 50,000
training images and 10,000 testing images. The classes are mutually
exclusive and there is no overlap between them.
!bc pycod
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
# We import the data set
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
# Normalize pixel values to be between 0 and 1 by dividing by 255.
train_images, test_images = train_images / 255.0, test_images / 255.0
!ec
!split
===== Verifying the data set =====
To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.
!bc pycod
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
# The CIFAR labels happen to be arrays,
# which is why you need the extra index
plt.xlabel(class_names[train_labels[i][0]])
plt.show()
!ec
!split
===== Set up the model =====
The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.
As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.
!bc pycod
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# Let's display the architecture of our model so far.
model.summary()
!ec
You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.
!split
===== Add Dense layers on top =====
To complete our model, you will feed the last output tensor from the
convolutional base (of shape (4, 4, 64)) into one or more Dense layers
to perform classification. Dense layers take vectors as input (which
are 1D), while the current output is a 3D tensor. First, you will
flatten (or unroll) the 3D output to 1D, then add one or more Dense
layers on top. CIFAR has 10 output classes, so you use a final Dense
layer with 10 outputs and a softmax activation.
!bc pycod
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
Here's the complete architecture of our model.
model.summary()
!ec
As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.
!split
===== Compile and train the model =====
!bc pycod
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
!ec
!split
===== Finally, evaluate the model =====
!bc pycod
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(test_acc)
!ec
!split
===== Recurrent neural networks: Overarching view =====