{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lab session 2: Multiple Outputs and Sparse GPs "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Gaussian Process Summer School, 13th September 2014\n",
"written by Ricardo Andrade Pacheco, Neil Lawrence and James Hensman"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this lab we are going to build on yestereday's work by looking at multiple output Gaussian processes and considering low rank approximations to Gaussian processes."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1 Getting started: Modelling Multiple Outputs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just as in the first lab, we firstly specify to include plots in the notebook and to import relevant libraries."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%pylab inline\n",
"import numpy as np\n",
"import pylab as pb\n",
"import GPy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We ned pods to run this notebook. You can install it using pip"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"``pip install pods``"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Running Example"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import pods\n",
"pods.datasets.authorize_download = lambda x: True\n",
"data = pods.datasets.olympic_sprints()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"X = data['X']\n",
"y = data['Y']\n",
"print(data['info'], data['details'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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']`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print (data['citation'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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']`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print (data['output_info'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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']`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print ('First column of X contains the olympic years.')\n",
"print (data['X'][:, 0])\n",
"print ('Second column of X contains the event index.')\n",
"print (data['X'][:, 1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's plot the data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"markers = ['bo', 'ro', 'bx', 'rx', 'bs', 'rs']\n",
"for i in range(6):\n",
" # extract the event \n",
" x_event = X[np.nonzero(X[:, 1]==i), 0]\n",
" y_event = y[np.nonzero(X[:, 1]==i), 0]\n",
" pb.plot(x_event, y_event, markers[i])\n",
"pb.title('Olympic Sprint Times')\n",
"xlabel('year')\n",
"ylabel('time/s')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"GPy.kern.Coregionalize?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"kern = GPy.kern.RBF(1, lengthscale=80)**GPy.kern.Coregionalize(1,output_dim=6, rank=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"model = GPy.models.GPRegression(X, y, kern)\n",
"model.optimize()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"for i in range(6):\n",
" model.plot(fignum=1,fixed_inputs=[(1, i)])\n",
"xlabel('years')\n",
"ylabel('time/s')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"kern1 = GPy.kern.RBF(1, lengthscale=80)**GPy.kern.Coregionalize(1, output_dim=6, rank=1)\n",
"kern2 = GPy.kern.Bias(1)**GPy.kern.Coregionalize(1,output_dim=6, rank=1)\n",
"kern = kern1 + kern2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"model = GPy.models.GPRegression(X, y, kern)\n",
"model.optimize()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"for i in range(6):\n",
" model.plot(fignum=1,fixed_inputs=[(1, i)])\n",
"xlabel('years')\n",
"ylabel('time/s')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"kern1 = GPy.kern.RBF(1, lengthscale=80) + GPy.kern.Bias(1)\n",
"kern2 = GPy.kern.Coregionalize(1, output_dim=6, rank=5)\n",
"kern = kern1**kern2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"model = GPy.models.GPRegression(X, y, kern)\n",
"model.optimize()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"for i in range(6):\n",
" model.plot(fignum=1,fixed_inputs=[(1, i)])\n",
"xlabel('years')\n",
"ylabel('time/s')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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()`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Question 1 answer here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2 Low Rank Approximations"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"X = np.sort(np.random.rand(50,1)*12,0)\n",
"k = GPy.kern.RBF(1)\n",
"K = k.K(X)\n",
"K+= np.eye(50)*0.01 # add some independence (noise) to K\n",
"y = np.random.multivariate_normal(np.zeros(50), K).reshape(50,1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Build a straightforward GP model of our simulation. We’ll also plot the posterior of $f$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"m = GPy.models.GPRegression(X,y)\n",
"m.optimize()\n",
"m.plot()\n",
"mu, var = m._raw_predict(X) # this fetches the posterior of f\n",
"pb.vlines(X[:,0], mu[:,0]-2.*np.sqrt(var[:,0]), mu[:,0]+2.*np.sqrt(var[:,0]),color='r')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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?\n",
"\n",
"*Hint:* \n",
"`X2 = np.delete(X,range(8),0)`\n",
"`y2 = np.delete(y,range(8),0)`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Exercise 2 answer here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Building the Low Rank Approximation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we’ll consider a GP that uses a low rank approximation to fit the data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"Z = np.random.rand(3,1)*12\n",
"m = GPy.models.SparseGPRegression(X,y,Z=Z)\n",
"print (m)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In GPy, the sparse inputs $\\mathbf{Z}$ are abbreviated 'iip' , for inducing input. Plot the posterior\n",
"of $u$ in the same manner as for the full GP:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"mu, var = m._raw_predict(Z) \n",
"pb.vlines(Z[:,0], mu[:,0]-2.*np.sqrt(var[:,0]), mu[:,0]+2.*np.sqrt(var[:,0]),color='r')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"a) Optimise and plot the model. The inducing inputs are marked – how\n",
"are they placed? You can move them around with e.g. `m['iip_2_0'] = 100` . What\n",
"happens to the likelihood? What happens to the fit if you remove an input?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Exercise 3 a answer"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"b) How does the fit of the sparse compare with the full GP? Play around\n",
"with the number of inducing inputs, the fit should improve as $M$ increases. How many\n",
"inducing points are needed? What do you think happens in higher dimensions?"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"# Exercise 3 b answer"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 4"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can you build a low rank Gaussian process with the intrinsic model of coregionalization? Do you have to treat the 2nd input (which specifies the event number) in a special way?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [conda root]",
"language": "python",
"name": "conda-root-py"
},
"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.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}