# Gaussian Process Summer School, Melbourne, Australia¶

### Neil D. Lawrence¶

In this lab we are going to build on yestereday's work by looking at multiple output Gaussian processes

## Getting started: Modelling Multiple Outputs¶

Just as in the first lab, we firstly specify to include plots in the notebook and to import relevant libraries.

In [25]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import GPy
import pods
from IPython.display import display


### Running Example¶

The first think we will look at is a multiple output model. Our aim is to jointly model all sprinting events from olympics since 1896. Data is provided by Rogers & Girolami's "First Course in Machine Learning". Firstly, let's load in the data.

In [26]:
data = pods.datasets.olympic_sprints()
X = data['X']
y = data['Y']
print data['info'], data['details']

Olympics sprint event winning for men and women to 2008. Data is from Rogers and Girolami's First Course in Machine Learning. Data from the textbook 'A First Course in Machine Learning'. Available from http://www.dcs.gla.ac.uk/~srogers/firstcourseml/.


When using data sets it's good practice to cite the originators of the data, you can get information about the source of the data from data['citation']

In [27]:
print data['citation']

A First Course in Machine Learning. Simon Rogers and Mark Girolami: Chapman & Hall/CRC, ISBN-13: 978-1439824146


The data consists of all the male and female sprinting data for 100m, 200m and 400m since 1896 (six outputs in total). The ouput information can be found from: data['output_info']

In [28]:
print data['output_info']

{0: '100m Men', 1: '100m Women', 2: '200m Men', 3: '200m Women', 4: '400m Men', 5: '400m Women'}


In GPy we deal with multiple output data in a particular way. We specify the output we are interested in for modelling as an additional input. So whilst for this data, normally, the only input would be the year of the event. We additionally have an input giving the index of the output we are modelling. This can be seen from examining data['X'].

In [29]:
#print 'First column of X contains the olympic years.'
#print data['X'][:, 0]
#print 'Second column of X contains the event index.'
#print data['X'][:, 1]


Now let's plot the data

In [30]:
markers = ['bo', 'ro', 'bx', 'rx', 'bs', 'rs']
for i in range(6):
# extract the event
x_event = X[np.nonzero(X[:, 1]==i), 0]
y_event = y[np.nonzero(X[:, 1]==i), 0]
plt.plot(x_event, y_event, markers[i])
plt.title('Olympic Sprint Times')
plt.xlabel('year')
plt.ylabel('time/s')

Out[30]:
<matplotlib.text.Text at 0x111127750>

In the plot above red is women's events, blue is men's. Squares are 400 m, crosses 200m and circles 100m. Not all events were run in all years, for example the women's 400 m only started in 1964.

We will look at modelling the data using coregionalization approaches described in this morning's lecture. We introduced these approaches through the Kronecker product. To indicate we want to construct a covariance function of this type in GPy we've overloaded the ** operator. Stricly speaking this operator means to the power of (like ^ in MATLAB). But for covariance functions we've used it to indicate a tensor product. The linear models of coregionalization we introduced in the lecture were all based on combining a matrix with a standard covariance function. We can think of the matrix as a particular type of covariance function, whose elements are referenced using the event indices. I.e. $k(0, 0)$ references the first row and column of the coregionalization matrix. $k(1, 0)$ references the second row and first column of the coregionalization matrix. Under this set up, we want to build a covariance where the first column from the features (the years) is passed to a covariance function, and the second column from the features (the event number) is passed to the coregionalisation matrix. Let's start by trying a intrinsic coregionalisation model (sometimes known as multitask Gaussian processes). Let's start by checking the help for the coregionalize covariance.

In [31]:
GPy.kern.Coregionalize?


The coregionalize matrix, $\mathbf{B}$, is itself is constructed from two other matrices, $\mathbf{B} = \mathbf{W}\mathbf{W}^\top + \text{diag}(\boldsymbol{\kappa})$. This allows us to specify a low rank form for the coregionalization matrix. However, for our first example we want to specify that the matrix $\mathbf{B}$ is not constrained to have a low rank form.

