[edit]
Special Topics: Gaussian Processes
Abstract
null
Setup
[edit]
First we download some libraries and files to support the notebook.
urllib.request.urlretrieve('https://raw.githubusercontent.com/lawrennd/talks/ghpages/mlai.py','mlai.py')
urllib.request.urlretrieve('https://raw.githubusercontent.com/lawrennd/talks/ghpages/teaching_plots.py','teaching_plots.py')
urllib.request.urlretrieve('https://raw.githubusercontent.com/lawrennd/talks/ghpages/gp_tutorial.py','gp_tutorial.py')
pods
[edit]
In Sheffield we created a suite of software tools for ‘Open Data Science’. Open data science is an approach to sharing code, models and data that should make it easier for companies, health professionals and scientists to gain access to data science techniques.
You can also check this blog post on Open Data Science.
The software can be installed using
from the command prompt where you can access your python installation.
The code is also available on github: https://github.com/sods/ods
Once pods
is installed, it can be imported in the usual manner.
Review
 Last week: Logistic Regression and Generalised Linear Models
 Introduced link functions and different transformations.
 Showed examples in classification and mentioned possibilities for disease rate models.
 This week:
 Gaussian Processes: non parametric Bayesian modelling }
Over the last two sessions we’ve begun considering classification models and logistic regresssion. In particular, for naive Bayes, we considered a set of assumptions that allowed us to build a joint model of our data set. In particular for naive Bayes we specified
 Data conditional independence.
 Feature conditional independence.
 Marginal likelihood of labels was Bernoulli distributed.
