diff --git a/doc/pub/NeuralNet/html/._NeuralNet-bs000.html b/doc/pub/NeuralNet/html/._NeuralNet-bs000.html index 2e947261f..2bdcf2c1b 100644 --- a/doc/pub/NeuralNet/html/._NeuralNet-bs000.html +++ b/doc/pub/NeuralNet/html/._NeuralNet-bs000.html @@ -279,7 +279,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Oct 3, 2019

+

Oct 4, 2019


diff --git a/doc/pub/NeuralNet/html/._NeuralNet-bs036.html b/doc/pub/NeuralNet/html/._NeuralNet-bs036.html index e0d2d92ea..d28c1f9a6 100644 --- a/doc/pub/NeuralNet/html/._NeuralNet-bs036.html +++ b/doc/pub/NeuralNet/html/._NeuralNet-bs036.html @@ -272,7 +272,7 @@ The scikit-learn dataset we will use consists of a selection of 1797 images of s

To feed data into a feed-forward neural network we need to represent -the inputs as a feature matrix \( X = (n_{inputs}, n_{features}) \). Each +the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each row represents an input, in this case a handwritten digit, and each column represents a feature, in this case a pixel. The correct answers, also known as labels or targets are @@ -282,7 +282,7 @@ represented as a 1D array of integers

As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: $$ X = \begin{bmatrix} 1.85 & 81\\ @@ -300,7 +300,7 @@ $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

Since each input image is a 2D matrix, we need to flatten the image (i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -feature matrix. This means we lose all spatial information in the +design/feature matrix. This means we lose all spatial information in the image, such as locality and translational invariance. More complicated architectures such as Convolutional Neural Networks can take advantage of such information, and are most commonly applied when analyzing diff --git a/doc/pub/NeuralNet/html/._NeuralNet-bs045.html b/doc/pub/NeuralNet/html/._NeuralNet-bs045.html index e68408501..d1a55cd86 100644 --- a/doc/pub/NeuralNet/html/._NeuralNet-bs045.html +++ b/doc/pub/NeuralNet/html/._NeuralNet-bs045.html @@ -273,9 +273,9 @@ reduces overfitting.

We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes: -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$

i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter. diff --git a/doc/pub/NeuralNet/html/NeuralNet-bs.html b/doc/pub/NeuralNet/html/NeuralNet-bs.html index 2e947261f..2bdcf2c1b 100644 --- a/doc/pub/NeuralNet/html/NeuralNet-bs.html +++ b/doc/pub/NeuralNet/html/NeuralNet-bs.html @@ -279,7 +279,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Oct 3, 2019

+

Oct 4, 2019


diff --git a/doc/pub/NeuralNet/html/NeuralNet-reveal.html b/doc/pub/NeuralNet/html/NeuralNet-reveal.html index ca21dfb52..056d7783c 100644 --- a/doc/pub/NeuralNet/html/NeuralNet-reveal.html +++ b/doc/pub/NeuralNet/html/NeuralNet-reveal.html @@ -148,7 +148,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

 
-

Oct 3, 2019

+

Oct 4, 2019


@@ -1445,7 +1445,7 @@ The scikit-learn dataset we will use consists of a selection of 1797 images of s

To feed data into a feed-forward neural network we need to represent -the inputs as a feature matrix \( X = (n_{inputs}, n_{features}) \). Each +the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each row represents an input, in this case a handwritten digit, and each column represents a feature, in this case a pixel. The correct answers, also known as labels or targets are @@ -1455,7 +1455,7 @@ represented as a 1D array of integers

As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example:

 
$$ X = \begin{bmatrix} @@ -1477,7 +1477,7 @@ $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

Since each input image is a 2D matrix, we need to flatten the image (i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -feature matrix. This means we lose all spatial information in the +design/feature matrix. This means we lose all spatial information in the image, such as locality and translational invariance. More complicated architectures such as Convolutional Neural Networks can take advantage of such information, and are most commonly applied when analyzing @@ -1944,9 +1944,9 @@ reduces overfitting. We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

 
-$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$

 

diff --git a/doc/pub/NeuralNet/html/NeuralNet-solarized.html b/doc/pub/NeuralNet/html/NeuralNet-solarized.html index 4a0d1d535..47d948a49 100644 --- a/doc/pub/NeuralNet/html/NeuralNet-solarized.html +++ b/doc/pub/NeuralNet/html/NeuralNet-solarized.html @@ -203,7 +203,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Oct 3, 2019

+

Oct 4, 2019












@@ -1368,7 +1368,7 @@ The scikit-learn dataset we will use consists of a selection of 1797 images of s

To feed data into a feed-forward neural network we need to represent -the inputs as a feature matrix \( X = (n_{inputs}, n_{features}) \). Each +the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each row represents an input, in this case a handwritten digit, and each column represents a feature, in this case a pixel. The correct answers, also known as labels or targets are @@ -1378,7 +1378,7 @@ represented as a 1D array of integers

As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: $$ X = \begin{bmatrix} 1.85 & 81\\ @@ -1396,7 +1396,7 @@ $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

Since each input image is a 2D matrix, we need to flatten the image (i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -feature matrix. This means we lose all spatial information in the +design/feature matrix. This means we lose all spatial information in the image, such as locality and translational invariance. More complicated architectures such as Convolutional Neural Networks can take advantage of such information, and are most commonly applied when analyzing @@ -1813,9 +1813,9 @@ reduces overfitting.

We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes: -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$

i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter. diff --git a/doc/pub/NeuralNet/html/NeuralNet.html b/doc/pub/NeuralNet/html/NeuralNet.html index 3d43606a9..477b39060 100644 --- a/doc/pub/NeuralNet/html/NeuralNet.html +++ b/doc/pub/NeuralNet/html/NeuralNet.html @@ -208,7 +208,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Oct 3, 2019

+

Oct 4, 2019












@@ -1373,7 +1373,7 @@ The scikit-learn dataset we will use consists of a selection of 1797 images of s

To feed data into a feed-forward neural network we need to represent -the inputs as a feature matrix \( X = (n_{inputs}, n_{features}) \). Each +the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each row represents an input, in this case a handwritten digit, and each column represents a feature, in this case a pixel. The correct answers, also known as labels or targets are @@ -1383,7 +1383,7 @@ represented as a 1D array of integers

As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: $$ X = \begin{bmatrix} 1.85 & 81\\ @@ -1401,7 +1401,7 @@ $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

Since each input image is a 2D matrix, we need to flatten the image (i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -feature matrix. This means we lose all spatial information in the +design/feature matrix. This means we lose all spatial information in the image, such as locality and translational invariance. More complicated architectures such as Convolutional Neural Networks can take advantage of such information, and are most commonly applied when analyzing @@ -1818,9 +1818,9 @@ reduces overfitting.

We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes: -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$

i.e. we sum up all the weights squared. The factor \( \lambda \) is known as a regularization parameter. diff --git a/doc/pub/NeuralNet/ipynb/NeuralNet.ipynb b/doc/pub/NeuralNet/ipynb/NeuralNet.ipynb index 55883a9a0..07597f0f5 100644 --- a/doc/pub/NeuralNet/ipynb/NeuralNet.ipynb +++ b/doc/pub/NeuralNet/ipynb/NeuralNet.ipynb @@ -10,7 +10,7 @@ " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Oct 3, 2019**\n", + "Date: **Oct 4, 2019**\n", "\n", "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", @@ -1656,7 +1656,7 @@ "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. \n", "\n", "To feed data into a feed-forward neural network we need to represent\n", - "the inputs as a feature matrix $X = (n_{inputs}, n_{features})$. Each\n", + "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n", "row represents an *input*, in this case a handwritten digit, and\n", "each column represents a *feature*, in this case a pixel. The\n", "correct answers, also known as *labels* or *targets* are\n", @@ -1665,7 +1665,7 @@ "\n", "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", "measurements of height (in m) \n", - "and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: \n", + "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n", "\n", "$$ X = \\begin{bmatrix}\n", "1.85 & 81\\\\\n", @@ -1681,7 +1681,7 @@ "\n", "Since each input image is a 2D matrix, we need to flatten the image\n", "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", - "feature matrix. This means we lose all spatial information in the\n", + "design/feature matrix. This means we lose all spatial information in the\n", "image, such as locality and translational invariance. More complicated\n", "architectures such as Convolutional Neural Networks can take advantage\n", "of such information, and are most commonly applied when analyzing\n", @@ -2077,9 +2077,9 @@ "\n", "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", "\n", - "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\hat{w} \\rvert \\rvert_2^2 \n", - "= \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", + "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", + "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\hat{w} \\rvert \\rvert_2^2 \n", + "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", "\n", "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", "\n", diff --git a/doc/pub/NeuralNet/ipynb/ipynb-NeuralNet-src.tar.gz b/doc/pub/NeuralNet/ipynb/ipynb-NeuralNet-src.tar.gz index 7ffbabbae..93c5e3fbc 100644 Binary files a/doc/pub/NeuralNet/ipynb/ipynb-NeuralNet-src.tar.gz and b/doc/pub/NeuralNet/ipynb/ipynb-NeuralNet-src.tar.gz differ diff --git a/doc/pub/NeuralNet/pdf/NeuralNet-minted.pdf b/doc/pub/NeuralNet/pdf/NeuralNet-minted.pdf index 6660c1526..aee99ab97 100644 Binary files a/doc/pub/NeuralNet/pdf/NeuralNet-minted.pdf and b/doc/pub/NeuralNet/pdf/NeuralNet-minted.pdf differ diff --git a/doc/pub/cnn/html/._cnn-bs000.html b/doc/pub/cnn/html/._cnn-bs000.html new file mode 100644 index 000000000..e7c61ae6e --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs000.html @@ -0,0 +1,219 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + +

+ + +
+ +

 

 

 

+ + + + + + +
+

Convolutional Neural Networks

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Oct 4, 2019

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs001.html b/doc/pub/cnn/html/._cnn-bs001.html new file mode 100644 index 000000000..f7162b471 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs001.html @@ -0,0 +1,220 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Convolutional Neural Networks (recognizing images)

+ +

+Convolutional Neural Networks (CNN) are very similar to ordinary Neural Networks. + +

+They are made up of neurons that have learnable weights and +biases. Each neuron receives some inputs, performs a dot product and +optionally follows it with a non-linearity. The whole network still +expresses a single differentiable score function: from the raw image +pixels on one end to class scores at the other. And they still have a +loss function (for example Softmax) on the last (fully-connected) layer +and all the tips/tricks we developed for learning regular Neural +Networks still apply (back propagation, gradient descent etc etc). + +

+What is the difference? CNN architectures make the explicit assumption that +the inputs are images, which allows us to encode certain properties +into the architecture. These then make the forward function more +efficient to implement and vastly reduce the amount of parameters in +the network. + +

+Here we provide only a superficial overview, for the more interested, we recommend highly the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs002.html b/doc/pub/cnn/html/._cnn-bs002.html new file mode 100644 index 000000000..da72f1335 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs002.html @@ -0,0 +1,219 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Regular NNs don’t scale well to full images

+ +

+As an example, consider +an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a +single fully-connected neuron in a first hidden layer of a regular +Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still +seems manageable, but clearly this fully-connected structure does not +scale to larger images. For example, an image of more respectable +size, say \( 200\times 200\times 3 \), would lead to neurons that have +\( 200\times 200\times 3 = 120,000 \) weights. + +

+We could have +several such neurons, and the parameters would add up quickly! Clearly, +this full connectivity is wasteful and the huge number of parameters +would quickly lead to possible overfitting. + +

+

+
+

Figure 1: A regular 3-layer Neural Network.

+

+
+ +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs003.html b/doc/pub/cnn/html/._cnn-bs003.html new file mode 100644 index 000000000..548d04054 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs003.html @@ -0,0 +1,232 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

3D volumes of neurons

+ +

+Convolutional Neural Networks take advantage of the fact that the +input consists of images and they constrain the architecture in a more +sensible way. + +

+In particular, unlike a regular Neural Network, the +layers of a CNN have neurons arranged in 3 dimensions: width, +height, depth. (Note that the word depth here refers to the third +dimension of an activation volume, not to the depth of a full Neural +Network, which can refer to the total number of layers in a network.) + +

+To understand it better, the above example of an image +with an input volume of +activations has dimensions \( 32\times 32\times 3 \) (width, height, +depth respectively). + +

+The neurons in a layer will +only be connected to a small region of the layer before it, instead of +all of the neurons in a fully-connected manner. Moreover, the final +output layer could for this specific image have dimensions \( 1\times 1 \times 10 \), +because by the +end of the CNN architecture we will reduce the full image into a +single vector of class scores, arranged along the depth +dimension. + +

+

+
+

Figure 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).

+

+
+ +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs004.html b/doc/pub/cnn/html/._cnn-bs004.html new file mode 100644 index 000000000..b062ec63f --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs004.html @@ -0,0 +1,216 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Layers used to build CNNs

+ +

+A simple CNN is a sequence of layers, and every layer of a CNN +transforms one volume of activations to another through a +differentiable function. We use three main types of layers to build +CNN architectures: Convolutional Layer, Pooling Layer, and +Fully-Connected Layer (exactly as seen in regular Neural Networks). We +will stack these layers to form a full CNN architecture. + +

+A simple CNN for image classification could have the architecture: + +

+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs005.html b/doc/pub/cnn/html/._cnn-bs005.html new file mode 100644 index 000000000..3b6e39cdb --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs005.html @@ -0,0 +1,213 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Transforming images

+ +

+CNNs transform the original image layer by layer from the original +pixel values to the final class scores. + +

+Observe that some layers contain +parameters and other 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. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs006.html b/doc/pub/cnn/html/._cnn-bs006.html new file mode 100644 index 000000000..7e9c0b935 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs006.html @@ -0,0 +1,216 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

CNNs in brief

+ +

+In summary: + +

+ +For more material on convolutional networks, we strongly recommend +the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231 which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs007.html b/doc/pub/cnn/html/._cnn-bs007.html new file mode 100644 index 000000000..edb264e5a --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs007.html @@ -0,0 +1,212 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

CNNs in more detail, building convolutional neural networks in Tensorflow and Keras

+ +

+As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. + +

+As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs008.html b/doc/pub/cnn/html/._cnn-bs008.html new file mode 100644 index 000000000..889ac0466 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs008.html @@ -0,0 +1,209 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Setting it up

+ +

+It means that to represent the entire +dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: +$$ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs009.html b/doc/pub/cnn/html/._cnn-bs009.html new file mode 100644 index 000000000..8af95be07 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs009.html @@ -0,0 +1,216 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The MNIST dataset again

+ +

+The MNIST dataset consists of grayscale images with a pixel size of +\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each +neuron in the first hidden layer. + +

+If we were to analyze images of size \( 128\times 128 \) we would require +\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights \( = 49152 \) are required for every +single neuron in the first hidden layer. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs010.html b/doc/pub/cnn/html/._cnn-bs010.html new file mode 100644 index 000000000..33be18ffd --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs010.html @@ -0,0 +1,215 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Strong correlations

+Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. + +

+Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a receptive. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs011.html b/doc/pub/cnn/html/._cnn-bs011.html new file mode 100644 index 000000000..f463dcb3b --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs011.html @@ -0,0 +1,221 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Layers of a CNN

+The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. + +

+A convolution is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. + +

+Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the Rectified Linear (ReLu) function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a pooling layer, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs012.html b/doc/pub/cnn/html/._cnn-bs012.html new file mode 100644 index 000000000..10f5deb64 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs012.html @@ -0,0 +1,212 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Systematic reduction

+ +

+By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs013.html b/doc/pub/cnn/html/._cnn-bs013.html new file mode 100644 index 000000000..1a6712a33 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs013.html @@ -0,0 +1,244 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Prerequisites: Collect and pre-process data

+

+ + +

# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+# RGB images have a depth of 3
+# our images are grayscale so they should have a depth of 1
+inputs = inputs[:,:,:,np.newaxis]
+
+print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# choose some random images to display
+n_inputs = len(inputs)
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+    plt.subplot(1, 5, i+1)
+    plt.axis('off')
+    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+    plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs014.html b/doc/pub/cnn/html/._cnn-bs014.html new file mode 100644 index 000000000..143189777 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs014.html @@ -0,0 +1,215 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Importing Keras and Tensorflow

+

+ + +

from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+# one-liner from scikit-learn library
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+                                                    test_size=test_size)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs015.html b/doc/pub/cnn/html/._cnn-bs015.html new file mode 100644 index 000000000..0d9bc57e3 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs015.html @@ -0,0 +1,342 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Using TensorFlow backend

+ +

+We need to define model and architecture and choose cost function and optmizer. +

+ + +

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})
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs016.html b/doc/pub/cnn/html/._cnn-bs016.html new file mode 100644 index 000000000..622052318 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs016.html @@ -0,0 +1,228 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Train the model