In [32]:
kern = GPy.kern.RBF(1, lengthscale=80)**GPy.kern.Coregionalize(1,output_dim=6, rank=5)
display(kern)

mul. Value Constraint Prior Tied to
rbf.variance 1.0 +ve
rbf.lengthscale 80.0 +ve
coregion.W (6, 5)
coregion.kappa (6,) +ve

Note here that the rank we specify is that of the $\mathbf{W}\mathbf{W}^\top$ part. When this part is combined with the diagonal matrix from $\mathbf{\kappa}$ the matrix $\mathbf{B}$ is totally general. This covariance function can now be used in a standard Gaussian process regression model. Let's build the model and optimize it.

In [33]:
X

Out[33]:
array([[  1.89600000e+03,   0.00000000e+00],
[  1.90000000e+03,   0.00000000e+00],
[  1.90400000e+03,   0.00000000e+00],
[  1.90600000e+03,   0.00000000e+00],
[  1.90800000e+03,   0.00000000e+00],
[  1.91200000e+03,   0.00000000e+00],
[  1.92000000e+03,   0.00000000e+00],
[  1.92400000e+03,   0.00000000e+00],
[  1.92800000e+03,   0.00000000e+00],
[  1.93200000e+03,   0.00000000e+00],
[  1.93600000e+03,   0.00000000e+00],
[  1.94800000e+03,   0.00000000e+00],
[  1.95200000e+03,   0.00000000e+00],
[  1.95600000e+03,   0.00000000e+00],
[  1.96000000e+03,   0.00000000e+00],
[  1.96400000e+03,   0.00000000e+00],
[  1.96800000e+03,   0.00000000e+00],
[  1.97200000e+03,   0.00000000e+00],
[  1.97600000e+03,   0.00000000e+00],
[  1.98000000e+03,   0.00000000e+00],
[  1.98400000e+03,   0.00000000e+00],
[  1.98800000e+03,   0.00000000e+00],
[  1.99200000e+03,   0.00000000e+00],
[  1.99600000e+03,   0.00000000e+00],
[  2.00000000e+03,   0.00000000e+00],
[  2.00400000e+03,   0.00000000e+00],
[  2.00800000e+03,   0.00000000e+00],
[  1.92800000e+03,   1.00000000e+00],
[  1.93200000e+03,   1.00000000e+00],
[  1.93600000e+03,   1.00000000e+00],
[  1.94800000e+03,   1.00000000e+00],
[  1.95200000e+03,   1.00000000e+00],
[  1.95600000e+03,   1.00000000e+00],
[  1.96000000e+03,   1.00000000e+00],
[  1.96400000e+03,   1.00000000e+00],
[  1.96800000e+03,   1.00000000e+00],
[  1.97200000e+03,   1.00000000e+00],
[  1.97600000e+03,   1.00000000e+00],
[  1.98000000e+03,   1.00000000e+00],
[  1.98400000e+03,   1.00000000e+00],
[  1.98800000e+03,   1.00000000e+00],
[  1.99200000e+03,   1.00000000e+00],
[  1.99600000e+03,   1.00000000e+00],
[  2.00000000e+03,   1.00000000e+00],
[  2.00400000e+03,   1.00000000e+00],
[  2.00800000e+03,   1.00000000e+00],
[  1.90000000e+03,   2.00000000e+00],
[  1.90400000e+03,   2.00000000e+00],
[  1.90800000e+03,   2.00000000e+00],
[  1.91200000e+03,   2.00000000e+00],
[  1.92000000e+03,   2.00000000e+00],
[  1.92400000e+03,   2.00000000e+00],
[  1.92800000e+03,   2.00000000e+00],
[  1.93200000e+03,   2.00000000e+00],
[  1.93600000e+03,   2.00000000e+00],
[  1.94800000e+03,   2.00000000e+00],
[  1.95200000e+03,   2.00000000e+00],
[  1.95600000e+03,   2.00000000e+00],
[  1.96000000e+03,   2.00000000e+00],
[  1.96400000e+03,   2.00000000e+00],
[  1.96800000e+03,   2.00000000e+00],
[  1.97200000e+03,   2.00000000e+00],
[  1.97600000e+03,   2.00000000e+00],
[  1.98000000e+03,   2.00000000e+00],
[  1.98400000e+03,   2.00000000e+00],
[  1.98800000e+03,   2.00000000e+00],
[  1.99200000e+03,   2.00000000e+00],
[  1.99600000e+03,   2.00000000e+00],
[  2.00000000e+03,   2.00000000e+00],
[  2.00400000e+03,   2.00000000e+00],
[  2.00800000e+03,   2.00000000e+00],
[  1.94800000e+03,   3.00000000e+00],
[  1.95200000e+03,   3.00000000e+00],
[  1.95600000e+03,   3.00000000e+00],
[  1.96000000e+03,   3.00000000e+00],
[  1.96400000e+03,   3.00000000e+00],
[  1.96800000e+03,   3.00000000e+00],
[  1.97200000e+03,   3.00000000e+00],
[  1.97600000e+03,   3.00000000e+00],
[  1.98000000e+03,   3.00000000e+00],
[  1.98400000e+03,   3.00000000e+00],
[  1.98800000e+03,   3.00000000e+00],
[  1.99200000e+03,   3.00000000e+00],
[  1.99600000e+03,   3.00000000e+00],
[  2.00000000e+03,   3.00000000e+00],
[  2.00400000e+03,   3.00000000e+00],
[  2.00800000e+03,   3.00000000e+00],
[  1.89600000e+03,   4.00000000e+00],
[  1.90000000e+03,   4.00000000e+00],
[  1.90400000e+03,   4.00000000e+00],
[  1.90600000e+03,   4.00000000e+00],
[  1.90800000e+03,   4.00000000e+00],
[  1.91200000e+03,   4.00000000e+00],
[  1.92000000e+03,   4.00000000e+00],
[  1.92400000e+03,   4.00000000e+00],
[  1.92800000e+03,   4.00000000e+00],
[  1.93200000e+03,   4.00000000e+00],
[  1.93600000e+03,   4.00000000e+00],
[  1.94800000e+03,   4.00000000e+00],
[  1.95200000e+03,   4.00000000e+00],
[  1.95600000e+03,   4.00000000e+00],
[  1.96000000e+03,   4.00000000e+00],
[  1.96400000e+03,   4.00000000e+00],
[  1.96800000e+03,   4.00000000e+00],
[  1.97200000e+03,   4.00000000e+00],
[  1.97600000e+03,   4.00000000e+00],
[  1.98000000e+03,   4.00000000e+00],
[  1.98400000e+03,   4.00000000e+00],
[  1.98800000e+03,   4.00000000e+00],
[  1.99200000e+03,   4.00000000e+00],
[  1.99600000e+03,   4.00000000e+00],
[  2.00000000e+03,   4.00000000e+00],
[  2.00400000e+03,   4.00000000e+00],
[  2.00800000e+03,   4.00000000e+00],
[  1.96400000e+03,   5.00000000e+00],
[  1.96800000e+03,   5.00000000e+00],
[  1.97200000e+03,   5.00000000e+00],
[  1.97600000e+03,   5.00000000e+00],
[  1.98000000e+03,   5.00000000e+00],
[  1.98400000e+03,   5.00000000e+00],
[  1.98800000e+03,   5.00000000e+00],
[  1.99200000e+03,   5.00000000e+00],
[  1.99600000e+03,   5.00000000e+00],
[  2.00000000e+03,   5.00000000e+00],
[  2.00400000e+03,   5.00000000e+00],
[  2.00800000e+03,   5.00000000e+00]])
In [9]:
model = GPy.models.GPRegression(X, y, kern)
model.optimize()


