Files
FYS-STK4155/doc/pub/week44/html/week44.html
T
Morten Hjorth-Jensen 4c49bc7747 update week44
2023-10-29 22:08:34 +01:00

1629 lines
84 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week44.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=week44 --no_mako
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/doconce/doconce/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Week 44, Convolutional Neural Networks (CNN)">
<title>Week 44, Convolutional Neural Networks (CNN)</title>
<style type="text/css">
/* bloodish style */
body {
font-family: Helvetica, Verdana, Arial, Sans-serif;
color: #404040;
background: #ffffff;
}
h1 { font-size: 1.8em; color: #8A0808; }
h2 { font-size: 1.6em; color: #8A0808; }
h3 { font-size: 1.4em; color: #8A0808; }
h4 { font-size: 1.2em; color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
p { text-indent: 0px; }
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-style: normal; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa; }div.highlight {
border: 1px solid #cfcfcf;
border-radius: 2px;
line-height: 1.21429em;
}
div.cell {
width: 100%;
padding: 5px 5px 5px 0;
margin: 0;
outline: none;
}
div.input {
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.inner_cell {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
box-flex: 1;
flex: 1;
}
div.input_area {
border: 1px solid #cfcfcf;
border-radius: 4px;
background: #f7f7f7;
line-height: 1.21429em;
}
div.input_area > div.highlight {
margin: .4em;
border: none;
padding: 0;
background-color: transparent;
}
div.output_wrapper {
position: relative;
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
.output {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
div.output_area {
padding: 0;
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.output_subarea {
padding: .4em .4em 0 .4em;
box-flex: 1;
flex: 1;
}
div.output_text {
text-align: left;
color: #000;
line-height: 1.21429em;
}
.alert-text-small { font-size: 80%; }
.alert-text-large { font-size: 130%; }
.alert-text-normal { font-size: 90%; }
.alert {
padding:8px 35px 8px 14px; margin-bottom:18px;
text-shadow:0 1px 0 rgba(255,255,255,0.5);
border:1px solid #bababa;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
color: #555;
background-color: #f8f8f8;
background-position: 10px 5px;
background-repeat: no-repeat;
background-size: 38px;
padding-left: 55px;
width: 75%;
}
.alert-block {padding-top:14px; padding-bottom:14px}
.alert-block > p, .alert-block > ul {margin-bottom:1em}
.alert li {margin-top: 1em}
.alert-block p+p {margin-top:5px}
.alert-notice { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_notice.png); }
.alert-summary { background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_summary.png); }
.alert-warning { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_warning.png); }
.alert-question {background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_question.png); }
div { text-align: justify; text-justify: inter-word; }
.tab {
padding-left: 1.5em;
}
div.toc p,a {
line-height: 1.3;
margin-top: 1.1;
margin-bottom: 1.1;
}
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Plan for week 44', 2, None, 'plan-for-week-44'),
('Material for Lecture Thursday November 2',
2,
None,
'material-for-lecture-thursday-november-2'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
'convolutional-neural-networks-recognizing-images'),
('What is the Difference', 2, None, 'what-is-the-difference'),
('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'),
('Key Idea', 2, None, 'key-idea'),
('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'),
('Convolution Examples: Polynomial multiplication',
2,
None,
'convolution-examples-polynomial-multiplication'),
('Efficient Polynomial Multiplication',
2,
None,
'efficient-polynomial-multiplication'),
('A more efficient way of coding the above Convolution',
2,
None,
'a-more-efficient-way-of-coding-the-above-convolution'),
('Convolution Examples: Principle of Superposition and Periodic '
'Forces (Fourier Transforms)',
2,
None,
'convolution-examples-principle-of-superposition-and-periodic-forces-fourier-transforms'),
('Principle of Superposition',
2,
None,
'principle-of-superposition'),
('Simple Code Example', 2, None, 'simple-code-example'),
('Wrapping up Fourier transforms',
2,
None,
'wrapping-up-fourier-transforms'),
('Finding the Coefficients', 2, None, 'finding-the-coefficients'),
('Final words on Fourier Transforms',
2,
None,
'final-words-on-fourier-transforms'),
('Two-dimensional Objects', 2, None, 'two-dimensional-objects'),
('Cross-Correlation', 2, None, 'cross-correlation'),
('More on Dimensionalities', 2, None, 'more-on-dimensionalities'),
('Further Dimensionality Remarks',
2,
None,
'further-dimensionality-remarks'),
('CNNs in more detail, Lecture from IN5400',
2,
None,
'cnns-in-more-detail-lecture-from-in5400'),
('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')]}
end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "AMS" },
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
}
});
</script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- ------------------- main content ---------------------- -->
<center>
<h1>Week 44, Convolutional Neural Networks (CNN)</h1>
</center> <!-- document title -->
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<!-- institution(s) -->
<center>
[1] <b>Department of Physics, University of Oslo</b>
</center>
<center>
[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b>
</center>
<br>
<center>
<h4>October 30-November 3</h4>
</center> <!-- date -->
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plan-for-week-44">Plan for week 44 </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Material for the active learning sessions on Tuesday and Wednesday</b>
<p>
<ul>
<li> Exercise on writing your own neural network code, application to the OR and XOR gates, see notes from last week</li>
<li> The exercise this week is a continuation from last week</li>
<li> Discussion of project 2</li>
<li> <a href="https://youtu.be/Ia6wwDLxqtM" target="_blank">Video of lab session from last week</a></li>
</ul>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b>Material for the lecture on Thursday November 2, 2023</b>
<p>
<ul>
<li> Convolutional Neural Networks</li>
<li> Readings and Videos:</li>
<ul>
<li> These lecture notes</li>
<li> For a more in depth discussion on neural networks we recommend Goodfellow et al chapter 9. See also chapter 11 and 12 on practicalities and applications</li>
<ul>
<li> Reading suggestions for implementation of CNNs: <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf" target="_blank">Aurelien Geron's chapter 13</a>.</li>
</ul>
<li> <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi" target="_blank">Video on Deep Learning</a></li>
<li> <a href="https://www.youtube.com/watch?v=iaSUYvmCekI&ab_channel=AlexanderAmini" target="_blank">Video on Convolutional Neural Networks from MIT</a></li>
<li> <a href="https://www.youtube.com/watch?v=bNb2fEVKeEo&list=PLC1qU-LWwrF64f4QKQT-Vg5Wr4qEE1Zxk&index=6&ab_channel=StanfordUniversitySchoolofEngineering" target="_blank">Video on CNNs from Stanford</a></li>
</ul>
</ul>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b>And Lecture material on CNNs</b>
<p>
<ul>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/v19/material/week5/in5400_2019_week5_convolutional_nerual_networks.pdf" target="_blank">Lectures from IN5400 spring 2019</a></li>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/v21/lecture-slides/in5400_2021_w5_lecture_convolutions.pdf" target="_blank">Lectures from IN5400 spring 2021</a></li>
<li> <a href="http://neuralnetworksanddeeplearning.com/chap6.html" target="_blank">See also Michael Nielsen's Lectures</a></li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="material-for-lecture-thursday-november-2">Material for Lecture Thursday November 2 </h2>
<!-- !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>
<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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="what-is-the-difference">What is the Difference </h2>
<p><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>
<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>
<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:
</p>
<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>
<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>
<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>
<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" width="500" align="bottom"></p>
</center>
<!-- !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>
<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>
<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>
<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" width="500" align="bottom"></p>
</center>
<!-- !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>
<p>A simple CNN for image classification could have the architecture:</p>
<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>
<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:</p>
<ul>
<li> A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)</li>
<li> There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)</li>
<li> Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function</li>
<li> Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don&#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>
<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>.
</p>
<p>The textbook by Goodfellow et al, see chapter 9 contains an in depth discussion as well.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="key-idea">Key Idea </h2>
<p>A dense neural network is representd by an affine operation (like matrix-matrix multiplication) where all parameters are included.</p>
<p>The key idea in CNNs for say imaging is that in images neighbor pixels tend to be related! So we connect
only neighboring neurons in the input instead of connecting all with the first hidden layer.
</p>
<p>We say we perform a filtering (convolution is the mathematical operation). </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="mathematics-of-cnns">Mathematics of CNNs </h2>
<p>The mathematics of CNNs is based on the mathematical operation of
<b>convolution</b>. In mathematics (in particular in functional analysis),
convolution is represented by mathematical operation (integration,
summation etc) on two function in order to produce a third function
that expresses how the shape of one gets modified by the other.
Convolution has a plethora of applications in a variety of disciplines, spanning from statistics to signal processing, computer vision, solutions of differential equations,linear algebra, engineering, and yes, machine learning.
</p>
<p>Mathematically, convolution is defined as follows (one-dimensional example):
Let us define a continuous function \( y(t) \) given by
</p>
$$
y(t) = \int x(a) w(t-a) da,
$$
<p>where \( x(a) \) represents a so-called input and \( w(t-a) \) is normally called the weight function or kernel.</p>
<p>The above integral is written in a more compact form as</p>
$$
y(t) = \left(x * w\right)(t).
$$
<p>The discretized version reads</p>
$$
y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a).
$$
<p>Computing the inverse of the above convolution operations is known as deconvolution.</p>
<p>How can we use this? And what does it mean? Let us study some familiar examples first.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="convolution-examples-polynomial-multiplication">Convolution Examples: Polynomial multiplication </h2>
<p>We have already met such an example in project 1 when we tried to set
up the design matrix for a two-dimensional function. This was an
example of polynomial multiplication. Let us recast such a problem in terms of the convolution operation.
Let us look a the following polynomials to second and third order, respectively:
</p>
$$
p(t) = \alpha_0+\alpha_1 t+\alpha_2 t^2,
$$
<p>and</p>
$$
s(t) = \beta_0+\beta_1 t+\beta_2 t^2+\beta_3 t^3.
$$
<p>The polynomial multiplication gives us a new polynomial of degree \( 5 \)</p>
$$
z(t) = \delta_0+\delta_1 t+\delta_2 t^2+\delta_3 t^3+\delta_4 t^4+\delta_5 t^5.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="efficient-polynomial-multiplication">Efficient Polynomial Multiplication </h2>
<p>Computing polynomial products can be implemented efficiently if we rewrite the more brute force multiplications using convolution.
We note first that the new coefficients are given as
</p>
$$
\begin{split}
\delta_0=&\alpha_0\beta_0\\
\delta_1=&\alpha_1\beta_0+\alpha_1\beta_0\\
\delta_2=&\alpha_0\beta_2+\alpha_1\beta_1+\alpha_2\beta_0\\
\delta_3=&\alpha_1\beta_2+\alpha_2\beta_1+\alpha_0\beta_3\\
\delta_4=&\alpha_2\beta_2+\alpha_1\beta_3\\
\delta_5=&\alpha_2\beta_3.\\
\end{split}
$$
<p>We note that \( \alpha_i=0 \) except for \( i\in \left\{0,1,2\right\} \) and \( \beta_i=0 \) except for \( i\in\left\{0,1,2,3\right\} \).</p>
<p>We can then rewrite the coefficients \( \delta_j \) using a discrete convolution as</p>
$$
\delta_j = \sum_{i=-\infty}^{i=\infty}\alpha_i\beta_{j-i}=(\alpha * \beta)_j,
$$
<p>or as a double sum with restriction \( l=i+j \)</p>
$$
\delta_l = \sum_{ij}\alpha_i\beta_{j}.
$$
<p>Do you see a potential drawback with these equations?</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-more-efficient-way-of-coding-the-above-convolution">A more efficient way of coding the above Convolution </h2>
<p>Since we only have a finite number of \( \alpha \) and \( \beta \) values
which are non-zero, we can rewrite the above convolution expressions
as a matrix-vector multiplication
</p>
$$
\boldsymbol{\delta}=\begin{bmatrix}\alpha_0 & 0 & 0 & 0 \\
\alpha_1 & \alpha_0 & 0 & 0 \\
\alpha_2 & \alpha_1 & \alpha_0 & 0 \\
0 & \alpha_2 & \alpha_1 & \alpha_0 \\
0 & 0 & \alpha_2 & \alpha_1 \\
0 & 0 & 0 & \alpha_2
\end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}.
$$
<p>The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding \( \beta \) and a vector holding \( \alpha \).
In this case we have
</p>
$$
\boldsymbol{\delta}=\begin{bmatrix}\beta_0 & 0 & 0 \\
\beta_1 & \beta_0 & 0 \\
\beta_2 & \beta_1 & \beta_0 \\
\beta_3 & \beta_2 & \beta_1 \\
0 & \beta_3 & \beta_2 \\
0 & 0 & \beta_3
\end{bmatrix}\begin{bmatrix} \alpha_0 \\ \alpha_1 \\ \alpha_2\end{bmatrix}.
$$
<p>Note that the use of these matrices is for mathematical purposes only and not implementation purposes.
When implementing the above equation we do not encode (and allocate memory) the matrices explicitely.
We rather code the convolutions in the minimal memory footprint that they require.
</p>
<p>Does the number of floating point operations change here when we use the commutative property?</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="convolution-examples-principle-of-superposition-and-periodic-forces-fourier-transforms">Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms) </h2>
<p>For problems with so-called harmonic oscillations, given by for example the following differential equation</p>
$$
m\frac{d^2x}{dt^2}+\eta\frac{dx}{dt}+x(t)=F(t),
$$
<p>where \( F(t) \) is an applied external force acting on the system (often called a driving force), one can use the theory of Fourier transformations to find the solutions of this type of equations.</p>
<p>If one has several driving forces, \( F(t)=\sum_n F_n(t) \), one can find
the particular solution to each \( F_n \), \( x_{pn}(t) \), and the particular
solution for the entire driving force is then given by a series like
</p>
$$
\begin{equation}
x_p(t)=\sum_nx_{pn}(t).
\label{_auto1}
\end{equation}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="principle-of-superposition">Principle of Superposition </h2>
<p>This is known as the principle of superposition. It only applies when
the homogenous equation is linear. If there were an anharmonic term
such as \( x^3 \) in the homogenous equation, then when one summed various
solutions, \( x=(\sum_n x_n)^2 \), one would get cross
terms. Superposition is especially useful when \( F(t) \) can be written
as a sum of sinusoidal terms, because the solutions for each
sinusoidal (sine or cosine) term is analytic.
</p>
<p>Driving forces are often periodic, even when they are not
sinusoidal. Periodicity implies that for some time \( \tau \)
</p>
$$
\begin{eqnarray}
F(t+\tau)=F(t).
\end{eqnarray}
$$
<p>One example of a non-sinusoidal periodic force is a square wave. Many
components in electric circuits are non-linear, e.g. diodes, which
makes many wave forms non-sinusoidal even when the circuits are being
driven by purely sinusoidal sources.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="simple-code-example">Simple Code Example </h2>
<p>The code here shows a typical example of such a square wave generated using the functionality included in the <b>scipy</b> Python package. We have used a period of \( \tau=0.2 \).</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">math</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">scipy</span> <span style="color: #008000; font-weight: bold">import</span> signal
<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"># number of points </span>
n <span style="color: #666666">=</span> <span style="color: #666666">500</span>
<span style="color: #408080; font-style: italic"># start and final times </span>
t0 <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
tn <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
<span style="color: #408080; font-style: italic"># Period </span>
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(t0, tn, n, endpoint<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
SqrSignal <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)
SqrSignal <span style="color: #666666">=</span> <span style="color: #666666">1.0+</span>signal<span style="color: #666666">.</span>square(<span style="color: #666666">2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*5*</span>t)
plt<span style="color: #666666">.</span>plot(t, SqrSignal)
plt<span style="color: #666666">.</span>ylim(<span style="color: #666666">-0.5</span>, <span style="color: #666666">2.5</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>For the sinusoidal example the
period is \( \tau=2\pi/\omega \). However, higher harmonics can also
satisfy the periodicity requirement. In general, any force that
satisfies the periodicity requirement can be expressed as a sum over
harmonics,
</p>
$$
\begin{equation}
F(t)=\frac{f_0}{2}+\sum_{n>0} f_n\cos(2n\pi t/\tau)+g_n\sin(2n\pi t/\tau).
\label{_auto2}
\end{equation}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="wrapping-up-fourier-transforms">Wrapping up Fourier transforms </h2>
<p>We can write down the answer for
\( x_{pn}(t) \), by substituting \( f_n/m \) or \( g_n/m \) for \( F_0/m \). By
writing each factor \( 2n\pi t/\tau \) as \( n\omega t \), with \( \omega\equiv
2\pi/\tau \),
</p>
$$
\begin{equation}
\label{eq:fourierdef1}
F(t)=\frac{f_0}{2}+\sum_{n>0}f_n\cos(n\omega t)+g_n\sin(n\omega t).
\end{equation}
$$
<p>The solutions for \( x(t) \) then come from replacing \( \omega \) with
\( n\omega \) for each term in the particular solution,
</p>
$$
\begin{eqnarray}
x_p(t)&=&\frac{f_0}{2k}+\sum_{n>0} \alpha_n\cos(n\omega t-\delta_n)+\beta_n\sin(n\omega t-\delta_n),\\
\nonumber
\alpha_n&=&\frac{f_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\
\nonumber
\beta_n&=&\frac{g_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\
\nonumber
\delta_n&=&\tan^{-1}\left(\frac{2\beta n\omega}{\omega_0^2-n^2\omega^2}\right).
\end{eqnarray}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="finding-the-coefficients">Finding the Coefficients </h2>
<p>Because the forces have been applied for a long time, any non-zero
damping eliminates the homogenous parts of the solution, so one need
only consider the particular solution for each \( n \).
</p>
<p>The problem is considered solved if one can find expressions for the
coefficients \( f_n \) and \( g_n \), even though the solutions are expressed
as an infinite sum. The coefficients can be extracted from the
function \( F(t) \) by
</p>
$$
\begin{eqnarray}
\label{eq:fourierdef2}
f_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\cos(2n\pi t/\tau),\\
\nonumber
g_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\sin(2n\pi t/\tau).
\end{eqnarray}
$$
<p>To check the consistency of these expressions and to verify
Eq. \eqref{eq:fourierdef2}, one can insert the expansion of \( F(t) \) in
Eq. \eqref{eq:fourierdef1} into the expression for the coefficients in
Eq. \eqref{eq:fourierdef2} and see whether
</p>
$$
\begin{eqnarray}
f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~\left\{
\frac{f_0}{2}+\sum_{m>0}f_m\cos(m\omega t)+g_m\sin(m\omega t)
\right\}\cos(n\omega t).
\end{eqnarray}
$$
<p>Immediately, one can throw away all the terms with \( g_m \) because they
convolute an even and an odd function. The term with \( f_0/2 \)
disappears because \( \cos(n\omega t) \) is equally positive and negative
over the interval and will integrate to zero. For all the terms
\( f_m\cos(m\omega t) \) appearing in the sum, one can use angle addition
formulas to see that \( \cos(m\omega t)\cos(n\omega
t)=(1/2)(\cos[(m+n)\omega t]+\cos[(m-n)\omega t] \). This will integrate
to zero unless \( m=n \). In that case the \( m=n \) term gives
</p>
$$
\begin{equation}
\int_{-\tau/2}^{\tau/2}dt~\cos^2(m\omega t)=\frac{\tau}{2},
\label{_auto3}
\end{equation}
$$
<p>and</p>
$$
\begin{eqnarray}
f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~f_n/2\\
\nonumber
&=&f_n~\checkmark.
\end{eqnarray}
$$
<p>The same method can be used to check for the consistency of \( g_n \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-words-on-fourier-transforms">Final words on Fourier Transforms </h2>
<p>The code here uses the Fourier series applied to a
square wave signal. The code here
visualizes the various approximations given by Fourier series compared
with a square wave with period \( T=0.2 \) (dimensionless time), width \( 0.1 \) and max value of the force \( F=2 \). We
see that when we increase the number of components in the Fourier
series, the Fourier series approximation gets closer and closer to the
square wave signal.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">math</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">scipy</span> <span style="color: #008000; font-weight: bold">import</span> signal
<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"># number of points </span>
n <span style="color: #666666">=</span> <span style="color: #666666">500</span>
<span style="color: #408080; font-style: italic"># start and final times </span>
t0 <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
tn <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
<span style="color: #408080; font-style: italic"># Period </span>
T <span style="color: #666666">=0.2</span>
<span style="color: #408080; font-style: italic"># Max value of square signal </span>
Fmax<span style="color: #666666">=</span> <span style="color: #666666">2.0</span>
<span style="color: #408080; font-style: italic"># Width of signal </span>
Width <span style="color: #666666">=</span> <span style="color: #666666">0.1</span>
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(t0, tn, n, endpoint<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
SqrSignal <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)
FourierSeriesSignal <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)
SqrSignal <span style="color: #666666">=</span> <span style="color: #666666">1.0+</span>signal<span style="color: #666666">.</span>square(<span style="color: #666666">2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*5*</span>t<span style="color: #666666">+</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>Width<span style="color: #666666">/</span>T)
a0 <span style="color: #666666">=</span> Fmax<span style="color: #666666">*</span>Width<span style="color: #666666">/</span>T
FourierSeriesSignal <span style="color: #666666">=</span> a0
Factor <span style="color: #666666">=</span> <span style="color: #666666">2.0*</span>Fmax<span style="color: #666666">/</span>np<span style="color: #666666">.</span>pi
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,<span style="color: #666666">500</span>):
FourierSeriesSignal <span style="color: #666666">+=</span> Factor<span style="color: #666666">/</span>(i)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>i<span style="color: #666666">*</span>Width<span style="color: #666666">/</span>T)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>cos(i<span style="color: #666666">*</span>t<span style="color: #666666">*2*</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">/</span>T)
plt<span style="color: #666666">.</span>plot(t, SqrSignal)
plt<span style="color: #666666">.</span>plot(t, FourierSeriesSignal)
plt<span style="color: #666666">.</span>ylim(<span style="color: #666666">-0.5</span>, <span style="color: #666666">2.5</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="two-dimensional-objects">Two-dimensional Objects </h2>
<p>We often use convolutions over more than one dimension at a time. If
we have a two-dimensional image \( I \) as input, we can have a <b>filter</b>
defined by a two-dimensional <b>kernel</b> \( K \). This leads to an output \( S \)
</p>
$$
S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(m,n)K(i-m,j-n).
$$
<p>Convolution is a commutatitave process, which means we can rewrite this equation as</p>
$$
S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i-m,j-n)K(m,n).
$$
<p>Normally the latter is more straightforward to implement in a machine elarning library since there is less variation in the range of values of \( m \) and \( n \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cross-correlation">Cross-Correlation </h2>
<p>Many deep learning libraries implement cross-correlation instead of convolution</p>
$$
S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i+m,j-+)K(m,n).
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-on-dimensionalities">More on Dimensionalities </h2>
<p>In feilds like signal processing (and imaging as well), one designs
so-called filters. These filters are defined by the convolutions and
are often hand-crafted. One may specify filters for smoothing, edge
detection, frequency reshaping, and similar operations. However with
neural networks the idea is to automatically learn the filters and use
many of them in conjunction with non-linear operations (activation
functions).
</p>
<p>As an example consider a neural network operating on sound sequence
data. Assume that we an input vector \( \boldsymbol{x} \) of length \( d=10^6 \). We
construct then a neural network with onle hidden layer only with
\( 10^4 \) nodes. This means that we will have a weight matrix with
\( 10^4\times 10^6=10^{10} \) weights to be determined, together with \( 10^4 \) biases.
</p>
<p>Assume furthermore that we have an output layer which is meant to train whether the sound sequence represents a human voice (true) or something else (false).
It means that we have only one output node. But since this output node connects to \( 10^4 \) nodes in the hidden layer, there are in total \( 10^4 \) weights to be determined for the output layer, plus one bias. In total we have
</p>
$$
\mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \approx 10^{10},
$$
<p>that is ten billion parameters to determine. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="further-dimensionality-remarks">Further Dimensionality Remarks </h2>
<p>In today&#8217;s architecture one can train such neural networks, however
this is a huge number of parameters for the task at hand. In general,
it is a very wasteful and inefficient use of dense matrices as
parameters. Just as importantly, such trained network parameters are
very specific for the type of input data on which they were trained
and the network is not likely to generalize easily to variations in
the input.
</p>
<p>The main principles that justify convolutions is locality of
information and repetion of patterns within the signal. Sound samples
of the input in adjacent spots are much more likely to affect each
other than those that are very far away. Similarly, sounds are
repeated in multiple times in the signal. While slightly simplistic,
reasoning about such a sound example demonstrates this. The same
principles then apply to images and other similar data.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cnns-in-more-detail-lecture-from-in5400">CNNs in more detail, Lecture from IN5400 </h2>
<ul>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/v19/material/week5/in5400_2019_week5_convolutional_nerual_networks.pdf" target="_blank">Lectures from IN5400 spring 2019</a></li>
</ul>
<!-- !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>
<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:
</p>
$$
(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
$$
<!-- !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>
<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>
<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>
<p>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>
<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>
<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>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># import necessary packages</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> datasets
<span style="color: #408080; font-style: italic"># ensure the same random numbers appear every time</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">0</span>)
<span style="color: #408080; font-style: italic"># display images in notebook</span>
<span style="color: #666666">%</span>matplotlib inline
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="importing-keras-and-tensorflow">Importing Keras and Tensorflow </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split -->
<h2 id="running-with-keras">Running with Keras </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-part">Final part </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-visualization">Final visualization </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># visual representation of grid search</span>
<span style="color: #408080; font-style: italic"># uses seaborn heatmap, 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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-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="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">tensorflow</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">tf</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">tensorflow.keras</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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="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="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="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>
<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="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>You can 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="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>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>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="finally-evaluate-the-model">Finally, evaluate the model </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">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>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>