Files
FYS-STK4155/doc/pub/cnn/ipynb/cnn.ipynb
T
2019-12-16 11:59:00 +01:00

739 lines
32 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- dom:TITLE: Convolutional Neural Networks -->\n",
"# Convolutional Neural Networks\n",
"<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->\n",
"<!-- Author: --> \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
"Date: **Dec 16, 2019**\n",
"\n",
"Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Convolutional Neural Networks (recognizing images)\n",
"\n",
"\n",
"Convolutional neural networks (CNNs) were developed during the last\n",
"decade of the previous century, with a focus on character recognition\n",
"tasks. Nowadays, CNNs are a central element in the spectacular success\n",
"of dee learning methods. The success in for example image\n",
"classifications have made them a central tool for most machine\n",
"learning practitioners.\n",
"\n",
"CNNs are very similar to ordinary Neural Networks.\n",
"They are made up of neurons that have learnable weights and\n",
"biases. Each neuron receives some inputs, performs a dot product and\n",
"optionally follows it with a non-linearity. The whole network still\n",
"expresses a single differentiable score function: from the raw image\n",
"pixels on one end to class scores at the other. And they still have a\n",
"loss function (for example Softmax) on the last (fully-connected) layer\n",
"and all the tips/tricks we developed for learning regular Neural\n",
"Networks still apply (back propagation, gradient descent etc etc).\n",
"\n",
"What is the difference? **CNN architectures make the explicit assumption that\n",
"the inputs are images, which allows us to encode certain properties\n",
"into the architecture. These then make the forward function more\n",
"efficient to implement and vastly reduce the amount of parameters in\n",
"the network.**\n",
"\n",
"Here we provide only a superficial overview, for the more interested, we recommend highly the course\n",
"[IN5400 Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
"and the slides of [CS231](http://cs231n.github.io/convolutional-networks/).\n",
"\n",
"Another good read is the article here <https://arxiv.org/pdf/1603.07285.pdf>. \n",
"\n",
"## Regular NNs dont scale well to full images\n",
"\n",
"As an example, consider\n",
"an image of size $32\\times 32\\times 3$ (32 wide, 32 high, 3 color channels), so a\n",
"single fully-connected neuron in a first hidden layer of a regular\n",
"Neural Network would have $32\\times 32\\times 3 = 3072$ weights. This amount still\n",
"seems manageable, but clearly this fully-connected structure does not\n",
"scale to larger images. For example, an image of more respectable\n",
"size, say $200\\times 200\\times 3$, would lead to neurons that have \n",
"$200\\times 200\\times 3 = 120,000$ weights. \n",
"\n",
"We could have\n",
"several such neurons, and the parameters would add up quickly! Clearly,\n",
"this full connectivity is wasteful and the huge number of parameters\n",
"would quickly lead to possible overfitting.\n",
"\n",
"<!-- dom:FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network. -->\n",
"<!-- begin figure -->\n",
"\n",
"<p>A regular 3-layer Neural Network.</p>\n",
"<img src=\"figslides/nn.jpeg\" width=500>\n",
"\n",
"<!-- end figure -->\n",
"\n",
"\n",
"## 3D volumes of neurons\n",
"\n",
"Convolutional Neural Networks take advantage of the fact that the\n",
"input consists of images and they constrain the architecture in a more\n",
"sensible way. \n",
"\n",
"In particular, unlike a regular Neural Network, the\n",
"layers of a CNN have neurons arranged in 3 dimensions: width,\n",
"height, depth. (Note that the word depth here refers to the third\n",
"dimension of an activation volume, not to the depth of a full Neural\n",
"Network, which can refer to the total number of layers in a network.)\n",
"\n",
"To understand it better, the above example of an image \n",
"with an input volume of\n",
"activations has dimensions $32\\times 32\\times 3$ (width, height,\n",
"depth respectively). \n",
"\n",
"The neurons in a layer will\n",
"only be connected to a small region of the layer before it, instead of\n",
"all of the neurons in a fully-connected manner. Moreover, the final\n",
"output layer could for this specific image have dimensions $1\\times 1 \\times 10$, \n",
"because by the\n",
"end of the CNN architecture we will reduce the full image into a\n",
"single vector of class scores, arranged along the depth\n",
"dimension. \n",
"\n",
"<!-- dom:FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). -->\n",
"<!-- begin figure -->\n",
"\n",
"<p>A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).</p>\n",
"<img src=\"figslides/cnn.jpeg\" width=500>\n",
"\n",
"<!-- end figure -->\n",
"\n",
"\n",
"\n",
"\n",
"<!-- !split -->\n",
"## Layers used to build CNNs\n",
"\n",
"\n",
"A simple CNN is a sequence of layers, and every layer of a CNN\n",
"transforms one volume of activations to another through a\n",
"differentiable function. We use three main types of layers to build\n",
"CNN architectures: Convolutional Layer, Pooling Layer, and\n",
"Fully-Connected Layer (exactly as seen in regular Neural Networks). We\n",
"will stack these layers to form a full CNN architecture.\n",
"\n",
"A simple CNN for image classification could have the architecture:\n",
"\n",
"* **INPUT** ($32\\times 32 \\times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.\n",
"\n",
"* **CONV** (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\\times 32\\times 12]$ if we decided to use 12 filters.\n",
"\n",
"* **RELU** layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\\times 32\\times 12]$).\n",
"\n",
"* **POOL** (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\\times 16\\times 12]$.\n",
"\n",
"* **FC** (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\\times 1\\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.\n",
"\n",
"## Transforming images\n",
"\n",
"CNNs transform the original image layer by layer from the original\n",
"pixel values to the final class scores. \n",
"\n",
"Observe that some layers contain\n",
"parameters and other dont. In particular, the CNN layers perform\n",
"transformations that are a function of not only the activations in the\n",
"input volume, but also of the parameters (the weights and biases of\n",
"the neurons). On the other hand, the RELU/POOL layers will implement a\n",
"fixed function. The parameters in the CONV/FC layers will be trained\n",
"with gradient descent so that the class scores that the CNN computes\n",
"are consistent with the labels in the training set for each image.\n",
"\n",
"\n",
"## CNNs in brief\n",
"\n",
"In summary:\n",
"\n",
"* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)\n",
"\n",
"* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n",
"\n",
"* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n",
"\n",
"* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL dont)\n",
"\n",
"* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesnt)\n",
"\n",
"For more material on convolutional networks, we strongly recommend\n",
"the course\n",
"[IN5400 Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
"and the slides of [CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n",
"\n",
"\n",
"## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n",
"\n",
"\n",
"As discussed above, CNNs are neural networks built from the assumption that the inputs\n",
"to the network are 2D images. This is important because the number of features or pixels in images\n",
"grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n",
"\n",
"As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n",
"are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n",
"In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n",
"matrices, typically 1 for each color dimension (Red, Green, Blue). \n",
"\n",
"\n",
"## Setting it up\n",
"\n",
"It means that to represent the entire\n",
"dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The MNIST dataset again\n",
"\n",
"The MNIST dataset consists of grayscale images with a pixel size of\n",
"$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n",
"neuron in the first hidden layer.\n",
"\n",
"If we were to analyze images of size $128\\times 128$ we would require\n",
"$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n",
"dealing with color images, as most images are, we have an image matrix\n",
"of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n",
"meaning 3 times the number of weights $= 49152$ are required for every\n",
"single neuron in the first hidden layer.\n",
"\n",
"\n",
"## Strong correlations\n",
"Images typically have strong local correlations, meaning that a small\n",
"part of the image varies little from its neighboring regions. If for\n",
"example we have an image of a blue car, we can roughly assume that a\n",
"small blue part of the image is surrounded by other blue regions.\n",
"\n",
"Therefore, instead of connecting every single pixel to a neuron in the\n",
"first hidden layer, as we have previously done with deep neural\n",
"networks, we can instead connect each neuron to a small part of the\n",
"image (in all 3 RGB depth dimensions). The size of each small area is\n",
"fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).\n",
"\n",
"\n",
"<!-- !split -->\n",
"## Layers of a CNN\n",
"The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n",
"The input image is typically a square matrix of depth 3. \n",
"\n",
"A **convolution** is performed on the image which outputs\n",
"a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n",
"\n",
"\n",
"Each filter slides along the input image, taking the dot product\n",
"between each small part of the image and the filter, in all depth\n",
"dimensions. This is then passed through a non-linear function,\n",
"typically the **Rectified Linear (ReLu)** function, which serves as the\n",
"activation of the neurons in the first convolutional layer. This is\n",
"further passed through a **pooling layer**, which reduces the size of the\n",
"convolutional layer, e.g. by taking the maximum or average across some\n",
"small regions, and this serves as input to the next convolutional\n",
"layer.\n",
"\n",
"\n",
"## Systematic reduction\n",
"\n",
"By systematically reducing the size of the input volume, through\n",
"convolution and pooling, the network should create representations of\n",
"small parts of the input, and then from them assemble representations\n",
"of larger areas. The final pooling layer is flattened to serve as\n",
"input to a hidden layer, such that each neuron in the final pooling\n",
"layer is connected to every single neuron in the hidden layer. This\n",
"then serves as input to the output layer, e.g. a softmax output for\n",
"classification.\n",
"\n",
"\n",
"## Prerequisites: Collect and pre-process data"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"# import necessary packages\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn import datasets\n",
"\n",
"\n",
"# ensure the same random numbers appear every time\n",
"np.random.seed(0)\n",
"\n",
"# display images in notebook\n",
"%matplotlib inline\n",
"plt.rcParams['figure.figsize'] = (12,12)\n",
"\n",
"\n",
"# download MNIST dataset\n",
"digits = datasets.load_digits()\n",
"\n",
"# define inputs and labels\n",
"inputs = digits.images\n",
"labels = digits.target\n",
"\n",
"# RGB images have a depth of 3\n",
"# our images are grayscale so they should have a depth of 1\n",
"inputs = inputs[:,:,:,np.newaxis]\n",
"\n",
"print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n",
"print(\"labels = (n_inputs) = \" + str(labels.shape))\n",
"\n",
"\n",
"# choose some random images to display\n",
"n_inputs = len(inputs)\n",
"indices = np.arange(n_inputs)\n",
"random_indices = np.random.choice(indices, size=5)\n",
"\n",
"for i, image in enumerate(digits.images[random_indices]):\n",
" plt.subplot(1, 5, i+1)\n",
" plt.axis('off')\n",
" plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n",
" plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Importing Keras and Tensorflow"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from keras.utils import to_categorical\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"# representation of labels\n",
"labels = to_categorical(labels)\n",
"\n",
"# split into train and test data\n",
"# one-liner from scikit-learn library\n",
"train_size = 0.8\n",
"test_size = 1 - train_size\n",
"X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n",
" test_size=test_size)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using TensorFlow backend\n",
"\n",
"We need to define model and architecture and choose cost function and optmizer."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\n",
"import tensorflow as tf\n",
"\n",
"class ConvolutionalNeuralNetworkTensorflow:\n",
" def __init__(\n",
" self,\n",
" X_train,\n",
" Y_train,\n",
" X_test,\n",
" Y_test,\n",
" n_filters=10,\n",
" n_neurons_connected=50,\n",
" n_categories=10,\n",
" receptive_field=3,\n",
" stride=1,\n",
" padding=1,\n",
" epochs=10,\n",
" batch_size=100,\n",
" eta=0.1,\n",
" lmbd=0.0):\n",
" \n",
" self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')\n",
" \n",
" self.X_train = X_train\n",
" self.Y_train = Y_train\n",
" self.X_test = X_test\n",
" self.Y_test = Y_test\n",
" \n",
" self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape\n",
" \n",
" self.n_filters = n_filters\n",
" self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)\n",
" self.n_neurons_connected = n_neurons_connected\n",
" self.n_categories = n_categories\n",
" \n",
" self.receptive_field = receptive_field\n",
" self.stride = stride\n",
" self.strides = [stride, stride, stride, stride]\n",
" self.padding = padding\n",
" \n",
" self.epochs = epochs\n",
" self.batch_size = batch_size\n",
" self.iterations = self.n_inputs // self.batch_size\n",
" self.eta = eta\n",
" self.lmbd = lmbd\n",
" \n",
" self.create_placeholders()\n",
" self.create_CNN()\n",
" self.create_loss()\n",
" self.create_optimiser()\n",
" self.create_accuracy()\n",
" \n",
" def create_placeholders(self):\n",
" with tf.name_scope('data'):\n",
" self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')\n",
" self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')\n",
" \n",
" def create_CNN(self):\n",
" with tf.name_scope('CNN'):\n",
" \n",
" # Convolutional layer\n",
" self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)\n",
" b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)\n",
" z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv\n",
" a_conv = tf.nn.relu(z_conv)\n",
" \n",
" # 2x2 max pooling\n",
" a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')\n",
" \n",
" # Fully connected layer\n",
" a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])\n",
" self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)\n",
" b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)\n",
" a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)\n",
" \n",
" # Output layer\n",
" self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)\n",
" b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)\n",
" self.z_out = tf.matmul(a_fc, self.W_out) + b_out\n",
" \n",
" def create_loss(self):\n",
" with tf.name_scope('loss'):\n",
" softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))\n",
" \n",
" regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)\n",
" regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)\n",
" regularizer_loss_out = tf.nn.l2_loss(self.W_out)\n",
" regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)\n",
" \n",
" self.loss = softmax_loss + regularizer_loss\n",
"\n",
" def create_accuracy(self):\n",
" with tf.name_scope('accuracy'):\n",
" probabilities = tf.nn.softmax(self.z_out)\n",
" predictions = tf.argmax(probabilities, 1)\n",
" labels = tf.argmax(self.Y, 1)\n",
" \n",
" correct_predictions = tf.equal(predictions, labels)\n",
" correct_predictions = tf.cast(correct_predictions, tf.float32)\n",
" self.accuracy = tf.reduce_mean(correct_predictions)\n",
" \n",
" def create_optimiser(self):\n",
" with tf.name_scope('optimizer'):\n",
" self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)\n",
" \n",
" def weight_variable(self, shape, name='', dtype=tf.float32):\n",
" initial = tf.truncated_normal(shape, stddev=0.1)\n",
" return tf.Variable(initial, name=name, dtype=dtype)\n",
" \n",
" def bias_variable(self, shape, name='', dtype=tf.float32):\n",
" initial = tf.constant(0.1, shape=shape)\n",
" return tf.Variable(initial, name=name, dtype=dtype)\n",
"\n",
" def fit(self):\n",
" data_indices = np.arange(self.n_inputs)\n",
"\n",
" with tf.Session() as sess:\n",
" sess.run(tf.global_variables_initializer())\n",
" for i in range(self.epochs):\n",
" for j in range(self.iterations):\n",
" chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)\n",
" batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]\n",
" \n",
" sess.run([CNN.loss, CNN.optimizer],\n",
" feed_dict={CNN.X: batch_X,\n",
" CNN.Y: batch_Y})\n",
" accuracy = sess.run(CNN.accuracy,\n",
" feed_dict={CNN.X: batch_X,\n",
" CNN.Y: batch_Y})\n",
" step = sess.run(CNN.global_step)\n",
" \n",
" self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],\n",
" feed_dict={CNN.X: self.X_train,\n",
" CNN.Y: self.Y_train})\n",
" \n",
" self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],\n",
" feed_dict={CNN.X: self.X_test,\n",
" CNN.Y: self.Y_test})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train the model\n",
"\n",
"We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"epochs = 100\n",
"batch_size = 100\n",
"n_filters = 10\n",
"n_neurons_connected = 50\n",
"n_categories = 10\n",
"\n",
"eta_vals = np.logspace(-5, 1, 7)\n",
"lmbd_vals = np.logspace(-5, 1, 7)\n",
"CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
" \n",
"for i, eta in enumerate(eta_vals):\n",
" for j, lmbd in enumerate(lmbd_vals):\n",
" CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,\n",
" n_filters=n_filters, n_neurons_connected=n_neurons_connected,\n",
" n_categories=n_categories, epochs=epochs, batch_size=batch_size,\n",
" eta=eta, lmbd=lmbd)\n",
" CNN.fit()\n",
" \n",
" print(\"Learning rate = \", eta)\n",
" print(\"Lambda = \", lmbd)\n",
" print(\"Test accuracy: %.3f\" % CNN.test_accuracy)\n",
" print()\n",
" \n",
" CNN_tf[i][j] = CNN"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Visualizing the results"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# visual representation of grid search\n",
"# uses seaborn heatmap, could probably do this in matplotlib\n",
"import seaborn as sns\n",
"\n",
"sns.set()\n",
"\n",
"train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
"test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
"\n",
"for i in range(len(eta_vals)):\n",
" for j in range(len(lmbd_vals)):\n",
" CNN = CNN_tf[i][j]\n",
"\n",
" train_accuracy[i][j] = CNN.train_accuracy\n",
" test_accuracy[i][j] = CNN.test_accuracy\n",
"\n",
" \n",
"fig, ax = plt.subplots(figsize = (10, 10))\n",
"sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
"ax.set_title(\"Training Accuracy\")\n",
"ax.set_ylabel(\"$\\eta$\")\n",
"ax.set_xlabel(\"$\\lambda$\")\n",
"plt.show()\n",
"\n",
"fig, ax = plt.subplots(figsize = (10, 10))\n",
"sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
"ax.set_title(\"Test Accuracy\")\n",
"ax.set_ylabel(\"$\\eta$\")\n",
"ax.set_xlabel(\"$\\lambda$\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- !split -->\n",
"## Running with Keras"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from keras.models import Sequential\n",
"from keras.layers.convolutional import Conv2D\n",
"from keras.layers.convolutional import MaxPooling2D\n",
"from keras.layers import Flatten\n",
"from keras.layers import Dense\n",
"from keras.regularizers import l2\n",
"from keras.optimizers import SGD\n",
"\n",
"def create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
" n_filters, n_neurons_connected, n_categories,\n",
" eta, lmbd):\n",
" model = Sequential()\n",
" model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n",
" activation='relu', kernel_regularizer=l2(lmbd)))\n",
" model.add(MaxPooling2D(pool_size=(2, 2)))\n",
" model.add(Flatten())\n",
" model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))\n",
" model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))\n",
" \n",
" sgd = SGD(lr=eta)\n",
" model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n",
" \n",
" return model\n",
"\n",
"epochs = 100\n",
"batch_size = 100\n",
"input_shape = X_train.shape[1:4]\n",
"receptive_field = 3\n",
"n_filters = 10\n",
"n_neurons_connected = 50\n",
"n_categories = 10\n",
"\n",
"eta_vals = np.logspace(-5, 1, 7)\n",
"lmbd_vals = np.logspace(-5, 1, 7)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Final part"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
" \n",
"for i, eta in enumerate(eta_vals):\n",
" for j, lmbd in enumerate(lmbd_vals):\n",
" CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
" n_filters, n_neurons_connected, n_categories,\n",
" eta, lmbd)\n",
" CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n",
" scores = CNN.evaluate(X_test, Y_test)\n",
" \n",
" CNN_keras[i][j] = CNN\n",
" \n",
" print(\"Learning rate = \", eta)\n",
" print(\"Lambda = \", lmbd)\n",
" print(\"Test accuracy: %.3f\" % scores[1])\n",
" print()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Final visualization"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" # visual representation of grid search\n",
" # uses seaborn heatmap, could probably do this in matplotlib\n",
" import seaborn as sns\n",
" \n",
" sns.set()\n",
" \n",
" train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
" test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
" \n",
" for i in range(len(eta_vals)):\n",
" for j in range(len(lmbd_vals)):\n",
" CNN = CNN_keras[i][j]\n",
" \n",
" train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n",
" test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n",
" \n",
" \n",
" fig, ax = plt.subplots(figsize = (10, 10))\n",
" sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
" ax.set_title(\"Training Accuracy\")\n",
" ax.set_ylabel(\"$\\eta$\")\n",
" ax.set_xlabel(\"$\\lambda$\")\n",
" plt.show()\n",
" \n",
" fig, ax = plt.subplots(figsize = (10, 10))\n",
" sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
" ax.set_title(\"Test Accuracy\")\n",
" ax.set_ylabel(\"$\\eta$\")\n",
" ax.set_xlabel(\"$\\lambda$\")\n",
" plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fun links\n",
"\n",
"1. [Self-Driving cars using a convolutional neural network](https://arxiv.org/abs/1604.07316)\n",
"\n",
"2. [Abstract art using convolutional neural networks](https://deepdreamgenerator.com/)"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}