We can plot the results using the ability to 'fix inputs' in the model.plot() function. We can specify that column 1 should be fixed to event number 2 by passing fixed_inputs = [(1, 2)] to the model. To plot the results for all events on the same figure we also specify fignum=1 in the loop as below.

In [10]:
for i in range(6):
model.plot(fignum=1,fixed_inputs=[(1, i)])
plt.xlabel('years')
plt.ylabel('time/s')

Out[10]:
<matplotlib.text.Text at 0x10fc52d10>

There is a lot we can do with this model. First of all, each of the races is a different length, so the series have a different mean. We can include another coregionalization term to deal with the mean. Below we do this and reduce the rank of the coregionalization matrix to 1.

In [11]:
kern1 = GPy.kern.RBF(1, lengthscale=80)**GPy.kern.Coregionalize(1,output_dim=6, rank=1)
kern2 = GPy.kern.Bias(1)**GPy.kern.Coregionalize(1,output_dim=6, rank=1)
kern = kern1 + kern2

In [12]:
model = GPy.models.GPRegression(X, y, kern)
model.optimize()

In [13]:
for i in range(6):
model.plot(fignum=1,fixed_inputs=[(1, i)])
plt.xlabel('years')
plt.ylabel('time/s')

Out[13]:
<matplotlib.text.Text at 0x111123850>