+ +

+We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters. +

+ + +

epochs = 100
+batch_size = 100
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+                                      n_filters=n_filters, n_neurons_connected=n_neurons_connected,
+                                      n_categories=n_categories, epochs=epochs, batch_size=batch_size,
+                                      eta=eta, lmbd=lmbd)
+        CNN.fit()
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % CNN.test_accuracy)
+        print()
+            
+        CNN_tf[i][j] = CNN
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs017.html b/doc/pub/cnn/html/._cnn-bs017.html new file mode 100644 index 000000000..8d1811b9c --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs017.html @@ -0,0 +1,231 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Visualizing the results

+ +

+ + +

# 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_tf[i][j]
+
+        train_accuracy[i][j] = CNN.train_accuracy
+        test_accuracy[i][j] = CNN.test_accuracy
+
+        
+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()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs018.html b/doc/pub/cnn/html/._cnn-bs018.html new file mode 100644 index 000000000..fcc3f2802 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs018.html @@ -0,0 +1,234 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Running with Keras

+ +

+ + +

from keras.models import Sequential
+from keras.layers.convolutional import Conv2D
+from keras.layers.convolutional import MaxPooling2D
+from keras.layers import Flatten
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd):
+    model = Sequential()
+    model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
+              activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(MaxPooling2D(pool_size=(2, 2)))
+    model.add(Flatten())
+    model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))
+    
+    sgd = SGD(lr=eta)
+    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+    
+    return model
+
+epochs = 100
+batch_size = 100
+input_shape = X_train.shape[1:4]
+receptive_field = 3
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs019.html b/doc/pub/cnn/html/._cnn-bs019.html new file mode 100644 index 000000000..b38719292 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs019.html @@ -0,0 +1,215 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Final part

+ +

+ + +

CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd)
+        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+        scores = CNN.evaluate(X_test, Y_test)
+        
+        CNN_keras[i][j] = CNN
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % scores[1])
+        print()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs020.html b/doc/pub/cnn/html/._cnn-bs020.html new file mode 100644 index 000000000..7902c7a40 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs020.html @@ -0,0 +1,228 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Final visualization

+ +

+ + +

# 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()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/cnn/html/._cnn-bs021.html b/doc/pub/cnn/html/._cnn-bs021.html new file mode 100644 index 000000000..0b02057c3 --- /dev/null +++ b/doc/pub/cnn/html/._cnn-bs021.html @@ -0,0 +1,197 @@ + + + + + + + + +Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Fun links

+ +
    +
  1. Self-Driving cars using a convolutional neural network
  2. +
  3. Abstract art using convolutional neural networks
  4. +
+ + +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/src/CNN/cnn-bs.html b/doc/pub/cnn/html/cnn-bs.html similarity index 99% rename from doc/src/CNN/cnn-bs.html rename to doc/pub/cnn/html/cnn-bs.html index f0244afef..e7c61ae6e 100644 --- a/doc/src/CNN/cnn-bs.html +++ b/doc/pub/cnn/html/cnn-bs.html @@ -167,7 +167,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Oct 3, 2019

+

Oct 4, 2019


diff --git a/doc/src/CNN/cnn-reveal.html b/doc/pub/cnn/html/cnn-reveal.html similarity index 99% rename from doc/src/CNN/cnn-reveal.html rename to doc/pub/cnn/html/cnn-reveal.html index 78ea52651..d961c1478 100644 --- a/doc/src/CNN/cnn-reveal.html +++ b/doc/pub/cnn/html/cnn-reveal.html @@ -148,7 +148,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

 
-

Oct 3, 2019

+

Oct 4, 2019


diff --git a/doc/src/CNN/cnn-solarized.html b/doc/pub/cnn/html/cnn-solarized.html similarity index 99% rename from doc/src/CNN/cnn-solarized.html rename to doc/pub/cnn/html/cnn-solarized.html index 4979fb1bb..2ee41b0cf 100644 --- a/doc/src/CNN/cnn-solarized.html +++ b/doc/pub/cnn/html/cnn-solarized.html @@ -110,7 +110,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Oct 3, 2019

+

Oct 4, 2019












