1442 lines
63 KiB
Plaintext
1442 lines
63 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Convolutional Neural Networks\n",
|
||
"\n",
|
||
"\n",
|
||
"Convolutional neural networks (CNNs) were developed during the last\n",
|
||
"decade of the previous century, with a focus on character recognition\n",
|
||
"tasks. Nowadays, CNNs are a central element in the spectacular success\n",
|
||
"of deep learning methods. The success in for example image\n",
|
||
"classifications have made them a central tool for most machine\n",
|
||
"learning practitioners.\n",
|
||
"\n",
|
||
"CNNs are very similar to ordinary Neural Networks.\n",
|
||
"They are made up of neurons that have learnable weights and\n",
|
||
"biases. Each neuron receives some inputs, performs a dot product and\n",
|
||
"optionally follows it with a non-linearity. The whole network still\n",
|
||
"expresses a single differentiable score function: from the raw image\n",
|
||
"pixels on one end to class scores at the other. And they still have a\n",
|
||
"loss function (for example Softmax) on the last (fully-connected) layer\n",
|
||
"and all the tips/tricks we developed for learning regular Neural\n",
|
||
"Networks still apply (back propagation, gradient descent etc etc).\n",
|
||
"\n",
|
||
"What is the difference? **CNN architectures make the explicit assumption that\n",
|
||
"the inputs are images, which allows us to encode certain properties\n",
|
||
"into the architecture. These then make the forward function more\n",
|
||
"efficient to implement and vastly reduce the amount of parameters in\n",
|
||
"the network.**\n",
|
||
"\n",
|
||
"Here we provide only a superficial overview, for the more interested, we recommend highly the course\n",
|
||
"[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
|
||
"and the slides of [CS231](http://cs231n.github.io/convolutional-networks/).\n",
|
||
"\n",
|
||
"Another good read is the article here <https://arxiv.org/pdf/1603.07285.pdf>. \n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Neural Networks vs CNNs\n",
|
||
"\n",
|
||
"Neural networks are defined as **affine transformations**, that is \n",
|
||
"a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an\n",
|
||
"output (to which a bias vector is usually added before passing the result\n",
|
||
"through a nonlinear activation function). This is applicable to any type of input, be it an\n",
|
||
"image, a sound clip or an unordered collection of features: whatever their\n",
|
||
"dimensionality, their representation can always be flattened into a vector\n",
|
||
"before the transformation.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Why CNNS for images, sound files, medical images from CT scans etc?\n",
|
||
"\n",
|
||
"However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic\n",
|
||
"structure. More formally, they share these important properties:\n",
|
||
"* They are stored as multi-dimensional arrays (think of the pixels of a figure) .\n",
|
||
"\n",
|
||
"* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).\n",
|
||
"\n",
|
||
"* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).\n",
|
||
"\n",
|
||
"These properties are not exploited when an affine transformation is applied; in\n",
|
||
"fact, all the axes are treated in the same way and the topological information\n",
|
||
"is not taken into account. Still, taking advantage of the implicit structure of\n",
|
||
"the data may prove very handy in solving some tasks, like computer vision and\n",
|
||
"speech recognition, and in these cases it would be best to preserve it. This is\n",
|
||
"where discrete convolutions come into play.\n",
|
||
"\n",
|
||
"A discrete convolution is a linear transformation that preserves this notion of\n",
|
||
"ordering. It is sparse (only a few input units contribute to a given output\n",
|
||
"unit) and reuses parameters (the same weights are applied to multiple locations\n",
|
||
"in the input).\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Regular NNs don’t 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",
|
||
"\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",
|
||
"\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 don’t. 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",
|
||
"\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 don’t)\n",
|
||
"\n",
|
||
"* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)\n",
|
||
"\n",
|
||
"For more material on convolutional networks, we strongly recommend\n",
|
||
"the course\n",
|
||
"[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
|
||
"and the slides of [CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\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",
|
||
"\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",
|
||
"\n",
|
||
"## Strong correlations\n",
|
||
"\n",
|
||
"Images typically have strong local correlations, meaning that a small\n",
|
||
"part of the image varies little from its neighboring regions. If for\n",
|
||
"example we have an image of a blue car, we can roughly assume that a\n",
|
||
"small blue part of the image is surrounded by other blue regions.\n",
|
||
"\n",
|
||
"Therefore, instead of connecting every single pixel to a neuron in the\n",
|
||
"first hidden layer, as we have previously done with deep neural\n",
|
||
"networks, we can instead connect each neuron to a small part of the\n",
|
||
"image (in all 3 RGB depth dimensions). The size of each small area is\n",
|
||
"fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).\n",
|
||
"\n",
|
||
"\n",
|
||
"\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",
|
||
"\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",
|
||
"\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 tensorflow.keras import datasets, layers, models\n",
|
||
"from tensorflow.keras.layers import Input\n",
|
||
"from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n",
|
||
"from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n",
|
||
"from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n",
|
||
"from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n",
|
||
"from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n",
|
||
"#from tensorflow.keras import Conv2D\n",
|
||
"#from tensorflow.keras import MaxPooling2D\n",
|
||
"#from tensorflow.keras import Flatten\n",
|
||
"\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"\n",
|
||
"# representation of labels\n",
|
||
"labels = to_categorical(labels)\n",
|
||
"\n",
|
||
"# split into train and test data\n",
|
||
"# one-liner from scikit-learn library\n",
|
||
"train_size = 0.8\n",
|
||
"test_size = 1 - train_size\n",
|
||
"X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n",
|
||
" test_size=test_size)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Running with Keras"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
|
||
" n_filters, n_neurons_connected, n_categories,\n",
|
||
" eta, lmbd):\n",
|
||
" model = Sequential()\n",
|
||
" model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n",
|
||
" activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
|
||
" model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n",
|
||
" model.add(layers.Flatten())\n",
|
||
" model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
|
||
" model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))\n",
|
||
" \n",
|
||
" sgd = optimizers.SGD(lr=eta)\n",
|
||
" model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n",
|
||
" \n",
|
||
" return model\n",
|
||
"\n",
|
||
"epochs = 100\n",
|
||
"batch_size = 100\n",
|
||
"input_shape = X_train.shape[1:4]\n",
|
||
"receptive_field = 3\n",
|
||
"n_filters = 10\n",
|
||
"n_neurons_connected = 50\n",
|
||
"n_categories = 10\n",
|
||
"\n",
|
||
"eta_vals = np.logspace(-5, 1, 7)\n",
|
||
"lmbd_vals = np.logspace(-5, 1, 7)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Final part"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 4,
|
||
"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": "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_keras[i][j]\n",
|
||
"\n",
|
||
" train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n",
|
||
" test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n",
|
||
"\n",
|
||
" \n",
|
||
"fig, ax = plt.subplots(figsize = (10, 10))\n",
|
||
"sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
|
||
"ax.set_title(\"Training Accuracy\")\n",
|
||
"ax.set_ylabel(\"$\\eta$\")\n",
|
||
"ax.set_xlabel(\"$\\lambda$\")\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"fig, ax = plt.subplots(figsize = (10, 10))\n",
|
||
"sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
|
||
"ax.set_title(\"Test Accuracy\")\n",
|
||
"ax.set_ylabel(\"$\\eta$\")\n",
|
||
"ax.set_xlabel(\"$\\lambda$\")\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## The CIFAR01 data set\n",
|
||
"\n",
|
||
"The CIFAR10 dataset contains 60,000 color images in 10 classes, with\n",
|
||
"6,000 images in each class. The dataset is divided into 50,000\n",
|
||
"training images and 10,000 testing images. The classes are mutually\n",
|
||
"exclusive and there is no overlap between them."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 6,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"import tensorflow as tf\n",
|
||
"\n",
|
||
"from tensorflow.keras import datasets, layers, models\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"\n",
|
||
"# We import the data set\n",
|
||
"(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()\n",
|
||
"\n",
|
||
"# Normalize pixel values to be between 0 and 1 by dividing by 255. \n",
|
||
"train_images, test_images = train_images / 255.0, test_images / 255.0"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Verifying the data set\n",
|
||
"\n",
|
||
"To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 7,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n",
|
||
" 'dog', 'frog', 'horse', 'ship', 'truck']\n",
|
||
"\n",
|
||
"plt.figure(figsize=(10,10))\n",
|
||
"for i in range(25):\n",
|
||
" plt.subplot(5,5,i+1)\n",
|
||
" plt.xticks([])\n",
|
||
" plt.yticks([])\n",
|
||
" plt.grid(False)\n",
|
||
" plt.imshow(train_images[i], cmap=plt.cm.binary)\n",
|
||
" # The CIFAR labels happen to be arrays, \n",
|
||
" # which is why you need the extra index\n",
|
||
" plt.xlabel(class_names[train_labels[i][0]])\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Set up the model\n",
|
||
"\n",
|
||
"The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.\n",
|
||
"\n",
|
||
"As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 8,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"model = models.Sequential()\n",
|
||
"model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\n",
|
||
"model.add(layers.MaxPooling2D((2, 2)))\n",
|
||
"model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
|
||
"model.add(layers.MaxPooling2D((2, 2)))\n",
|
||
"model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
|
||
"\n",
|
||
"# Let's display the architecture of our model so far.\n",
|
||
"\n",
|
||
"model.summary()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Add Dense layers on top\n",
|
||
"\n",
|
||
"To complete our model, you will feed the last output tensor from the\n",
|
||
"convolutional base (of shape (4, 4, 64)) into one or more Dense layers\n",
|
||
"to perform classification. Dense layers take vectors as input (which\n",
|
||
"are 1D), while the current output is a 3D tensor. First, you will\n",
|
||
"flatten (or unroll) the 3D output to 1D, then add one or more Dense\n",
|
||
"layers on top. CIFAR has 10 output classes, so you use a final Dense\n",
|
||
"layer with 10 outputs and a softmax activation."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 9,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"model.add(layers.Flatten())\n",
|
||
"model.add(layers.Dense(64, activation='relu'))\n",
|
||
"model.add(layers.Dense(10))\n",
|
||
"Here's the complete architecture of our model.\n",
|
||
"\n",
|
||
"model.summary()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.\n",
|
||
"\n",
|
||
"\n",
|
||
"## Compile and train the model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 10,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"model.compile(optimizer='adam',\n",
|
||
" loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
|
||
" metrics=['accuracy'])\n",
|
||
"\n",
|
||
"history = model.fit(train_images, train_labels, epochs=10, \n",
|
||
" validation_data=(test_images, test_labels))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Finally, evaluate the model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 11,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"plt.plot(history.history['accuracy'], label='accuracy')\n",
|
||
"plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n",
|
||
"plt.xlabel('Epoch')\n",
|
||
"plt.ylabel('Accuracy')\n",
|
||
"plt.ylim([0.5, 1])\n",
|
||
"plt.legend(loc='lower right')\n",
|
||
"\n",
|
||
"test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n",
|
||
"\n",
|
||
"print(test_acc)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Recurrent neural networks: Overarching view\n",
|
||
"\n",
|
||
"Till now our focus has been, including convolutional neural networks\n",
|
||
"as well, on feedforward neural networks. The output or the activations\n",
|
||
"flow only in one direction, from the input layer to the output layer.\n",
|
||
"\n",
|
||
"A recurrent neural network (RNN) looks very much like a feedforward\n",
|
||
"neural network, except that it also has connections pointing\n",
|
||
"backward. \n",
|
||
"\n",
|
||
"RNNs are used to analyze time series data such as stock prices, and\n",
|
||
"tell you when to buy or sell. In autonomous driving systems, they can\n",
|
||
"anticipate car trajectories and help avoid accidents. More generally,\n",
|
||
"they can work on sequences of arbitrary lengths, rather than on\n",
|
||
"fixed-sized inputs like all the nets we have discussed so far. For\n",
|
||
"example, they can take sentences, documents, or audio samples as\n",
|
||
"input, making them extremely useful for natural language processing\n",
|
||
"systems such as automatic translation and speech-to-text.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Set up of an RNN\n",
|
||
"\n",
|
||
"\n",
|
||
"Text to come.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## A simple example"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 12,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Start importing packages\n",
|
||
"import pandas as pd\n",
|
||
"import numpy as np\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"import tensorflow as tf\n",
|
||
"from tensorflow.keras import datasets, layers, models\n",
|
||
"from tensorflow.keras.layers import Input\n",
|
||
"from tensorflow.keras.models import Model, Sequential \n",
|
||
"from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
|
||
"from tensorflow.keras import optimizers \n",
|
||
"from tensorflow.keras import regularizers \n",
|
||
"from tensorflow.keras.utils import to_categorical \n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"# convert into dataset matrix\n",
|
||
"def convertToMatrix(data, step):\n",
|
||
" X, Y =[], []\n",
|
||
" for i in range(len(data)-step):\n",
|
||
" d=i+step \n",
|
||
" X.append(data[i:d,])\n",
|
||
" Y.append(data[d,])\n",
|
||
" return np.array(X), np.array(Y)\n",
|
||
"\n",
|
||
"step = 4\n",
|
||
"N = 1000 \n",
|
||
"Tp = 800 \n",
|
||
"\n",
|
||
"t=np.arange(0,N)\n",
|
||
"x=np.sin(0.02*t)+2*np.random.rand(N)\n",
|
||
"df = pd.DataFrame(x)\n",
|
||
"df.head()\n",
|
||
"\n",
|
||
"plt.plot(df)\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"values=df.values\n",
|
||
"train,test = values[0:Tp,:], values[Tp:N,:]\n",
|
||
"\n",
|
||
"# add step elements into train and test\n",
|
||
"test = np.append(test,np.repeat(test[-1,],step))\n",
|
||
"train = np.append(train,np.repeat(train[-1,],step))\n",
|
||
" \n",
|
||
"trainX,trainY =convertToMatrix(train,step)\n",
|
||
"testX,testY =convertToMatrix(test,step)\n",
|
||
"trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\n",
|
||
"testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n",
|
||
"\n",
|
||
"model = Sequential()\n",
|
||
"model.add(SimpleRNN(units=32, input_shape=(1,step), activation=\"relu\"))\n",
|
||
"model.add(Dense(8, activation=\"relu\")) \n",
|
||
"model.add(Dense(1))\n",
|
||
"model.compile(loss='mean_squared_error', optimizer='rmsprop')\n",
|
||
"model.summary()\n",
|
||
"\n",
|
||
"model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)\n",
|
||
"trainPredict = model.predict(trainX)\n",
|
||
"testPredict= model.predict(testX)\n",
|
||
"predicted=np.concatenate((trainPredict,testPredict),axis=0)\n",
|
||
"\n",
|
||
"trainScore = model.evaluate(trainX, trainY, verbose=0)\n",
|
||
"print(trainScore)\n",
|
||
"\n",
|
||
"index = df.index.values\n",
|
||
"plt.plot(index,df)\n",
|
||
"plt.plot(index,predicted)\n",
|
||
"plt.axvline(df.index[Tp], c=\"r\")\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## An extrapolation example\n",
|
||
"\n",
|
||
"The following code provides an example of how recurrent neural\n",
|
||
"networks can be used to extrapolate to unknown values of physics data\n",
|
||
"sets. Specifically, the data sets used in this program come from\n",
|
||
"a quantum mechanical many-body calculation of energies as functions of the number of particles."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 13,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"\n",
|
||
"# For matrices and calculations\n",
|
||
"import numpy as np\n",
|
||
"# For machine learning (backend for keras)\n",
|
||
"import tensorflow as tf\n",
|
||
"# User-friendly machine learning library\n",
|
||
"# Front end for TensorFlow\n",
|
||
"import tensorflow.keras\n",
|
||
"# Different methods from Keras needed to create an RNN\n",
|
||
"# This is not necessary but it shortened function calls \n",
|
||
"# that need to be used in the code.\n",
|
||
"from tensorflow.keras import datasets, layers, models\n",
|
||
"from tensorflow.keras.layers import Input\n",
|
||
"from tensorflow.keras import regularizers\n",
|
||
"from tensorflow.keras.models import Model, Sequential\n",
|
||
"from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
|
||
"# For timing the code\n",
|
||
"from timeit import default_timer as timer\n",
|
||
"# For plotting\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"\n",
|
||
"\n",
|
||
"# The data set\n",
|
||
"datatype='VaryDimension'\n",
|
||
"X_tot = np.arange(2, 42, 2)\n",
|
||
"y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,\n",
|
||
"\t-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, \n",
|
||
"\t-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Formatting the Data\n",
|
||
"\n",
|
||
"The way the recurrent neural networks are trained in this program\n",
|
||
"differs from how machine learning algorithms are usually trained.\n",
|
||
"Typically a machine learning algorithm is trained by learning the\n",
|
||
"relationship between the x data and the y data. In this program, the\n",
|
||
"recurrent neural network will be trained to recognize the relationship\n",
|
||
"in a sequence of y values. This is type of data formatting is\n",
|
||
"typically used time series forcasting, but it can also be used in any\n",
|
||
"extrapolation (time series forecasting is just a specific type of\n",
|
||
"extrapolation along the time axis). This method of data formatting\n",
|
||
"does not use the x data and assumes that the y data are evenly spaced.\n",
|
||
"\n",
|
||
"For a standard machine learning algorithm, the training data has the\n",
|
||
"form of (x,y) so the machine learning algorithm learns to assiciate a\n",
|
||
"y value with a given x value. This is useful when the test data has x\n",
|
||
"values within the same range as the training data. However, for this\n",
|
||
"application, the x values of the test data are outside of the x values\n",
|
||
"of the training data and the traditional method of training a machine\n",
|
||
"learning algorithm does not work as well. For this reason, the\n",
|
||
"recurrent neural network is trained on sequences of y values of the\n",
|
||
"form ((y1, y2), y3), so that the network is concerned with learning\n",
|
||
"the pattern of the y data and not the relation between the x and y\n",
|
||
"data. As long as the pattern of y data outside of the training region\n",
|
||
"stays relatively stable compared to what was inside the training\n",
|
||
"region, this method of training can produce accurate extrapolations to\n",
|
||
"y values far removed from the training data set.\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- -->\n",
|
||
"<!-- The idea behind formatting the data in this way comes from [this resource](https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/) and [this one](https://fairyonice.github.io/Understand-Keras%27s-RNN-behind-the-scenes-with-a-sin-wave-example.html). -->\n",
|
||
"<!-- -->\n",
|
||
"<!-- The following method takes in a y data set and formats it so the \"x data\" are of the form (y1, y2) and the \"y data\" are of the form y3, with extra brackets added in to make the resulting arrays compatable with both Keras and Tensorflow. -->\n",
|
||
"<!-- -->\n",
|
||
"<!-- Note: Using a sequence length of two is not required for time series forecasting so any lenght of sequence could be used (for example instead of ((y1, y2) y3) you could change the length of sequence to be 4 and the resulting data points would have the form ((y1, y2, y3, y4), y5)). While the following method can be used to create a data set of any sequence length, the remainder of the code expects the length of sequence to be 2. This is because the data sets are very small and the higher the lenght of the sequence the less resulting data points. -->"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 14,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# FORMAT_DATA\n",
|
||
"def format_data(data, length_of_sequence = 2): \n",
|
||
" \"\"\"\n",
|
||
" Inputs:\n",
|
||
" data(a numpy array): the data that will be the inputs to the recurrent neural\n",
|
||
" network\n",
|
||
" length_of_sequence (an int): the number of elements in one iteration of the\n",
|
||
" sequence patter. For a function approximator use length_of_sequence = 2.\n",
|
||
" Returns:\n",
|
||
" rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its\n",
|
||
" dimensions are length of data - length of sequence, length of sequence, \n",
|
||
" dimnsion of data\n",
|
||
" rnn_output (a numpy array): the training data for the neural network\n",
|
||
" Formats data to be used in a recurrent neural network.\n",
|
||
" \"\"\"\n",
|
||
"\n",
|
||
" X, Y = [], []\n",
|
||
" for i in range(len(data)-length_of_sequence):\n",
|
||
" # Get the next length_of_sequence elements\n",
|
||
" a = data[i:i+length_of_sequence]\n",
|
||
" # Get the element that immediately follows that\n",
|
||
" b = data[i+length_of_sequence]\n",
|
||
" # Reshape so that each data point is contained in its own array\n",
|
||
" a = np.reshape (a, (len(a), 1))\n",
|
||
" X.append(a)\n",
|
||
" Y.append(b)\n",
|
||
" rnn_input = np.array(X)\n",
|
||
" rnn_output = np.array(Y)\n",
|
||
"\n",
|
||
" return rnn_input, rnn_output\n",
|
||
"\n",
|
||
"\n",
|
||
"# ## Defining the Recurrent Neural Network Using Keras\n",
|
||
"# \n",
|
||
"# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.\n",
|
||
"\n",
|
||
"def rnn(length_of_sequences, batch_size = None, stateful = False):\n",
|
||
" \"\"\"\n",
|
||
" Inputs:\n",
|
||
" length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
|
||
" when the data is formatted\n",
|
||
" batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
|
||
" stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
|
||
" Returns:\n",
|
||
" model (a Keras model): The recurrent neural network that is built and compiled by this\n",
|
||
" method\n",
|
||
" Builds and compiles a recurrent neural network with one hidden layer and returns the model.\n",
|
||
" \"\"\"\n",
|
||
" # Number of neurons in the input and output layers\n",
|
||
" in_out_neurons = 1\n",
|
||
" # Number of neurons in the hidden layer\n",
|
||
" hidden_neurons = 200\n",
|
||
" # Define the input layer\n",
|
||
" inp = Input(batch_shape=(batch_size, \n",
|
||
" length_of_sequences, \n",
|
||
" in_out_neurons)) \n",
|
||
" # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to \n",
|
||
" # the network immediately after the input layer\n",
|
||
" rnn = SimpleRNN(hidden_neurons, \n",
|
||
" return_sequences=False,\n",
|
||
" stateful = stateful,\n",
|
||
" name=\"RNN\")(inp)\n",
|
||
" # Define the output layer as a dense neural network layer (standard neural network layer)\n",
|
||
" #and add it to the network immediately after the hidden layer.\n",
|
||
" dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
|
||
" # Create the machine learning model starting with the input layer and ending with the \n",
|
||
" # output layer\n",
|
||
" model = Model(inputs=[inp],outputs=[dens])\n",
|
||
" # Compile the machine learning model using the mean squared error function as the loss \n",
|
||
" # function and an Adams optimizer.\n",
|
||
" model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
|
||
" return model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Predicting New Points With A Trained Recurrent Neural Network"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 15,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def test_rnn (x1, y_test, plot_min, plot_max):\n",
|
||
" \"\"\"\n",
|
||
" Inputs:\n",
|
||
" x1 (a list or numpy array): The complete x component of the data set\n",
|
||
" y_test (a list or numpy array): The complete y component of the data set\n",
|
||
" plot_min (an int or float): the smallest x value used in the training data\n",
|
||
" plot_max (an int or float): the largest x valye used in the training data\n",
|
||
" Returns:\n",
|
||
" None.\n",
|
||
" Uses a trained recurrent neural network model to predict future points in the \n",
|
||
" series. Computes the MSE of the predicted data set from the true data set, saves\n",
|
||
" the predicted data set to a csv file, and plots the predicted and true data sets w\n",
|
||
" while also displaying the data range used for training.\n",
|
||
" \"\"\"\n",
|
||
" # Add the training data as the first dim points in the predicted data array as these\n",
|
||
" # are known values.\n",
|
||
" y_pred = y_test[:dim].tolist()\n",
|
||
" # Generate the first input to the trained recurrent neural network using the last two \n",
|
||
" # points of the training data. Based on how the network was trained this means that it\n",
|
||
" # will predict the first point in the data set after the training data. All of the \n",
|
||
" # brackets are necessary for Tensorflow.\n",
|
||
" next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])\n",
|
||
" # Save the very last point in the training data set. This will be used later.\n",
|
||
" last = [y_test[dim-1]]\n",
|
||
"\n",
|
||
" # Iterate until the complete data set is created.\n",
|
||
" for i in range (dim, len(y_test)):\n",
|
||
" # Predict the next point in the data set using the previous two points.\n",
|
||
" next = model.predict(next_input)\n",
|
||
" # Append just the number of the predicted data set\n",
|
||
" y_pred.append(next[0][0])\n",
|
||
" # Create the input that will be used to predict the next data point in the data set.\n",
|
||
" next_input = np.array([[last, next[0]]], dtype=np.float64)\n",
|
||
" last = next\n",
|
||
"\n",
|
||
" # Print the mean squared error between the known data set and the predicted data set.\n",
|
||
" print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())\n",
|
||
" # Save the predicted data set as a csv file for later use\n",
|
||
" name = datatype + 'Predicted'+str(dim)+'.csv'\n",
|
||
" np.savetxt(name, y_pred, delimiter=',')\n",
|
||
" # Plot the known data set and the predicted data set. The red box represents the region that was used\n",
|
||
" # for the training data.\n",
|
||
" fig, ax = plt.subplots()\n",
|
||
" ax.plot(x1, y_test, label=\"true\", linewidth=3)\n",
|
||
" ax.plot(x1, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
|
||
" ax.legend()\n",
|
||
" # Created a red region to represent the points used in the training data.\n",
|
||
" ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')\n",
|
||
" plt.show()\n",
|
||
"\n",
|
||
"# Check to make sure the data set is complete\n",
|
||
"assert len(X_tot) == len(y_tot)\n",
|
||
"\n",
|
||
"# This is the number of points that will be used in as the training data\n",
|
||
"dim=12\n",
|
||
"\n",
|
||
"# Separate the training data from the whole data set\n",
|
||
"X_train = X_tot[:dim]\n",
|
||
"y_train = y_tot[:dim]\n",
|
||
"\n",
|
||
"\n",
|
||
"# Generate the training data for the RNN, using a sequence of 2\n",
|
||
"rnn_input, rnn_training = format_data(y_train, 2)\n",
|
||
"\n",
|
||
"\n",
|
||
"# Create a recurrent neural network in Keras and produce a summary of the \n",
|
||
"# machine learning model\n",
|
||
"model = rnn(length_of_sequences = rnn_input.shape[1])\n",
|
||
"model.summary()\n",
|
||
"\n",
|
||
"# Start the timer. Want to time training+testing\n",
|
||
"start = timer()\n",
|
||
"# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
|
||
"# validation split. Setting verbose to True prints information about each training iteration.\n",
|
||
"hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
|
||
" verbose=True,validation_split=0.05)\n",
|
||
"\n",
|
||
"for label in [\"loss\",\"val_loss\"]:\n",
|
||
" plt.plot(hist.history[label],label=label)\n",
|
||
"\n",
|
||
"plt.ylabel(\"loss\")\n",
|
||
"plt.xlabel(\"epoch\")\n",
|
||
"plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
|
||
"plt.legend()\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"# Use the trained neural network to predict more points of the data set\n",
|
||
"test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
|
||
"# Stop the timer and calculate the total time needed.\n",
|
||
"end = timer()\n",
|
||
"print('Time: ', end-start)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Other Things to Try\n",
|
||
"\n",
|
||
"\n",
|
||
"Changing the size of the recurrent neural network and its parameters\n",
|
||
"can drastically change the results you get from the model. The below\n",
|
||
"code takes the simple recurrent neural network from above and adds a\n",
|
||
"second hidden layer, changes the number of neurons in the hidden\n",
|
||
"layer, and explicitly declares the activation function of the hidden\n",
|
||
"layers to be a sigmoid function. The loss function and optimizer can\n",
|
||
"also be changed but are kept the same as the above network. These\n",
|
||
"parameters can be tuned to provide the optimal result from the\n",
|
||
"network. For some ideas on how to improve the performance of a\n",
|
||
"[recurrent neural network](https://danijar.com/tips-for-training-recurrent-neural-networks)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 16,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
|
||
" \"\"\"\n",
|
||
" Inputs:\n",
|
||
" length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
|
||
" when the data is formatted\n",
|
||
" batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
|
||
" stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
|
||
" Returns:\n",
|
||
" model (a Keras model): The recurrent neural network that is built and compiled by this\n",
|
||
" method\n",
|
||
" Builds and compiles a recurrent neural network with two hidden layers and returns the model.\n",
|
||
" \"\"\"\n",
|
||
" # Number of neurons in the input and output layers\n",
|
||
" in_out_neurons = 1\n",
|
||
" # Number of neurons in the hidden layer, increased from the first network\n",
|
||
" hidden_neurons = 500\n",
|
||
" # Define the input layer\n",
|
||
" inp = Input(batch_shape=(batch_size, \n",
|
||
" length_of_sequences, \n",
|
||
" in_out_neurons)) \n",
|
||
" # Create two hidden layers instead of one hidden layer. Explicitly set the activation\n",
|
||
" # function to be the sigmoid function (the default value is hyperbolic tangent)\n",
|
||
" rnn1 = SimpleRNN(hidden_neurons, \n",
|
||
" return_sequences=True, # This needs to be True if another hidden layer is to follow\n",
|
||
" stateful = stateful, activation = 'sigmoid',\n",
|
||
" name=\"RNN1\")(inp)\n",
|
||
" rnn2 = SimpleRNN(hidden_neurons, \n",
|
||
" return_sequences=False, activation = 'sigmoid',\n",
|
||
" stateful = stateful,\n",
|
||
" name=\"RNN2\")(rnn1)\n",
|
||
" # Define the output layer as a dense neural network layer (standard neural network layer)\n",
|
||
" #and add it to the network immediately after the hidden layer.\n",
|
||
" dens = Dense(in_out_neurons,name=\"dense\")(rnn2)\n",
|
||
" # Create the machine learning model starting with the input layer and ending with the \n",
|
||
" # output layer\n",
|
||
" model = Model(inputs=[inp],outputs=[dens])\n",
|
||
" # Compile the machine learning model using the mean squared error function as the loss \n",
|
||
" # function and an Adams optimizer.\n",
|
||
" model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
|
||
" return model\n",
|
||
"\n",
|
||
"# Check to make sure the data set is complete\n",
|
||
"assert len(X_tot) == len(y_tot)\n",
|
||
"\n",
|
||
"# This is the number of points that will be used in as the training data\n",
|
||
"dim=12\n",
|
||
"\n",
|
||
"# Separate the training data from the whole data set\n",
|
||
"X_train = X_tot[:dim]\n",
|
||
"y_train = y_tot[:dim]\n",
|
||
"\n",
|
||
"\n",
|
||
"# Generate the training data for the RNN, using a sequence of 2\n",
|
||
"rnn_input, rnn_training = format_data(y_train, 2)\n",
|
||
"\n",
|
||
"\n",
|
||
"# Create a recurrent neural network in Keras and produce a summary of the \n",
|
||
"# machine learning model\n",
|
||
"model = rnn_2layers(length_of_sequences = 2)\n",
|
||
"model.summary()\n",
|
||
"\n",
|
||
"# Start the timer. Want to time training+testing\n",
|
||
"start = timer()\n",
|
||
"# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
|
||
"# validation split. Setting verbose to True prints information about each training iteration.\n",
|
||
"hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
|
||
" verbose=True,validation_split=0.05)\n",
|
||
"\n",
|
||
"\n",
|
||
"# This section plots the training loss and the validation loss as a function of training iteration.\n",
|
||
"# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
|
||
"# being overtrained.\n",
|
||
"for label in [\"loss\",\"val_loss\"]:\n",
|
||
" plt.plot(hist.history[label],label=label)\n",
|
||
"\n",
|
||
"plt.ylabel(\"loss\")\n",
|
||
"plt.xlabel(\"epoch\")\n",
|
||
"plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
|
||
"plt.legend()\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"# Use the trained neural network to predict more points of the data set\n",
|
||
"test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
|
||
"# Stop the timer and calculate the total time needed.\n",
|
||
"end = timer()\n",
|
||
"print('Time: ', end-start)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Other Types of Recurrent Neural Networks\n",
|
||
"\n",
|
||
"Besides a simple recurrent neural network layer, there are two other\n",
|
||
"commonly used types of recurrent neural network layers: Long Short\n",
|
||
"Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short\n",
|
||
"introduction to these layers see <https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b>\n",
|
||
"and <https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b>.\n",
|
||
"\n",
|
||
"The first network created below is similar to the previous network,\n",
|
||
"but it replaces the SimpleRNN layers with LSTM layers. The second\n",
|
||
"network below has two hidden layers made up of GRUs, which are\n",
|
||
"preceeded by two dense (feeddorward) neural network layers. These\n",
|
||
"dense layers \"preprocess\" the data before it reaches the recurrent\n",
|
||
"layers. This architecture has been shown to improve the performance\n",
|
||
"of recurrent neural networks (see the link above and also\n",
|
||
"<https://arxiv.org/pdf/1807.02857.pdf>."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 17,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
|
||
" \"\"\"\n",
|
||
" Inputs:\n",
|
||
" length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
|
||
" when the data is formatted\n",
|
||
" batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
|
||
" stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
|
||
" Returns:\n",
|
||
" model (a Keras model): The recurrent neural network that is built and compiled by this\n",
|
||
" method\n",
|
||
" Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.\n",
|
||
" \"\"\"\n",
|
||
" # Number of neurons on the input/output layer and the number of neurons in the hidden layer\n",
|
||
" in_out_neurons = 1\n",
|
||
" hidden_neurons = 250\n",
|
||
" # Input Layer\n",
|
||
" inp = Input(batch_shape=(batch_size, \n",
|
||
" length_of_sequences, \n",
|
||
" in_out_neurons)) \n",
|
||
" # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)\n",
|
||
" rnn= LSTM(hidden_neurons, \n",
|
||
" return_sequences=True,\n",
|
||
" stateful = stateful,\n",
|
||
" name=\"RNN\", use_bias=True, activation='tanh')(inp)\n",
|
||
" rnn1 = LSTM(hidden_neurons, \n",
|
||
" return_sequences=False,\n",
|
||
" stateful = stateful,\n",
|
||
" name=\"RNN1\", use_bias=True, activation='tanh')(rnn)\n",
|
||
" # Output layer\n",
|
||
" dens = Dense(in_out_neurons,name=\"dense\")(rnn1)\n",
|
||
" # Define the midel\n",
|
||
" model = Model(inputs=[inp],outputs=[dens])\n",
|
||
" # Compile the model\n",
|
||
" model.compile(loss='mean_squared_error', optimizer='adam') \n",
|
||
" # Return the model\n",
|
||
" return model\n",
|
||
"\n",
|
||
"def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):\n",
|
||
" \"\"\"\n",
|
||
" Inputs:\n",
|
||
" length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
|
||
" when the data is formatted\n",
|
||
" batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
|
||
" stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
|
||
" Returns:\n",
|
||
" model (a Keras model): The recurrent neural network that is built and compiled by this\n",
|
||
" method\n",
|
||
" Builds and compiles a recurrent neural network with four hidden layers (two dense followed by\n",
|
||
" two GRU layers) and returns the model.\n",
|
||
" \"\"\" \n",
|
||
" # Number of neurons on the input/output layers and hidden layers\n",
|
||
" in_out_neurons = 1\n",
|
||
" hidden_neurons = 250\n",
|
||
" # Input layer\n",
|
||
" inp = Input(batch_shape=(batch_size, \n",
|
||
" length_of_sequences, \n",
|
||
" in_out_neurons)) \n",
|
||
" # Hidden Dense (feedforward) layers\n",
|
||
" dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)\n",
|
||
" dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)\n",
|
||
" # Hidden GRU layers\n",
|
||
" rnn1 = GRU(hidden_neurons, \n",
|
||
" return_sequences=True,\n",
|
||
" stateful = stateful,\n",
|
||
" name=\"RNN1\", use_bias=True)(dnn1)\n",
|
||
" rnn = GRU(hidden_neurons, \n",
|
||
" return_sequences=False,\n",
|
||
" stateful = stateful,\n",
|
||
" name=\"RNN\", use_bias=True)(rnn1)\n",
|
||
" # Output layer\n",
|
||
" dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
|
||
" # Define the model\n",
|
||
" model = Model(inputs=[inp],outputs=[dens])\n",
|
||
" # Compile the mdoel\n",
|
||
" model.compile(loss='mean_squared_error', optimizer='adam') \n",
|
||
" # Return the model\n",
|
||
" return model\n",
|
||
"\n",
|
||
"# Check to make sure the data set is complete\n",
|
||
"assert len(X_tot) == len(y_tot)\n",
|
||
"\n",
|
||
"# This is the number of points that will be used in as the training data\n",
|
||
"dim=12\n",
|
||
"\n",
|
||
"# Separate the training data from the whole data set\n",
|
||
"X_train = X_tot[:dim]\n",
|
||
"y_train = y_tot[:dim]\n",
|
||
"\n",
|
||
"\n",
|
||
"# Generate the training data for the RNN, using a sequence of 2\n",
|
||
"rnn_input, rnn_training = format_data(y_train, 2)\n",
|
||
"\n",
|
||
"\n",
|
||
"# Create a recurrent neural network in Keras and produce a summary of the \n",
|
||
"# machine learning model\n",
|
||
"# Change the method name to reflect which network you want to use\n",
|
||
"model = dnn2_gru2(length_of_sequences = 2)\n",
|
||
"model.summary()\n",
|
||
"\n",
|
||
"# Start the timer. Want to time training+testing\n",
|
||
"start = timer()\n",
|
||
"# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
|
||
"# validation split. Setting verbose to True prints information about each training iteration.\n",
|
||
"hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
|
||
" verbose=True,validation_split=0.05)\n",
|
||
"\n",
|
||
"\n",
|
||
"# This section plots the training loss and the validation loss as a function of training iteration.\n",
|
||
"# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
|
||
"# being overtrained.\n",
|
||
"for label in [\"loss\",\"val_loss\"]:\n",
|
||
" plt.plot(hist.history[label],label=label)\n",
|
||
"\n",
|
||
"plt.ylabel(\"loss\")\n",
|
||
"plt.xlabel(\"epoch\")\n",
|
||
"plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
|
||
"plt.legend()\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"# Use the trained neural network to predict more points of the data set\n",
|
||
"test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
|
||
"# Stop the timer and calculate the total time needed.\n",
|
||
"end = timer()\n",
|
||
"print('Time: ', end-start)\n",
|
||
"\n",
|
||
"\n",
|
||
"# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)\n",
|
||
"# \n",
|
||
"# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.\n",
|
||
"\n",
|
||
"# Check to make sure the data set is complete\n",
|
||
"assert len(X_tot) == len(y_tot)\n",
|
||
"\n",
|
||
"# This is the number of points that will be used in as the training data\n",
|
||
"dim=12\n",
|
||
"\n",
|
||
"# Separate the training data from the whole data set\n",
|
||
"X_train = X_tot[:dim]\n",
|
||
"y_train = y_tot[:dim]\n",
|
||
"\n",
|
||
"# Reshape the data for Keras specifications\n",
|
||
"X_train = X_train.reshape((dim, 1))\n",
|
||
"y_train = y_train.reshape((dim, 1))\n",
|
||
"\n",
|
||
"\n",
|
||
"# Create a recurrent neural network in Keras and produce a summary of the \n",
|
||
"# machine learning model\n",
|
||
"# Set the sequence length to 1 for regular data formatting \n",
|
||
"model = rnn(length_of_sequences = 1)\n",
|
||
"model.summary()\n",
|
||
"\n",
|
||
"# Start the timer. Want to time training+testing\n",
|
||
"start = timer()\n",
|
||
"# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
|
||
"# validation split. Setting verbose to True prints information about each training iteration.\n",
|
||
"hist = model.fit(X_train, y_train, batch_size=None, epochs=150, \n",
|
||
" verbose=True,validation_split=0.05)\n",
|
||
"\n",
|
||
"\n",
|
||
"# This section plots the training loss and the validation loss as a function of training iteration.\n",
|
||
"# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
|
||
"# being overtrained.\n",
|
||
"for label in [\"loss\",\"val_loss\"]:\n",
|
||
" plt.plot(hist.history[label],label=label)\n",
|
||
"\n",
|
||
"plt.ylabel(\"loss\")\n",
|
||
"plt.xlabel(\"epoch\")\n",
|
||
"plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
|
||
"plt.legend()\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"# Use the trained neural network to predict the remaining data points\n",
|
||
"X_pred = X_tot[dim:]\n",
|
||
"X_pred = X_pred.reshape((len(X_pred), 1))\n",
|
||
"y_model = model.predict(X_pred)\n",
|
||
"y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))\n",
|
||
"\n",
|
||
"# Plot the known data set and the predicted data set. The red box represents the region that was used\n",
|
||
"# for the training data.\n",
|
||
"fig, ax = plt.subplots()\n",
|
||
"ax.plot(X_tot, y_tot, label=\"true\", linewidth=3)\n",
|
||
"ax.plot(X_tot, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
|
||
"ax.legend()\n",
|
||
"# Created a red region to represent the points used in the training data.\n",
|
||
"ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"# Stop the timer and calculate the total time needed.\n",
|
||
"end = timer()\n",
|
||
"print('Time: ', end-start)"
|
||
]
|
||
}
|
||
],
|
||
"metadata": {},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 4
|
||
}
|