This is a simple form of the linear model of coregionalization. Note how confident the model is about what the women's 400 m performance would have been. You might feel that the model is being over confident in this region. Perhaps we are forcing too much sharing of information between the sprints. We could return to the intrinsic coregionalization model and force the two base covariance functions to share the same coregionalization matrix.

In [14]:
kern1 = GPy.kern.RBF(1, lengthscale=80) + GPy.kern.Bias(1)
kern1.name = 'rbf_plus_bias'
kern2 = GPy.kern.Coregionalize(1,output_dim=6, rank=5)
kern = kern1**kern2
kern.name = 'product'
display(kern)

product. Value Constraint Prior Tied to
rbf_plus_bias.rbf.variance 1.0 +ve
rbf_plus_bias.rbf.lengthscale 80.0 +ve
rbf_plus_bias.bias.variance 1.0 +ve
coregion.W (6, 5)
coregion.kappa (6,) +ve
In [15]:
model = GPy.models.GPRegression(X, y, kern)
model.optimize()

In [16]:
for i in range(6):
model.plot(fignum=1,fixed_inputs=[(1, i)])
plt.xlabel('years')
plt.ylabel('time/s')

Out[16]:
<matplotlib.text.Text at 0x111345b90>

### Exercise 1¶

Can you fix the issue with over confidence in this model? Some things you might try include (a) adding additional covariance functions to handle shorter lengthscale effects. (b) Changing the rank of the coregionalization matrix. (c) Adding a coregionalized noise model using GPy.kern.white().

In [19]:
# Question 1 answer here


Predictions in the multioutput case can be very effected by our covariance function design. This reflects the themes we saw on the first day where the importance of covariance function choice was emphasized at design time.

Can you build a covariance matrix that coregionalizes separately over the sex of the athletes and the event identity? Does this matrix perform better?

In [17]:
# set up the inputs to index sex and event separately.
X2 = np.zeros((X.shape[0], 3))
X2[:, 0] = X[:, 0]
X2[:, 1] = np.remainder(X[:, 1],2) == 1
X2[:, 2] = np.floor(X[:, 1]/2)

In [18]:
kern1 = (GPy.kern.RBF(1, lengthscale=80, active_dims=0)
*GPy.kern.Coregionalize(1, output_dim=2, rank=1, active_dims=1, name='coregion1')
*GPy.kern.Coregionalize(1, output_dim=3, rank=1, active_dims=2, name='coregion2'))

kern2 = (GPy.kern.Bias(1, active_dims=0)
*GPy.kern.Coregionalize(1, output_dim=2, rank=0, active_dims=1)
*GPy.kern.Coregionalize(1, output_dim=3, rank=0, active_dims=2)
)

kern = kern1+ kern2

display(kern)
#print "First coregion:", [(k.name, k.active_dims) for k in kern.parts[0].parts]
#print "Second         ", [(k.name, k.active_dims) for k in kern.parts[0].parts[1].parts]

model = GPy.models.GPRegression(X2, y, kern)
display(model.optimize('scg', messages=1))

add. Value Constraint Prior Tied to
mul_1.rbf.variance 1.0 +ve
mul_1.rbf.lengthscale 80.0 +ve
mul_1.coregion1.W (2, 1)
mul_1.coregion1.kappa (2,) +ve
mul_1.coregion2.W (3, 1)
mul_1.coregion2.kappa (3,) +ve
mul_2.bias.variance 1.0 +ve
mul_2.coregion_1.W []
mul_2.coregion_1.kappa (2,) +ve
mul_2.coregion_2.W []
mul_2.coregion_2.kappa (3,) +ve
Running Scaled Conjugate Gradients Code:
secs      i      f              |g|
0.079  0004   4.412059e+02   1.588177e+07
0.25  0013   1.889763e+02   3.545411e+03
0.34  0017   1.747042e+02   5.996503e+02
0.48  0023   1.553625e+02   4.725374e+01
0.71  0035   1.478497e+02   8.996330e+00
2  0100   1.367246e+02   1.347589e+01
5  0248   1.311545e+02   1.763250e+00
7.2  0377   1.306778e+02   3.491745e-02
18  0953   1.304859e+02   1.704097e-02
19  0986   1.304824e+02   2.679884e-03
Optimization finished in 19.044 Seconds


None
In [19]:
display(model)


Model: GP regression
Log-likelihood: -130.482376392
Number of Parameters: 19

GP_regression. Value Constraint Prior Tied to
Gaussian_noise.variance 0.322503741245 +ve
In [22]:
model.add.mul_1.coregion1.W

Out[22]:
Index GP_regression.add.mul_1.coregion2.W Constraint Prior Tied to
[0 0]-2.4773371925N/A
[1 0]-5.00748406387N/A
[2 0]-11.1726954204N/A
In [43]:
for i in range(2):
for j in range(3):
model.plot(fignum=1,fixed_inputs=[(1, i), (2, j)])
plt.xlabel('years')
plt.ylabel('time/s')

Out[43]:
<matplotlib.text.Text at 0x1107cf910>
In [33]:
55*4/60

Out[33]:
3
In [23]:
for sex in range(2):
c = 'magenta' if sex == 1 else 'blue'
for event in range(3):
model.plot(fignum=1,fixed_inputs=[(1, sex), (2, event)],linecol=c,fillcol=c)
plt.xlabel('years')
plt.ylabel('time/s')

Out[23]:
<matplotlib.text.Text at 0x11182c410>
In [24]:
display(model)


Model: GP regression
Log-likelihood: -130.482376392
Number of Parameters: 19

GP_regression. Value Constraint Prior Tied to
Gaussian_noise.variance 0.322503741245 +ve

## Low Rank Approximations¶

In the worst case, inference in a Gaussian process is $\mathcal{O}(n^3)$ computational complexity and $\mathcal{O}(n^2)$ storage. For efficient inference in larger data sets we need to consider approximations. One approach is low rank approximation of the covariance matrix (also known as sparse approximations or perhaps more accurately parsimonious approximations). We'll study these approximations by first creating a simple data set by sampling from a GP.

In [25]:
X = np.sort(np.random.rand(50,1)*12,0)
k = GPy.kern.RBF(1)
K = k.K(X)
K+= np.eye(50)*0.01 # add some independence (noise) to K
y = np.random.multivariate_normal(np.zeros(50), K).reshape(50,1)


Build a straightforward GP model of our simulation. We’ll also plot the posterior of $f$.

In [28]:
model = GPy.models.GPRegression(X,y)
model.optimize()
fig = plt.figure()
model.plot_f(ax=ax)
model._raw_predict?
mu, var = model._raw_predict(X) # this fetches the posterior of f

plt.vlines(X[:,0], mu[:,0]-2.*np.sqrt(var[:,0]), mu[:,0]+2.*np.sqrt(var[:,0]),color='r',lw=2)

Out[28]:
<matplotlib.collections.LineCollection at 0x1105f5910>

### Exercise 2¶

One thought that occurs is as follows. Do we need all the data to create this posterior estimate? Are any of the data points redundant? What happens to the model if you remove some data?

Hint:

X2 = np.delete(X,range(8),0)
y2 = np.delete(y,range(8),0)

In [29]:
# Exercise 2 answer here


### Building the Low Rank Approximation¶

Now we’ll consider a GP that uses a low rank approximation to fit the data.

In [30]:
Z = np.random.rand(3,1)*12
model = GPy.models.SparseGPRegression(X,y,Z=Z)
display(model)

clang: warning: argument unused during compilation: '-fopenmp'
In file included from /Users/neil/.cache/scipy/python27_compiled/sc_1790bf65208b11355ffcfd4b65a5f1092.cpp:11:
In file included from /Users/neil/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/weave/blitz/blitz/array.h:26:
In file included from /Users/neil/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/weave/blitz/blitz/array-impl.h:37:
/Users/neil/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/weave/blitz/blitz/range.h:120:34: warning: '&&' within '||' [-Wlogical-op-parentheses]
return ((first_ < last_) && (stride_ == 1) || (first_ == last_));
~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~ ~~
/Users/neil/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/weave/blitz/blitz/range.h:120:34: note: place parentheses around the '&&' expression to silence this warning
return ((first_ < last_) && (stride_ == 1) || (first_ == last_));
^
(                                 )
In file included from /Users/neil/.cache/scipy/python27_compiled/sc_1790bf65208b11355ffcfd4b65a5f1092.cpp:23:
In file included from /Users/neil/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:4:
In file included from /Users/neil/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17:
In file included from /Users/neil/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1761:
/Users/neil/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: "Using deprecated NumPy API, disable it by "          "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-W#warnings]
#warning "Using deprecated NumPy API, disable it by " \
^
#include <omp.h>
^
2 warnings and 1 error generated.

Weave compilation failed. Falling back to (slower) numpy implementation



Model: sparse gp mpi
Log-likelihood: -89.690592049
Number of Parameters: 6

sparse_gp_mpi. Value Constraint Prior Tied to
inducing inputs (3, 1)
rbf.variance 1.0 +ve
rbf.lengthscale 1.0 +ve
Gaussian_noise.variance 1.0 +ve

In GPy, the sparse inputs $\mathbf{Z}$ are abbreviated 'iip' , for inducing input. Plot the posterior of $u$ in the same manner as for the full GP:

In [31]:
mu, var = model._raw_predict(Z)
plt.vlines(Z[:,0], mu[:,0]-2.*np.sqrt(var[:,0]), mu[:,0]+2.*np.sqrt(var[:,0]),color='r')

Out[31]:
<matplotlib.collections.LineCollection at 0x1106aebd0>

### Exercise 3¶

Optimise and plot the model. The inducing inputs are marked – how are they placed? You can move them around with e.g. m['iip_2_0'] = 100 . What happens to the likelihood? What happens to the fit if you remove an input?

In [32]:
# Exercise 3 answer


### Exercise 4¶

How does the fit of the sparse compare with the full GP? Play around with the number of inducing inputs, the fit should improve as $M$ increases. How many inducing points are needed? What do you think happens in higher dimensions?

# Exercise 5 answer