This allowed us to specify the joint density of our labels and our input data, $p(\dataVector, \inputMatrix\boldsymbol{\theta})$. And we conditioned on the training data to make predictions about the test data.
Generalized Linear Models
Logistic regression is part of a wider class of models known as generalized linear models. In these models we determine that some characteristic of the model is speicified by a function that is liniear in the parameters. So we might suggest that
$$
\log \frac{p(\inputVector)}{1p(\inputVector)} = \mappingFunction(\inputVector; \mappingVector)
$$
where $\mappingFunction(\inputVector; \mappingVector)$ is a linearintheparameters function (here the parameters are $\mappingVector$, which is generally nonlinear in the inputs. So far we have considered basis function models of the form
$$
\mappingFunction(\inputVector) =
\mappingVector^\top \basisVector(\inputVector).
$$
When we form a Gaussian process we do something that is slightly more akin to the naive Bayes approach, but actually is closely related to the generalized linear model approach.
Gaussian Processes
[edit]
Models where we model the entire joint distribution of our training data, $p(\dataVector, \inputMatrix)$ are sometimes described as generative models. Because we can use sampling to generate data sets that represent all our assumptions. However, as we discussed in the sessions on and , this can be a bad idea, because if our assumptions are wrong then we can make poor predictions. We can try to make more complex assumptions about data to alleviate the problem, but then this typically leads to challenges for tractable application of the sum and rules of probability that are needed to compute the relevant marginal and conditional densities. If we know the form of the question we wish to answer then we typically try and represent that directly, through $p(\dataVector\inputMatrix)$. In practice, we also have been making assumptions of conditional independence given the model parameters,
$$
p(\dataVector\inputMatrix, \mappingVector) =
\prod_{i=1}^{\numData} p(\dataScalar_i  \inputVector_i, \mappingVector)
$$
Gaussian processes are not normally considered to be generative models, but we will be much more interested in the principles of conditioning in Gaussian processes because we will use conditioning to make predictions between our test and training data. We will avoid the data conditional indpendence assumption in favour of a richer assumption about the data, in a Gaussian process we assume data is jointly Gaussian with a particular mean and covariance,
$$
\dataVector\inputMatrix \sim \gaussianSamp{\mathbf{m}(\inputMatrix)}{\kernelMatrix(\inputMatrix)},
$$
where the conditioning is on the inputs $\inputMatrix$ which are used for computing the mean and covariance. For this reason they are known as mean and covariance functions.
Prediction Across Two Points with GPs
[edit]
 The single contour of the Gaussian density represents the joint distribution, $p(\mappingFunction_1, \mappingFunction_2)$
 We observe that $\mappingFunction_1=?$
Conditional density: $p(\mappingFunction_2\mappingFunction_1=?)$
Prediction of $\mappingFunction_2$ from $\mappingFunction_1$ requires conditional density.
Conditional density is also Gaussian.
$$ p(\mappingFunction_2\mappingFunction_1) = {\mathcal{N}\left(\mappingFunction_2\frac{\kernelScalar_{1, 2}}{\kernelScalar_{1, 1}}\mappingFunction_1,\kernelScalar_{2, 2}  \frac{\kernelScalar_{1,2}^2}{\kernelScalar_{1,1}}\right)} $$
where covariance of joint density is given by
$$ \kernelMatrix= \begin{bmatrix} \kernelScalar_{1, 1} & \kernelScalar_{1, 2}\\ \kernelScalar_{2, 1} & \kernelScalar_{2, 2}\end{bmatrix} $$
 The single contour of the Gaussian density represents the joint distribution, $p(\mappingFunction_1, \mappingFunction_8)$
 We observe a value for $\mappingFunction_1=?$
Conditional density: $p(\mappingFunction_5\mappingFunction_1=?)$.
Prediction of $\mappingFunctionVector_*$ from $\mappingFunctionVector$ requires multivariate conditional density.
Multivariate conditional density is also Gaussian.
$$ p(\mappingFunctionVector_*\mappingFunctionVector) = {\mathcal{N}\left(\mappingFunctionVector_*\kernelMatrix_{*,\mappingFunctionVector}\kernelMatrix_{\mappingFunctionVector,\mappingFunctionVector}^{1}\mappingFunctionVector,\kernelMatrix_{*,*}\kernelMatrix_{*,\mappingFunctionVector} \kernelMatrix_{\mappingFunctionVector,\mappingFunctionVector}^{1}\kernelMatrix_{\mappingFunctionVector,*}\right)} $$
Here covariance of joint density is given by
$$ \kernelMatrix= \begin{bmatrix} \kernelMatrix_{\mappingFunctionVector, \mappingFunctionVector} & \kernelMatrix_{*, \mappingFunctionVector}\\ \kernelMatrix_{\mappingFunctionVector, *} & \kernelMatrix_{*, *}\end{bmatrix} $$Prediction of $\mappingFunctionVector_*$ from $\mappingFunctionVector$ requires multivariate conditional density.
Multivariate conditional density is also Gaussian.
$$ p(\mappingFunctionVector_*\mappingFunctionVector) = {\mathcal{N}\left(\mappingFunctionVector_*\meanVector,\conditionalCovariance\right)} $$
$$ \meanVector= \kernelMatrix_{*,\mappingFunctionVector}\kernelMatrix_{\mappingFunctionVector,\mappingFunctionVector}^{1}\mappingFunctionVector $$
$$ \conditionalCovariance = \kernelMatrix_{*,*}\kernelMatrix_{*,\mappingFunctionVector} \kernelMatrix_{\mappingFunctionVector,\mappingFunctionVector}^{1}\kernelMatrix_{\mappingFunctionVector,*} $$
Here covariance of joint density is given by
$$ \kernelMatrix= \begin{bmatrix} \kernelMatrix_{\mappingFunctionVector, \mappingFunctionVector} & \kernelMatrix_{*, \mappingFunctionVector}\\ \kernelMatrix_{\mappingFunctionVector, *} & \kernelMatrix_{*, *}\end{bmatrix} $$
Marginal Likelihood
[edit]
To understand the Gaussian process we’re going to build on our understanding of the marginal likelihood for Bayesian regression. In the session on we sampled directly from the weight vector, $\mappingVector$ and applied it to the basis matrix $\basisMatrix$ to obtain a sample from the prior and a sample from the posterior. It is often helpful to think of modeling techniques as generative models. To give some thought as to what the process for obtaining data from the model is. From the perspective of Gaussian processes, we want to start by thinking of basis function models, where the parameters are sampled from a prior, but move to thinking about sampling from the marginal likelihood directly.
Sampling from the Prior
The first thing we’ll do is to set up the parameters of the model, these include the parameters of the prior, the parameters of the basis functions and the noise level.
# set prior variance on w
alpha = 4.
# set the order of the polynomial basis set
degree = 5
# set the noise variance
sigma2 = 0.01
Now we have the variance, we can sample from the prior distribution to see what form we are imposing on the functions a priori.
Let’s now compute a range of values to make predictions at, spanning the new space of inputs,
def polynomial(x, degree, loc, scale):
degrees = np.arange(degree+1)
return ((xloc)/scale)**degrees
now let’s build the basis matrices. First we load in the data
loc = 1950.
scale = 100.
num_data = x.shape[0]
num_pred_data = 100 # how many points to use for plotting predictions
x_pred = np.linspace(1880, 2030, num_pred_data)[:, np.newaxis] # input locations for predictions
Phi_pred = polynomial(x_pred, degree=degree, loc=loc, scale=scale)
Phi = polynomial(x, degree=degree, loc=loc, scale=scale)
Weight Space View
To generate typical functional predictions from the model, we need a set of model parameters. We assume that the parameters are drawn independently from a Gaussian density,
$$
\weightVector \sim \gaussianSamp{\zerosVector}{\alpha\eye},
$$
then we can combine this with the definition of our prediction function $\mappingFunction(\inputVector)$,
$$
\mappingFunction(\inputVector) = \weightVector^\top \basisVector(\inputVector).
$$
We can now sample from the prior density to obtain a vector $\weightVector$ using the function np.random.normal
and combine these parameters with our basis to create some samples of what $\mappingFunction(\inputVector)$ looks like,
Function Space View
The process we have used to generate the samples is a two stage process. To obtain each function, we first generated a sample from the prior,
$$
\weightVector \sim \gaussianSamp{\zerosVector}{\alpha \eye}
$$
then if we compose our basis matrix, $\basisMatrix$ from the basis functions associated with each row then we get,
$$
\basisMatrix = \begin{bmatrix}\basisVector(\inputVector_1) \\ \vdots \\
\basisVector(\inputVector_\numData)\end{bmatrix}
$$
then we can write down the vector of function values, as evaluated at
$$
\mappingFunctionVector = \begin{bmatrix} \mappingFunction_1
\\ \vdots \mappingFunction_\numData\end{bmatrix}
$$
in the form
$$
\mappingFunctionVector = \basisMatrix\weightVector.
$$
Now we can use standard properties of multivariate Gaussians to write down the probability density that is implied over $\mappingFunctionVector$. In particular we know that if $\weightVector$ is sampled from a multivariate normal (or multivariate Gaussian) with covariance $\alpha \eye$ and zero mean, then assuming that $\basisMatrix$ is a deterministic matrix (i.e. it is not sampled from a probability density) then the vector $\mappingFunctionVector$ will also be distributed according to a zero mean multivariate normal as follows,
$$
\mappingFunctionVector \sim \gaussianSamp{\zerosVector}{\alpha \basisMatrix\basisMatrix^\top}.
$$
The question now is, what happens if we sample $\mappingFunctionVector$ directly from this density, rather than first sampling $\weightVector$ and then multiplying by $\basisMatrix$. Let’s try this. First of all we define the covariance as
$$
\kernelMatrix = \alpha
\basisMatrix\basisMatrix^\top.
$$
Now we can use the np.random.multivariate_normal
command for sampling from a multivariate normal with covariance given by $\kernelMatrix$ and zero mean,
fig, ax = plt.subplots(figsize=plot.big_wide_figsize)
for i in range(10):
f_sample = np.random.multivariate_normal(mean=np.zeros(x_pred.size), cov=K)
ax.plot(x_pred.flatten(), f_sample.flatten(), linewidth=2)
mlai.write_figure('gpsamplebasisfunction.svg', directory='../slides/diagrams/kern')
The samples appear very similar to those which we obtained indirectly. That is no surprise because they are effectively drawn from the same mutivariate normal density. However, when sampling $\mappingFunctionVector$ directly we created the covariance for $\mappingFunctionVector$. We can visualise the form of this covaraince in an image in python with a colorbar to show scale.
This image is the covariance expressed between different points on the function. In regression we normally also add independent Gaussian noise to obtain our observations $\dataVector$,
$$
\dataVector = \mappingFunctionVector + \boldsymbol{\epsilon}
$$
where the noise is sampled from an independent Gaussian distribution with variance $\dataStd^2$,
$$
\epsilon \sim \gaussianSamp{\zerosVector}{\dataStd^2\eye}.
$$
we can use properties of Gaussian variables, i.e. the fact that sum of two Gaussian variables is also Gaussian, and that it’s covariance is given by the sum of the two covariances, whilst the mean is given by the sum of the means, to write down the marginal likelihood,
$$
\dataVector \sim \gaussianSamp{\zerosVector}{\basisMatrix\basisMatrix^\top +\dataStd^2\eye}.
$$
Sampling directly from this density gives us the noise corrupted functions,
K = alpha*Phi_pred@Phi_pred.T + sigma2*np.eye(x_pred.size)
for i in range(10):
y_sample = np.random.multivariate_normal(mean=np.zeros(x_pred.size), cov=K)
ax.plot(x_pred.flatten(), y_sample.flatten())
mlai.write_figure('gpsamplebasisfunctionplusnoise.svg',
'../slides/diagrams/kern')
where the effect of our noise term is to roughen the sampled functions, we can also increase the variance of the noise to see a different effect,
fig, ax = plt.subplots(figsize=plot.big_wide_figsize)
for i in range(10):
y_sample = np.random.multivariate_normal(mean=np.zeros(x_pred.size), cov=K)
plt.plot(x_pred.flatten(), y_sample.flatten())
mlai.write_figure('gpsamplebasisfunctionpluslargenoise.svg',
'../slides/diagrams/kern')
Exercise 1
Function Space Reflection How do you include the noise term when sampling in the weight space point of view?
Nondegenerate Gaussian Processes
[edit]
The process described above is degenerate. The covariance function is of rank at most $\numHidden$ and since the theoretical amount of data could always increase $\numData \rightarrow \infty$, the covariance function is not full rank. This means as we increase the amount of data to infinity, there will come a point where we can’t normalize the process because the multivariate Gaussian has the form,
$$
\gaussianDist{\mappingFunctionVector}{\zerosVector}{\kernelMatrix} = \frac{1}{\left(2\pi\right)^{\frac{\numData}{2}}\det{\kernelMatrix}^\frac{1}{2}} \exp\left(\frac{\mappingFunctionVector^\top\kernelMatrix \mappingFunctionVector}{2}\right)
$$
and a nondegenerate kernel matrix leads to $\det{\kernelMatrix} = 0$ defeating the normalization (it’s equivalent to finding a projection in the high dimensional Gaussian where the variance of the the resulting univariate Gaussian is zero, i.e. there is a null space on the covariance, or alternatively you can imagine there are one or more directions where the Gaussian has become the delta function).
In the machine learning field, it was Radford Neal (Neal 1994) that realized the potential of the next step. In his 1994 thesis, he was considering Bayesian neural networks, of the type we described above, and in considered what would happen if you took the number of hidden nodes, or neurons, to infinity, i.e. $\numHidden \rightarrow \infty$.
In loose terms, what Radford considers is what happens to the elements of the covariance function,
$$
\begin{align*}
\kernel_\mappingFunction\left(\inputVector_i, \inputVector_j\right) & = \alpha \activationVector\left(\mappingMatrix_1, \inputVector_i\right)^\top \activationVector\left(\mappingMatrix_1, \inputVector_j\right)\\
& = \alpha \sum_k \activationScalar\left(\mappingVector^{(1)}_k, \inputVector_i\right) \activationScalar\left(\mappingVector^{(1)}_k, \inputVector_j\right)
\end{align*}
$$
if instead of considering a finite number you sample infinitely many of these activation functions, sampling parameters from a prior density, $p(\mappingVectorTwo)$, for each one,
$$
\kernel_\mappingFunction\left(\inputVector_i, \inputVector_j\right) = \alpha \int \activationScalar\left(\mappingVector^{(1)}, \inputVector_i\right) \activationScalar\left(\mappingVector^{(1)}, \inputVector_j\right) p(\mappingVector^{(1)}) \text{d}\mappingVector^{(1)}
$$
And that’s not only for Gaussian $p(\mappingVectorTwo)$. In fact this result holds for a range of activations, and a range of prior densities because of the central limit theorem.
To write it in the form of a probabilistic program, as long as the distribution for ϕ_{i} implied by this short probabilistic program,
$$
\begin{align*}
\mappingVectorTwo & \sim p(\cdot)\\
\phi_i & = \activationScalar\left(\mappingVectorTwo, \inputVector_i\right),
\end{align*}
$$
has finite variance, then the result of taking the number of hidden units to infinity, with appropriate scaling, is also a Gaussian process.
Further Reading
To understand this argument in more detail, I highly recommend reading chapter 2 of Neal’s thesis (Neal 1994), which remains easy to read and clear today. Indeed, for readers interested in Bayesian neural networks, both Raford Neal’s and David MacKay’s PhD thesis (MacKay 1992) remain essential reading. Both theses embody a clarity of thought, and an ability to weave together threads from different fields that was the business of machine learning in the 1990s. Radford and David were also pioneers in making their software widely available and publishing material on the web.
Gaussian Process
[edit]
In our we sampled from the prior over paraemters. Through the properties of multivariate Gaussian densities this prior over parameters implies a particular density for our data observations, $\dataVector$. In this session we sampled directly from this distribution for our data, avoiding the intermediate weightspace representation. This is the approach taken by Gaussian processes. In a Gaussian process you specify the covariance function directly, rather than implicitly through a basis matrix and a prior over parameters. Gaussian processes have the advantage that they can be nonparametric, which in simple terms means that they can have infinite basis functions. In the lectures we introduced the exponentiated quadratic covariance, also known as the RBF or the Gaussian or the squared exponential covariance function. This covariance function is specified by
$$
\kernelScalar(\inputVector, \inputVector^\prime) = \alpha \exp\left( \frac{\left\Vert \inputVector\inputVector^\prime\right\Vert^2}{2\ell^2}\right),
$$
where $\left\Vert\inputVector  \inputVector^\prime\right\Vert^2$ is the squared distance between the two input vectors
$$
\left\Vert\inputVector  \inputVector^\prime\right\Vert^2 = (\inputVector  \inputVector^\prime)^\top (\inputVector  \inputVector^\prime)
$$
Let’s build a covariance matrix based on this function. First we define the form of the covariance function,
We can use this to compute directly the covariance for $\mappingFunctionVector$ at the points given by x_pred
. Let’s define a new function K()
which does this,
Now we can image the resulting covariance,
To visualise the covariance between the points we can use the imshow
function in matplotlib.
Finally, we can sample functions from the marginal likelihood.
Exercise 2
Moving Parameters Have a play with the parameters for this covariance function (the lengthscale and the variance) and see what effects the parameters have on the types of functions you observe.
Bayesian Inference by Rejection Sampling
[edit]
One view of Bayesian inference is to assume we are given a mechanism for generating samples, where we assume that mechanism is representing on accurate view on the way we believe the world works.
This mechanism is known as our prior belief.
We combine our prior belief with our observations of the real world by discarding all those samples that are inconsistent with our prior. The likelihood defines mathematically what we mean by inconsistent with the prior. The higher the noise level in the likelihood, the looser the notion of consistent.
The samples that remain are considered to be samples from the posterior.
This approach to Bayesian inference is closely related to two sampling techniques known as rejection sampling and importance sampling. It is realized in practice in an approach known as approximate Bayesian computation (ABC) or likelihoodfree inference.
In practice, the algorithm is often too slow to be practical, because most samples will be inconsistent with the data and as a result the mechanism has to be operated many times to obtain a few posterior samples.
However, in the Gaussian process case, when the likelihood also assumes Gaussian noise, we can operate this mechanism mathematically, and obtain the posterior density analytically. This is the benefit of Gaussian processes.
First we will load in two python functions for computing the covariance function.
Next we sample from a multivariate normal density (a multivariate Gaussian), using the covariance function as the covariance matrix.
Gaussian Process
The Gaussian process perspective takes the marginal likelihood of the data to be a joint Gaussian density with a covariance given by $\kernelMatrix$. So the model likelihood is of the form,
$$
p(\dataVector\inputMatrix) =
\frac{1}{(2\pi)^{\frac{\numData}{2}}\kernelMatrix^{\frac{1}{2}}}
\exp\left(\frac{1}{2}\dataVector^\top \left(\kernelMatrix+\dataStd^2
\eye\right)^{1}\dataVector\right)
$$
where the input data, $\inputMatrix$, influences the density through the covariance matrix, $\kernelMatrix$ whose elements are computed through the covariance function, $\kernelScalar(\inputVector, \inputVector^\prime)$.
This means that the negative log likelihood (the objective function) is given by,
$$
\errorFunction(\boldsymbol{\theta}) = \frac{1}{2} \log \kernelMatrix
+ \frac{1}{2} \dataVector^\top \left(\kernelMatrix +
\dataStd^2\eye\right)^{1}\dataVector
$$
where the parameters of the model are also embedded in the covariance function, they include the parameters of the kernel (such as lengthscale and variance), and the noise variance, $\dataStd^2$. Let’s create a class in python for storing these variables.
Making Predictions
We now have a probability density that represents functions. How do we make predictions with this density? The density is known as a process because it is consistent. By consistency, here, we mean that the model makes predictions for $\mappingFunctionVector$ that are unaffected by future values of $\mappingFunctionVector^*$ that are currently unobserved (such as test points). If we think of $\mappingFunctionVector^*$ as test points, we can still write down a joint probability density over the training observations, $\mappingFunctionVector$ and the test observations, $\mappingFunctionVector^*$. This joint probability density will be Gaussian, with a covariance matrix given by our covariance function, $\kernelScalar(\inputVector_i, \inputVector_j)$.
$$
\begin{bmatrix}\mappingFunctionVector \\ \mappingFunctionVector^*\end{bmatrix} \sim \gaussianSamp{\zerosVector}{\begin{bmatrix} \kernelMatrix & \kernelMatrix_\ast \\
\kernelMatrix_\ast^\top & \kernelMatrix_{\ast,\ast}\end{bmatrix}}
$$
where here $\kernelMatrix$ is the covariance computed between all the training points, $\kernelMatrix_\ast$ is the covariance matrix computed between the training points and the test points and $\kernelMatrix_{\ast,\ast}$ is the covariance matrix computed betwen all the tests points and themselves. To be clear, let’s compute these now for our example, using x
and y
for the training data (although y
doesn’t enter the covariance) and x_pred
as the test locations.
# set covariance function parameters
variance = 16.0
lengthscale = 8
# set noise variance
sigma2 = 0.05
kernel = Kernel(eq_cov, variance=variance, lengthscale=lengthscale)
K = kernel.K(x, x)
K_star = kernel.K(x, x_pred)
K_starstar = kernel.K(x_pred, x_pred)
Now we use this structure to visualise the covariance between test data and training data. This structure is how information is passed between test and training data. Unlike the maximum likelihood formalisms we’ve been considering so far, the structure expresses correlation between our different data points. However, just like the we now have a joint density between some variables of interest. In particular we have the joint density over $p(\mappingFunctionVector, \mappingFunctionVector^*)$. The joint density is Gaussian and zero mean. It is specified entirely by the covariance matrix, $\kernelMatrix$. That covariance matrix is, in turn, defined by a covariance function. Now we will visualise the form of that covariance in the form of the matrix,
$$
\begin{bmatrix} \kernelMatrix & \kernelMatrix_\ast \\ \kernelMatrix_\ast^\top
& \kernelMatrix_{\ast,\ast}\end{bmatrix}
$$
There are four blocks to this color plot. The upper left block is the covariance of the training data with itself, $\kernelMatrix$. We see some structure here due to the missing data from the first and second world wars. Alongside this covariance (to the right and below) we see the cross covariance between the training and the test data ($\kernelMatrix_*$ and $\kernelMatrix_*^\top$). This is giving us the covariation between our training and our test data. Finally the lower right block The banded structure we now observe is because some of the training points are near to some of the test points. This is how we obtain ‘communication’ between our training data and our test data. If there is no structure in $\kernelMatrix_*$ then our belief about the test data simply matches our prior.
The Importance of the Covariance Function
[edit]
The covariance function encapsulates our assumptions about the data. The equations for the distribution of the prediction function, given the training observations, are highly sensitive to the covariation between the test locations and the training locations as expressed by the matrix $\kernelMatrix_*$. We defined a matrix A which allowed us to express our conditional mean in the form,
$$
\meanVector_\mappingFunction = \mathbf{A}^\top \dataVector,
$$
where $\dataVector$ were our training observations. In other words our mean predictions are always a linear weighted combination of our training data. The weights are given by computing the covariation between the training and the test data ($\kernelMatrix_*$) and scaling it by the inverse covariance of the training data observations, $\left[\kernelMatrix + \dataStd^2 \eye\right]^{1}$. This inverse is the main computational object that needs to be resolved for a Gaussian process. It has a computational burden which is $O(\numData^3)$ and a storage burden which is $O(\numData^2)$. This makes working with Gaussian processes computationally intensive for the situation where $\numData>10,000$.
Improving the Numerics
[edit]
In practice we shouldn’t be using matrix inverse directly to solve the GP system. One more stable way is to compute the Cholesky decomposition of the kernel matrix. The log determinant of the covariance can also be derived from the Cholesky decomposition.
Capacity Control
Gaussian processes are sometimes seen as part of a wider family of methods known as kernel methods. Kernel methods are also based around covariance functions, but in the field they are known as Mercer kernels. Mercer kernels have interpretations as inner products in potentially infinite dimensional Hilbert spaces. This interpretation arises because, if we take α = 1, then the kernel can be expressed as
$$
\kernelMatrix = \basisMatrix\basisMatrix^\top
$$
which imples the elements of the kernel are given by,
$$
\kernelScalar(\inputVector, \inputVector^\prime) = \basisVector(\inputVector)^\top \basisVector(\inputVector^\prime).
$$
So we see that the kernel function is developed from an inner product between the basis functions. Mercer’s theorem tells us that any valid positive definite function can be expressed as this inner product but with the caveat that the inner product could be infinite length. This idea has been used quite widely to kernelize algorithms that depend on inner products. The kernel functions are equivalent to covariance functions and they are parameterized accordingly. In the kernel modeling community it is generally accepted that kernel parameter estimation is a difficult problem and the normal solution is to cross validate to obtain parameters. This can cause difficulties when a large number of kernel parameters need to be estimated. In Gaussian process modelling kernel parameter estimation (in the simplest case proceeds) by maximum likelihood. This involves taking gradients of the likelihood with respect to the parameters of the covariance function.
Gradients of the Likelihood
The easiest conceptual way to obtain the gradients is a two step process. The first step involves taking the gradient of the likelihood with respect to the covariance function, the second step involves considering the gradient of the covariance function with respect to its parameters.
Overall Process Scale
In general we won’t be able to find parameters of the covariance function through fixed point equations, we will need to do gradient based optimization.
Capacity Control and Data Fit
The objective function can be decomposed into two terms, a capacity control term, and a data fit term. The capacity control term is the log determinant of the covariance. The data fit term is the matrix inner product between the data and the inverse covariance.
Learning Covariance Parameters
[edit]
Can we determine covariance parameters from the data?
$$
\gaussianDist{\dataVector}{\mathbf{0}}{\kernelMatrix}=\frac{1}{(2\pi)^\frac{\numData}{2}{\det{\kernelMatrix}^{\frac{1}{2}}}}{\exp\left(\frac{\dataVector^{\top}\kernelMatrix^{1}\dataVector}{2}\right)}
$$
$$
\begin{aligned}
\gaussianDist{\dataVector}{\mathbf{0}}{\kernelMatrix}=\frac{1}{(2\pi)^\frac{\numData}{2}\color{blue}{\det{\kernelMatrix}^{\frac{1}{2}}}}\color{red}{\exp\left(\frac{\dataVector^{\top}\kernelMatrix^{1}\dataVector}{2}\right)}
\end{aligned}
$$
$$
\begin{aligned}
\log \gaussianDist{\dataVector}{\mathbf{0}}{\kernelMatrix}=&\color{blue}{\frac{1}{2}\log\det{\kernelMatrix}}\color{red}{\frac{\dataVector^{\top}\kernelMatrix^{1}\dataVector}{2}} \\ &\frac{\numData}{2}\log2\pi
\end{aligned}
$$
$$
\errorFunction(\parameterVector) = \color{blue}{\frac{1}{2}\log\det{\kernelMatrix}} + \color{red}{\frac{\dataVector^{\top}\kernelMatrix^{1}\dataVector}{2}}
$$
Capacity Control through the Determinant
[edit]
The parameters are inside the covariance function (matrix).
$$\kernelScalar_{i, j} = \kernelScalar(\inputVals_i, \inputVals_j; \parameterVector)$$
$$\kernelMatrix = \rotationMatrix \eigenvalueMatrix^2 \rotationMatrix^\top$$

$\eigenvalueMatrix$ represents distance on axes. $\rotationMatrix$ gives rotation. 
 $\eigenvalueMatrix$ is diagonal, $\rotationMatrix^\top\rotationMatrix = \eye$.
 Useful representation since $\det{\kernelMatrix} = \det{\eigenvalueMatrix^2} = \det{\eigenvalueMatrix}^2$.
Quadratic Data Fit
[edit]
Data Fit Term
[edit]
Exponentiated Quadratic Covariance
[edit]
The exponentiated quadratic covariance, also known as the Gaussian covariance or the RBF covariance and the squared exponential. Covariance between two points is related to the negative exponential of the squared distnace between those points. This covariance function can be derived in a few different ways: as the infinite limit of a radial basis function neural network, as diffusion in the heat equation, as a Gaussian filter in Fourier space or as the composition as a series of linear filters applied to a base function.
The covariance takes the following form,
$$
\kernelScalar(\inputVector, \inputVector^\prime) = \alpha \exp\left(\frac{\ltwoNorm{\inputVector\inputVector^\prime}^2}{2\lengthScale^2}\right)
$$
where ℓ is the length scale or time scale of the process and α represents the overall process variance.
$$\kernelScalar(\inputVector, \inputVector^\prime) = \alpha \exp\left(\frac{\ltwoNorm{\inputVector\inputVector^\prime}^2}{2\lengthScale^2}\right)$$

Olympic Marathon Data
[edit]


The first thing we will do is load a standard data set for regression modelling. The data consists of the pace of Olympic Gold Medal Marathon winners for the Olympics from 1896 to present. First we load in the data and plot.
data = pods.datasets.olympic_marathon_men()
x = data['X']
y = data['Y']
offset = y.mean()
scale = np.sqrt(y.var())
Things to notice about the data include the outlier in 1904, in this year, the olympics was in St Louis, USA. Organizational problems and challenges with dust kicked up by the cars following the race meant that participants got lost, and only very few participants completed.
More recent years see more consistently quick marathons.
Alan Turing
[edit]


If we had to summarise the objectives of machine learning in one word, a very good candidate for that word would be generalization. What is generalization? From a human perspective it might be summarised as the ability to take lessons learned in one domain and apply them to another domain. If we accept the definition given in the first session for machine learning,
$$
\text{data} + \text{model} \stackrel{\text{compute}}{\rightarrow} \text{prediction}
$$
then we see that without a model we can’t generalise: we only have data. Data is fine for answering very specific questions, like “Who won the Olympic Marathon in 2012?”, because we have that answer stored, however, we are not given the answer to many other questions. For example, Alan Turing was a formidable marathon runner, in 1946 he ran a time 2 hours 46 minutes (just under four minutes per kilometer, faster than I and most of the other Endcliffe Park Run runners can do 5 km). What is the probability he would have won an Olympics if one had been held in 1946?
To answer this question we need to generalize, but before we formalize the concept of generalization let’s introduce some formal representation of what it means to generalize in machine learning.
Our first objective will be to perform a Gaussian process fit to the data, we’ll do this using the GPy software.
m_full = GPy.models.GPRegression(x,yhat)
_ = m_full.optimize() # Optimize parameters of covariance function
The first command sets up the model, then m_full.optimize()
optimizes the parameters of the covariance function and the noise level of the model. Once the fit is complete, we’ll try creating some test points, and computing the output of the GP model in terms of the mean and standard deviation of the posterior functions between 1870 and 2030. We plot the mean function and the standard deviation at 200 locations. We can obtain the predictions using y_mean, y_var = m_full.predict(xt)
xt = np.linspace(1870,2030,200)[:,np.newaxis]
yt_mean, yt_var = m_full.predict(xt)
yt_sd=np.sqrt(yt_var)
Now we plot the results using the helper function in teaching_plots
.
Fit Quality
In the fit we see that the error bars (coming mainly from the noise variance) are quite large. This is likely due to the outlier point in 1904, ignoring that point we can see that a tighter fit is obtained. To see this make a version of the model, m_clean
, where that point is removed.
x_clean=np.vstack((x[0:2, :], x[3:, :]))
y_clean=np.vstack((y[0:2, :], y[3:, :]))
m_clean = GPy.models.GPRegression(x_clean,y_clean)
_ = m_clean.optimize()
Gene Expression Example
[edit]
We now consider an example in gene expression. Gene expression is the measurement of mRNA levels expressed in cells. These mRNA levels show which genes are ‘switched on’ and producing data. In the example we will use a Gaussian process to determine whether a given gene is active, or we are merely observing a noise response.
Della Gatta Gene Data
[edit]
 Given given expression levels in the form of a time series from Della Gatta et al. (2008).
data = pods.datasets.della_gatta_TRP63_gene_expression(data_set='della_gatta',gene_number=937)
x = data['X']
y = data['Y']
offset = y.mean()
scale = np.sqrt(y.var())
 Want to detect if a gene is expressed or not, fit a GP to each gene Kalaitzis and Lawrence (2011).
Our first objective will be to perform a Gaussian process fit to the data, we’ll do this using the GPy software.
m_full = GPy.models.GPRegression(x,yhat)
m_full.kern.lengthscale=50
_ = m_full.optimize() # Optimize parameters of covariance function
Initialize the length scale parameter (which here actually represents a time scale of the covariance function) to a reasonable value. Default would be 1, but here we set it to 50 minutes, given points are arriving across zero to 250 minutes.
xt = np.linspace(20,260,200)[:,np.newaxis]
yt_mean, yt_var = m_full.predict(xt)
yt_sd=np.sqrt(yt_var)
Now we plot the results using the helper function in teaching_plots
.
Now we try a model initialized with a longer length scale.
m_full2 = GPy.models.GPRegression(x,yhat)
m_full2.kern.lengthscale=2000
_ = m_full2.optimize() # Optimize parameters of covariance function
Now we try a model initialized with a lower noise.
m_full3 = GPy.models.GPRegression(x,yhat)
m_full3.kern.lengthscale=20
m_full3.likelihood.variance=0.001
_ = m_full3.optimize() # Optimize parameters of covariance function
Example: Prediction of Malaria Incidence in Uganda
[edit]
As an example of using Gaussian process models within the full pipeline from data to decsion, we’ll consider the prediction of Malaria incidence in Uganda. For the purposes of this study malaria reports come in two forms, HMIS reports from health centres and Sentinel data, which is curated by the WHO. There are limited sentinel sites and many HMIS sites.
The work is from Ricardo Andrade Pacheco’s PhD thesis, completed in collaboration with John Quinn and Martin Mubangizi (AndradePacheco et al. 2014; Mubangizi et al. 2014). John and Martin were initally from the AIDEV group from the University of Makerere in Kampala and more latterly they were based at UN Global Pulse in Kampala.
Malaria data is spatial data. Uganda is split into districts, and health reports can be found for each district. This suggests that models such as conditional random fields could be used for spatial modelling, but there are two complexities with this. First of all, occasionally districts split into two. Secondly, sentinel sites are a specific location within a district, such as Nagongera which is a sentinel site based in the Tororo district.
(AndradePacheco et al. 2014; Mubangizi et al. 2014)
Stephen Kiprotich, the 2012 gold medal winner from the London Olympics, comes from Kapchorwa district, in eastern Uganda, near the border with Kenya.
The common standard for collecting health data on the African continent is from the Health management information systems (HMIS). However, this data suffers from missing values (Gething et al. 2006) and diagnosis of diseases like typhoid and malaria may be confounded.
World Health Organization Sentinel Surveillance systems are set up “when highquality data are needed about a particular disease that cannot be obtained through a passive system”. Several sentinel sites give accurate assessment of malaria disease levels in Uganda, including a site in Nagongera.
In collaboration with the AI Research Group at Makerere we chose to investigate whether Gaussian process models could be used to assimilate information from these two different sources of disease informaton. Further, we were interested in whether local information on rainfall and temperature could be used to improve malaria estimates.
The aim of the project was to use WHO Sentinel sites, alongside rainfall and temperature, to improve predictions from HMIS data of levels of malaria.
Early Warning Systems
Health monitoring system for the Kabarole district. Here we have fitted the reports with a Gaussian process with an additive covariance function. It has two components, one is a long time scale component (in red above) the other is a short time scale component (in blue).
Monitoring proceeds by considering two aspects of the curve. Is the blue line (the short term report signal) above the red (which represents the long term trend? If so we have higher than expected reports. If this is the case and the gradient is still positive (i.e. reports are going up) we encode this with a red color. If it is the case and the gradient of the blue line is negative (i.e. reports are going down) we encode this with an amber color. Conversely, if the blue line is below the red and decreasing, we color green. On the other hand if it is below red but increasing, we color yellow.
This gives us an early warning system for disease. Red is a bad situation getting worse, amber is bad, but improving. Green is good and getting better and yellow good but degrading.
Finally, there is a gray region which represents when the scale of the effect is small.
These colors can now be observed directly on a spatial map of the districts to give an immediate impression of the current status of the disease across the country.
Additive Covariance
[edit]
An additive covariance function is derived from considering the result of summing two Gaussian processes together. If the first Gaussian process is g( ⋅ ), governed by covariance $\kernelScalar_g(\cdot, \cdot)$ and the second process is h( ⋅ ), governed by covariance $\kernelScalar_h(\cdot, \cdot)$ then the combined process f( ⋅ ) = g( ⋅ ) + h( ⋅ ) is govererned by a covariance function,
$$
\kernelScalar_f(\inputVector, \inputVector^\prime) = \kernelScalar_g(\inputVector, \inputVector^\prime) + \kernelScalar_h(\inputVector, \inputVector^\prime)
$$
$$\kernelScalar_f(\inputVector, \inputVector^\prime) = \kernelScalar_g(\inputVector, \inputVector^\prime) + \kernelScalar_h(\inputVector, \inputVector^\prime)$$

Analysis of US Birth Rates
[edit]
There’s a nice analysis of US birth rates by Gaussian processes with additive covariances in Gelman et al. (2013). A combination of covariance functions are used to take account of weekly and yearly trends. The analysis is summarized on the cover of the book.


Basis Function Covariance
[edit]
The fixed basis function covariance just comes from the properties of a multivariate Gaussian, if we decide
$$
\mappingFunctionVector=\basisMatrix\mappingVector
$$
and then we assume
$$
\mappingVector \sim \gaussianSamp{\zerosVector}{\alpha\eye}
$$
then it follows from the properties of a multivariate Gaussian that
$$
\mappingFunctionVector \sim \gaussianSamp{\zerosVector}{\alpha\basisMatrix\basisMatrix^\top}
$$
meaning that the vector of observations from the function is jointly distributed as a Gaussian process and the covariance matrix is $\kernelMatrix = \alpha\basisMatrix \basisMatrix^\top$, each element of the covariance matrix can then be found as the inner product between two rows of the basis funciton matrix.
$$\kernel(\inputVector, \inputVector^\prime) = \basisVector(\inputVector)^\top \basisVector(\inputVector^\prime)$$

Brownian Covariance
[edit]
Brownian motion is also a Gaussian process. It follows a Gaussian random walk, with diffusion occuring at each time point driven by a Gaussian input. This implies it is both Markov and Gaussian. The covariance function for Brownian motion has the form
$$
\kernelScalar(t, t^\prime)=\alpha \min(t, t^\prime)
$$
$$\kernelScalar(t, t^\prime)=\alpha \min(t, t^\prime)$$

MLP Covariance
[edit]
The multilayer perceptron (MLP) covariance, also known as the neural network covariance or the arcsin covariance, is derived by considering the infinite limit of a neural network.
$$\kernelScalar(\inputVector, \inputVector^\prime) = \alpha \arcsin\left(\frac{w \inputVector^\top \inputVector^\prime + b}{\sqrt{\left(w \inputVector^\top \inputVector + b + 1\right)\left(w \left.\inputVector^\prime\right.^\top \inputVector^\prime + b + 1\right)}}\right)$$

GPSS: Gaussian Process Summer School
[edit]
If you’re interested in finding out more about Gaussian processes, you can attend the Gaussian process summer school, or view the lectures and material on line. Details of the school, future events and past events can be found at the website http://gpss.cc.
GPy: A Gaussian Process Framework in Python
[edit]
Gaussian processes are a flexible tool for nonparametric analysis with uncertainty. The GPy software was started in Sheffield to provide a easy to use interface to GPs. One which allowed the user to focus on the modelling rather than the mathematics.
GPy is a BSD licensed software code base for implementing Gaussian process models in python. This allows GPs to be combined with a wide variety of software libraries.
The software itself is available on GitHub and the team welcomes contributions.
The aim for GPy is to be a probabilisticstyle programming language, i.e. you specify the model rather than the algorithm. As well as a large range of covariance functions the software allows for nonGaussian likelihoods, multivariate outputs, dimensionality reduction and approximations for larger data sets.
The documentation for GPy can be found here.
Thanks!
For more information on these subjects and more you might want to check the following resources.
 twitter: @lawrennd
 podcast: The Talking Machines
 newspaper: Guardian Profile Page
 blog: http://inverseprobability.com
References
AndradePacheco, Ricardo, Martin Mubangizi, John Quinn, and Neil D. Lawrence. 2014. “Consistent Mapping of Government Malaria Records Across a Changing Territory Delimitation.” Malaria Journal 13 (Suppl 1). https://doi.org/10.1186/1475287513S1P5.
Della Gatta, Giusy, Mukesh Bansal, Alberto AmbesiImpiombato, Dario Antonini, Caterina Missero, and Diego di Bernardo. 2008. “Direct Targets of the Trp63 Transcription Factor Revealed by a Combination of Gene Expression Profiling and Reverse Engineering.” Genome Research 18 (6): 939–48. https://doi.org/10.1101/gr.073601.107.
Gelman, Andrew, John B. Carlin, Hal S. Stern, and Donald B. Rubin. 2013. Bayesian Data Analysis. 3rd ed. Chapman; Hall.
Gething, Peter W., Abdisalan M. Noor, Priscilla W. Gikandi, Esther A. A. Ogara, Simon I. Hay, Mark S. Nixon, Robert W. Snow, and Peter M. Atkinson. 2006. “Improving Imperfect Data from Health Management Information Systems in Africa Using Space–Time Geostatistics.” PLoS Medicine 3 (6). https://doi.org/10.1371/journal.pmed.0030271.
Kalaitzis, Alfredo A., and Neil D. Lawrence. 2011. “A Simple Approach to Ranking Differentially Expressed Gene Expression Time Courses Through Gaussian Process Regression.” BMC Bioinformatics 12 (180). https://doi.org/10.1186/1471210512180.
MacKay, David J. C. 1992. “Bayesian Methods for Adaptive Models.” PhD thesis, California Institute of Technology.
Mubangizi, Martin, Ricardo AndradePacheco, Michael Thomas Smith, John Quinn, and Neil D. Lawrence. 2014. “Malaria Surveillance with Multiple Data Sources Using Gaussian Process Models.” In 1st International Conference on the Use of Mobile ICT in Africa.
Neal, Radford M. 1994. “Bayesian Learning for Neural Networks.” PhD thesis, Dept. of Computer Science, University of Toronto.