程序代写代做代考 python cache chain 02_Single_layer_models

02_Single_layer_models

$
ewcommand{vct}[1]{oldsymbol{#1}}

ewcommand{mtx}[1]{mathbf{#1}}

ewcommand{ r}{^mathrm{T}}

ewcommand{
eals}{mathbb{R}}

ewcommand{lpa}{left(}

ewcommand{
pa}{
ight)}

ewcommand{lsb}{left[}

ewcommand{
sb}{
ight]}

ewcommand{lbr}{leftlbrace}

ewcommand{
br}{
ight
brace}

ewcommand{fset}[1]{lbr #1
br}

ewcommand{pd}[2]{frac{partial #1}{partial #2}}$

Single layer models¶
In this lab we will implement a single-layer network model consisting of solely of an affine transformation of the inputs. The relevant material for this was covered in the slides of the first lecture.

We will first implement the forward propagation of inputs to the network to produce predicted outputs. We will then move on to considering how to use gradients of an error function evaluated on the outputs to compute the gradients with respect to the model parameters to allow us to perform an iterative gradient-descent training procedure. In the final exercise you will use an interactive visualisation to explore the role of some of the different hyperparameters of gradient-descent based training methods.

A note on random number generators¶
It is generally a good practice (for machine learning applications not for cryptography!) to seed a pseudo-random number generator once at the beginning of each experiment. This makes it easier to reproduce results as the same random draws will produced each time the experiment is run (e.g. the same random initialisations used for parameters). Therefore generally when we need to generate random values during this course, we will create a seeded random number generator object as we do in the cell below.

In [1]:

import numpy as np
seed = 27092016
rng = np.random.RandomState(seed)

Exercise 1: linear and affine transforms¶
Any linear transform (also called a linear map) of a finite-dimensional vector space can be parametrised by a matrix. So for example if we consider $vct{x} in
eals^{D}$ as the input space of a model with $D$ dimensional real-valued inputs, then a matrix $mtx{W} in
eals^{K imes D}$ can be used to define a prediction model consisting solely of a linear transform of the inputs

egin{equation}
vct{y} = mtx{W} vct{x}
qquad
Leftrightarrow
qquad
y_k = sum_{d=1}^D lpa W_{kd} x_d
pa quad forall k in fset{1 dots K}
end{equation}with here $vct{y} in
eals^K$ the $K$-dimensional real-valued output of the model. Geometrically we can think of a linear transform doing some combination of rotation, scaling, reflection and shearing of the input.

An affine transform consists of a linear transform plus an additional translation parameterised by a vector $vct{b} in
eals^K$. A model consisting of an affine transformation of the inputs can then be defined as

egin{equation}
vct{y} = mtx{W}vct{x} + vct{b}
qquad
Leftrightarrow
qquad
y_k = sum_{d=1}^D lpa W_{kd} x_d
pa + b_k quad forall k in fset{1 dots K}
end{equation}In machine learning we will usually refer to the matrix $mtx{W}$ as a weight matrix and the vector $vct{b}$ as a bias vector.

Generally rather than working with a single data vector $vct{x}$ we will work with batches of datapoints $fset{vct{x}^{(b)}}_{b=1}^B$. We could calculate the outputs for each input in the batch sequentially

egin{align}
vct{y}^{(1)} &= mtx{W}vct{x}^{(1)} + vct{b}\
vct{y}^{(2)} &= mtx{W}vct{x}^{(2)} + vct{b}\
dots &\
vct{y}^{(B)} &= mtx{W}vct{x}^{(B)} + vct{b}\
end{align}by looping over each input in the batch and calculating the output. However in general loops in Python are slow (particularly compared to compiled and typed languages such as C). This is due at least in part to the large overhead in dynamically inferring variable types. In general therefore wherever possible we want to avoid having loops in which such overhead will become the dominant computational cost.

For array based numerical operations, one way of overcoming this bottleneck is to vectorise operations. NumPy ndarrays are typed arrays for which operations such as basic elementwise arithmetic and linear algebra operations such as computing matrix-matrix or matrix-vector products are implemented by calls to highly-optimised compiled libraries. Therefore if you can implement code directly using NumPy operations on arrays rather than by looping over array elements it is often possible to make very substantial performance gains.

As a simple example we can consider adding up two arrays a and b and writing the result to a third array c. First lets initialise a and b with arbitrary values by running the cell below.

In [2]:

size = 1000
a = np.arange(size)
b = np.ones(size)

Now let’s time how long it takes to add up each pair of values in the two array and write the results to a third array using a loop-based implementation. We will use the %%timeit magic briefly mentioned in the previous lab notebook specifying the number of times to loop the code as 100 and to give the best of 3 repeats. Run the cell below to get a print out of the average time taken.

In [3]:

%%timeit -n 100 -r 3
c = np.empty(size)
for i in range(size):
c[i] = a[i] + b[i]

100 loops, best of 3: 2.18 ms per loop

And now we will perform the corresponding summation with the overloaded addition operator of NumPy arrays. Again run the cell below to get a print out of the average time taken.

In [4]:

%%timeit -n 100 -r 3
c = a + b

The slowest run took 4.89 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.42 µs per loop

The first loop-based implementation should have taken on the order of milliseconds ($10^{-3}$s) while the vectorised implementation should have taken on the order of microseconds ($10^{-6}$s), i.e. a $sim1000 imes$ speedup. Hopefully this simple example should make it clear why we want to vectorise operations whenever possible!

Getting back to our affine model, ideally rather than individually computing the output corresponding to each input we should compute the outputs for all inputs in a batch using a vectorised implementation. As you saw last week, data providers return batches of inputs as arrays of shape (batch_size, input_dim). In the mathematical notation used earlier we can consider this as a matrix $mtx{X}$ of dimensionality $B imes D$, and in particular

egin{equation}
mtx{X} = lsb vct{x}^{(1)} ~ vct{x}^{(2)} ~ dots ~ vct{x}^{(B)}
sb r
end{equation}i.e. the $b^{ extrm{th}}$ input vector $vct{x}^{(b)}$ corresponds to the $b^{ extrm{th}}$ row of $mtx{X}$. If we define the $B imes K$ matrix of outputs $mtx{Y}$ similarly as

egin{equation}
mtx{Y} = lsb vct{y}^{(1)} ~ vct{y}^{(2)} ~ dots ~ vct{y}^{(B)}
sb r
end{equation}then we can express the relationship between $mtx{X}$ and $mtx{Y}$ using matrix multiplication and addition as

egin{equation}
mtx{Y} = mtx{X} mtx{W} r + mtx{B}
end{equation}where $mtx{B} = lsb vct{b} ~ vct{b} ~ dots ~ vct{b}
sb r$ i.e. a $B imes K$ matrix with each row corresponding to the bias vector. The weight matrix needs to be transposed here as the inner dimensions of a matrix multiplication must match i.e. for $mtx{C} = mtx{A} mtx{B}$ then if $mtx{A}$ is of dimensionality $K imes L$ and $mtx{B}$ is of dimensionality $M imes N$ then it must be the case that $L = M$ and $mtx{C}$ will be of dimensionality $K imes N$.

The first exercise for this lab is to implement forward propagation for a single-layer model consisting of an affine transformation of the inputs in the fprop function given as skeleton code in the cell below. This should work for a batch of inputs of shape (batch_size, input_dim) producing a batch of outputs of shape (batch_size, output_dim).

You will probably want to use the NumPy dot function and broadcasting features to implement this efficiently. If you are not familiar with either / both of these you may wish to read the hints section below which gives some details on these before attempting the exercise.

In [5]:

def fprop(inputs, weights, biases):
“””Forward propagates activations through the layer transformation.

For inputs `x`, outputs `y`, weights `W` and biases `b` the layer
corresponds to `y = W x + b`.

Args:
inputs: Array of layer inputs of shape (batch_size, input_dim).
weights: Array of weight parameters of shape
(output_dim, input_dim).
biases: Array of bias parameters of shape (output_dim, ).

Returns:
outputs: Array of layer outputs of shape (batch_size, output_dim).
“””
return inputs.dot(weights.T) + biases

Once you have implemented fprop in the cell above you can test your implementation by running the cell below.

In [6]:

inputs = np.array([[0., -1., 2.], [-6., 3., 1.]])
weights = np.array([[2., -3., -1.], [-5., 7., 2.]])
biases = np.array([5., -3.])
true_outputs = np.array([[6., -6.], [-17., 50.]])

if not np.allclose(fprop(inputs, weights, biases), true_outputs):
print(‘Wrong outputs computed.’)
else:
print(‘All outputs correct!’)

All outputs correct!

Hints: Using the dot function and broadcasting¶
For those new to NumPy below are some details on the dot function and broadcasting feature of NumPy that you may want to use for implementing the first exercise. If you are already familiar with these and have already completed the first exercise you can move on straight to second exercise.

numpy.dot function¶
Matrix-matrix, matrix-vector and vector-vector (dot) products can all be computed in NumPy using the dot function. For example if A and B are both two dimensional arrays, then C = np.dot(A, B) or equivalently C = A.dot(B) will both compute the matrix product of A and B assuming A and B have compatible dimensions. Similarly if a and b are one dimensional arrays then c = np.dot(a, b) / c = a.dot(b) will compute the scalar / dot product of the two arrays. If A is a two-dimensional array and b a one-dimensional array np.dot(A, b) / A.dot(b) will compute the matrix-vector product of A and b. Examples of all three of these product types are shown in the cell below:

In [7]:

# Initiliase arrays with arbitrary values
A = np.arange(9).reshape((3, 3))
B = np.ones((3, 3)) * 2
a = np.array([-1., 0., 1.])
b = np.array([0.1, 0.2, 0.3])
print(A.dot(B)) # Matrix-matrix product
print(B.dot(A)) # Reversed product of above A.dot(B) != B.dot(A) in general
print(A.dot(b)) # Matrix-vector product
print(b.dot(A)) # Again A.dot(b) != b.dot(A) unless A is symmetric i.e. A == A.T
print(a.dot(b)) # Vector-vector scalar product

[[ 6. 6. 6.]
[ 24. 24. 24.]
[ 42. 42. 42.]]
[[ 18. 24. 30.]
[ 18. 24. 30.]
[ 18. 24. 30.]]
[ 0.8 2.6 4.4]
[ 2.4 3. 3.6]
0.2

Broadcasting¶
Another NumPy feature it will be helpful to get familiar with is broadcasting. Broadcasting allows you to apply operations to arrays of different shapes, for example to add a one-dimensional array to a two-dimensional array or multiply a multidimensional array by a scalar. The complete set of rules for broadcasting as explained in the official documentation page just linked to can sound a bit complex: you might find the visual explanation on this page more intuitive. The cell below gives a few examples:

In [8]:

# Initiliase arrays with arbitrary values
A = np.arange(6).reshape((3, 2))
b = np.array([0.1, 0.2])
c = np.array([-1., 0., 1.])
print(A + b) # Add b elementwise to all rows of A
print((A.T + c).T) # Add b elementwise to all columns of A
print(A * b) # Multiply each row of A elementise by b

[[ 0.1 1.2]
[ 2.1 3.2]
[ 4.1 5.2]]
[[-1. 0.]
[ 2. 3.]
[ 5. 6.]]
[[ 0. 0.2]
[ 0.2 0.6]
[ 0.4 1. ]]

Exercise 2: visualising random models¶

In this exercise you will use your fprop implementation to visualise the outputs of a single-layer affine transform model with two-dimensional inputs and a one-dimensional output. In this simple case we can visualise the joint input-output space on a 3D axis.

For this task and the learning experiments later in the notebook we will use a regression dataset from the UCI machine learning repository. In particular we will use a version of the Combined Cycle Power Plant dataset, where the task is to predict the energy output of a power plant given observations of the local ambient conditions (e.g. temperature, pressure and humidity).

The original dataset has four input dimensions and a single target output dimension. We have preprocessed the dataset by whitening it, a common preprocessing step. We will only use the first two dimensions of the whitened inputs (corresponding to the first two principal components of the inputs) so we can easily visualise the joint input-output space.

The dataset has been wrapped in the CCPPDataProvider class in the mlp.data_providers module and the data included as a compressed file in the data directory as ccpp_data.npz. Running the cell below will initialise an instance of this class, get a single batch of inputs and outputs and import the necessary matplotlib objects.

In [9]:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mlp.data_providers import CCPPDataProvider
%matplotlib notebook

data_provider = CCPPDataProvider(
which_set=’train’,
input_dims=[0, 1],
batch_size=5000,
max_num_batches=1,
shuffle_order=False
)

input_dim, output_dim = 2, 1

inputs, targets = data_provider.next()

Here we used the %matplotlib notebook magic command rather than the %matplotlib inline we used in the previous lab as this allows us to produce interactive 3D plots which you can rotate and zoom in/out by dragging with the mouse and scrolling the mouse-wheel respectively. Once you have finished interacting with a plot you can close it to produce a static inline plot using the button in the top-right corner.

Now run the cell below to plot the predicted outputs of a randomly initialised model across the two dimensional input space as well as the true target outputs. This sort of visualisation can be a useful method (in low dimensions) to assess how well the model is likely to be able to fit the data and to judge appropriate initialisation scales for the parameters. Each time you re-run the cell a new set of random parameters will be sampled

Some questions to consider:

How do the weights and bias initialisation scale affect the sort of predicted input-output relationships? Magnitude of weights initialisation scale determines how steep along the two input directions the plane predictions lie on is. The magnitude of the bias initialisation scale determines the typical offset of the plane from the output = 0. plane.

Does the linear form of the model seem appropriate for the data here? While it appears a linear-model will not be able to fully capture the input-output relationship evident in the data with there some degree of non-linearity seeming to be present, as a first approximation a linear model seems a reasonable choice as a simple model for the data.

In [10]:

weights_init_range = 0.5
biases_init_range = 0.1

# Randomly initialise weights matrix
weights = rng.uniform(
low=-weights_init_range,
high=weights_init_range,
size=(output_dim, input_dim)
)

# Randomly initialise biases vector
biases = rng.uniform(
low=-biases_init_range,
high=biases_init_range,
size=output_dim
)
# Calculate predicted model outputs
outputs = fprop(inputs, weights, biases)

# Plot target and predicted outputs against inputs on same axis
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection=’3d’)
ax.plot(inputs[:, 0], inputs[:, 1], targets[:, 0], ‘r.’, ms=2)
ax.plot(inputs[:, 0], inputs[:, 1], outputs[:, 0], ‘b.’, ms=2)
ax.set_xlabel(‘Input dim 1’)
ax.set_ylabel(‘Input dim 2’)
ax.set_zlabel(‘Output’)
ax.legend([‘Targets’, ‘Predictions’], frameon=False)
fig.tight_layout()

Exercise 3: computing the error function and its gradient¶
Here we will consider the task of regression as covered in the first lecture slides. The aim in a regression problem is given inputs $fset{vct{x}^{(n)}}_{n=1}^N$ to produce outputs $fset{vct{y}^{(n)}}_{n=1}^N$ that are as ‘close’ as possible to a set of target outputs $fset{vct{t}^{(n)}}_{n=1}^N$. The measure of ‘closeness’ or distance between target and predicted outputs is a design choice.

A very common choice is the squared Euclidean distance between the predicted and target outputs. This can be computed as the sum of the squared differences between each element in the target and predicted outputs. A common convention is to multiply this value by $frac{1}{2}$ as this gives a slightly nicer expression for the error gradient. The error for the $n^{ extrm{th}}$ training example is then

egin{equation}
E^{(n)} = frac{1}{2} sum_{k=1}^K lbr lpa y^{(n)}_k – t^{(n)}_k
pa^2
br.
end{equation}The overall error is then the average of this value across all training examples

egin{equation}
ar{E} = frac{1}{N} sum_{n=1}^N lbr E^{(n)}
br.
end{equation}Note here we are using a slightly different convention from the lectures. There the overall error was considered to be the sum of the individual error terms rather than the mean. To differentiate between the two we will use $ar{E}$ to represent the average error here as opposed to sum of errors $E$ as used in the slides with $ar{E} = frac{E}{N}$. Normalising by the number of training examples is helpful to do in practice as this means we can more easily compare errors across data sets / batches of different sizes, and more importantly it means the size of our gradient updates will be independent of the number of training examples summed over.

The regression problem is then to find parameters of the model which minimise $ar{E}$. For our simple single-layer affine model here that corresponds to finding weights $mtx{W}$ and biases $vct{b}$ which minimise $ar{E}$.

As mentioned in the lecture, for this simple case there is actually a closed form solution for the optimal weights and bias parameters. This is the linear least-squares solution those doing MLPR will have come across.

However in general we will be interested in models where closed form solutions do not exist. We will therefore generally use iterative, gradient descent based training methods to find parameters which (locally) minimise the error function. A basic requirement of being able to do gradient-descent based training is (unsuprisingly) the ability to evaluate gradients of the error function.

In the next exercise we will consider how to calculate gradients of the error function with respect to the model parameters $mtx{W}$ and $vct{b}$, but as a first step here we will consider the gradient of the error function with respect to the model outputs $fset{vct{y}^{(n)}}_{n=1}^N$. This can be written

egin{equation}
pd{ar{E}}{vct{y}^{(n)}} = frac{1}{N} lpa vct{y}^{(n)} – vct{t}^{(n)}
pa
qquad Leftrightarrow qquad
pd{ar{E}}{y^{(n)}_k} = frac{1}{N} lpa y^{(n)}_k – t^{(n)}_k
pa quad forall k in fset{1 dots K}
end{equation}i.e. the gradient of the error function with respect to the $n^{ extrm{th}}$ model output is just the difference between the $n^{ extrm{th}}$ model and target outputs, corresponding to the $vct{delta}^{(n)}$ terms mentioned in the lecture slides.

The third exercise is, using the equations given above, to implement functions computing the mean sum of squared differences error and its gradient with respect to the model outputs. You should implement the functions using the provided skeleton definitions in the cell below.

In [11]:

def error(outputs, targets):
“””Calculates error function given a batch of outputs and targets.

Args:
outputs: Array of model outputs of shape (batch_size, output_dim).
targets: Array of target outputs of shape (batch_size, output_dim).

Returns:
Scalar error function value.
“””
return 0.5 * ((outputs – targets)**2).sum() / outputs.shape[0]

def error_grad(outputs, targets):
“””Calculates gradient of error function with respect to model outputs.

Args:
outputs: Array of model outputs of shape (batch_size, output_dim).
targets: Array of target outputs of shape (batch_size, output_dim).

Returns:
Gradient of error function with respect to outputs.
This will be an array of shape (batch_size, output_dim).
“””
return (outputs – targets) / outputs.shape[0]

Check your implementation by running the test cell below.

In [12]:

outputs = np.array([[1., 2.], [-1., 0.], [6., -5.], [-1., 1.]])
targets = np.array([[0., 1.], [3., -2.], [7., -3.], [1., -2.]])
true_error = 5.
true_error_grad = np.array([[0.25, 0.25], [-1., 0.5], [-0.25, -0.5], [-0.5, 0.75]])

if not error(outputs, targets) == true_error:
print(‘Error calculated incorrectly.’)
elif not np.allclose(error_grad(outputs, targets), true_error_grad):
print(‘Error gradient calculated incorrectly.’)
else:
print(‘Error function and gradient computed correctly!’)

Error function and gradient computed correctly!

Exercise 4: computing gradients with respect to the parameters¶
In the previous exercise you implemented a function computing the gradient of the error function with respect to the model outputs. For gradient-descent based training, we need to be able to evaluate the gradient of the error function with respect to the model parameters.

Using the chain rule for derivatives we can write the partial deriviative of the error function with respect to single elements of the weight matrix and bias vector as

egin{equation}
pd{ar{E}}{W_{kj}} = sum_{n=1}^N lbr pd{ar{E}}{y^{(n)}_k} pd{y^{(n)}_k}{W_{kj}}
br
quad extrm{and} quad
pd{ar{E}}{b_k} = sum_{n=1}^N lbr pd{ar{E}}{y^{(n)}_k} pd{y^{(n)}_k}{b_k}
br.
end{equation}From the definition of our model at the beginning we have

egin{equation}
y^{(n)}_k = sum_{d=1}^D lbr W_{kd} x^{(n)}_d
br + b_k
quad Rightarrow quad
pd{y^{(n)}_k}{W_{kj}} = x^{(n)}_j
quad extrm{and} quad
pd{y^{(n)}_k}{b_k} = 1.
end{equation}Putting this together we get that

egin{equation}
pd{ar{E}}{W_{kj}} =
sum_{n=1}^N lbr pd{ar{E}}{y^{(n)}_k} x^{(n)}_j
br
quad extrm{and} quad
pd{ar{E}}{b_{k}} =
sum_{n=1}^N lbr pd{ar{E}}{y^{(n)}_k}
br.
end{equation}Although this may seem a bit of a roundabout way to get to these results, this method of decomposing the error gradient with respect to the parameters in terms of the gradient of the error function with respect to the model outputs and the derivatives of the model outputs with respect to the model parameters, will be key when calculating the parameter gradients of more complex models later in the course.

Your task in this exercise is to implement a function calculating the gradient of the error function with respect to the weight and bias parameters of the model given the already computed gradient of the error function with respect to the model outputs. You should implement this in the grads_wrt_params function in the cell below.

In [13]:

def grads_wrt_params(inputs, grads_wrt_outputs):
“””Calculates gradients with respect to model parameters.

Args:
inputs: array of inputs to model of shape (batch_size, input_dim)
grads_wrt_to_outputs: array of gradients of with respect to the model
outputs of shape (batch_size, output_dim).

Returns:
list of arrays of gradients with respect to the model parameters
`[grads_wrt_weights, grads_wrt_biases]`.
“””
grads_wrt_weights = grads_wrt_outputs.T.dot(inputs)
grads_wrt_biases = grads_wrt_outputs.sum(0)
return [grads_wrt_weights, grads_wrt_biases]

Check your implementation by running the test cell below.

In [14]:

inputs = np.array([[1., 2., 3.], [-1., 4., -9.]])
grads_wrt_outputs = np.array([[-1., 1.], [2., -3.]])
true_grads_wrt_weights = np.array([[-3., 6., -21.], [4., -10., 30.]])
true_grads_wrt_biases = np.array([1., -2.])

grads_wrt_weights, grads_wrt_biases = grads_wrt_params(
inputs, grads_wrt_outputs)

if not np.allclose(true_grads_wrt_weights, grads_wrt_weights):
print(‘Gradients with respect to weights incorrect.’)
elif not np.allclose(true_grads_wrt_biases, grads_wrt_biases):
print(‘Gradients with respect to biases incorrect.’)
else:
print(‘All parameter gradients calculated correctly!’)

All parameter gradients calculated correctly!

Exercise 5: wrapping the functions into reusable components¶
In exercises 1, 3 and 4 you implemented methods to compute the predicted outputs of our model, evaluate the error function and its gradient on the outputs and finally to calculate the gradients of the error with respect to the model parameters. Together they constitute all the basic ingredients we need to implement a gradient-descent based iterative learning procedure for the model.

Although you could implement training code which directly uses the functions you defined, this would only be usable for this particular model architecture. In subsequent labs we will want to use the affine transform functions as the basis for more interesting multi-layer models. We will therefore wrap the implementations you just wrote in to reusable components that we can build more complex models with later in the course.

In the mlp.layers module, use your implementations of fprop and grad_wrt_params above to implement the corresponding methods in the skeleton AffineLayer class provided.
In the mlp.errors module use your implementation of error and error_grad to implement the __call__ and grad methods respectively of the skeleton SumOfSquaredDiffsError class provided. Note __call__ is a special Python method that allows an object to be used with a function call syntax.

Run the cell below to use your completed AffineLayer and SumOfSquaredDiffsError implementations to train a single-layer model using batch gradient descent on the CCCP dataset.

In [15]:

from mlp.layers import AffineLayer
from mlp.errors import SumOfSquaredDiffsError
from mlp.models import SingleLayerModel
from mlp.initialisers import UniformInit, ConstantInit
from mlp.learning_rules import GradientDescentLearningRule
from mlp.optimisers import Optimiser
import logging

# Seed a random number generator
seed = 27092016
rng = np.random.RandomState(seed)

# Set up a logger object to print info about the training run to stdout
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.handlers = [logging.StreamHandler()]

# Create data provider objects for the CCPP training set
train_data = CCPPDataProvider(‘train’, [0, 1], batch_size=100, rng=rng)
input_dim, output_dim = 2, 1

# Create a parameter initialiser which will sample random uniform values
# from [-0.1, 0.1]
param_init = UniformInit(-0.1, 0.1, rng=rng)

# Create our single layer model
layer = AffineLayer(input_dim, output_dim, param_init, param_init)
model = SingleLayerModel(layer)

# Initialise the error object
error = SumOfSquaredDiffsError()

# Use a basic gradient descent learning rule with a small learning rate
learning_rule = GradientDescentLearningRule(learning_rate=1e-2)

# Use the created objects to initialise a new Optimiser instance.
optimiser = Optimiser(model, error, learning_rule, train_data)

# Run the optimiser for 5 epochs (full passes through the training set)
# printing statistics every epoch.
stats, keys, run_time = optimiser.train(num_epochs=10, stats_interval=1)

# Plot the change in the error over training.
fig = plt.figure(figsize=(8, 4))
ax = fig.add_subplot(111)
ax.plot(np.arange(1, stats.shape[0] + 1), stats[:, keys[‘error(train)’]])
ax.set_xlabel(‘Epoch number’)
ax.set_ylabel(‘Error’)

Epoch 1: 0.00s to complete
error(train)=1.67e-01, cost(param)=0.00e+00
Epoch 2: 0.00s to complete
error(train)=9.30e-02, cost(param)=0.00e+00
Epoch 3: 0.00s to complete
error(train)=7.95e-02, cost(param)=0.00e+00
Epoch 4: 0.00s to complete
error(train)=7.71e-02, cost(param)=0.00e+00
Epoch 5: 0.00s to complete
error(train)=7.66e-02, cost(param)=0.00e+00
Epoch 6: 0.00s to complete
error(train)=7.65e-02, cost(param)=0.00e+00
Epoch 7: 0.00s to complete
error(train)=7.65e-02, cost(param)=0.00e+00
Epoch 8: 0.00s to complete
error(train)=7.65e-02, cost(param)=0.00e+00
Epoch 9: 0.00s to complete
error(train)=7.63e-02, cost(param)=0.00e+00
Epoch 10: 0.00s to complete
error(train)=7.64e-02, cost(param)=0.00e+00

Out[15]:

Using similar code to previously we can now visualise the joint input-output space for the trained model. If you implemented the required methods correctly you should now see a much improved fit between predicted and target outputs when running the cell below.

In [16]:

data_provider = CCPPDataProvider(
which_set=’train’,
input_dims=[0, 1],
batch_size=5000,
max_num_batches=1,
shuffle_order=False
)

inputs, targets = data_provider.next()

# Calculate predicted model outputs
outputs = model.fprop(inputs)[-1]

# Plot target and predicted outputs against inputs on same axis
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection=’3d’)
ax.plot(inputs[:, 0], inputs[:, 1], targets[:, 0], ‘r.’, ms=2)
ax.plot(inputs[:, 0], inputs[:, 1], outputs[:, 0], ‘b.’, ms=2)
ax.set_xlabel(‘Input dim 1’)
ax.set_ylabel(‘Input dim 2’)
ax.set_zlabel(‘Output’)
ax.legend([‘Targets’, ‘Predictions’], frameon=False)
fig.tight_layout()

Exercise 6: visualising training trajectories in parameter space¶

Running the cell below will display an interactive widget which plots the trajectories of gradient-based training of the single-layer affine model on the CCPP dataset in the three dimensional parameter space (two weights plus bias) from random initialisations. Also shown on the right is a plot of the evolution of the error function (evaluated on the current batch) over training. By moving the sliders you can alter the training hyperparameters to investigate the effect they have on how training procedes.

Some questions to explore:

Are there multiple local minima in parameter space here? Why? In this case there is a single unique global minima, as suggested by the fact random parameter initialisations consistently converge to the same point in parameter space. As mentioned previously there is a closed form solution for the optimal weights and biases for this simple single-layer affine model linear least squares) and the error function is convex.

What happens to learning for very small learning rates? And very large learning rates? For very small learning rates, the training proceeds very slowly and the parameters do not tend to converge to the global optimum unless a lot of training epochs are used. For very large learning rates, the gradient descent dynamic becomes increasingly instable, leading to large oscillations or at extreme values divergence in the parameter space.

How does the batch size affect learning? Smaller batch sizes generally lead to quicker initial learning as the parameters are updated more frequently (more batches in an epoch) however as the batch becomes smaller the error estimate calculated from the batch and its gradients become increasingly noisy estimates for the true error function / gradients. This can be observed by the less smooth trajectories in parameter space for lower batch sizes and greater noise in the batch error curves.

Note: You don’t need to understand how the code below works. The idea of this exercise is to help you understand the role of the various hyperparameters involved in gradient-descent based training methods.

In [17]:

from ipywidgets import interact
%matplotlib inline

def setup_figure():
# create figure and axes
fig = plt.figure(figsize=(12, 6))
ax1 = fig.add_axes([0., 0., 0.5, 1.], projection=’3d’)
ax2 = fig.add_axes([0.6, 0.1, 0.4, 0.8])
# set axes properties
ax2.spines[‘right’].set_visible(False)
ax2.spines[‘top’].set_visible(False)
ax2.yaxis.set_ticks_position(‘left’)
ax2.xaxis.set_ticks_position(‘bottom’)
ax2.set_yscale(‘log’)
ax1.set_xlim((-2, 2))
ax1.set_ylim((-2, 2))
ax1.set_zlim((-2, 2))
#set axes labels and title
ax1.set_title(‘Parameter trajectories over training’)
ax1.set_xlabel(‘Weight 1’)
ax1.set_ylabel(‘Weight 2’)
ax1.set_zlabel(‘Bias’)
ax2.set_title(‘Batch errors over training’)
ax2.set_xlabel(‘Batch update number’)
ax2.set_ylabel(‘Batch error’)
return fig, ax1, ax2

def visualise_training(n_epochs=1, batch_size=200, log_lr=-1., n_inits=5,
w_scale=1., b_scale=1., elev=30., azim=0.):
fig, ax1, ax2 = setup_figure()
# create seeded random number generator
rng = np.random.RandomState(1234)
# create data provider
data_provider = CCPPDataProvider(
input_dims=[0, 1],
batch_size=batch_size,
shuffle_order=False,
)
learning_rate = 10 ** log_lr
n_batches = data_provider.num_batches
weights_traj = np.empty((n_inits, n_epochs * n_batches + 1, 1, 2))
biases_traj = np.empty((n_inits, n_epochs * n_batches + 1, 1))
errors_traj = np.empty((n_inits, n_epochs * n_batches))
# randomly initialise parameters
weights = rng.uniform(-w_scale, w_scale, (n_inits, 1, 2))
biases = rng.uniform(-b_scale, b_scale, (n_inits, 1))
# store initial parameters
weights_traj[:, 0] = weights
biases_traj[:, 0] = biases
# iterate across different initialisations
for i in range(n_inits):
# iterate across epochs
for e in range(n_epochs):
# iterate across batches
for b, (inputs, targets) in enumerate(data_provider):
outputs = fprop(inputs, weights[i], biases[i])
errors_traj[i, e * n_batches + b] = error(outputs, targets)
grad_wrt_outputs = error_grad(outputs, targets)
weights_grad, biases_grad = grads_wrt_params(inputs, grad_wrt_outputs)
weights[i] -= learning_rate * weights_grad
biases[i] -= learning_rate * biases_grad
weights_traj[i, e * n_batches + b + 1] = weights[i]
biases_traj[i, e * n_batches + b + 1] = biases[i]
# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, n_inits))
# plot all trajectories
for i in range(n_inits):
lines_1 = ax1.plot(
weights_traj[i, :, 0, 0],
weights_traj[i, :, 0, 1],
biases_traj[i, :, 0],
‘-‘, c=colors[i], lw=2)
lines_2 = ax2.plot(
np.arange(n_batches * n_epochs),
errors_traj[i],
c=colors[i]
)
ax1.view_init(elev, azim)
plt.show()

w = interact(
visualise_training,
elev=(-90, 90, 2),
azim=(-180, 180, 2),
n_epochs=(1, 5),
batch_size=(100, 1000, 100),
log_lr=(-3., 1.),
w_scale=(0., 2.),
b_scale=(0., 2.),
n_inits=(1, 10)
)

for child in w.widget.children:
child.layout.width = ‘100%’

Posted in Uncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *