mlpractical/notebooks/03_Multiple_layer_models.ipynb
2017-10-06 14:46:19 +01:00

751 lines
44 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Multiple layer models and Activation Functions\n",
"\n",
"In this notebook we will explore network models with multiple layers of transformations. This will build upon the single-layer affine model we looked at in the previous notebook and use material covered in the [second](http://www.inf.ed.ac.uk/teaching/courses/mlp/2016/mlp02-sln.pdf) and [third](http://www.inf.ed.ac.uk/teaching/courses/mlp/2016/mlp03-mlp.pdf) lectures.\n",
"\n",
"You will need to use these models for the experiments you will be running in the first coursework so part of the aim of this lab will be to get you familiar with how to construct multiple layer models in our framework and how to train them.\n",
"\n",
"## What is a layer?\n",
"\n",
"Often when discussing (neural) network models, a network layer is taken to mean an input to output transformation of the form\n",
"\n",
"\\begin{equation}\n",
" \\boldsymbol{y} = \\boldsymbol{f}(\\mathbf{W} \\boldsymbol{x} + \\boldsymbol{b})\n",
" \\qquad\n",
" \\Leftrightarrow\n",
" \\qquad\n",
" y_k = f\\left(\\sum_{d=1}^D \\left( W_{kd} x_d \\right) + b_k \\right)\n",
"\\end{equation}\n",
"\n",
"where $\\mathbf{W}$ and $\\boldsymbol{b}$ parameterise an affine transformation as discussed in the previous notebook, and $f$ is a function applied elementwise to the result of the affine transformation. For example a common choice for $f$ is the logistic sigmoid function \n",
"\\begin{equation}\n",
" f(u) = \\frac{1}{1 + \\exp(-u)}.\n",
"\\end{equation}\n",
"\n",
"In the second lecture slides you were shown how to train a model consisting of an affine transformation followed by the elementwise logistic sigmoid using gradient descent. This was referred to as a 'sigmoid single-layer network'.\n",
"\n",
"In the previous notebook we also referred to single-layer models, where in that case the layer was an affine transformation, with you implementing the various necessary methods for the `AffineLayer` class before using an instance of that class within a `SingleLayerModel` on a regression problem. We could in that case consider the function $f$ to simply be the identity function $f(u) = u$. In the code for the labs we will however use a slightly different convention. Here we will consider the affine transformations and subsequent elementwise function $f$ to each be a separate transformation layer. \n",
"\n",
"This will mean we can combine our already implemented `AffineLayer` class with any non-linear function applied to the outputs just by implementing a layer object for the relevant non-linearity and then stacking the two layers together. An alternative would be to have our new layer objects inherit from `AffineLayer` and then call the relevant parent class methods in the child class however this would mean we need to include a lot of the same boilerplate code in every new class.\n",
"\n",
"To give a concrete example, in the `mlp.layers` module there is a definition for a `SigmoidLayer` equivalent to the following (documentation strings have been removed here for brevity)\n",
"\n",
"```python\n",
"class SigmoidLayer(Layer):\n",
"\n",
" def fprop(self, inputs):\n",
" return 1. / (1. + np.exp(-inputs))\n",
"\n",
" def bprop(self, inputs, outputs, grads_wrt_outputs):\n",
" return grads_wrt_outputs * outputs * (1. - outputs)\n",
"```\n",
"\n",
"As you can see this `SigmoidLayer` class has a very lightweight definition, defining just two key methods:\n",
"\n",
" * `fprop` which takes a batch of activations at the input to the layer and forward propagates them to produce activates at the outputs (directly equivalently to the `fprop` method you implemented for then `AffineLayer` in the previous notebook),\n",
" * `brop` which takes a batch of gradients with respect to the outputs of the layer and backward propagates them to calculate gradients with respect to the inputs of the layer (explained in more detail below).\n",
" \n",
"This `SigmoidLayer` class only implements the logistic sigmoid non-linearity transformation and so does not have any parameters. Therefore unlike `AffineLayer` it is derived directly from the base `Layer` class rather than `LayerWithParameters` and does not need to implement `grads_wrt_params` or `params` methods. \n",
"\n",
"To create a model consisting of an affine transformation followed by applying an elementwise logistic sigmoid transformation we first create a list of the two layer objects (in the order they are applied from inputs to outputs) and then use this to instantiate a new `MultipleLayerModel` object:\n",
"\n",
"```python\n",
"from mlp.layers import AffineLayer, SigmoidLayer\n",
"from mlp.models import MultipleLayerModel\n",
"\n",
"layers = [AffineLayer(input_dim, output_dim), SigmoidLayer()]\n",
"model = MultipleLayerModel(layers)\n",
"```\n",
"\n",
"Because of the modular way in which the layers are defined we can also stack an arbitrarily long sequence of layers together to produce deeper models. For instance the following would define a model consisting of three pairs of affine and logistic sigmoid transformations.\n",
"\n",
"```python\n",
"model = MultipleLayerModel([\n",
" AffineLayer(input_dim, hidden_dim), SigmoidLayer(),\n",
" AffineLayer(hidden_dim, hidden_dim), SigmoidLayer(),\n",
" AffineLayer(hidden_dim, output_dim), SigmoidLayer(),\n",
"])\n",
"```\n",
"\n",
"## Back-propagation of gradients\n",
" \n",
"To allow training models consisting of a stack of multiple layers, all layers need to implement a `bprop` method in addition to the `fprop` we encountered in the previous week. \n",
"\n",
"The `bprop` method takes gradients of an error function with respect to the *outputs* of a layer and uses these gradients to calculate gradients of the error function with respect to the *inputs* of a layer. As the inputs to a non-input layer in a multiple-layer model consist of the outputs of the previous layer, this means we can calculate the gradients of the error function with respect to the outputs of every layer in the model by iteratively propagating the gradients backwards through the layers of the model (i.e. from the last to first layer), hence the term 'back-propagation' or 'bprop' for short. A block diagram illustrating this is shown for a three layer model below.\n",
"\n",
"<img src='res/fprop-bprop-block-diagram.png' />\n",
"\n",
"For a layer with parameters, the gradients with respect to the layer outputs are required to calculate gradients with respect to the layer parameters. Therefore by combining backward propagation of gradients through the model with computing the gradients with respect to parameters in the relevant layers we can calculate gradients of the error function with respect to all of the parameters of a multiple-layer model in a very efficient manner (in fact the computational cost of computing gradients with respect to all of the parameters of the model using this method will only be a constant factor times the cost of calculating the model outputs in the forwards pass).\n",
"\n",
"We so far have abstractly talked about calculating gradients with respect to the inputs of a layer using gradients with respect to the layer outputs. More concretely we will be using the chain rule for derivatives to do this, similarly to how we used the chain rule in exercise 4 of the previous notebook to calculate gradients with respect to the parameters of an affine layer given gradients with respect to the outputs of the layer.\n",
"\n",
"In particular if our layer has a batch of $B$ vector inputs each of dimension $D$, $\\left\\lbrace \\boldsymbol{x}^{(b)} \\right\\rbrace_{b=1}^B$, and produces a batch of $B$ vector outputs each of dimension $K$, $\\left\\lbrace \\boldsymbol{y}^{(b)}\\right\\rbrace_{b=1}^B$, then we can calculate the gradient with respect to the $d^\\textrm{th}$ dimension of the $b^{\\textrm{th}}$ input given the gradients with respect to the $b^{\\textrm{th}}$ output using\n",
"\n",
"\\begin{equation}\n",
" \\frac{\\partial \\bar{E}}{\\partial x^{(b)}_d} = \n",
" \\sum_{k=1}^K \\left( \n",
" \\frac{\\partial \\bar{E}}{\\partial y^{(b)}_k} \\frac{\\partial y^{(b)}_k}{\\partial x^{(b)}_d} \n",
" \\right).\n",
"\\end{equation}\n",
"\n",
"Mathematically therefore the `bprop` method takes an array of gradients with respect to the outputs $\\frac{\\partial y^{(b)}_k}{\\partial x^{(b)}_d}$ and applies a sum-product operation with the partial derivatives of each output with respect to each input $\\frac{\\partial \\bar{E}}{\\partial y^{(b)}_k}$ to produce gradients with respect to the inputs of the layer $\\frac{\\partial \\bar{E}}{\\partial x^{(b)}_d}$.\n",
"\n",
"For the affine transformation used in the `AffineLayer` implemented last week, i.e a forwards propagation corresponding to \n",
"\n",
"\\begin{equation}\n",
" y^{(b)}_k = \\sum_{d=1}^D \\left( W_{kd} x^{(b)}_d \\right) + b_k\n",
"\\end{equation}\n",
"\n",
"then the corresponding partial derivatives of layer outputs with respect to inputs are\n",
"\n",
"\\begin{equation}\n",
" \\frac{\\partial y^{(b)}_k}{\\partial x^{(b)}_d} = W_{kd}\n",
"\\end{equation}\n",
"\n",
"and so the backwards-propagation method for the `AffineLayer` takes the following form\n",
"\n",
"\\begin{equation}\n",
" \\frac{\\partial \\bar{E}}{\\partial x^{(b)}_d} = \n",
" \\sum_{k=1}^K \\left( \\frac{\\partial \\bar{E}}{\\partial y^{(b)}_k} W_{kd} \\right).\n",
"\\end{equation}\n",
"\n",
"This can be efficiently implemented in NumPy using the `dot` function\n",
"\n",
"```python\n",
"class AffineLayer(LayerWithParameters):\n",
"\n",
" # ... [implementation of remaining methods from previous week] ...\n",
" \n",
" def bprop(self, inputs, outputs, grads_wrt_outputs):\n",
" return grads_wrt_outputs.dot(self.weights)\n",
"```\n",
"\n",
"An important special case applies when the outputs of a layer are an elementwise function of the inputs such that $y^{(b)}_k$ only depends on $x^{(b)}_d$ when $d = k$. In this case the partial derivatives $\\frac{\\partial y^{(b)}_k}{\\partial x^{(b)}_d}$ will be zero for $k \\neq d$ and so the above summation collapses to a single term, giving\n",
"\n",
"\\begin{equation}\n",
" \\frac{\\partial \\bar{E}}{\\partial x^{(b)}_d} = \n",
" \\frac{\\partial \\bar{E}}{\\partial y^{(b)}_d} \\frac{\\partial y^{(b)}_d}{\\partial x^{(b)}_d}\n",
"\\end{equation}\n",
"\n",
"i.e. to calculate the gradient with respect to the $b^{\\textrm{th}}$ input vector we just perform an elementwise multiplication of the gradient with respect to the $b^{\\textrm{th}}$ output vector with the vector of derivatives of the outputs with respect to the inputs. This case applies to the `SigmoidLayer` and to all other layers applying an elementwise function to their inputs.\n",
"\n",
"For the logistic sigmoid layer we have that\n",
"\n",
"\\begin{equation}\n",
" y^{(b)}_d = \\frac{1}{1 + \\exp(-x^{(b)}_d)}\n",
" \\qquad\n",
" \\Rightarrow\n",
" \\qquad\n",
" \\frac{\\partial y^{(b)}_d}{\\partial x^{(b)}_d} = \n",
" \\frac{\\exp(-x^{(b)}_d)}{\\left[ 1 + \\exp(-x^{(b)}_d) \\right]^2} =\n",
" y^{(b)}_d \\left[ 1 - y^{(b)}_d \\right]\n",
"\\end{equation}\n",
"\n",
"which you should now be able relate to the implementation of `SigmoidLayer.bprop` given earlier:\n",
"\n",
"```python\n",
"class SigmoidLayer(Layer):\n",
"\n",
" def fprop(self, inputs):\n",
" return 1. / (1. + np.exp(-inputs))\n",
"\n",
" def bprop(self, inputs, outputs, grads_wrt_outputs):\n",
" return grads_wrt_outputs * outputs * (1. - outputs)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1: training a softmax model on MNIST\n",
"\n",
"For this first exercise we will train a model consisting of an affine transformation plus softmax on a multiclass classification task: classifying the digit labels for handwritten digit images from the MNIST data set introduced in the first notebook.\n",
"\n",
"First run the cell below to import the necessary modules and classes and to load the MNIST data provider objects. As it takes a little while to load the MNIST data from disk into memory it is worth loading the data providers just once in a separate cell like this rather than recreating the objects for every training run.\n",
"\n",
"We are loading two data provider objects here - one corresponding to the training data set and a second to use as a *validation* data set. This is data we do not train the model on but measure the performance of the trained model on to assess its ability to *generalise* to unseen data. \n",
"\n",
"If you are in the Monday or Tuesday lab sessions you will not yet have had the lecture introducing the concepts of generalisation and validation data sets (though those doing MLPR alongside this course should already be familiar with these ideas). As you will need to report both training and validation set performances in your experiments for the first coursework assignment we are providing code here to give an example of how to do this."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import logging\n",
"from mlp.layers import AffineLayer, SoftmaxLayer, SigmoidLayer\n",
"from mlp.errors import CrossEntropyError, CrossEntropySoftmaxError\n",
"from mlp.models import SingleLayerModel, MultipleLayerModel\n",
"from mlp.initialisers import UniformInit\n",
"from mlp.learning_rules import GradientDescentLearningRule\n",
"from mlp.data_providers import MNISTDataProvider\n",
"from mlp.optimisers import Optimiser\n",
"%matplotlib inline\n",
"plt.style.use('ggplot')\n",
"\n",
"# Seed a random number generator\n",
"seed = 6102016 \n",
"rng = np.random.RandomState(seed)\n",
"\n",
"# Set up a logger object to print info about the training run to stdout\n",
"logger = logging.getLogger()\n",
"logger.setLevel(logging.INFO)\n",
"logger.handlers = [logging.StreamHandler()]\n",
"\n",
"# Create data provider objects for the MNIST data set\n",
"train_data = MNISTDataProvider('train', rng=rng)\n",
"valid_data = MNISTDataProvider('valid', rng=rng)\n",
"input_dim, output_dim = 784, 10"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To minimise replication of code and allow you to run experiments more quickly a helper function is provided below which trains a model and plots the evolution of the error and classification accuracy of the model (on both training and validation sets) over training."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def train_model_and_plot_stats(\n",
" model, error, learning_rule, train_data, valid_data, num_epochs, stats_interval):\n",
"\n",
" # As well as monitoring the error over training also monitor classification\n",
" # accuracy i.e. proportion of most-probable predicted classes being equal to targets\n",
" data_monitors={'acc': lambda y, t: (y.argmax(-1) == t.argmax(-1)).mean()}\n",
"\n",
" # Use the created objects to initialise a new Optimiser instance.\n",
" optimiser = Optimiser(\n",
" model, error, learning_rule, train_data, valid_data, data_monitors)\n",
"\n",
" # Run the optimiser for 5 epochs (full passes through the training set)\n",
" # printing statistics every epoch.\n",
" stats, keys = optimiser.train(num_epochs=num_epochs, stats_interval=stats_interval)\n",
"\n",
" # Plot the change in the validation and training set error over training.\n",
" fig_1 = plt.figure(figsize=(8, 4))\n",
" ax_1 = fig_1.add_subplot(111)\n",
" for k in ['error(train)', 'error(valid)']:\n",
" ax_1.plot(np.arange(1, stats.shape[0]) * stats_interval, \n",
" stats[1:, keys[k]], label=k)\n",
" ax_1.legend(loc=0)\n",
" ax_1.set_xlabel('Epoch number')\n",
"\n",
" # Plot the change in the validation and training set accuracy over training.\n",
" fig_2 = plt.figure(figsize=(8, 4))\n",
" ax_2 = fig_2.add_subplot(111)\n",
" for k in ['acc(train)', 'acc(valid)']:\n",
" ax_2.plot(np.arange(1, stats.shape[0]) * stats_interval, \n",
" stats[1:, keys[k]], label=k)\n",
" ax_2.legend(loc=0)\n",
" ax_2.set_xlabel('Epoch number')\n",
" \n",
" return stats, keys, fig_1, ax_1, fig_2, ax_2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Running the cell below will create a model consisting of an affine layer follower by a softmax transformation and train it on the MNIST data set by minimising the multi-class cross entropy error function using a basic gradient descent learning rule. By using the helper function defined above, at the end of training curves of the evolution of the error function and also classification accuracy of the model over the training epochs will be plotted.\n",
"\n",
"You should try running the code for various settings of the training hyperparameters defined at the beginning of the cell to get a feel for how these affect how training proceeds. You may wish to create multiple copies of the cell below to allow you to keep track of and compare the results across different hyperparameter settings."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Epoch 5: 4.1s to complete\n",
" error(train)=3.11e-01, acc(train)=9.13e-01, error(valid)=2.92e-01, acc(valid)=9.18e-01\n",
"Epoch 10: 3.8s to complete\n",
" error(train)=2.89e-01, acc(train)=9.20e-01, error(valid)=2.77e-01, acc(valid)=9.23e-01\n",
"Epoch 15: 5.1s to complete\n",
" error(train)=2.79e-01, acc(train)=9.22e-01, error(valid)=2.70e-01, acc(valid)=9.24e-01\n",
"Epoch 20: 4.0s to complete\n",
" error(train)=2.72e-01, acc(train)=9.24e-01, error(valid)=2.66e-01, acc(valid)=9.26e-01\n",
"Epoch 25: 4.1s to complete\n",
" error(train)=2.68e-01, acc(train)=9.25e-01, error(valid)=2.66e-01, acc(valid)=9.26e-01\n",
"Epoch 30: 4.8s to complete\n",
" error(train)=2.63e-01, acc(train)=9.27e-01, error(valid)=2.62e-01, acc(valid)=9.26e-01\n",
"Epoch 35: 6.0s to complete\n",
" error(train)=2.60e-01, acc(train)=9.28e-01, error(valid)=2.61e-01, acc(valid)=9.28e-01\n",
"Epoch 40: 4.4s to complete\n",
" error(train)=2.59e-01, acc(train)=9.28e-01, error(valid)=2.61e-01, acc(valid)=9.28e-01\n",
"Epoch 45: 4.3s to complete\n",
" error(train)=2.55e-01, acc(train)=9.29e-01, error(valid)=2.59e-01, acc(valid)=9.29e-01\n",
"Epoch 50: 6.6s to complete\n",
" error(train)=2.54e-01, acc(train)=9.30e-01, error(valid)=2.59e-01, acc(valid)=9.30e-01\n",
"Epoch 55: 4.0s to complete\n",
" error(train)=2.52e-01, acc(train)=9.29e-01, error(valid)=2.59e-01, acc(valid)=9.30e-01\n",
"Epoch 60: 3.9s to complete\n",
" error(train)=2.52e-01, acc(train)=9.29e-01, error(valid)=2.60e-01, acc(valid)=9.29e-01\n",
"Epoch 65: 3.9s to complete\n",
" error(train)=2.50e-01, acc(train)=9.31e-01, error(valid)=2.58e-01, acc(valid)=9.30e-01\n",
"Epoch 70: 5.1s to complete\n",
" error(train)=2.49e-01, acc(train)=9.31e-01, error(valid)=2.59e-01, acc(valid)=9.31e-01\n",
"Epoch 75: 4.8s to complete\n",
" error(train)=2.47e-01, acc(train)=9.32e-01, error(valid)=2.58e-01, acc(valid)=9.30e-01\n",
"Epoch 80: 5.1s to complete\n",
" error(train)=2.46e-01, acc(train)=9.31e-01, error(valid)=2.58e-01, acc(valid)=9.31e-01\n",
"Epoch 85: 4.2s to complete\n",
" error(train)=2.45e-01, acc(train)=9.32e-01, error(valid)=2.58e-01, acc(valid)=9.31e-01\n",
"Epoch 90: 4.8s to complete\n",
" error(train)=2.44e-01, acc(train)=9.32e-01, error(valid)=2.58e-01, acc(valid)=9.30e-01\n",
"Epoch 95: 4.4s to complete\n",
" error(train)=2.44e-01, acc(train)=9.32e-01, error(valid)=2.58e-01, acc(valid)=9.30e-01\n",
"Epoch 100: 4.2s to complete\n",
" error(train)=2.43e-01, acc(train)=9.33e-01, error(valid)=2.59e-01, acc(valid)=9.29e-01\n"
]
},
{
"ename": "ValueError",
"evalue": "too many values to unpack (expected 2)",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-3-642f4d4ba05f>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 33\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 34\u001b[0m _ = train_model_and_plot_stats(\n\u001b[0;32m---> 35\u001b[0;31m model, error, learning_rule, train_data, valid_data, num_epochs, stats_interval)\n\u001b[0m",
"\u001b[0;32m<ipython-input-2-6cae5fb8b536>\u001b[0m in \u001b[0;36mtrain_model_and_plot_stats\u001b[0;34m(model, error, learning_rule, train_data, valid_data, num_epochs, stats_interval)\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;31m# Run the optimiser for 5 epochs (full passes through the training set)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 13\u001b[0m \u001b[0;31m# printing statistics every epoch.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 14\u001b[0;31m \u001b[0mstats\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkeys\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0moptimiser\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtrain\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnum_epochs\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mnum_epochs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstats_interval\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mstats_interval\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 15\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0;31m# Plot the change in the validation and training set error over training.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mValueError\u001b[0m: too many values to unpack (expected 2)"
]
}
],
"source": [
"# Set training run hyperparameters\n",
"batch_size = 100 # number of data points in a batch\n",
"init_scale = 0.1 # scale for random parameter initialisation\n",
"learning_rate = 0.1 # learning rate for gradient descent\n",
"num_epochs = 100 # number of training epochs to perform\n",
"stats_interval = 5 # epoch interval between recording and printing stats\n",
"\n",
"# Reset random number generator and data provider states on each run\n",
"# to ensure reproducibility of results\n",
"rng.seed(seed)\n",
"train_data.reset()\n",
"valid_data.reset()\n",
"\n",
"# Alter data-provider batch size\n",
"train_data.batch_size = batch_size \n",
"valid_data.batch_size = batch_size\n",
"\n",
"# Create a parameter initialiser which will sample random uniform values\n",
"# from [-init_scale, init_scale]\n",
"param_init = UniformInit(-init_scale, init_scale, rng=rng)\n",
"\n",
"# Create affine + softmax model\n",
"model = MultipleLayerModel([\n",
" AffineLayer(input_dim, output_dim, param_init, param_init),\n",
" SoftmaxLayer()\n",
"])\n",
"\n",
"# Initialise a cross entropy error object\n",
"error = CrossEntropyError()\n",
"\n",
"# Use a basic gradient descent learning rule\n",
"learning_rule = GradientDescentLearningRule(learning_rate=learning_rate)\n",
"\n",
"_ = train_model_and_plot_stats(\n",
" model, error, learning_rule, train_data, valid_data, num_epochs, stats_interval)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Optional extra: more efficient softmax gradient evaluation\n",
"\n",
"In the lectures you were shown that for certain combinations of error function and final output layers, that the expressions for the gradients take particularly simple forms. \n",
"\n",
"In particular it can be shown that the combinations of \n",
"\n",
" * logistic sigmoid output layer and binary cross entropy error function\n",
" * softmax output layer and cross entropy error function\n",
" \n",
"lead to particularly simple forms for the gradients of the error function with respect to the inputs to the final layer. In particular for the latter softmax and cross entropy error function case we have that\n",
"\n",
"\\begin{equation}\n",
" y^{(b)}_k = \\textrm{Softmax}_k\\left(\\boldsymbol{x}^{(b)}\\right) = \\frac{\\exp(x^{(b)}_k)}{\\sum_{d=1}^D \\left\\lbrace \\exp(x^{(b)}_d) \\right\\rbrace}\n",
" \\qquad\n",
" E^{(b)} = \\textrm{CrossEntropy}\\left(\\boldsymbol{y}^{(b)},\\,\\boldsymbol{t}^{(b)}\\right) = -\\sum_{d=1}^D \\left\\lbrace t^{(b)}_d \\log(y^{(b)}_d) \\right\\rbrace\n",
"\\end{equation}\n",
"\n",
"and it can be shown (this is an instructive mathematical exercise if you want a challenge!) that\n",
"\n",
"\\begin{equation}\n",
" \\frac{\\partial E^{(b)}}{\\partial x^{(b)}_d} = y^{(b)}_d - t^{(b)}_d.\n",
"\\end{equation}\n",
"\n",
"The combination of `CrossEntropyError` and `SoftmaxLayer` used to train the model above calculate this gradient less directly by first calculating the gradient of the error with respect to the model outputs in `CrossEntropyError.grad` and then back-propagating this gradient to the inputs of the softmax layer using `SoftmaxLayer.bprop`.\n",
"\n",
"Rather than computing the gradient in two steps like this we can instead wrap the softmax transformation in to the definition of the error function and make use of the simpler gradient expression above. More explicitly we define an error function as follows\n",
"\n",
"\\begin{equation}\n",
" E^{(b)} = \\textrm{CrossEntropySoftmax}\\left(\\boldsymbol{y}^{(b)},\\,\\boldsymbol{t}^{(b)}\\right) = -\\sum_{d=1}^D \\left\\lbrace t^{(b)}_d \\log\\left[\\textrm{Softmax}_d\\left( \\boldsymbol{y}^{(b)}\\right)\\right]\\right\\rbrace\n",
"\\end{equation}\n",
"\n",
"with corresponding gradient\n",
"\n",
"\\begin{equation}\n",
" \\frac{\\partial E^{(b)}}{\\partial y^{(b)}_d} = \\textrm{Softmax}_d\\left( \\boldsymbol{y}^{(b)}\\right) - t^{(b)}_d.\n",
"\\end{equation}\n",
"\n",
"The final layer of the model will then be an affine transformation which produces unbounded output values corresponding to the logarithms of the unnormalised predicted class probabilities. An implementation of this error function is provided in `CrossEntropySoftmaxError`. The cell below sets up a model with a single affine transformation layer and trains it on MNIST using this new cost. If you run it with equivalent hyperparameters to one of your runs with the alternative formulation above you should get identical error and classification curves (other than floating point error) but with a minor improvement in training speed.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Set training run hyperparameters\n",
"batch_size = 100 # number of data points in a batch\n",
"init_scale = 0.1 # scale for random parameter initialisation\n",
"learning_rate = 0.1 # learning rate for gradient descent\n",
"num_epochs = 100 # number of training epochs to perform\n",
"stats_interval = 5 # epoch interval between recording and printing stats\n",
"\n",
"# Reset random number generator and data provider states on each run\n",
"# to ensure reproducibility of results\n",
"rng.seed(seed)\n",
"train_data.reset()\n",
"valid_data.reset()\n",
"\n",
"# Alter data-provider batch size\n",
"train_data.batch_size = batch_size \n",
"valid_data.batch_size = batch_size\n",
"\n",
"# Create a parameter initialiser which will sample random uniform values\n",
"# from [-init_scale, init_scale]\n",
"param_init = UniformInit(-init_scale, init_scale, rng=rng)\n",
"\n",
"# Create affine model (outputs are logs of unnormalised class probabilities)\n",
"model = SingleLayerModel(\n",
" AffineLayer(input_dim, output_dim, param_init, param_init)\n",
")\n",
"\n",
"# Initialise the error object\n",
"error = CrossEntropySoftmaxError()\n",
"\n",
"# Use a basic gradient descent learning rule\n",
"learning_rule = GradientDescentLearningRule(learning_rate=learning_rate)\n",
"\n",
"_ = train_model_and_plot_stats(\n",
" model, error, learning_rule, train_data, valid_data, num_epochs, stats_interval)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2: training deeper models on MNIST\n",
"\n",
"We are now going to investigate using deeper multiple-layer model archictures for the MNIST classification task. You should experiment with training models with two to five `AffineLayer` transformations interleaved with `SigmoidLayer` nonlinear transformations. Intermediate hidden layers between the input and output should have a dimension of 100. For example the `layers` definition of a model with two `AffineLayer` transformations would be\n",
"\n",
"```python\n",
"layers = [\n",
" AffineLayer(input_dim, 100),\n",
" SigmoidLayer(),\n",
" AffineLayer(100, output_dim),\n",
" SoftmaxLayer()\n",
"]\n",
"```\n",
"\n",
"If you read through the extension to the first exercise you may wish to use the `CrossEntropySoftmaxError` without the final `SoftmaxLayer`.\n",
"\n",
"Use the code from the first exercise as a starting point and start with training hyperparameters which gave reasonable performance for the shallow architecture trained previously.\n",
"\n",
"Some questions to investigate:\n",
"\n",
" * How does increasing the number of layers affect the model's performance on the training data set? And on the validation data set?\n",
" * Do deeper models seem to be harder or easier to train (e.g. in terms of ease of choosing training hyperparameters to give good final performance and/or quick convergence)?\n",
" * Do the models seem to be sensitive to the choice of the parameter initialisation range? Can you think of any reasons for why setting individual parameter initialisation scales for each `AffineLayer` in a model might be useful? Can you come up with (or find) any heuristics for setting the parameter initialisation scales?\n",
" \n",
"You do not need to come up with explanations for all of these (though if you can that's great!), they are meant as prompts to get you thinking about the various issues involved in training multiple-layer models. \n",
"\n",
"You may wish to start with shorter pilot training runs (by decreasing the number of training epochs) for each of the model architectures to get an initial idea of appropriate hyperparameter settings before doing one or two longer training runs to assess the final performance of the architectures."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Models with two affine layers"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Models with three affine layers"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Models with four affine layers"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Models with five affine layers"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 3: Hyperbolic tangent and rectified linear layers\n",
"\n",
"In the models we have been investigating so far we have been applying elementwise logistic sigmoid transformations to the outputs of intermediate (affine) layers. The logistic sigmoid is just one particular choice of an elementwise non-linearity we can use. \n",
"\n",
"As mentioned in [lecture 3](http://www.inf.ed.ac.uk/teaching/courses/mlp/2017-18/mlp03-mlp.pdf), although logistic sigmoid has some favourable properties in terms of interpretability, there are also disadvantages from a computational perspective. In particular that the gradients of the sigmoid become very close to zero (and may actually become exactly zero to a finite numerical precision) for very positive or negative inputs, and that the outputs are non-centred - they cover the interval $[0,\\,1]$ so negative outputs are never produced.\n",
"\n",
"Two alternative elementwise non-linearities which are often used in multiple layer models are the hyperbolic tangent and the rectified linear function.\n",
"\n",
"For a hyperbolic tangent (`Tanh`) layer the forward propagation corresponds to\n",
"\n",
"\\begin{equation}\n",
" y^{(b)}_k = \n",
" \\tanh\\left(x^{(b)}_k\\right) = \n",
" \\frac{\\exp\\left(x^{(b)}_k\\right) - \\exp\\left(-x^{(b)}_k\\right)}{\\exp\\left(x^{(b)}_k\\right) + \\exp\\left(-x^{(b)}_k\\right)}\n",
"\\end{equation}\n",
"\n",
"which has corresponding partial derivatives\n",
"\n",
"\\begin{equation}\n",
" \\frac{\\partial y^{(b)}_k}{\\partial x^{(b)}_d} = \n",
" \\begin{cases} \n",
" 1 - \\left(y^{(b)}_k\\right)^2 & \\quad k = d \\\\\n",
" 0 & \\quad k \\neq d\n",
" \\end{cases}.\n",
"\\end{equation}\n",
"\n",
"For a rectified linear (`Relu`) layer the forward propagation corresponds to\n",
"\n",
"\\begin{equation}\n",
" y^{(b)}_k = \n",
" \\max\\left(0,\\,x^{(b)}_k\\right)\n",
"\\end{equation}\n",
"\n",
"which has corresponding partial derivatives\n",
"\n",
"\\begin{equation}\n",
" \\frac{\\partial y^{(b)}_k}{\\partial x^{(b)}_d} = \n",
" \\begin{cases} \n",
" 1 & \\quad k = d \\quad\\textrm{and} &x^{(b)}_d > 0 \\\\\n",
" 0 & \\quad k \\neq d \\quad\\textrm{or} &x^{(b)}_d < 0\n",
" \\end{cases}.\n",
"\\end{equation}\n",
"\n",
"Using these definitions implement the `fprop` and `bprop` methods for the skeleton `TanhLayer` and `ReluLayer` class definitions below."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"from mlp.layers import Layer\n",
"\n",
"class TanhLayer(Layer):\n",
" \"\"\"Layer implementing an element-wise hyperbolic tangent transformation.\"\"\"\n",
"\n",
" def fprop(self, inputs):\n",
" \"\"\"Forward propagates activations through the layer transformation.\n",
"\n",
" For inputs `x` and outputs `y` this corresponds to `y = tanh(x)`.\n",
" \"\"\"\n",
" raise NotImplementedError('Delete this raise statement and write your code here instead.')\n",
"\n",
" def bprop(self, inputs, outputs, grads_wrt_outputs):\n",
" \"\"\"Back propagates gradients through a layer.\n",
"\n",
" Given gradients with respect to the outputs of the layer calculates the\n",
" gradients with respect to the layer inputs.\n",
" \"\"\"\n",
" raise NotImplementedError('Delete this raise statement and write your code here instead.')\n",
"\n",
" def __repr__(self):\n",
" return 'TanhLayer'\n",
" \n",
"\n",
"class ReluLayer(Layer):\n",
" \"\"\"Layer implementing an element-wise rectified linear transformation.\"\"\"\n",
"\n",
" def fprop(self, inputs):\n",
" \"\"\"Forward propagates activations through the layer transformation.\n",
"\n",
" For inputs `x` and outputs `y` this corresponds to `y = max(0, x)`.\n",
" \"\"\"\n",
" raise NotImplementedError('Delete this raise statement and write your code here instead.')\n",
"\n",
" def bprop(self, inputs, outputs, grads_wrt_outputs):\n",
" \"\"\"Back propagates gradients through a layer.\n",
"\n",
" Given gradients with respect to the outputs of the layer calculates the\n",
" gradients with respect to the layer inputs.\n",
" \"\"\"\n",
" raise NotImplementedError('Delete this raise statement and write your code here instead.')\n",
"\n",
" def __repr__(self):\n",
" return 'ReluLayer'"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"ename": "NotImplementedError",
"evalue": "Delete this raise statement and write your code here instead.",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNotImplementedError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-7-43646f1c28da>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m [-4.27819393, 0., 7.11577763]])\n\u001b[1;32m 9\u001b[0m \u001b[0mtanh_layer\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mTanhLayer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mtanh_outputs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtanh_layer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfprop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtest_inputs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 11\u001b[0m \u001b[0mall_correct\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mtanh_outputs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshape\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0mtest_tanh_outputs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m<ipython-input-6-4f7b50b779ab>\u001b[0m in \u001b[0;36mfprop\u001b[0;34m(self, inputs)\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0mFor\u001b[0m \u001b[0minputs\u001b[0m\u001b[0;31m \u001b[0m\u001b[0;31m`\u001b[0m\u001b[0mx\u001b[0m\u001b[0;31m`\u001b[0m \u001b[0;32mand\u001b[0m \u001b[0moutputs\u001b[0m\u001b[0;31m \u001b[0m\u001b[0;31m`\u001b[0m\u001b[0my\u001b[0m\u001b[0;31m`\u001b[0m \u001b[0mthis\u001b[0m \u001b[0mcorresponds\u001b[0m \u001b[0mto\u001b[0m\u001b[0;31m \u001b[0m\u001b[0;31m`\u001b[0m\u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtanh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \"\"\"\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mNotImplementedError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Delete this raise statement and write your code here instead.'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 13\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 14\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mbprop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minputs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0moutputs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mgrads_wrt_outputs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mNotImplementedError\u001b[0m: Delete this raise statement and write your code here instead."
]
}
],
"source": [
"test_inputs = np.array([[0.1, -0.2, 0.3], [-0.4, 0.5, -0.6]])\n",
"test_grads_wrt_outputs = np.array([[5., 10., -10.], [-5., 0., 10.]])\n",
"test_tanh_outputs = np.array(\n",
" [[ 0.09966799, -0.19737532, 0.29131261],\n",
" [-0.37994896, 0.46211716, -0.53704957]])\n",
"test_tanh_grads_wrt_inputs = np.array(\n",
" [[ 4.95033145, 9.61042983, -9.15136962],\n",
" [-4.27819393, 0., 7.11577763]])\n",
"tanh_layer = TanhLayer()\n",
"tanh_outputs = tanh_layer.fprop(test_inputs)\n",
"all_correct = True\n",
"if not tanh_outputs.shape == test_tanh_outputs.shape:\n",
" print('TanhLayer.fprop returned array with wrong shape.')\n",
" all_correct = False\n",
"elif not np.allclose(test_tanh_outputs, tanh_outputs):\n",
" print('TanhLayer.fprop calculated incorrect outputs.')\n",
" all_correct = False\n",
"tanh_grads_wrt_inputs = tanh_layer.bprop(\n",
" test_inputs, tanh_outputs, test_grads_wrt_outputs)\n",
"if not tanh_grads_wrt_inputs.shape == test_tanh_grads_wrt_inputs.shape:\n",
" print('TanhLayer.bprop returned array with wrong shape.')\n",
" all_correct = False\n",
"elif not np.allclose(tanh_grads_wrt_inputs, test_tanh_grads_wrt_inputs):\n",
" print('TanhLayer.bprop calculated incorrect gradients with respect to inputs.')\n",
" all_correct = False\n",
"if all_correct:\n",
" print('Outputs and gradients calculated correctly for TanhLayer.')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"test_inputs = np.array([[0.1, -0.2, 0.3], [-0.4, 0.5, -0.6]])\n",
"test_grads_wrt_outputs = np.array([[5., 10., -10.], [-5., 0., 10.]])\n",
"test_relu_outputs = np.array([[0.1, 0., 0.3], [0., 0.5, 0.]])\n",
"test_relu_grads_wrt_inputs = np.array([[5., 0., -10.], [-0., 0., 0.]])\n",
"relu_layer = ReluLayer()\n",
"relu_outputs = relu_layer.fprop(test_inputs)\n",
"all_correct = True\n",
"if not relu_outputs.shape == test_relu_outputs.shape:\n",
" print('ReluLayer.fprop returned array with wrong shape.')\n",
" all_correct = False\n",
"elif not np.allclose(test_relu_outputs, relu_outputs):\n",
" print('ReluLayer.fprop calculated incorrect outputs.')\n",
" all_correct = False\n",
"relu_grads_wrt_inputs = relu_layer.bprop(\n",
" test_inputs, relu_outputs, test_grads_wrt_outputs)\n",
"if not relu_grads_wrt_inputs.shape == test_relu_grads_wrt_inputs.shape:\n",
" print('ReluLayer.bprop returned array with wrong shape.')\n",
" all_correct = False\n",
"elif not np.allclose(relu_grads_wrt_inputs, test_relu_grads_wrt_inputs):\n",
" print('ReluLayer.bprop calculated incorrect gradients with respect to inputs.')\n",
" all_correct = False\n",
"if all_correct:\n",
" print('Outputs and gradients calculated correctly for ReluLayer.')"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.2"
}
},
"nbformat": 4,
"nbformat_minor": 1
}