diff --git a/doc/src/CNN/cnn.html b/doc/pub/cnn/html/cnn.html similarity index 99% rename from doc/src/CNN/cnn.html rename to doc/pub/cnn/html/cnn.html index 176bc3958..c107d9f86 100644 --- a/doc/src/CNN/cnn.html +++ b/doc/pub/cnn/html/cnn.html @@ -115,7 +115,7 @@ MathJax.Hub.Config({

[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Oct 3, 2019

+

Oct 4, 2019












diff --git a/doc/src/CNN/reveal.js/.gitignore b/doc/pub/cnn/html/reveal.js/.gitignore similarity index 100% rename from doc/src/CNN/reveal.js/.gitignore rename to doc/pub/cnn/html/reveal.js/.gitignore diff --git a/doc/src/CNN/reveal.js/.travis.yml b/doc/pub/cnn/html/reveal.js/.travis.yml similarity index 100% rename from doc/src/CNN/reveal.js/.travis.yml rename to doc/pub/cnn/html/reveal.js/.travis.yml diff --git a/doc/src/CNN/reveal.js/CONTRIBUTING.md b/doc/pub/cnn/html/reveal.js/CONTRIBUTING.md similarity index 100% rename from doc/src/CNN/reveal.js/CONTRIBUTING.md rename to doc/pub/cnn/html/reveal.js/CONTRIBUTING.md diff --git a/doc/src/CNN/reveal.js/Gruntfile.js b/doc/pub/cnn/html/reveal.js/Gruntfile.js similarity index 100% rename from doc/src/CNN/reveal.js/Gruntfile.js rename to doc/pub/cnn/html/reveal.js/Gruntfile.js diff --git a/doc/src/CNN/reveal.js/LICENSE b/doc/pub/cnn/html/reveal.js/LICENSE similarity index 100% rename from doc/src/CNN/reveal.js/LICENSE rename to doc/pub/cnn/html/reveal.js/LICENSE diff --git a/doc/src/CNN/reveal.js/README.md b/doc/pub/cnn/html/reveal.js/README.md similarity index 100% rename from doc/src/CNN/reveal.js/README.md rename to doc/pub/cnn/html/reveal.js/README.md diff --git a/doc/src/CNN/reveal.js/bower.json b/doc/pub/cnn/html/reveal.js/bower.json similarity index 100% rename from doc/src/CNN/reveal.js/bower.json rename to doc/pub/cnn/html/reveal.js/bower.json diff --git a/doc/src/CNN/reveal.js/css/images/cbc_footer.png b/doc/pub/cnn/html/reveal.js/css/images/cbc_footer.png similarity index 100% rename from doc/src/CNN/reveal.js/css/images/cbc_footer.png rename to doc/pub/cnn/html/reveal.js/css/images/cbc_footer.png diff --git a/doc/src/CNN/reveal.js/css/images/cbc_symbol.png b/doc/pub/cnn/html/reveal.js/css/images/cbc_symbol.png similarity index 100% rename from doc/src/CNN/reveal.js/css/images/cbc_symbol.png rename to doc/pub/cnn/html/reveal.js/css/images/cbc_symbol.png diff --git a/doc/src/CNN/reveal.js/css/images/simula_footer.png b/doc/pub/cnn/html/reveal.js/css/images/simula_footer.png similarity index 100% rename from doc/src/CNN/reveal.js/css/images/simula_footer.png rename to doc/pub/cnn/html/reveal.js/css/images/simula_footer.png diff --git a/doc/src/CNN/reveal.js/css/images/simula_logo.png b/doc/pub/cnn/html/reveal.js/css/images/simula_logo.png similarity index 100% rename from doc/src/CNN/reveal.js/css/images/simula_logo.png rename to doc/pub/cnn/html/reveal.js/css/images/simula_logo.png diff --git a/doc/src/CNN/reveal.js/css/images/simula_symbol.png b/doc/pub/cnn/html/reveal.js/css/images/simula_symbol.png similarity index 100% rename from doc/src/CNN/reveal.js/css/images/simula_symbol.png rename to doc/pub/cnn/html/reveal.js/css/images/simula_symbol.png diff --git a/doc/src/CNN/reveal.js/css/images/uio_footer.png b/doc/pub/cnn/html/reveal.js/css/images/uio_footer.png similarity index 100% rename from doc/src/CNN/reveal.js/css/images/uio_footer.png rename to doc/pub/cnn/html/reveal.js/css/images/uio_footer.png diff --git a/doc/src/CNN/reveal.js/css/images/uio_symbol.png b/doc/pub/cnn/html/reveal.js/css/images/uio_symbol.png similarity index 100% rename from doc/src/CNN/reveal.js/css/images/uio_symbol.png rename to doc/pub/cnn/html/reveal.js/css/images/uio_symbol.png diff --git a/doc/src/CNN/reveal.js/css/print/paper.css b/doc/pub/cnn/html/reveal.js/css/print/paper.css similarity index 100% rename from doc/src/CNN/reveal.js/css/print/paper.css rename to doc/pub/cnn/html/reveal.js/css/print/paper.css diff --git a/doc/src/CNN/reveal.js/css/print/pdf.css b/doc/pub/cnn/html/reveal.js/css/print/pdf.css similarity index 100% rename from doc/src/CNN/reveal.js/css/print/pdf.css rename to doc/pub/cnn/html/reveal.js/css/print/pdf.css diff --git a/doc/src/CNN/reveal.js/css/reveal.css b/doc/pub/cnn/html/reveal.js/css/reveal.css similarity index 100% rename from doc/src/CNN/reveal.js/css/reveal.css rename to doc/pub/cnn/html/reveal.js/css/reveal.css diff --git a/doc/src/CNN/reveal.js/css/reveal.scss b/doc/pub/cnn/html/reveal.js/css/reveal.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/reveal.scss rename to doc/pub/cnn/html/reveal.js/css/reveal.scss diff --git a/doc/src/CNN/reveal.js/css/theme/README.md b/doc/pub/cnn/html/reveal.js/css/theme/README.md similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/README.md rename to doc/pub/cnn/html/reveal.js/css/theme/README.md diff --git a/doc/src/CNN/reveal.js/css/theme/beige.css b/doc/pub/cnn/html/reveal.js/css/theme/beige.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/beige.css rename to doc/pub/cnn/html/reveal.js/css/theme/beige.css diff --git a/doc/src/CNN/reveal.js/css/theme/beigesmall.css b/doc/pub/cnn/html/reveal.js/css/theme/beigesmall.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/beigesmall.css rename to doc/pub/cnn/html/reveal.js/css/theme/beigesmall.css diff --git a/doc/src/CNN/reveal.js/css/theme/black.css b/doc/pub/cnn/html/reveal.js/css/theme/black.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/black.css rename to doc/pub/cnn/html/reveal.js/css/theme/black.css diff --git a/doc/src/CNN/reveal.js/css/theme/blood.css b/doc/pub/cnn/html/reveal.js/css/theme/blood.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/blood.css rename to doc/pub/cnn/html/reveal.js/css/theme/blood.css diff --git a/doc/src/CNN/reveal.js/css/theme/cbc.css b/doc/pub/cnn/html/reveal.js/css/theme/cbc.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/cbc.css rename to doc/pub/cnn/html/reveal.js/css/theme/cbc.css diff --git a/doc/src/CNN/reveal.js/css/theme/darkgray.css b/doc/pub/cnn/html/reveal.js/css/theme/darkgray.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/darkgray.css rename to doc/pub/cnn/html/reveal.js/css/theme/darkgray.css diff --git a/doc/src/CNN/reveal.js/css/theme/default.css b/doc/pub/cnn/html/reveal.js/css/theme/default.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/default.css rename to doc/pub/cnn/html/reveal.js/css/theme/default.css diff --git a/doc/src/CNN/reveal.js/css/theme/league.css b/doc/pub/cnn/html/reveal.js/css/theme/league.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/league.css rename to doc/pub/cnn/html/reveal.js/css/theme/league.css diff --git a/doc/src/CNN/reveal.js/css/theme/moon.css b/doc/pub/cnn/html/reveal.js/css/theme/moon.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/moon.css rename to doc/pub/cnn/html/reveal.js/css/theme/moon.css diff --git a/doc/src/CNN/reveal.js/css/theme/night.css b/doc/pub/cnn/html/reveal.js/css/theme/night.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/night.css rename to doc/pub/cnn/html/reveal.js/css/theme/night.css diff --git a/doc/src/CNN/reveal.js/css/theme/serif.css b/doc/pub/cnn/html/reveal.js/css/theme/serif.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/serif.css rename to doc/pub/cnn/html/reveal.js/css/theme/serif.css diff --git a/doc/src/CNN/reveal.js/css/theme/simple.css b/doc/pub/cnn/html/reveal.js/css/theme/simple.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/simple.css rename to doc/pub/cnn/html/reveal.js/css/theme/simple.css diff --git a/doc/src/CNN/reveal.js/css/theme/simula.css b/doc/pub/cnn/html/reveal.js/css/theme/simula.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/simula.css rename to doc/pub/cnn/html/reveal.js/css/theme/simula.css diff --git a/doc/src/CNN/reveal.js/css/theme/sky.css b/doc/pub/cnn/html/reveal.js/css/theme/sky.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/sky.css rename to doc/pub/cnn/html/reveal.js/css/theme/sky.css diff --git a/doc/src/CNN/reveal.js/css/theme/solarized.css b/doc/pub/cnn/html/reveal.js/css/theme/solarized.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/solarized.css rename to doc/pub/cnn/html/reveal.js/css/theme/solarized.css diff --git a/doc/src/CNN/reveal.js/css/theme/source/beige.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/beige.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/beige.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/beige.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/beigesmall.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/beigesmall.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/beigesmall.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/beigesmall.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/black.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/black.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/black.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/black.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/blood.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/blood.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/blood.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/blood.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/cbc.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/cbc.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/cbc.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/cbc.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/darkgray.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/darkgray.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/darkgray.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/darkgray.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/default.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/default.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/default.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/default.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/league.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/league.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/league.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/league.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/moon.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/moon.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/moon.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/moon.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/night.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/night.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/night.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/night.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/serif.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/serif.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/serif.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/serif.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/simple.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/simple.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/simple.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/simple.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/simula.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/simula.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/simula.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/simula.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/sky.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/sky.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/sky.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/sky.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/solarized.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/solarized.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/solarized.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/solarized.scss diff --git a/doc/src/CNN/reveal.js/css/theme/source/white.scss b/doc/pub/cnn/html/reveal.js/css/theme/source/white.scss similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/source/white.scss rename to doc/pub/cnn/html/reveal.js/css/theme/source/white.scss diff --git a/doc/pub/cnn/html/reveal.js/css/theme/template/mixins.scss b/doc/pub/cnn/html/reveal.js/css/theme/template/mixins.scss new file mode 100644 index 000000000..e0c560692 --- /dev/null +++ b/doc/pub/cnn/html/reveal.js/css/theme/template/mixins.scss @@ -0,0 +1,29 @@ +@mixin vertical-gradient( $top, $bottom ) { + background: $top; + background: -moz-linear-gradient( top, $top 0%, $bottom 100% ); + background: -webkit-gradient( linear, left top, left bottom, color-stop(0%,$top), color-stop(100%,$bottom) ); + background: -webkit-linear-gradient( top, $top 0%, $bottom 100% ); + background: -o-linear-gradient( top, $top 0%, $bottom 100% ); + background: -ms-linear-gradient( top, $top 0%, $bottom 100% ); + background: linear-gradient( top, $top 0%, $bottom 100% ); +} + +@mixin horizontal-gradient( $top, $bottom ) { + background: $top; + background: -moz-linear-gradient( left, $top 0%, $bottom 100% ); + background: -webkit-gradient( linear, left top, right top, color-stop(0%,$top), color-stop(100%,$bottom) ); + background: -webkit-linear-gradient( left, $top 0%, $bottom 100% ); + background: -o-linear-gradient( left, $top 0%, $bottom 100% ); + background: -ms-linear-gradient( left, $top 0%, $bottom 100% ); + background: linear-gradient( left, $top 0%, $bottom 100% ); +} + +@mixin radial-gradient( $outer, $inner, $type: circle ) { + background: $outer; + background: -moz-radial-gradient( center, $type cover, $inner 0%, $outer 100% ); + background: -webkit-gradient( radial, center center, 0px, center center, 100%, color-stop(0%,$inner), color-stop(100%,$outer) ); + background: -webkit-radial-gradient( center, $type cover, $inner 0%, $outer 100% ); + background: -o-radial-gradient( center, $type cover, $inner 0%, $outer 100% ); + background: -ms-radial-gradient( center, $type cover, $inner 0%, $outer 100% ); + background: radial-gradient( center, $type cover, $inner 0%, $outer 100% ); +} \ No newline at end of file diff --git a/doc/pub/cnn/html/reveal.js/css/theme/template/settings.scss b/doc/pub/cnn/html/reveal.js/css/theme/template/settings.scss new file mode 100644 index 000000000..e706e19c5 --- /dev/null +++ b/doc/pub/cnn/html/reveal.js/css/theme/template/settings.scss @@ -0,0 +1,34 @@ +// Base settings for all themes that can optionally be +// overridden by the super-theme + +// Background of the presentation +$backgroundColor: #2b2b2b; + +// Primary/body text +$mainFont: 'Lato', sans-serif; +$mainFontSize: 30px; /* changed (by hpl) from 36px; */ +$mainColor: #eee; + +// Headings +$headingMargin: 0 0 20px 0; +$headingFont: 'League Gothic', Impact, sans-serif; +$headingColor: #eee; +$headingLineHeight: 0.9em; +$headingLetterSpacing: 0.02em; +$headingTextTransform: none; /* changed (by hpl) from uppercase; */ +$headingTextShadow: 0px 0px 6px rgba(0,0,0,0.2); +$heading1TextShadow: $headingTextShadow; + +// Links and actions +$linkColor: #13DAEC; +$linkColorHover: lighten( $linkColor, 20% ); + +// Text selection +$selectionBackgroundColor: #FF5E99; +$selectionColor: #fff; + +// Generates the presentation background, can be overridden +// to return a background image or gradient +@mixin bodyBackground() { + background: $backgroundColor; +} \ No newline at end of file diff --git a/doc/pub/cnn/html/reveal.js/css/theme/template/theme.scss b/doc/pub/cnn/html/reveal.js/css/theme/template/theme.scss new file mode 100644 index 000000000..b1dbc2736 --- /dev/null +++ b/doc/pub/cnn/html/reveal.js/css/theme/template/theme.scss @@ -0,0 +1,171 @@ +// Base theme template for reveal.js + +/********************************************* + * GLOBAL STYLES + *********************************************/ + +body { + @include bodyBackground(); + background-color: $backgroundColor; +} + +.reveal { + font-family: $mainFont; + font-size: $mainFontSize; + font-weight: normal; + letter-spacing: -0.02em; + color: $mainColor; +} + +::selection { + color: $selectionColor; + background: $selectionBackgroundColor; + text-shadow: none; +} + +/********************************************* + * HEADERS + *********************************************/ + +.reveal h1, +.reveal h2, +.reveal h3, +.reveal h4, +.reveal h5, +.reveal h6 { + margin: $headingMargin; + color: $headingColor; + + font-family: $headingFont; + line-height: $headingLineHeight; + letter-spacing: $headingLetterSpacing; + + text-transform: $headingTextTransform; + text-shadow: $headingTextShadow; +} + +.reveal h1 { + line-height: 1.2em; /* added by hpl */ + text-shadow: $heading1TextShadow; +} + + +/********************************************* + * LINKS + *********************************************/ + +.reveal a:not(.image) { + color: $linkColor; + text-decoration: none; + + -webkit-transition: color .15s ease; + -moz-transition: color .15s ease; + -ms-transition: color .15s ease; + -o-transition: color .15s ease; + transition: color .15s ease; +} + .reveal a:not(.image):hover { + color: $linkColorHover; + + text-shadow: none; + border: none; + } + +.reveal .roll span:after { + color: #fff; + background: darken( $linkColor, 15% ); +} + + +/********************************************* + * IMAGES + *********************************************/ + +.reveal section img { + margin: 15px 0px; + background: rgba(255,255,255,0.12); + border: 4px solid $mainColor; + + box-shadow: 0 0 10px rgba(0, 0, 0, 0.15); + + -webkit-transition: all .2s linear; + -moz-transition: all .2s linear; + -ms-transition: all .2s linear; + -o-transition: all .2s linear; + transition: all .2s linear; +} + + .reveal a:hover img { + background: rgba(255,255,255,0.2); + border-color: $linkColor; + + box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); + } + + +/********************************************* + * NAVIGATION CONTROLS + *********************************************/ + +.reveal .controls div.navigate-left, +.reveal .controls div.navigate-left.enabled { + border-right-color: $linkColor; +} + +.reveal .controls div.navigate-right, +.reveal .controls div.navigate-right.enabled { + border-left-color: $linkColor; +} + +.reveal .controls div.navigate-up, +.reveal .controls div.navigate-up.enabled { + border-bottom-color: $linkColor; +} + +.reveal .controls div.navigate-down, +.reveal .controls div.navigate-down.enabled { + border-top-color: $linkColor; +} + +.reveal .controls div.navigate-left.enabled:hover { + border-right-color: $linkColorHover; +} + +.reveal .controls div.navigate-right.enabled:hover { + border-left-color: $linkColorHover; +} + +.reveal .controls div.navigate-up.enabled:hover { + border-bottom-color: $linkColorHover; +} + +.reveal .controls div.navigate-down.enabled:hover { + border-top-color: $linkColorHover; +} + + +/********************************************* + * PROGRESS BAR + *********************************************/ + +.reveal .progress { + background: rgba(0,0,0,0.2); +} + .reveal .progress span { + background: $linkColor; + + -webkit-transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985); + -moz-transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985); + -ms-transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985); + -o-transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985); + transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985); + } + +/********************************************* + * SLIDE NUMBER + *********************************************/ +.reveal .slide-number { + color: $linkColor; +} + + diff --git a/doc/src/CNN/reveal.js/css/theme/white.css b/doc/pub/cnn/html/reveal.js/css/theme/white.css similarity index 100% rename from doc/src/CNN/reveal.js/css/theme/white.css rename to doc/pub/cnn/html/reveal.js/css/theme/white.css diff --git a/doc/src/CNN/reveal.js/index.html b/doc/pub/cnn/html/reveal.js/index.html similarity index 100% rename from doc/src/CNN/reveal.js/index.html rename to doc/pub/cnn/html/reveal.js/index.html diff --git a/doc/src/CNN/reveal.js/js/reveal.js b/doc/pub/cnn/html/reveal.js/js/reveal.js similarity index 100% rename from doc/src/CNN/reveal.js/js/reveal.js rename to doc/pub/cnn/html/reveal.js/js/reveal.js diff --git a/doc/src/CNN/reveal.js/lib/css/zenburn.css b/doc/pub/cnn/html/reveal.js/lib/css/zenburn.css similarity index 100% rename from doc/src/CNN/reveal.js/lib/css/zenburn.css rename to doc/pub/cnn/html/reveal.js/lib/css/zenburn.css diff --git a/doc/src/CNN/reveal.js/lib/font/league-gothic/LICENSE b/doc/pub/cnn/html/reveal.js/lib/font/league-gothic/LICENSE similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/league-gothic/LICENSE rename to doc/pub/cnn/html/reveal.js/lib/font/league-gothic/LICENSE diff --git a/doc/src/CNN/reveal.js/lib/font/league-gothic/league-gothic.css b/doc/pub/cnn/html/reveal.js/lib/font/league-gothic/league-gothic.css similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/league-gothic/league-gothic.css rename to doc/pub/cnn/html/reveal.js/lib/font/league-gothic/league-gothic.css diff --git a/doc/src/CNN/reveal.js/lib/font/league-gothic/league-gothic.eot b/doc/pub/cnn/html/reveal.js/lib/font/league-gothic/league-gothic.eot similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/league-gothic/league-gothic.eot rename to doc/pub/cnn/html/reveal.js/lib/font/league-gothic/league-gothic.eot diff --git a/doc/src/CNN/reveal.js/lib/font/league-gothic/league-gothic.ttf b/doc/pub/cnn/html/reveal.js/lib/font/league-gothic/league-gothic.ttf similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/league-gothic/league-gothic.ttf rename to doc/pub/cnn/html/reveal.js/lib/font/league-gothic/league-gothic.ttf diff --git a/doc/src/CNN/reveal.js/lib/font/league-gothic/league-gothic.woff b/doc/pub/cnn/html/reveal.js/lib/font/league-gothic/league-gothic.woff similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/league-gothic/league-gothic.woff rename to doc/pub/cnn/html/reveal.js/lib/font/league-gothic/league-gothic.woff diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/LICENSE b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/LICENSE similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/LICENSE rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/LICENSE diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.eot b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.eot similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.eot rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.eot diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.ttf b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.ttf similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.ttf rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.ttf diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.woff b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.woff similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.woff rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-italic.woff diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.eot b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.eot similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.eot rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.eot diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.ttf b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.ttf similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.ttf rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.ttf diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.woff b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.woff similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.woff rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-regular.woff diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.eot b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.eot similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.eot rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.eot diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.ttf b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.ttf similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.ttf rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.ttf diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.woff b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.woff similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.woff rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibold.woff diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.eot b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.eot similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.eot rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.eot diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.ttf b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.ttf similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.ttf rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.ttf diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.woff b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.woff similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.woff rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro-semibolditalic.woff diff --git a/doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro.css b/doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro.css similarity index 100% rename from doc/src/CNN/reveal.js/lib/font/source-sans-pro/source-sans-pro.css rename to doc/pub/cnn/html/reveal.js/lib/font/source-sans-pro/source-sans-pro.css diff --git a/doc/src/CNN/reveal.js/lib/js/classList.js b/doc/pub/cnn/html/reveal.js/lib/js/classList.js similarity index 100% rename from doc/src/CNN/reveal.js/lib/js/classList.js rename to doc/pub/cnn/html/reveal.js/lib/js/classList.js diff --git a/doc/src/CNN/reveal.js/lib/js/head.min.js b/doc/pub/cnn/html/reveal.js/lib/js/head.min.js similarity index 100% rename from doc/src/CNN/reveal.js/lib/js/head.min.js rename to doc/pub/cnn/html/reveal.js/lib/js/head.min.js diff --git a/doc/src/CNN/reveal.js/lib/js/html5shiv.js b/doc/pub/cnn/html/reveal.js/lib/js/html5shiv.js similarity index 100% rename from doc/src/CNN/reveal.js/lib/js/html5shiv.js rename to doc/pub/cnn/html/reveal.js/lib/js/html5shiv.js diff --git a/doc/src/CNN/reveal.js/package.json b/doc/pub/cnn/html/reveal.js/package.json similarity index 100% rename from doc/src/CNN/reveal.js/package.json rename to doc/pub/cnn/html/reveal.js/package.json diff --git a/doc/src/CNN/reveal.js/plugin/highlight/highlight.js b/doc/pub/cnn/html/reveal.js/plugin/highlight/highlight.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/highlight/highlight.js rename to doc/pub/cnn/html/reveal.js/plugin/highlight/highlight.js diff --git a/doc/src/CNN/reveal.js/plugin/leap/leap.js b/doc/pub/cnn/html/reveal.js/plugin/leap/leap.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/leap/leap.js rename to doc/pub/cnn/html/reveal.js/plugin/leap/leap.js diff --git a/doc/src/CNN/reveal.js/plugin/markdown/example.html b/doc/pub/cnn/html/reveal.js/plugin/markdown/example.html similarity index 100% rename from doc/src/CNN/reveal.js/plugin/markdown/example.html rename to doc/pub/cnn/html/reveal.js/plugin/markdown/example.html diff --git a/doc/src/CNN/reveal.js/plugin/markdown/example.md b/doc/pub/cnn/html/reveal.js/plugin/markdown/example.md similarity index 100% rename from doc/src/CNN/reveal.js/plugin/markdown/example.md rename to doc/pub/cnn/html/reveal.js/plugin/markdown/example.md diff --git a/doc/src/CNN/reveal.js/plugin/markdown/markdown.js b/doc/pub/cnn/html/reveal.js/plugin/markdown/markdown.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/markdown/markdown.js rename to doc/pub/cnn/html/reveal.js/plugin/markdown/markdown.js diff --git a/doc/src/CNN/reveal.js/plugin/markdown/marked.js b/doc/pub/cnn/html/reveal.js/plugin/markdown/marked.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/markdown/marked.js rename to doc/pub/cnn/html/reveal.js/plugin/markdown/marked.js diff --git a/doc/src/CNN/reveal.js/plugin/math/math.js b/doc/pub/cnn/html/reveal.js/plugin/math/math.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/math/math.js rename to doc/pub/cnn/html/reveal.js/plugin/math/math.js diff --git a/doc/src/CNN/reveal.js/plugin/multiplex/client.js b/doc/pub/cnn/html/reveal.js/plugin/multiplex/client.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/multiplex/client.js rename to doc/pub/cnn/html/reveal.js/plugin/multiplex/client.js diff --git a/doc/src/CNN/reveal.js/plugin/multiplex/index.js b/doc/pub/cnn/html/reveal.js/plugin/multiplex/index.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/multiplex/index.js rename to doc/pub/cnn/html/reveal.js/plugin/multiplex/index.js diff --git a/doc/src/CNN/reveal.js/plugin/multiplex/master.js b/doc/pub/cnn/html/reveal.js/plugin/multiplex/master.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/multiplex/master.js rename to doc/pub/cnn/html/reveal.js/plugin/multiplex/master.js diff --git a/doc/src/CNN/reveal.js/plugin/notes-server/client.js b/doc/pub/cnn/html/reveal.js/plugin/notes-server/client.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/notes-server/client.js rename to doc/pub/cnn/html/reveal.js/plugin/notes-server/client.js diff --git a/doc/src/CNN/reveal.js/plugin/notes-server/index.js b/doc/pub/cnn/html/reveal.js/plugin/notes-server/index.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/notes-server/index.js rename to doc/pub/cnn/html/reveal.js/plugin/notes-server/index.js diff --git a/doc/src/CNN/reveal.js/plugin/notes-server/notes.html b/doc/pub/cnn/html/reveal.js/plugin/notes-server/notes.html similarity index 100% rename from doc/src/CNN/reveal.js/plugin/notes-server/notes.html rename to doc/pub/cnn/html/reveal.js/plugin/notes-server/notes.html diff --git a/doc/src/CNN/reveal.js/plugin/notes/notes.html b/doc/pub/cnn/html/reveal.js/plugin/notes/notes.html similarity index 100% rename from doc/src/CNN/reveal.js/plugin/notes/notes.html rename to doc/pub/cnn/html/reveal.js/plugin/notes/notes.html diff --git a/doc/src/CNN/reveal.js/plugin/notes/notes.js b/doc/pub/cnn/html/reveal.js/plugin/notes/notes.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/notes/notes.js rename to doc/pub/cnn/html/reveal.js/plugin/notes/notes.js diff --git a/doc/src/CNN/reveal.js/plugin/print-pdf/print-pdf.js b/doc/pub/cnn/html/reveal.js/plugin/print-pdf/print-pdf.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/print-pdf/print-pdf.js rename to doc/pub/cnn/html/reveal.js/plugin/print-pdf/print-pdf.js diff --git a/doc/src/CNN/reveal.js/plugin/remotes/remotes.js b/doc/pub/cnn/html/reveal.js/plugin/remotes/remotes.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/remotes/remotes.js rename to doc/pub/cnn/html/reveal.js/plugin/remotes/remotes.js diff --git a/doc/src/CNN/reveal.js/plugin/search/search.js b/doc/pub/cnn/html/reveal.js/plugin/search/search.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/search/search.js rename to doc/pub/cnn/html/reveal.js/plugin/search/search.js diff --git a/doc/src/CNN/reveal.js/plugin/zoom-js/zoom.js b/doc/pub/cnn/html/reveal.js/plugin/zoom-js/zoom.js similarity index 100% rename from doc/src/CNN/reveal.js/plugin/zoom-js/zoom.js rename to doc/pub/cnn/html/reveal.js/plugin/zoom-js/zoom.js diff --git a/doc/src/CNN/reveal.js/test/examples/assets/image1.png b/doc/pub/cnn/html/reveal.js/test/examples/assets/image1.png similarity index 100% rename from doc/src/CNN/reveal.js/test/examples/assets/image1.png rename to doc/pub/cnn/html/reveal.js/test/examples/assets/image1.png diff --git a/doc/src/CNN/reveal.js/test/examples/assets/image2.png b/doc/pub/cnn/html/reveal.js/test/examples/assets/image2.png similarity index 100% rename from doc/src/CNN/reveal.js/test/examples/assets/image2.png rename to doc/pub/cnn/html/reveal.js/test/examples/assets/image2.png diff --git a/doc/src/CNN/reveal.js/test/examples/barebones.html b/doc/pub/cnn/html/reveal.js/test/examples/barebones.html similarity index 100% rename from doc/src/CNN/reveal.js/test/examples/barebones.html rename to doc/pub/cnn/html/reveal.js/test/examples/barebones.html diff --git a/doc/src/CNN/reveal.js/test/examples/embedded-media.html b/doc/pub/cnn/html/reveal.js/test/examples/embedded-media.html similarity index 100% rename from doc/src/CNN/reveal.js/test/examples/embedded-media.html rename to doc/pub/cnn/html/reveal.js/test/examples/embedded-media.html diff --git a/doc/src/CNN/reveal.js/test/examples/math.html b/doc/pub/cnn/html/reveal.js/test/examples/math.html similarity index 100% rename from doc/src/CNN/reveal.js/test/examples/math.html rename to doc/pub/cnn/html/reveal.js/test/examples/math.html diff --git a/doc/src/CNN/reveal.js/test/examples/slide-backgrounds.html b/doc/pub/cnn/html/reveal.js/test/examples/slide-backgrounds.html similarity index 100% rename from doc/src/CNN/reveal.js/test/examples/slide-backgrounds.html rename to doc/pub/cnn/html/reveal.js/test/examples/slide-backgrounds.html diff --git a/doc/src/CNN/reveal.js/test/examples/slide-transitions.html b/doc/pub/cnn/html/reveal.js/test/examples/slide-transitions.html similarity index 100% rename from doc/src/CNN/reveal.js/test/examples/slide-transitions.html rename to doc/pub/cnn/html/reveal.js/test/examples/slide-transitions.html diff --git a/doc/src/CNN/reveal.js/test/qunit-1.12.0.css b/doc/pub/cnn/html/reveal.js/test/qunit-1.12.0.css similarity index 100% rename from doc/src/CNN/reveal.js/test/qunit-1.12.0.css rename to doc/pub/cnn/html/reveal.js/test/qunit-1.12.0.css diff --git a/doc/src/CNN/reveal.js/test/qunit-1.12.0.js b/doc/pub/cnn/html/reveal.js/test/qunit-1.12.0.js similarity index 100% rename from doc/src/CNN/reveal.js/test/qunit-1.12.0.js rename to doc/pub/cnn/html/reveal.js/test/qunit-1.12.0.js diff --git a/doc/src/CNN/reveal.js/test/test-markdown-element-attributes.html b/doc/pub/cnn/html/reveal.js/test/test-markdown-element-attributes.html similarity index 100% rename from doc/src/CNN/reveal.js/test/test-markdown-element-attributes.html rename to doc/pub/cnn/html/reveal.js/test/test-markdown-element-attributes.html diff --git a/doc/src/CNN/reveal.js/test/test-markdown-element-attributes.js b/doc/pub/cnn/html/reveal.js/test/test-markdown-element-attributes.js similarity index 100% rename from doc/src/CNN/reveal.js/test/test-markdown-element-attributes.js rename to doc/pub/cnn/html/reveal.js/test/test-markdown-element-attributes.js diff --git a/doc/src/CNN/reveal.js/test/test-markdown-slide-attributes.html b/doc/pub/cnn/html/reveal.js/test/test-markdown-slide-attributes.html similarity index 100% rename from doc/src/CNN/reveal.js/test/test-markdown-slide-attributes.html rename to doc/pub/cnn/html/reveal.js/test/test-markdown-slide-attributes.html diff --git a/doc/src/CNN/reveal.js/test/test-markdown-slide-attributes.js b/doc/pub/cnn/html/reveal.js/test/test-markdown-slide-attributes.js similarity index 100% rename from doc/src/CNN/reveal.js/test/test-markdown-slide-attributes.js rename to doc/pub/cnn/html/reveal.js/test/test-markdown-slide-attributes.js diff --git a/doc/src/CNN/reveal.js/test/test-markdown.html b/doc/pub/cnn/html/reveal.js/test/test-markdown.html similarity index 100% rename from doc/src/CNN/reveal.js/test/test-markdown.html rename to doc/pub/cnn/html/reveal.js/test/test-markdown.html diff --git a/doc/src/CNN/reveal.js/test/test-markdown.js b/doc/pub/cnn/html/reveal.js/test/test-markdown.js similarity index 100% rename from doc/src/CNN/reveal.js/test/test-markdown.js rename to doc/pub/cnn/html/reveal.js/test/test-markdown.js diff --git a/doc/src/CNN/reveal.js/test/test-pdf.html b/doc/pub/cnn/html/reveal.js/test/test-pdf.html similarity index 100% rename from doc/src/CNN/reveal.js/test/test-pdf.html rename to doc/pub/cnn/html/reveal.js/test/test-pdf.html diff --git a/doc/src/CNN/reveal.js/test/test-pdf.js b/doc/pub/cnn/html/reveal.js/test/test-pdf.js similarity index 100% rename from doc/src/CNN/reveal.js/test/test-pdf.js rename to doc/pub/cnn/html/reveal.js/test/test-pdf.js diff --git a/doc/src/CNN/reveal.js/test/test.html b/doc/pub/cnn/html/reveal.js/test/test.html similarity index 100% rename from doc/src/CNN/reveal.js/test/test.html rename to doc/pub/cnn/html/reveal.js/test/test.html diff --git a/doc/src/CNN/reveal.js/test/test.js b/doc/pub/cnn/html/reveal.js/test/test.js similarity index 100% rename from doc/src/CNN/reveal.js/test/test.js rename to doc/pub/cnn/html/reveal.js/test/test.js diff --git a/doc/src/CNN/cnn.ipynb b/doc/pub/cnn/ipynb/cnn.ipynb similarity index 99% rename from doc/src/CNN/cnn.ipynb rename to doc/pub/cnn/ipynb/cnn.ipynb index 07b751bcb..955777445 100644 --- a/doc/src/CNN/cnn.ipynb +++ b/doc/pub/cnn/ipynb/cnn.ipynb @@ -10,7 +10,7 @@ " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Oct 3, 2019**\n", + "Date: **Oct 4, 2019**\n", "\n", "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", diff --git a/doc/src/CNN/ipynb-cnn-src.tar.gz b/doc/pub/cnn/ipynb/ipynb-cnn-src.tar.gz similarity index 99% rename from doc/src/CNN/ipynb-cnn-src.tar.gz rename to doc/pub/cnn/ipynb/ipynb-cnn-src.tar.gz index 2231ed096..c8178c47c 100644 Binary files a/doc/src/CNN/ipynb-cnn-src.tar.gz and b/doc/pub/cnn/ipynb/ipynb-cnn-src.tar.gz differ diff --git a/doc/src/CNN/cnn-minted.pdf b/doc/pub/cnn/pdf/cnn-minted.pdf similarity index 99% rename from doc/src/CNN/cnn-minted.pdf rename to doc/pub/cnn/pdf/cnn-minted.pdf index f2e9ec1f8..4ebda3c6c 100644 Binary files a/doc/src/CNN/cnn-minted.pdf and b/doc/pub/cnn/pdf/cnn-minted.pdf differ diff --git a/doc/src/CNN/_minted-cnn/default.pygstyle b/doc/src/CNN/_minted-cnn/default.pygstyle deleted file mode 100644 index e69de29bb..000000000 diff --git a/doc/src/CNN/cnn-plain-minted.tex b/doc/src/CNN/cnn-plain-minted.tex deleted file mode 100644 index 6fb87ff00..000000000 --- a/doc/src/CNN/cnn-plain-minted.tex +++ /dev/null @@ -1,781 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% - - -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{fancyvrb} % packages needed for verbatim environments -\usepackage{minted} -\usemintedstyle{default} - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% Tricks for having figures close to where they are defined: -% 1. define less restrictive rules for where to put figures -\setcounter{topnumber}{2} -\setcounter{bottomnumber}{2} -\setcounter{totalnumber}{4} -\renewcommand{\topfraction}{0.95} -\renewcommand{\bottomfraction}{0.95} -\renewcommand{\textfraction}{0} -\renewcommand{\floatpagefraction}{0.75} -% floatpagefraction must always be less than topfraction! -% 2. ensure all figures are flushed before next section -\usepackage[section]{placeins} -% 3. enable begin{figure}[H] (often leads to ugly pagebreaks) -%\usepackage{float}\restylefloat{figure} - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Convolutional Neural Networks -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Oct 3, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection*{Convolutional Neural Networks (recognizing images)} - -Convolutional Neural Networks (CNN) are very similar to ordinary Neural Networks. - -They are made up of neurons that have learnable weights and -biases. Each neuron receives some inputs, performs a dot product and -optionally follows it with a non-linearity. The whole network still -expresses a single differentiable score function: from the raw image -pixels on one end to class scores at the other. And they still have a -loss function (for example Softmax) on the last (fully-connected) layer -and all the tips/tricks we developed for learning regular Neural -Networks still apply (back propagation, gradient descent etc etc). - -What is the difference? \textbf{CNN architectures make the explicit assumption that -the inputs are images, which allows us to encode certain properties -into the architecture. These then make the forward function more -efficient to implement and vastly reduce the amount of parameters in -the network.} - -Here we provide only a superficial overview, for the more interested, we recommend highly the course -\href{{https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html}}{IN5400 – Machine Learning for Image Analysis} -and the slides of \href{{http://cs231n.github.io/convolutional-networks/}}{CS231}. - -% !split -\subsection*{Regular NNs don’t scale well to full images} - -As an example, consider -an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a -single fully-connected neuron in a first hidden layer of a regular -Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still -seems manageable, but clearly this fully-connected structure does not -scale to larger images. For example, an image of more respectable -size, say $200\times 200\times 3$, would lead to neurons that have -$200\times 200\times 3 = 120,000$ weights. - -We could have -several such neurons, and the parameters would add up quickly! Clearly, -this full connectivity is wasteful and the huge number of parameters -would quickly lead to possible overfitting. - - -\begin{figure}[!ht] % - \centerline{\includegraphics[width=0.6\linewidth]{figslides/nn.jpeg}} - \caption{ - A regular 3-layer Neural Network. - } -\end{figure} -%\clearpage % flush figures - - -% !split -\subsection*{3D volumes of neurons} - -Convolutional Neural Networks take advantage of the fact that the -input consists of images and they constrain the architecture in a more -sensible way. - -In particular, unlike a regular Neural Network, the -layers of a CNN have neurons arranged in 3 dimensions: width, -height, depth. (Note that the word depth here refers to the third -dimension of an activation volume, not to the depth of a full Neural -Network, which can refer to the total number of layers in a network.) - -To understand it better, the above example of an image -with an input volume of -activations has dimensions $32\times 32\times 3$ (width, height, -depth respectively). - -The neurons in a layer will -only be connected to a small region of the layer before it, instead of -all of the neurons in a fully-connected manner. Moreover, the final -output layer could for this specific image have dimensions $1\times 1 \times 10$, -because by the -end of the CNN architecture we will reduce the full image into a -single vector of class scores, arranged along the depth -dimension. - - -\begin{figure}[!ht] % - \centerline{\includegraphics[width=0.6\linewidth]{figslides/cnn.jpeg}} - \caption{ - 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). - } -\end{figure} -%\clearpage % flush figures - - - - -% !split -\subsection*{Layers used to build CNNs} - - -A simple CNN is a sequence of layers, and every layer of a CNN -transforms one volume of activations to another through a -differentiable function. We use three main types of layers to build -CNN architectures: Convolutional Layer, Pooling Layer, and -Fully-Connected Layer (exactly as seen in regular Neural Networks). We -will stack these layers to form a full CNN architecture. - -A simple CNN for image classification could have the architecture: - -\begin{itemize} -\item \textbf{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. - -\item \textbf{CONV} (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters. - -\item \textbf{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]$). - -\item \textbf{POOL} (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$. - -\item \textbf{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. -\end{itemize} - -\noindent -% !split -\subsection*{Transforming images} - -CNNs transform the original image layer by layer from the original -pixel values to the final class scores. - -Observe that some layers contain -parameters and other 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. - - -% !split -\subsection*{CNNs in brief} - -In summary: - -\begin{itemize} -\item 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) - -\item There are a few distinct types of Layers (e.g.~CONV/FC/RELU/POOL are by far the most popular) - -\item Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function - -\item Each Layer may or may not have parameters (e.g.~CONV/FC do, RELU/POOL don’t) - -\item Each Layer may or may not have additional hyperparameters (e.g.~CONV/FC/POOL do, RELU doesn’t) -\end{itemize} - -\noindent -For more material on convolutional networks, we strongly recommend -the course -\href{{https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html}}{IN5400 – Machine Learning for Image Analysis} -and the slides of \href{{http://cs231n.github.io/convolutional-networks/}}{CS231} which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). \href{{http://neuralnetworksanddeeplearning.com/chap6.html}}{Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs}. - - -% !split -\subsection*{CNNs in more detail, building convolutional neural networks in Tensorflow and Keras} - - -As discussed above, CNNs are neural networks built from the assumption that the inputs -to the network are 2D images. This is important because the number of features or pixels in images -grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. - -As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks -are the \textbf{convolutional} and \textbf{pooling} layers stacked in pairs between the input and the hidden layer. -In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D -matrices, typically 1 for each color dimension (Red, Green, Blue). - - -% !split -\subsection*{Setting it up} - -It means that to represent the entire -dataset of images, we require a 4D matrix or \textbf{tensor}. This tensor has the dimensions: -\[ -(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . -\] - -% !split -\subsection*{The MNIST dataset again} - -The MNIST dataset consists of grayscale images with a pixel size of -$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each -neuron in the first hidden layer. - -If we were to analyze images of size $128\times 128$ we would require -$128 \times 128 = 16384$ weights to each neuron. Even worse if we were -dealing with color images, as most images are, we have an image matrix -of size $128\times 128$ for each color dimension (Red, Green, Blue), -meaning 3 times the number of weights $= 49152$ are required for every -single neuron in the first hidden layer. - - -% !split -\subsection*{Strong correlations} -Images typically have strong local correlations, meaning that a small -part of the image varies little from its neighboring regions. If for -example we have an image of a blue car, we can roughly assume that a -small blue part of the image is surrounded by other blue regions. - -Therefore, instead of connecting every single pixel to a neuron in the -first hidden layer, as we have previously done with deep neural -networks, we can instead connect each neuron to a small part of the -image (in all 3 RGB depth dimensions). The size of each small area is -fixed, and known as a \href{{https://en.wikipedia.org/wiki/Receptive_field}}{receptive}. - - -% !split -\subsection*{Layers of a CNN} -The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. -The input image is typically a square matrix of depth 3. - -A \textbf{convolution} is performed on the image which outputs -a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as \textbf{filters}. - - -Each filter slides along the input image, taking the dot product -between each small part of the image and the filter, in all depth -dimensions. This is then passed through a non-linear function, -typically the \textbf{Rectified Linear (ReLu)} function, which serves as the -activation of the neurons in the first convolutional layer. This is -further passed through a \textbf{pooling layer}, which reduces the size of the -convolutional layer, e.g.~by taking the maximum or average across some -small regions, and this serves as input to the next convolutional -layer. - - -% !split -\subsection*{Systematic reduction} - -By systematically reducing the size of the input volume, through -convolution and pooling, the network should create representations of -small parts of the input, and then from them assemble representations -of larger areas. The final pooling layer is flattened to serve as -input to a hidden layer, such that each neuron in the final pooling -layer is connected to every single neuron in the hidden layer. This -then serves as input to the output layer, e.g.~a softmax output for -classification. - - -% !split -\subsection*{Prerequisites: Collect and pre-process data} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -# RGB images have a depth of 3 -# our images are grayscale so they should have a depth of 1 -inputs = inputs[:,:,:,np.newaxis] - -print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# choose some random images to display -n_inputs = len(inputs) -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -\end{minted} - - -% !split -\subsection*{Importing Keras and Tensorflow} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from keras.utils import to_categorical -from sklearn.model_selection import train_test_split - -# representation of labels -labels = to_categorical(labels) - -# split into train and test data -# one-liner from scikit-learn library -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) -\end{minted} - -% !split -\subsection*{Using TensorFlow backend} - -We need to define model and architecture and choose cost function and optmizer. -\begin{Verbatim}[numbers=none,fontsize=\fontsize{9pt}{9pt},baselinestretch=0.95] - -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}) -\end{Verbatim} - -% !split -\subsection*{Train the model} - -We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -epochs = 100 -batch_size = 100 -n_filters = 10 -n_neurons_connected = 50 -n_categories = 10 - -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test, - n_filters=n_filters, n_neurons_connected=n_neurons_connected, - n_categories=n_categories, epochs=epochs, batch_size=batch_size, - eta=eta, lmbd=lmbd) - CNN.fit() - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % CNN.test_accuracy) - print() - - CNN_tf[i][j] = CNN -\end{minted} - -% !split -\subsection*{Visualizing the results} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# 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_tf[i][j] - - train_accuracy[i][j] = CNN.train_accuracy - test_accuracy[i][j] = CNN.test_accuracy - - -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() -\end{minted} - -% !split -\subsection*{Running with Keras} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from keras.models import Sequential -from keras.layers.convolutional import Conv2D -from keras.layers.convolutional import MaxPooling2D -from keras.layers import Flatten -from keras.layers import Dense -from keras.regularizers import l2 -from keras.optimizers import SGD - -def create_convolutional_neural_network_keras(input_shape, receptive_field, - n_filters, n_neurons_connected, n_categories, - eta, lmbd): - model = Sequential() - model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same', - activation='relu', kernel_regularizer=l2(lmbd))) - model.add(MaxPooling2D(pool_size=(2, 2))) - model.add(Flatten()) - model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd))) - model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd))) - - sgd = SGD(lr=eta) - model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) - - return model - -epochs = 100 -batch_size = 100 -input_shape = X_train.shape[1:4] -receptive_field = 3 -n_filters = 10 -n_neurons_connected = 50 -n_categories = 10 - -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -\end{minted} - -% !split -\subsection*{Final part} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - CNN = create_convolutional_neural_network_keras(input_shape, receptive_field, - n_filters, n_neurons_connected, n_categories, - eta, lmbd) - CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) - scores = CNN.evaluate(X_test, Y_test) - - CNN_keras[i][j] = CNN - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % scores[1]) - print() -\end{minted} - -% !split -\subsection*{Final visualization} - -\begin{Verbatim}[numbers=none,fontsize=\fontsize{9pt}{9pt},baselinestretch=0.95] -# 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() -\end{Verbatim} - -% !split -\subsection*{Fun links} - -\begin{enumerate} -\item \href{{https://arxiv.org/abs/1604.07316}}{Self-Driving cars using a convolutional neural network} - -\item \href{{https://deepdreamgenerator.com/}}{Abstract art using convolutional neural networks} -\end{enumerate} - -\noindent - -% ------------------- end of main content --------------- - -\end{document} - diff --git a/doc/src/CNN/cnn.p.tex b/doc/src/CNN/cnn.p.tex deleted file mode 100644 index 97e61e91d..000000000 --- a/doc/src/CNN/cnn.p.tex +++ /dev/null @@ -1,811 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% -% #ifdef PTEX2TEX_EXPLANATION -%% -%% The file follows the ptex2tex extended LaTeX format, see -%% ptex2tex: http://code.google.com/p/ptex2tex/ -%% -%% Run -%% ptex2tex myfile -%% or -%% doconce ptex2tex myfile -%% -%% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex. -%% (The ptex2tex program: http://code.google.com/p/ptex2tex) -%% Many preprocess options can be added to ptex2tex or doconce ptex2tex -%% -%% ptex2tex -DMINTED myfile -%% doconce ptex2tex myfile envir=minted -%% -%% ptex2tex will typeset code environments according to a global or local -%% .ptex2tex.cfg configure file. doconce ptex2tex will typeset code -%% according to options on the command line (just type doconce ptex2tex to -%% see examples). If doconce ptex2tex has envir=minted, it enables the -%% minted style without needing -DMINTED. -% #endif - -% #define PREAMBLE - -% #ifdef PREAMBLE -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{ptex2tex} -% #ifdef MINTED -\usepackage{minted} -\usemintedstyle{default} -% #endif - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% Tricks for having figures close to where they are defined: -% 1. define less restrictive rules for where to put figures -\setcounter{topnumber}{2} -\setcounter{bottomnumber}{2} -\setcounter{totalnumber}{4} -\renewcommand{\topfraction}{0.95} -\renewcommand{\bottomfraction}{0.95} -\renewcommand{\textfraction}{0} -\renewcommand{\floatpagefraction}{0.75} -% floatpagefraction must always be less than topfraction! -% 2. ensure all figures are flushed before next section -\usepackage[section]{placeins} -% 3. enable begin{figure}[H] (often leads to ugly pagebreaks) -%\usepackage{float}\restylefloat{figure} - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE -% #endif - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Convolutional Neural Networks -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Oct 3, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection{Convolutional Neural Networks (recognizing images)} - -Convolutional Neural Networks (CNN) are very similar to ordinary Neural Networks. - -They are made up of neurons that have learnable weights and -biases. Each neuron receives some inputs, performs a dot product and -optionally follows it with a non-linearity. The whole network still -expresses a single differentiable score function: from the raw image -pixels on one end to class scores at the other. And they still have a -loss function (for example Softmax) on the last (fully-connected) layer -and all the tips/tricks we developed for learning regular Neural -Networks still apply (back propagation, gradient descent etc etc). - -What is the difference? \textbf{CNN architectures make the explicit assumption that -the inputs are images, which allows us to encode certain properties -into the architecture. These then make the forward function more -efficient to implement and vastly reduce the amount of parameters in -the network.} - -Here we provide only a superficial overview, for the more interested, we recommend highly the course -\href{{https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html}}{IN5400 – Machine Learning for Image Analysis} -and the slides of \href{{http://cs231n.github.io/convolutional-networks/}}{CS231}. - -% !split -\subsection{Regular NNs don’t scale well to full images} - -As an example, consider -an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a -single fully-connected neuron in a first hidden layer of a regular -Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still -seems manageable, but clearly this fully-connected structure does not -scale to larger images. For example, an image of more respectable -size, say $200\times 200\times 3$, would lead to neurons that have -$200\times 200\times 3 = 120,000$ weights. - -We could have -several such neurons, and the parameters would add up quickly! Clearly, -this full connectivity is wasteful and the huge number of parameters -would quickly lead to possible overfitting. - - -\begin{figure}[!ht] % - \centerline{\includegraphics[width=0.6\linewidth]{figslides/nn.jpeg}} - \caption{ - A regular 3-layer Neural Network. - } -\end{figure} -%\clearpage % flush figures - - -% !split -\subsection{3D volumes of neurons} - -Convolutional Neural Networks take advantage of the fact that the -input consists of images and they constrain the architecture in a more -sensible way. - -In particular, unlike a regular Neural Network, the -layers of a CNN have neurons arranged in 3 dimensions: width, -height, depth. (Note that the word depth here refers to the third -dimension of an activation volume, not to the depth of a full Neural -Network, which can refer to the total number of layers in a network.) - -To understand it better, the above example of an image -with an input volume of -activations has dimensions $32\times 32\times 3$ (width, height, -depth respectively). - -The neurons in a layer will -only be connected to a small region of the layer before it, instead of -all of the neurons in a fully-connected manner. Moreover, the final -output layer could for this specific image have dimensions $1\times 1 \times 10$, -because by the -end of the CNN architecture we will reduce the full image into a -single vector of class scores, arranged along the depth -dimension. - - -\begin{figure}[!ht] % - \centerline{\includegraphics[width=0.6\linewidth]{figslides/cnn.jpeg}} - \caption{ - 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). - } -\end{figure} -%\clearpage % flush figures - - - - -% !split -\subsection{Layers used to build CNNs} - - -A simple CNN is a sequence of layers, and every layer of a CNN -transforms one volume of activations to another through a -differentiable function. We use three main types of layers to build -CNN architectures: Convolutional Layer, Pooling Layer, and -Fully-Connected Layer (exactly as seen in regular Neural Networks). We -will stack these layers to form a full CNN architecture. - -A simple CNN for image classification could have the architecture: - -\begin{itemize} -\item \textbf{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. - -\item \textbf{CONV} (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters. - -\item \textbf{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]$). - -\item \textbf{POOL} (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$. - -\item \textbf{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. -\end{itemize} - -\noindent -% !split -\subsection{Transforming images} - -CNNs transform the original image layer by layer from the original -pixel values to the final class scores. - -Observe that some layers contain -parameters and other 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. - - -% !split -\subsection{CNNs in brief} - -In summary: - -\begin{itemize} -\item 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) - -\item There are a few distinct types of Layers (e.g.~CONV/FC/RELU/POOL are by far the most popular) - -\item Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function - -\item Each Layer may or may not have parameters (e.g.~CONV/FC do, RELU/POOL don’t) - -\item Each Layer may or may not have additional hyperparameters (e.g.~CONV/FC/POOL do, RELU doesn’t) -\end{itemize} - -\noindent -For more material on convolutional networks, we strongly recommend -the course -\href{{https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html}}{IN5400 – Machine Learning for Image Analysis} -and the slides of \href{{http://cs231n.github.io/convolutional-networks/}}{CS231} which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). \href{{http://neuralnetworksanddeeplearning.com/chap6.html}}{Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs}. - - -% !split -\subsection{CNNs in more detail, building convolutional neural networks in Tensorflow and Keras} - - -As discussed above, CNNs are neural networks built from the assumption that the inputs -to the network are 2D images. This is important because the number of features or pixels in images -grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. - -As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks -are the \textbf{convolutional} and \textbf{pooling} layers stacked in pairs between the input and the hidden layer. -In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D -matrices, typically 1 for each color dimension (Red, Green, Blue). - - -% !split -\subsection{Setting it up} - -It means that to represent the entire -dataset of images, we require a 4D matrix or \textbf{tensor}. This tensor has the dimensions: -\[ -(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . -\] - -% !split -\subsection{The MNIST dataset again} - -The MNIST dataset consists of grayscale images with a pixel size of -$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each -neuron in the first hidden layer. - -If we were to analyze images of size $128\times 128$ we would require -$128 \times 128 = 16384$ weights to each neuron. Even worse if we were -dealing with color images, as most images are, we have an image matrix -of size $128\times 128$ for each color dimension (Red, Green, Blue), -meaning 3 times the number of weights $= 49152$ are required for every -single neuron in the first hidden layer. - - -% !split -\subsection{Strong correlations} -Images typically have strong local correlations, meaning that a small -part of the image varies little from its neighboring regions. If for -example we have an image of a blue car, we can roughly assume that a -small blue part of the image is surrounded by other blue regions. - -Therefore, instead of connecting every single pixel to a neuron in the -first hidden layer, as we have previously done with deep neural -networks, we can instead connect each neuron to a small part of the -image (in all 3 RGB depth dimensions). The size of each small area is -fixed, and known as a \href{{https://en.wikipedia.org/wiki/Receptive_field}}{receptive}. - - -% !split -\subsection{Layers of a CNN} -The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. -The input image is typically a square matrix of depth 3. - -A \textbf{convolution} is performed on the image which outputs -a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as \textbf{filters}. - - -Each filter slides along the input image, taking the dot product -between each small part of the image and the filter, in all depth -dimensions. This is then passed through a non-linear function, -typically the \textbf{Rectified Linear (ReLu)} function, which serves as the -activation of the neurons in the first convolutional layer. This is -further passed through a \textbf{pooling layer}, which reduces the size of the -convolutional layer, e.g.~by taking the maximum or average across some -small regions, and this serves as input to the next convolutional -layer. - - -% !split -\subsection{Systematic reduction} - -By systematically reducing the size of the input volume, through -convolution and pooling, the network should create representations of -small parts of the input, and then from them assemble representations -of larger areas. The final pooling layer is flattened to serve as -input to a hidden layer, such that each neuron in the final pooling -layer is connected to every single neuron in the hidden layer. This -then serves as input to the output layer, e.g.~a softmax output for -classification. - - -% !split -\subsection{Prerequisites: Collect and pre-process data} -\bpycod -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -# RGB images have a depth of 3 -# our images are grayscale so they should have a depth of 1 -inputs = inputs[:,:,:,np.newaxis] - -print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# choose some random images to display -n_inputs = len(inputs) -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -\epycod - - -% !split -\subsection{Importing Keras and Tensorflow} -\bpycod -from keras.utils import to_categorical -from sklearn.model_selection import train_test_split - -# representation of labels -labels = to_categorical(labels) - -# split into train and test data -# one-liner from scikit-learn library -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) -\epycod - -% !split -\subsection{Using TensorFlow backend} - -We need to define model and architecture and choose cost function and optmizer. -\bpycid - -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}) -\epycid - -% !split -\subsection{Train the model} - -We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters. -\bpycod -epochs = 100 -batch_size = 100 -n_filters = 10 -n_neurons_connected = 50 -n_categories = 10 - -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test, - n_filters=n_filters, n_neurons_connected=n_neurons_connected, - n_categories=n_categories, epochs=epochs, batch_size=batch_size, - eta=eta, lmbd=lmbd) - CNN.fit() - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % CNN.test_accuracy) - print() - - CNN_tf[i][j] = CNN -\epycod - -% !split -\subsection{Visualizing the results} - -\bpycod -# 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_tf[i][j] - - train_accuracy[i][j] = CNN.train_accuracy - test_accuracy[i][j] = CNN.test_accuracy - - -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() -\epycod - -% !split -\subsection{Running with Keras} - -\bpycod -from keras.models import Sequential -from keras.layers.convolutional import Conv2D -from keras.layers.convolutional import MaxPooling2D -from keras.layers import Flatten -from keras.layers import Dense -from keras.regularizers import l2 -from keras.optimizers import SGD - -def create_convolutional_neural_network_keras(input_shape, receptive_field, - n_filters, n_neurons_connected, n_categories, - eta, lmbd): - model = Sequential() - model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same', - activation='relu', kernel_regularizer=l2(lmbd))) - model.add(MaxPooling2D(pool_size=(2, 2))) - model.add(Flatten()) - model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd))) - model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd))) - - sgd = SGD(lr=eta) - model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) - - return model - -epochs = 100 -batch_size = 100 -input_shape = X_train.shape[1:4] -receptive_field = 3 -n_filters = 10 -n_neurons_connected = 50 -n_categories = 10 - -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -\epycod - -% !split -\subsection{Final part} - -\bpycod -CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - CNN = create_convolutional_neural_network_keras(input_shape, receptive_field, - n_filters, n_neurons_connected, n_categories, - eta, lmbd) - CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) - scores = CNN.evaluate(X_test, Y_test) - - CNN_keras[i][j] = CNN - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % scores[1]) - print() -\epycod - -% !split -\subsection{Final visualization} - -\bccq -# 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() -\eccq - -% !split -\subsection{Fun links} - -\begin{enumerate} -\item \href{{https://arxiv.org/abs/1604.07316}}{Self-Driving cars using a convolutional neural network} - -\item \href{{https://deepdreamgenerator.com/}}{Abstract art using convolutional neural networks} -\end{enumerate} - -\noindent - -% ------------------- end of main content --------------- - -% #ifdef PREAMBLE -\end{document} -% #endif - diff --git a/doc/src/CNN/cnn.tex b/doc/src/CNN/cnn.tex deleted file mode 100644 index 6fb87ff00..000000000 --- a/doc/src/CNN/cnn.tex +++ /dev/null @@ -1,781 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% - - -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{fancyvrb} % packages needed for verbatim environments -\usepackage{minted} -\usemintedstyle{default} - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% Tricks for having figures close to where they are defined: -% 1. define less restrictive rules for where to put figures -\setcounter{topnumber}{2} -\setcounter{bottomnumber}{2} -\setcounter{totalnumber}{4} -\renewcommand{\topfraction}{0.95} -\renewcommand{\bottomfraction}{0.95} -\renewcommand{\textfraction}{0} -\renewcommand{\floatpagefraction}{0.75} -% floatpagefraction must always be less than topfraction! -% 2. ensure all figures are flushed before next section -\usepackage[section]{placeins} -% 3. enable begin{figure}[H] (often leads to ugly pagebreaks) -%\usepackage{float}\restylefloat{figure} - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Convolutional Neural Networks -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Oct 3, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection*{Convolutional Neural Networks (recognizing images)} - -Convolutional Neural Networks (CNN) are very similar to ordinary Neural Networks. - -They are made up of neurons that have learnable weights and -biases. Each neuron receives some inputs, performs a dot product and -optionally follows it with a non-linearity. The whole network still -expresses a single differentiable score function: from the raw image -pixels on one end to class scores at the other. And they still have a -loss function (for example Softmax) on the last (fully-connected) layer -and all the tips/tricks we developed for learning regular Neural -Networks still apply (back propagation, gradient descent etc etc). - -What is the difference? \textbf{CNN architectures make the explicit assumption that -the inputs are images, which allows us to encode certain properties -into the architecture. These then make the forward function more -efficient to implement and vastly reduce the amount of parameters in -the network.} - -Here we provide only a superficial overview, for the more interested, we recommend highly the course -\href{{https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html}}{IN5400 – Machine Learning for Image Analysis} -and the slides of \href{{http://cs231n.github.io/convolutional-networks/}}{CS231}. - -% !split -\subsection*{Regular NNs don’t scale well to full images} - -As an example, consider -an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a -single fully-connected neuron in a first hidden layer of a regular -Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still -seems manageable, but clearly this fully-connected structure does not -scale to larger images. For example, an image of more respectable -size, say $200\times 200\times 3$, would lead to neurons that have -$200\times 200\times 3 = 120,000$ weights. - -We could have -several such neurons, and the parameters would add up quickly! Clearly, -this full connectivity is wasteful and the huge number of parameters -would quickly lead to possible overfitting. - - -\begin{figure}[!ht] % - \centerline{\includegraphics[width=0.6\linewidth]{figslides/nn.jpeg}} - \caption{ - A regular 3-layer Neural Network. - } -\end{figure} -%\clearpage % flush figures - - -% !split -\subsection*{3D volumes of neurons} - -Convolutional Neural Networks take advantage of the fact that the -input consists of images and they constrain the architecture in a more -sensible way. - -In particular, unlike a regular Neural Network, the -layers of a CNN have neurons arranged in 3 dimensions: width, -height, depth. (Note that the word depth here refers to the third -dimension of an activation volume, not to the depth of a full Neural -Network, which can refer to the total number of layers in a network.) - -To understand it better, the above example of an image -with an input volume of -activations has dimensions $32\times 32\times 3$ (width, height, -depth respectively). - -The neurons in a layer will -only be connected to a small region of the layer before it, instead of -all of the neurons in a fully-connected manner. Moreover, the final -output layer could for this specific image have dimensions $1\times 1 \times 10$, -because by the -end of the CNN architecture we will reduce the full image into a -single vector of class scores, arranged along the depth -dimension. - - -\begin{figure}[!ht] % - \centerline{\includegraphics[width=0.6\linewidth]{figslides/cnn.jpeg}} - \caption{ - 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). - } -\end{figure} -%\clearpage % flush figures - - - - -% !split -\subsection*{Layers used to build CNNs} - - -A simple CNN is a sequence of layers, and every layer of a CNN -transforms one volume of activations to another through a -differentiable function. We use three main types of layers to build -CNN architectures: Convolutional Layer, Pooling Layer, and -Fully-Connected Layer (exactly as seen in regular Neural Networks). We -will stack these layers to form a full CNN architecture. - -A simple CNN for image classification could have the architecture: - -\begin{itemize} -\item \textbf{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. - -\item \textbf{CONV} (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters. - -\item \textbf{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]$). - -\item \textbf{POOL} (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$. - -\item \textbf{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. -\end{itemize} - -\noindent -% !split -\subsection*{Transforming images} - -CNNs transform the original image layer by layer from the original -pixel values to the final class scores. - -Observe that some layers contain -parameters and other 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. - - -% !split -\subsection*{CNNs in brief} - -In summary: - -\begin{itemize} -\item 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) - -\item There are a few distinct types of Layers (e.g.~CONV/FC/RELU/POOL are by far the most popular) - -\item Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function - -\item Each Layer may or may not have parameters (e.g.~CONV/FC do, RELU/POOL don’t) - -\item Each Layer may or may not have additional hyperparameters (e.g.~CONV/FC/POOL do, RELU doesn’t) -\end{itemize} - -\noindent -For more material on convolutional networks, we strongly recommend -the course -\href{{https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html}}{IN5400 – Machine Learning for Image Analysis} -and the slides of \href{{http://cs231n.github.io/convolutional-networks/}}{CS231} which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). \href{{http://neuralnetworksanddeeplearning.com/chap6.html}}{Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs}. - - -% !split -\subsection*{CNNs in more detail, building convolutional neural networks in Tensorflow and Keras} - - -As discussed above, CNNs are neural networks built from the assumption that the inputs -to the network are 2D images. This is important because the number of features or pixels in images -grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. - -As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks -are the \textbf{convolutional} and \textbf{pooling} layers stacked in pairs between the input and the hidden layer. -In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D -matrices, typically 1 for each color dimension (Red, Green, Blue). - - -% !split -\subsection*{Setting it up} - -It means that to represent the entire -dataset of images, we require a 4D matrix or \textbf{tensor}. This tensor has the dimensions: -\[ -(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . -\] - -% !split -\subsection*{The MNIST dataset again} - -The MNIST dataset consists of grayscale images with a pixel size of -$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each -neuron in the first hidden layer. - -If we were to analyze images of size $128\times 128$ we would require -$128 \times 128 = 16384$ weights to each neuron. Even worse if we were -dealing with color images, as most images are, we have an image matrix -of size $128\times 128$ for each color dimension (Red, Green, Blue), -meaning 3 times the number of weights $= 49152$ are required for every -single neuron in the first hidden layer. - - -% !split -\subsection*{Strong correlations} -Images typically have strong local correlations, meaning that a small -part of the image varies little from its neighboring regions. If for -example we have an image of a blue car, we can roughly assume that a -small blue part of the image is surrounded by other blue regions. - -Therefore, instead of connecting every single pixel to a neuron in the -first hidden layer, as we have previously done with deep neural -networks, we can instead connect each neuron to a small part of the -image (in all 3 RGB depth dimensions). The size of each small area is -fixed, and known as a \href{{https://en.wikipedia.org/wiki/Receptive_field}}{receptive}. - - -% !split -\subsection*{Layers of a CNN} -The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. -The input image is typically a square matrix of depth 3. - -A \textbf{convolution} is performed on the image which outputs -a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as \textbf{filters}. - - -Each filter slides along the input image, taking the dot product -between each small part of the image and the filter, in all depth -dimensions. This is then passed through a non-linear function, -typically the \textbf{Rectified Linear (ReLu)} function, which serves as the -activation of the neurons in the first convolutional layer. This is -further passed through a \textbf{pooling layer}, which reduces the size of the -convolutional layer, e.g.~by taking the maximum or average across some -small regions, and this serves as input to the next convolutional -layer. - - -% !split -\subsection*{Systematic reduction} - -By systematically reducing the size of the input volume, through -convolution and pooling, the network should create representations of -small parts of the input, and then from them assemble representations -of larger areas. The final pooling layer is flattened to serve as -input to a hidden layer, such that each neuron in the final pooling -layer is connected to every single neuron in the hidden layer. This -then serves as input to the output layer, e.g.~a softmax output for -classification. - - -% !split -\subsection*{Prerequisites: Collect and pre-process data} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -# RGB images have a depth of 3 -# our images are grayscale so they should have a depth of 1 -inputs = inputs[:,:,:,np.newaxis] - -print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# choose some random images to display -n_inputs = len(inputs) -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -\end{minted} - - -% !split -\subsection*{Importing Keras and Tensorflow} -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from keras.utils import to_categorical -from sklearn.model_selection import train_test_split - -# representation of labels -labels = to_categorical(labels) - -# split into train and test data -# one-liner from scikit-learn library -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) -\end{minted} - -% !split -\subsection*{Using TensorFlow backend} - -We need to define model and architecture and choose cost function and optmizer. -\begin{Verbatim}[numbers=none,fontsize=\fontsize{9pt}{9pt},baselinestretch=0.95] - -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}) -\end{Verbatim} - -% !split -\subsection*{Train the model} - -We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -epochs = 100 -batch_size = 100 -n_filters = 10 -n_neurons_connected = 50 -n_categories = 10 - -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test, - n_filters=n_filters, n_neurons_connected=n_neurons_connected, - n_categories=n_categories, epochs=epochs, batch_size=batch_size, - eta=eta, lmbd=lmbd) - CNN.fit() - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % CNN.test_accuracy) - print() - - CNN_tf[i][j] = CNN -\end{minted} - -% !split -\subsection*{Visualizing the results} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# 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_tf[i][j] - - train_accuracy[i][j] = CNN.train_accuracy - test_accuracy[i][j] = CNN.test_accuracy - - -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() -\end{minted} - -% !split -\subsection*{Running with Keras} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from keras.models import Sequential -from keras.layers.convolutional import Conv2D -from keras.layers.convolutional import MaxPooling2D -from keras.layers import Flatten -from keras.layers import Dense -from keras.regularizers import l2 -from keras.optimizers import SGD - -def create_convolutional_neural_network_keras(input_shape, receptive_field, - n_filters, n_neurons_connected, n_categories, - eta, lmbd): - model = Sequential() - model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same', - activation='relu', kernel_regularizer=l2(lmbd))) - model.add(MaxPooling2D(pool_size=(2, 2))) - model.add(Flatten()) - model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd))) - model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd))) - - sgd = SGD(lr=eta) - model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) - - return model - -epochs = 100 -batch_size = 100 -input_shape = X_train.shape[1:4] -receptive_field = 3 -n_filters = 10 -n_neurons_connected = 50 -n_categories = 10 - -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -\end{minted} - -% !split -\subsection*{Final part} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - CNN = create_convolutional_neural_network_keras(input_shape, receptive_field, - n_filters, n_neurons_connected, n_categories, - eta, lmbd) - CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) - scores = CNN.evaluate(X_test, Y_test) - - CNN_keras[i][j] = CNN - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % scores[1]) - print() -\end{minted} - -% !split -\subsection*{Final visualization} - -\begin{Verbatim}[numbers=none,fontsize=\fontsize{9pt}{9pt},baselinestretch=0.95] -# 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() -\end{Verbatim} - -% !split -\subsection*{Fun links} - -\begin{enumerate} -\item \href{{https://arxiv.org/abs/1604.07316}}{Self-Driving cars using a convolutional neural network} - -\item \href{{https://deepdreamgenerator.com/}}{Abstract art using convolutional neural networks} -\end{enumerate} - -\noindent - -% ------------------- end of main content --------------- - -\end{document} - diff --git a/doc/src/NeuralNet/NeuralNet.do.txt b/doc/src/NeuralNet/NeuralNet.do.txt index e7eb11109..0403336ce 100644 --- a/doc/src/NeuralNet/NeuralNet.do.txt +++ b/doc/src/NeuralNet/NeuralNet.do.txt @@ -1054,7 +1054,7 @@ The MNIST dataset consists of 70 000 images of size $28\times 28$ pixels, each l 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. To feed data into a feed-forward neural network we need to represent -the inputs as a feature matrix $X = (n_{inputs}, n_{features})$. Each +the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each row represents an *input*, in this case a handwritten digit, and each column represents a *feature*, in this case a pixel. The correct answers, also known as *labels* or *targets* are @@ -1063,7 +1063,7 @@ $Y = (n_{inputs}) = (5, 3, 1, 8,...)$. As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: $$ X = \begin{bmatrix} 1.85 & 81\\ @@ -1079,7 +1079,7 @@ $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ Since each input image is a 2D matrix, we need to flatten the image (i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -feature matrix. This means we lose all spatial information in the +design/feature matrix. This means we lose all spatial information in the image, such as locality and translational invariance. More complicated architectures such as Convolutional Neural Networks can take advantage of such information, and are most commonly applied when analyzing @@ -1430,9 +1430,9 @@ reduces *overfitting*. We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ i.e. we sum up all the weights squared. The factor $\lambda$ is known as a regularization parameter.