upgrading neural nets with cans
This commit is contained in:
@@ -6,9 +6,9 @@ Automatically generated HTML file from DocOnce source
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="DocOnce: https://github.com/hplgit/doconce/" />
|
||||
<meta name="description" content="Data Analysis and Machine Learning: Neural networks, from the simple perceptron to deep learning">
|
||||
<meta name="description" content="Data Analysis and Machine Learning: Neural networks, from the simple perceptron to deep learning and convolutional networks">
|
||||
|
||||
<title>Data Analysis and Machine Learning: Neural networks, from the simple perceptron to deep learning</title>
|
||||
<title>Data Analysis and Machine Learning: Neural networks, from the simple perceptron to deep learning and convolutional networks</title>
|
||||
|
||||
|
||||
<style type="text/css">
|
||||
@@ -176,8 +176,30 @@ div { text-align: justify; text-justify: inter-word; }
|
||||
'___sec67'),
|
||||
('3D volumes of neurons', 2, None, '___sec68'),
|
||||
('Layers used to build CNNs', 2, None, '___sec69'),
|
||||
('CNNs in brief', 2, None, '___sec70'),
|
||||
('CNNs in more detail', 2, None, '___sec71')]}
|
||||
('Transforming images', 2, None, '___sec70'),
|
||||
('CNNs in brief', 2, None, '___sec71'),
|
||||
('CNNs in more detail, building convolutional neural networks in '
|
||||
'Tensorflow and Keras',
|
||||
2,
|
||||
None,
|
||||
'___sec72'),
|
||||
('Setting it up', 2, None, '___sec73'),
|
||||
('The MNIST dataset again', 2, None, '___sec74'),
|
||||
('Strong correlations', 2, None, '___sec75'),
|
||||
('Layers of a CNN', 2, None, '___sec76'),
|
||||
('Systematic reduction', 2, None, '___sec77'),
|
||||
('Prerequisites: Collect and pre-process data',
|
||||
2,
|
||||
None,
|
||||
'___sec78'),
|
||||
('Importing Keras and Tensorflow', 2, None, '___sec79'),
|
||||
('Using TensorFlow backend', 2, None, '___sec80'),
|
||||
('Train the model', 2, None, '___sec81'),
|
||||
('Visualizing the results', 2, None, '___sec82'),
|
||||
('Running with Keras', 2, None, '___sec83'),
|
||||
('Final part', 2, None, '___sec84'),
|
||||
('Final visualization', 2, None, '___sec85'),
|
||||
('Fun links', 2, None, '___sec86')]}
|
||||
end of tocinfo -->
|
||||
|
||||
<body>
|
||||
@@ -203,7 +225,7 @@ MathJax.Hub.Config({
|
||||
|
||||
|
||||
|
||||
<center><h1>Data Analysis and Machine Learning: Neural networks, from the simple perceptron to deep learning</h1></center> <!-- document title -->
|
||||
<center><h1>Data Analysis and Machine Learning: Neural networks, from the simple perceptron to deep learning and convolutional networks</h1></center> <!-- document title -->
|
||||
|
||||
<p>
|
||||
<!-- author(s): Morten Hjorth-Jensen -->
|
||||
@@ -219,7 +241,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 18, 2018</h4></center> <!-- date -->
|
||||
<center><h4>Oct 19, 2018</h4></center> <!-- date -->
|
||||
<br>
|
||||
<p>
|
||||
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
||||
@@ -1379,7 +1401,7 @@ Here we will be using the MNIST dataset, which is readily available through the
|
||||
package. You may also find it for example <a href="http://yann.lecun.com/exdb/mnist/" target="_blank">here</a>.
|
||||
The <em>MNIST</em> (Modified National Institute of Standards and Technology) database is a large database
|
||||
of handwritten digits that is commonly used for training various image processing systems.
|
||||
The MNIST dataset consists of 70 000 images of size 28x28 pixels, each labeled from 0 to 9.
|
||||
The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9.
|
||||
The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database.
|
||||
|
||||
<p>
|
||||
@@ -2981,14 +3003,17 @@ and the slides of <a href="http://cs231n.github.io/convolutional-networks/" targ
|
||||
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*32*3 = 3072 \) weights. This amount still
|
||||
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*200*3 =120,000 \) weights. Moreover, we would almost certainly want to have
|
||||
several such neurons, so the parameters would add up quickly! Clearly,
|
||||
\( 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 overfitting.
|
||||
would quickly lead to possible overfitting.
|
||||
|
||||
<p>
|
||||
<center> <!-- FIGURE -->
|
||||
@@ -3054,19 +3079,35 @@ will stack these layers to form a full CNN architecture.
|
||||
A simple CNN for image classification could have the architecture:
|
||||
|
||||
<ul>
|
||||
<li> 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.</li>
|
||||
<li> CONV 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> 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] \)).</li>
|
||||
<li> POOL layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as \( [16\times 16\times 12] \).</li>
|
||||
<li> 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.</li>
|
||||
<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>
|
||||
|
||||
In this way, CNNs transform the original image layer by layer from the original pixel values to the final class scores. Note that some layers contain parameters and other don’t. In particular, the CONV/FC 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 --><br><br><br><br><br><br><br><br><br><br>
|
||||
|
||||
<h2 id="___sec70">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’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="___sec70">CNNs in brief </h2>
|
||||
<h2 id="___sec71">CNNs in brief </h2>
|
||||
|
||||
<p>
|
||||
In summary:
|
||||
@@ -3079,12 +3120,518 @@ In summary:
|
||||
<li> Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)</li>
|
||||
</ul>
|
||||
|
||||
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
||||
|
||||
<h2 id="___sec71">CNNs in more detail </h2>
|
||||
For more material on convolutional networks, we strongly recommend
|
||||
the course
|
||||
<a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html" target="_blank">IN5400 – Machine Learning for Image Analysis</a>
|
||||
and the slides of <a href="http://cs231n.github.io/convolutional-networks/" target="_blank">CS231</a> which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). <a href="http://neuralnetworksanddeeplearning.com/chap6.html" target="_blank">Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs</a>.
|
||||
|
||||
<p>
|
||||
More material to come with examples.
|
||||
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
||||
|
||||
<h2 id="___sec72">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="___sec73">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="___sec74">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="___sec75">Strong correlations </h2>
|
||||
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="___sec76">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="___sec77">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="___sec78">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">'figure.figsize'</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; font-weight: bold">print</span>(<span style="color: #BA2121">"inputs = (n_inputs, pixel_width, pixel_height, depth) = "</span> <span style="color: #666666">+</span> <span style="color: #008000">str</span>(inputs<span style="color: #666666">.</span>shape))
|
||||
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">"labels = (n_inputs) = "</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">'off'</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">'nearest'</span>)
|
||||
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Label: </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121">"</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="___sec79">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">keras.utils</span> <span style="color: #008000; font-weight: bold">import</span> to_categorical
|
||||
<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 --><br><br><br><br><br><br><br><br><br><br>
|
||||
|
||||
<h2 id="___sec80">Using TensorFlow backend </h2>
|
||||
|
||||
<p>
|
||||
We need to define model and architecture and choose cost function and optmizer.
|
||||
<p>
|
||||
|
||||
<!-- code=text (!bc pycid) typeset with pygments style "default" -->
|
||||
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>import tensorflow as tf
|
||||
|
||||
class ConvolutionalNeuralNetworkTensorflow:
|
||||
def __init__(
|
||||
self,
|
||||
X_train,
|
||||
Y_train,
|
||||
X_test,
|
||||
Y_test,
|
||||
n_filters=10,
|
||||
n_neurons_connected=50,
|
||||
n_categories=10,
|
||||
receptive_field=3,
|
||||
stride=1,
|
||||
padding=1,
|
||||
epochs=10,
|
||||
batch_size=100,
|
||||
eta=0.1,
|
||||
lmbd=0.0,
|
||||
):
|
||||
|
||||
self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
|
||||
|
||||
self.X_train = X_train
|
||||
self.Y_train = Y_train
|
||||
self.X_test = X_test
|
||||
self.Y_test = Y_test
|
||||
|
||||
self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape
|
||||
|
||||
self.n_filters = n_filters
|
||||
self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)
|
||||
self.n_neurons_connected = n_neurons_connected
|
||||
self.n_categories = n_categories
|
||||
|
||||
self.receptive_field = receptive_field
|
||||
self.stride = stride
|
||||
self.strides = [stride, stride, stride, stride]
|
||||
self.padding = padding
|
||||
|
||||
self.epochs = epochs
|
||||
self.batch_size = batch_size
|
||||
self.iterations = self.n_inputs // self.batch_size
|
||||
self.eta = eta
|
||||
self.lmbd = lmbd
|
||||
|
||||
self.create_placeholders()
|
||||
self.create_CNN()
|
||||
self.create_loss()
|
||||
self.create_optimiser()
|
||||
self.create_accuracy()
|
||||
|
||||
def create_placeholders(self):
|
||||
with tf.name_scope('data'):
|
||||
self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')
|
||||
self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
|
||||
|
||||
def create_CNN(self):
|
||||
with tf.name_scope('CNN'):
|
||||
|
||||
# Convolutional layer
|
||||
self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)
|
||||
b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)
|
||||
z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv
|
||||
a_conv = tf.nn.relu(z_conv)
|
||||
|
||||
# 2x2 max pooling
|
||||
a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')
|
||||
|
||||
# Fully connected layer
|
||||
a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])
|
||||
self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)
|
||||
b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)
|
||||
a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)
|
||||
|
||||
# Output layer
|
||||
self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)
|
||||
b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
|
||||
self.z_out = tf.matmul(a_fc, self.W_out) + b_out
|
||||
|
||||
def create_loss(self):
|
||||
with tf.name_scope('loss'):
|
||||
softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
|
||||
|
||||
regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)
|
||||
regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)
|
||||
regularizer_loss_out = tf.nn.l2_loss(self.W_out)
|
||||
regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)
|
||||
|
||||
self.loss = softmax_loss + regularizer_loss
|
||||
|
||||
def create_accuracy(self):
|
||||
with tf.name_scope('accuracy'):
|
||||
probabilities = tf.nn.softmax(self.z_out)
|
||||
predictions = tf.argmax(probabilities, 1)
|
||||
labels = tf.argmax(self.Y, 1)
|
||||
|
||||
correct_predictions = tf.equal(predictions, labels)
|
||||
correct_predictions = tf.cast(correct_predictions, tf.float32)
|
||||
self.accuracy = tf.reduce_mean(correct_predictions)
|
||||
|
||||
def create_optimiser(self):
|
||||
with tf.name_scope('optimizer'):
|
||||
self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
|
||||
|
||||
def weight_variable(self, shape, name='', dtype=tf.float32):
|
||||
initial = tf.truncated_normal(shape, stddev=0.1)
|
||||
return tf.Variable(initial, name=name, dtype=dtype)
|
||||
|
||||
def bias_variable(self, shape, name='', dtype=tf.float32):
|
||||
initial = tf.constant(0.1, shape=shape)
|
||||
return tf.Variable(initial, name=name, dtype=dtype)
|
||||
|
||||
def fit(self):
|
||||
data_indices = np.arange(self.n_inputs)
|
||||
|
||||
with tf.Session() as sess:
|
||||
sess.run(tf.global_variables_initializer())
|
||||
for i in range(self.epochs):
|
||||
for j in range(self.iterations):
|
||||
chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
|
||||
batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
|
||||
|
||||
sess.run([CNN.loss, CNN.optimizer],
|
||||
feed_dict={CNN.X: batch_X,
|
||||
CNN.Y: batch_Y})
|
||||
accuracy = sess.run(CNN.accuracy,
|
||||
feed_dict={CNN.X: batch_X,
|
||||
CNN.Y: batch_Y})
|
||||
step = sess.run(CNN.global_step)
|
||||
|
||||
self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],
|
||||
feed_dict={CNN.X: self.X_train,
|
||||
CNN.Y: self.Y_train})
|
||||
|
||||
self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],
|
||||
feed_dict={CNN.X: self.X_test,
|
||||
CNN.Y: self.Y_test})
|
||||
</pre></div>
|
||||
<p>
|
||||
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
||||
|
||||
<h2 id="___sec81">Train the model </h2>
|
||||
|
||||
<p>
|
||||
We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters.
|
||||
<p>
|
||||
|
||||
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
||||
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>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>
|
||||
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>)
|
||||
CNN_tf <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> ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
|
||||
n_filters<span style="color: #666666">=</span>n_filters, n_neurons_connected<span style="color: #666666">=</span>n_neurons_connected,
|
||||
n_categories<span style="color: #666666">=</span>n_categories, epochs<span style="color: #666666">=</span>epochs, batch_size<span style="color: #666666">=</span>batch_size,
|
||||
eta<span style="color: #666666">=</span>eta, lmbd<span style="color: #666666">=</span>lmbd)
|
||||
CNN<span style="color: #666666">.</span>fit()
|
||||
|
||||
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">"Learning rate = "</span>, eta)
|
||||
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">"Lambda = "</span>, lmbd)
|
||||
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">"Test accuracy: </span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121">"</span> <span style="color: #666666">%</span> CNN<span style="color: #666666">.</span>test_accuracy)
|
||||
<span style="color: #008000; font-weight: bold">print</span>()
|
||||
|
||||
CNN_tf[i][j] <span style="color: #666666">=</span> CNN
|
||||
</pre></div>
|
||||
<p>
|
||||
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
||||
|
||||
<h2 id="___sec82">Visualizing the results </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_tf[i][j]
|
||||
|
||||
train_accuracy[i][j] <span style="color: #666666">=</span> CNN<span style="color: #666666">.</span>train_accuracy
|
||||
test_accuracy[i][j] <span style="color: #666666">=</span> CNN<span style="color: #666666">.</span>test_accuracy
|
||||
|
||||
|
||||
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">True</span>, ax<span style="color: #666666">=</span>ax, cmap<span style="color: #666666">=</span><span style="color: #BA2121">"viridis"</span>)
|
||||
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">"Training Accuracy"</span>)
|
||||
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"$\eta$"</span>)
|
||||
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"$\lambda$"</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">True</span>, ax<span style="color: #666666">=</span>ax, cmap<span style="color: #666666">=</span><span style="color: #BA2121">"viridis"</span>)
|
||||
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">"Test Accuracy"</span>)
|
||||
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"$\eta$"</span>)
|
||||
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"$\lambda$"</span>)
|
||||
plt<span style="color: #666666">.</span>show()
|
||||
</pre></div>
|
||||
<p>
|
||||
<!-- !split -->
|
||||
|
||||
<h2 id="___sec83">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">from</span> <span style="color: #0000FF; font-weight: bold">keras.models</span> <span style="color: #008000; font-weight: bold">import</span> Sequential
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">keras.layers.convolutional</span> <span style="color: #008000; font-weight: bold">import</span> Conv2D
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">keras.layers.convolutional</span> <span style="color: #008000; font-weight: bold">import</span> MaxPooling2D
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">keras.layers</span> <span style="color: #008000; font-weight: bold">import</span> Flatten
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">keras.layers</span> <span style="color: #008000; font-weight: bold">import</span> Dense
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">keras.regularizers</span> <span style="color: #008000; font-weight: bold">import</span> l2
|
||||
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">keras.optimizers</span> <span style="color: #008000; font-weight: bold">import</span> SGD
|
||||
|
||||
<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(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">'same'</span>,
|
||||
activation<span style="color: #666666">=</span><span style="color: #BA2121">'relu'</span>, kernel_regularizer<span style="color: #666666">=</span>l2(lmbd)))
|
||||
model<span style="color: #666666">.</span>add(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(Flatten())
|
||||
model<span style="color: #666666">.</span>add(Dense(n_neurons_connected, activation<span style="color: #666666">=</span><span style="color: #BA2121">'relu'</span>, kernel_regularizer<span style="color: #666666">=</span>l2(lmbd)))
|
||||
model<span style="color: #666666">.</span>add(Dense(n_categories, activation<span style="color: #666666">=</span><span style="color: #BA2121">'softmax'</span>, kernel_regularizer<span style="color: #666666">=</span>l2(lmbd)))
|
||||
|
||||
sgd <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">'categorical_crossentropy'</span>, optimizer<span style="color: #666666">=</span>sgd, metrics<span style="color: #666666">=</span>[<span style="color: #BA2121">'accuracy'</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="___sec84">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; font-weight: bold">print</span>(<span style="color: #BA2121">"Learning rate = "</span>, eta)
|
||||
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">"Lambda = "</span>, lmbd)
|
||||
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">"Test accuracy: </span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121">"</span> <span style="color: #666666">%</span> scores[<span style="color: #666666">1</span>])
|
||||
<span style="color: #008000; font-weight: bold">print</span>()
|
||||
</pre></div>
|
||||
<p>
|
||||
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
||||
|
||||
<h2 id="___sec85">Final visualization </h2>
|
||||
|
||||
<p>
|
||||
|
||||
<!-- code=text typeset with pygments style "default" -->
|
||||
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span># 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()
|
||||
</pre></div>
|
||||
<p>
|
||||
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
||||
|
||||
<h2 id="___sec86">Fun links </h2>
|
||||
|
||||
<ol>
|
||||
<li> <a href="https://arxiv.org/abs/1604.07316" target="_blank">Self-Driving cars using a convolutional neural network</a></li>
|
||||
<li> <a href="https://deepdreamgenerator.com/" target="_blank">Abstract art using convolutional neural networks</a></li>
|
||||
</ol>
|
||||
|
||||
|
||||
<!-- ------------------- end of main content --------------- -->
|
||||
|
||||
|
||||
Reference in New Issue
Block a user