{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Deep Gaussian Processes: A Motivation and Introduction\n",
"\n",
"### [Neil D. Lawrence](http://inverseprobability.com), University of\n",
"\n",
"Cambridge\n",
"\n",
"### 2022-06-06"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Abstract**: Modern machine learning methods have driven significant\n",
"advances in artificial intelligence, with notable examples coming from\n",
"Deep Learning, enabling super-human performance in the game of Go and\n",
"highly accurate prediction of protein folding e.g. AlphaFold. In this\n",
"talk we look at deep learning from the perspective of Gaussian\n",
"processes. Deep Gaussian processes extend the notion of deep learning to\n",
"propagate uncertainty alongside function values. We’ll explain why this\n",
"is important and show some simple examples."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"::: {.cell .markdown}\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Fourth Industrial Revolution\n",
"\n",
"\\[edit\\]\n",
"\n",
"The fourth industrial revolution bears the particular hallmark of being\n",
"the first revolution that has been named before it has happened. This is\n",
"particularly unfortunate, because it is not in fact an industrial\n",
"revolution at all. Nor is it necessarily a distinct phenomenon. It is\n",
"part of a revolution in information, one that goes back to digitisation\n",
"and the invention of the silicon chip.\n",
"\n",
"Or to put it more precisely, it is a revolution in how information can\n",
"affect the physical world. The interchange between information and the\n",
"physical world."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install notutils"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# What is Machine Learning?\n",
"\n",
"\\[edit\\]\n",
"\n",
"What is machine learning? At its most basic level machine learning is a\n",
"combination of\n",
"\n",
"$$\\text{data} + \\text{model} \\stackrel{\\text{compute}}{\\rightarrow} \\text{prediction}$$\n",
"\n",
"where *data* is our observations. They can be actively or passively\n",
"acquired (meta-data). The *model* contains our assumptions, based on\n",
"previous experience. That experience can be other data, it can come from\n",
"transfer learning, or it can merely be our beliefs about the\n",
"regularities of the universe. In humans our models include our inductive\n",
"biases. The *prediction* is an action to be taken or a categorization or\n",
"a quality score. The reason that machine learning has become a mainstay\n",
"of artificial intelligence is the importance of predictions in\n",
"artificial intelligence. The data and the model are combined through\n",
"computation.\n",
"\n",
"In practice we normally perform machine learning using two functions. To\n",
"combine data with a model we typically make use of:\n",
"\n",
"**a prediction function** a function which is used to make the\n",
"predictions. It includes our beliefs about the regularities of the\n",
"universe, our assumptions about how the world works, e.g., smoothness,\n",
"spatial similarities, temporal similarities.\n",
"\n",
"**an objective function** a function which defines the cost of\n",
"misprediction. Typically, it includes knowledge about the world’s\n",
"generating processes (probabilistic objectives) or the costs we pay for\n",
"mispredictions (empirical risk minimization).\n",
"\n",
"The combination of data and model through the prediction function and\n",
"the objective function leads to a *learning algorithm*. The class of\n",
"prediction functions and objective functions we can make use of is\n",
"restricted by the algorithms they lead to. If the prediction function or\n",
"the objective function are too complex, then it can be difficult to find\n",
"an appropriate learning algorithm. Much of the academic field of machine\n",
"learning is the quest for new learning algorithms that allow us to bring\n",
"different types of models and data together.\n",
"\n",
"A useful reference for state of the art in machine learning is the UK\n",
"Royal Society Report, [Machine Learning: Power and Promise of Computers\n",
"that Learn by\n",
"Example](https://royalsociety.org/~/media/policy/projects/machine-learning/publications/machine-learning-report.pdf).\n",
"\n",
"You can also check my post blog post on [What is Machine\n",
"Learning?](http://inverseprobability.com/2017/07/17/what-is-machine-learning)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## What does Machine Learning do?\n",
"\n",
"\\[edit\\]\n",
"\n",
"Any process of automation allows us to scale what we do by codifying a\n",
"process in some way that makes it efficient and repeatable. Machine\n",
"learning automates by emulating human (or other actions) found in data.\n",
"Machine learning codifies in the form of a mathematical function that is\n",
"learnt by a computer. If we can create these mathematical functions in\n",
"ways in which they can interconnect, then we can also build systems.\n",
"\n",
"Machine learning works through codifing a prediction of interest into a\n",
"mathematical function. For example, we can try and predict the\n",
"probability that a customer wants to by a jersey given knowledge of\n",
"their age, and the latitude where they live. The technique known as\n",
"logistic regression estimates the odds that someone will by a jumper as\n",
"a linear weighted sum of the features of interest.\n",
"\n",
"$$ \\text{odds} = \\frac{p(\\text{bought})}{p(\\text{not bought})} $$\n",
"\n",
"$$ \\log \\text{odds} = \\beta_0 + \\beta_1 \\text{age} + \\beta_2 \\text{latitude}.$$\n",
"Here $\\beta_0$, $\\beta_1$ and $\\beta_2$ are the parameters of the model.\n",
"If $\\beta_1$ and $\\beta_2$ are both positive, then the log-odds that\n",
"someone will buy a jumper increase with increasing latitude and age, so\n",
"the further north you are and the older you are the more likely you are\n",
"to buy a jumper. The parameter $\\beta_0$ is an offset parameter, and\n",
"gives the log-odds of buying a jumper at zero age and on the equator. It\n",
"is likely to be negative[1] indicating that the purchase is\n",
"odds-against. This is actually a classical statistical model, and models\n",
"like logistic regression are widely used to estimate probabilities from\n",
"ad-click prediction to risk of disease.\n",
"\n",
"This is called a generalized linear model, we can also think of it as\n",
"estimating the *probability* of a purchase as a nonlinear function of\n",
"the features (age, lattitude) and the parameters (the $\\beta$ values).\n",
"The function is known as the *sigmoid* or [logistic\n",
"function](https://en.wikipedia.org/wiki/Logistic_regression), thus the\n",
"name *logistic* regression.\n",
"\n",
"$$ p(\\text{bought}) = \\sigma\\left(\\beta_0 + \\beta_1 \\text{age} + \\beta_2 \\text{latitude}\\right).$$\n",
"In the case where we have *features* to help us predict, we sometimes\n",
"denote such features as a vector, $\\mathbf{ x}$, and we then use an\n",
"inner product between the features and the parameters,\n",
"$\\boldsymbol{\\beta}^\\top \\mathbf{ x}= \\beta_1 x_1 + \\beta_2 x_2 + \\beta_3 x_3 ...$,\n",
"to represent the argument of the sigmoid.\n",
"\n",
"$$ p(\\text{bought}) = \\sigma\\left(\\boldsymbol{\\beta}^\\top \\mathbf{ x}\\right).$$\n",
"More generally, we aim to predict some aspect of our data, $y$, by\n",
"relating it through a mathematical function, $f(\\cdot)$, to the\n",
"parameters, $\\boldsymbol{\\beta}$ and the data, $\\mathbf{ x}$.\n",
"\n",
"$$ y= f\\left(\\mathbf{ x}, \\boldsymbol{\\beta}\\right).$$ We call\n",
"$f(\\cdot)$ the *prediction function*.\n",
"\n",
"To obtain the fit to data, we use a separate function called the\n",
"*objective function* that gives us a mathematical representation of the\n",
"difference between our predictions and the real data.\n",
"\n",
"$$E(\\boldsymbol{\\beta}, \\mathbf{Y}, \\mathbf{X})$$ A commonly used\n",
"examples (for example in a regression problem) is least squares,\n",
"$$E(\\boldsymbol{\\beta}, \\mathbf{Y}, \\mathbf{X}) = \\sum_{i=1}^n\\left(y_i - f(\\mathbf{ x}_i, \\boldsymbol{\\beta})\\right)^2.$$\n",
"\n",
"If a linear prediction function is combined with the least squares\n",
"objective function then that gives us a classical *linear regression*,\n",
"another classical statistical model. Statistics often focusses on linear\n",
"models because it makes interpretation of the model easier.\n",
"Interpretation is key in statistics because the aim is normally to\n",
"validate questions by analysis of data. Machine learning has typically\n",
"focussed more on the prediction function itself and worried less about\n",
"the interpretation of parameters, which are normally denoted by\n",
"$\\mathbf{w}$ instead of $\\boldsymbol{\\beta}$. As a result *non-linear*\n",
"functions are explored more often as they tend to improve quality of\n",
"predictions but at the expense of interpretability.\n",
"\n",
"[1] The logarithm of a number less than one is negative, for a number\n",
"greater than one the logarithm is positive. So if odds are greater than\n",
"evens (odds-on) the log-odds are positive, if the odds are less than\n",
"evens (odds-against) the log-odds will be negative."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Deep Learning\n",
"\n",
"\\[edit\\]\n",
"\n",
"Classical statistical models and simple machine learning models have a\n",
"great deal in common. The main difference between the fields is\n",
"philosophical. Machine learning practitioners are typically more\n",
"concerned with the quality of prediciton (e.g. measured by ROC curve)\n",
"while statisticians tend to focus more on the interpretability of the\n",
"model and the validity of any decisions drawn from that interpretation.\n",
"For example, a statistical model may be used to validate whether a large\n",
"scale intervention (such as the mass provision of mosquito nets) has had\n",
"a long term effect on disease (such as malaria). In this case one of the\n",
"covariates is likely to be the provision level of nets in a particular\n",
"region. The response variable would be the rate of malaria disease in\n",
"the region. The parmaeter, $\\beta_1$ associated with that covariate will\n",
"demonstrate a positive or negative effect which would be validated in\n",
"answering the question. The focus in statistics would be less on the\n",
"accuracy of the response variable and more on the validity of the\n",
"interpretation of the effect variable, $\\beta_1$.\n",
"\n",
"A machine learning practitioner on the other hand would typically denote\n",
"the parameter $w_1$, instead of $\\beta_1$ and would only be interested\n",
"in the output of the prediction function, $f(\\cdot)$ rather than the\n",
"parameter itself. The general formalism of the prediction function\n",
"allows for *non-linear* models. In machine learning, the emphasis on\n",
"prediction over interpretability means that non-linear models are often\n",
"used. The parameters, $\\mathbf{w}$, are a means to an end (good\n",
"prediction) rather than an end in themselves (interpretable).\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## DeepFace\n",
"\n",
"\\[edit\\]\n",
"\n",
"\n",
"\n",
"Figure: The DeepFace architecture (Taigman et al., 2014), visualized\n",
"through colors to represent the functional mappings at each layer. There\n",
"are 120 million parameters in the model.\n",
"\n",
"The DeepFace architecture (Taigman et al., 2014) consists of layers that\n",
"deal with *translation* invariances, known as convolutional layers.\n",
"These layers are followed by three locally-connected layers and two\n",
"fully-connected layers. Color illustrates feature maps produced at each\n",
"layer. The neural network includes more than 120 million parameters,\n",
"where more than 95% come from the local and fully connected layers."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Deep Learning as Pinball\n",
"\n",
"\\[edit\\]\n",
"\n",
"\n",
"\n",
"Figure: Deep learning models are composition of simple functions. We\n",
"can think of a pinball machine as an analogy. Each layer of pins\n",
"corresponds to one of the layers of functions in the model. Input data\n",
"is represented by the location of the ball from left to right when it is\n",
"dropped in from the top. Output class comes from the position of the\n",
"ball as it leaves the pins at the bottom.\n",
"\n",
"Sometimes deep learning models are described as being like the brain, or\n",
"too complex to understand, but one analogy I find useful to help the\n",
"gist of these models is to think of them as being similar to early pin\n",
"ball machines.\n",
"\n",
"In a deep neural network, we input a number (or numbers), whereas in\n",
"pinball, we input a ball.\n",
"\n",
"Think of the location of the ball on the left-right axis as a single\n",
"number. Our simple pinball machine can only take one number at a time.\n",
"As the ball falls through the machine, each layer of pins can be thought\n",
"of as a different layer of ‘neurons.’ Each layer acts to move the ball\n",
"from left to right.\n",
"\n",
"In a pinball machine, when the ball gets to the bottom it might fall\n",
"into a hole defining a score, in a neural network, that is equivalent to\n",
"the decision: a classification of the input object.\n",
"\n",
"An image has more than one number associated with it, so it is like\n",
"playing pinball in a *hyper-space*.\n",
"\n",
"\n",
"\n",
"Figure: At initialization, the pins, which represent the parameters\n",
"of the function, aren’t in the right place to bring the balls to the\n",
"correct decisions.\n",
"\n",
"\n",
"\n",
"Figure: After learning the pins are now in the right place to bring\n",
"the balls to the correct decisions.\n",
"\n",
"Learning involves moving all the pins to be in the correct position, so\n",
"that the ball ends up in the right place when it’s fallen through the\n",
"machine. But moving all these pins in hyperspace can be difficult.\n",
"\n",
"In a hyper-space you have to put a lot of data through the machine for\n",
"to explore the positions of all the pins. Even when you feed many\n",
"millions of data points through the machine, there are likely to be\n",
"regions in the hyper-space where no ball has passed. When future test\n",
"data passes through the machine in a new route unusual things can\n",
"happen.\n",
"\n",
"*Adversarial examples* exploit this high dimensional space. If you have\n",
"access to the pinball machine, you can use gradient methods to find a\n",
"position for the ball in the hyper space where the image looks like one\n",
"thing, but will be classified as another.\n",
"\n",
"Probabilistic methods explore more of the space by considering a range\n",
"of possible paths for the ball through the machine. This helps to make\n",
"them more data efficient and gives some robustness to adversarial\n",
"examples."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Deep Neural Network\n",
"\n",
"\\[edit\\]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install daft"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib\n",
"# Comment for google colab (no latex available)\n",
"#matplotlib.rc('text', usetex=True)\n",
"#matplotlib.rcParams['text.latex.preamble']=[r\"\\usepackage{amsmath}\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import mlai.plot as plot"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#plot.deep_nn(diagrams='./deepgp/')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: A deep neural network. Input nodes are shown at the bottom.\n",
"Each hidden layer is the result of applying an affine transformation to\n",
"the previous layer and placing through an activation function.\n",
"\n",
"Mathematically, each layer of a neural network is given through\n",
"computing the activation function, $\\phi(\\cdot)$, contingent on the\n",
"previous layer, or the inputs. In this way the activation functions, are\n",
"composed to generate more complex interactions than would be possible\n",
"with any single layer. $$\n",
"\\begin{align*}\n",
" \\mathbf{ h}_{1} &= \\phi\\left(\\mathbf{W}_1 \\mathbf{ x}\\right)\\\\\n",
" \\mathbf{ h}_{2} &= \\phi\\left(\\mathbf{W}_2\\mathbf{ h}_{1}\\right)\\\\\n",
" \\mathbf{ h}_{3} &= \\phi\\left(\\mathbf{W}_3 \\mathbf{ h}_{2}\\right)\\\\\n",
" f&= \\mathbf{ w}_4 ^\\top\\mathbf{ h}_{3}\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## AlphaGo\n",
"\n",
"\\[edit\\]\n",
"\n",
"In January 2016, the UK company DeepMind’s machine learning system\n",
"AlphaGo won a challenge match in which it beat the world champion Go\n",
"player, Lee Se-Deol.\n",
"\n",
"\n",
"\n",
"Figure: AlphaGo’s win made the front cover of the journal Nature.\n",
"\n",
"Go is a board game that is known to be over 2,500 years old. It is\n",
"considered challenging for computer systems becaue of its branching\n",
"factor: the number of possible moves that can be made at a given board\n",
"postion. The branching factor of Chess is around 35. The branching\n",
"factor of Go is around 250. This makes Go less susceptible to exhaustive\n",
"search techniques which were a foundation of DeepBlue, the chess machine\n",
"that was able to win against Gary Kasparov in 1997. As a result, many\n",
"commentators predicted that Go was out of the reach of contemporary AI\n",
"systems, with some predicting that beating the world champion wouldn’t\n",
"occur until 2025."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from IPython.lib.display import YouTubeVideo\n",
"YouTubeVideo('WXuK6gekU1Y')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Figure: The AlphaGo documentary tells the story of the tournament\n",
"between Lee Se-dol and AlphaGo.\n",
"\n",
"While exhaustive search was beyond the reach of computer systems, they\n",
"combined stochastic search of the game tree with neural networks. But\n",
"when training those neural networks vast quantities of data and game\n",
"play were used. I wrote more about this at the time in the Guardian\n",
"article “Guardian article on [Google AI versus the Go\n",
"grandmaster](https://www.theguardian.com/media-network/2016/jan/28/google-ai-go-grandmaster-real-winner-deepmind).”\n",
"\n",
"However, despite the many millions of matches that AlphaGo had played,\n",
"Lee Sedol managed to find a board position that was distinct from\n",
"anything AlphaGo had seen before. Within the high dimensional pinball\n",
"machine that made up AlphaGo’s decision making systems, Lee Sedol found\n",
"a niche, an Achillean chink in AlphaGo’s armour. He found a path through\n",
"the neural network where no data had every been before. He found a\n",
"location in feature space “where there be dragons.” A space where the\n",
"model had not seen data before and one where it became confused.\n",
"\n",
"
\n",
"
\n",
"
\n",
"\n",
"\n",
"\n",
"
\n",
"
\n",
"\n",
"\n",
"\n",
"
\n",
"
\n",
"
\n",
"\n",
"Figure: Move 78 of [Game\n",
"4](https://en.wikipedia.org/wiki/AlphaGo_versus_Lee_Sedol#Game_4) was\n",
"critical in allowing Lee Se-dol to win the match. Described by [Gu\n",
"Li](https://en.wikipedia.org/wiki/Gu_Li_(Go_player)) as a ‘divine\n",
"move.’\n",
"\n",
"This is a remarkable achievement, a human, with far less experience than\n",
"the machine of the game, was able to outplay by placing the machine in\n",
"an unfamiliar situation. In honour of this achievements, I like to call\n",
"these voids in the machines understanding “Sedolian voids.”"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Uber ATG\n",
"\n",
"Unfortunately, such Sedolian voids are not constrained to game playing\n",
"machines. On March 18th 2018, just two years after AlphaGo’s victory,\n",
"the Uber ATG self-driving vehicle killed a pedestrian in Tuscson\n",
"Arizona. The neural networks that were trained on pedestrian detection\n",
"did not detect Elaine because she was pushing a bicycle, laden with her\n",
"bags, across the highway.[1] This situation represented a Sedolian void\n",
"for the neural network, and it failed to stop the car.\n",
"\n",
"[1] The NTSB Report on the accident can be found online here:\n",
"."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from IPython.lib.display import YouTubeVideo\n",
"YouTubeVideo('iWGhXof45zI')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Figure: A vehicle operated by Uber ATG was involved in a fatal crash\n",
"when it killed pedestrian Elaine Herzberg, 49.\n",
"\n",
"Characterising the regions where this is happening for these models\n",
"remains an outstanding challenge.\n",
"\n",
"In practice, we normally also have uncertainty associated with these\n",
"functions. Uncertainty in the prediction function arises from\n",
"\n",
"1. scarcity of training data and\n",
"2. mismatch between the set of prediction functions we choose and all\n",
" possible prediction functions.\n",
"\n",
"There are also challenges around specification of the objective\n",
"function, but for we will save those for another day. For the moment,\n",
"let us focus on the prediction function."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Bayesian Inference by Rejection Sampling\n",
"\n",
"\\[edit\\]\n",
"\n",
"One view of Bayesian inference is to assume we are given a mechanism for\n",
"generating samples, where we assume that mechanism is representing an\n",
"accurate view on the way we believe the world works.\n",
"\n",
"This mechanism is known as our *prior* belief.\n",
"\n",
"We combine our prior belief with our observations of the real world by\n",
"discarding all those prior samples that are inconsistent with our\n",
"observations. The *likelihood* defines mathematically what we mean by\n",
"inconsistent with the observations. The higher the noise level in the\n",
"likelihood, the looser the notion of consistent.\n",
"\n",
"The samples that remain are samples from the *posterior*.\n",
"\n",
"This approach to Bayesian inference is closely related to two sampling\n",
"techniques known as *rejection sampling* and *importance sampling*. It\n",
"is realized in practice in an approach known as *approximate Bayesian\n",
"computation* (ABC) or likelihood-free inference.\n",
"\n",
"In practice, the algorithm is often too slow to be practical, because\n",
"most samples will be inconsistent with the observations and as a result\n",
"the mechanism must be operated many times to obtain a few posterior\n",
"samples.\n",
"\n",
"However, in the Gaussian process case, when the likelihood also assumes\n",
"Gaussian noise, we can operate this mechanism mathematically, and obtain\n",
"the posterior density *analytically*. This is the benefit of Gaussian\n",
"processes.\n",
"\n",
"First, we will load in two python functions for computing the covariance\n",
"function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%load -n mlai.Kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# %load -n mlai.Kernel\n",
"class Kernel():\n",
" \"\"\"Covariance function\n",
" :param function: covariance function\n",
" :type function: function\n",
" :param name: name of covariance function\n",
" :type name: string\n",
" :param shortname: abbreviated name of covariance function\n",
" :type shortname: string\n",
" :param formula: latex formula of covariance function\n",
" :type formula: string\n",
" :param function: covariance function\n",
" :type function: function\n",
" :param \\**kwargs:\n",
" See below\n",
"\n",
" :Keyword Arguments:\n",
" * \"\"\"\n",
"\n",
" def __init__(self, function, name=None, shortname=None, formula=None, **kwargs): \n",
" self.function=function\n",
" self.formula = formula\n",
" self.name = name\n",
" self.shortname = shortname\n",
" self.parameters=kwargs\n",
" \n",
" def K(self, X, X2=None):\n",
" \"\"\"Compute the full covariance function given a kernel function for two data points.\"\"\"\n",
" if X2 is None:\n",
" X2 = X\n",
" K = np.zeros((X.shape[0], X2.shape[0]))\n",
" for i in np.arange(X.shape[0]):\n",
" for j in np.arange(X2.shape[0]):\n",
" K[i, j] = self.function(X[i, :], X2[j, :], **self.parameters)\n",
"\n",
" return K\n",
"\n",
" def diag(self, X):\n",
" \"\"\"Compute the diagonal of the covariance function\"\"\"\n",
" diagK = np.zeros((X.shape[0], 1))\n",
" for i in range(X.shape[0]): \n",
" diagK[i] = self.function(X[i, :], X[i, :], **self.parameters)\n",
" return diagK\n",
"\n",
" def _repr_html_(self):\n",
" raise NotImplementedError"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%load -n mlai.eq_cov"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# %load -n mlai.eq_cov\n",
"def eq_cov(x, x_prime, variance=1., lengthscale=1.):\n",
" \"\"\"Exponentiated quadratic covariance function.\"\"\"\n",
" diffx = x - x_prime\n",
" return variance*np.exp(-0.5*np.dot(diffx, diffx)/lengthscale**2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"kernel = Kernel(function=eq_cov,\n",
" name='Exponentiated Quadratic',\n",
" shortname='eq', \n",
" lengthscale=0.25)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we sample from a multivariate normal density (a multivariate\n",
"Gaussian), using the covariance function as the covariance matrix."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"np.random.seed(10)\n",
"import mlai.plot as plot"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot.rejection_samples(kernel=kernel, \n",
" diagrams='./gp')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import notutils as nu\n",
"from ipywidgets import IntSlider"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"nu.display_plots('gp_rejection_sample{sample:0>3}.png', \n",
" directory='./gp', \n",
" sample=IntSlider(1,1,5,1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"\n",
"\n",
"Figure: One view of Bayesian inference is we have a machine for\n",
"generating samples (the *prior*), and we discard all samples\n",
"inconsistent with our data, leaving the samples of interest (the\n",
"*posterior*). This is a rejection sampling view of Bayesian inference.\n",
"The Gaussian process allows us to do this analytically by multiplying\n",
"the *prior* by the *likelihood*."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Structure of Priors\n",
"\n",
"\\[edit\\]\n",
"\n",
"Even in the early days of Gaussian processes in machine learning, it was\n",
"understood that we were throwing something fundamental away. This is\n",
"perhaps captured best by David MacKay in his 1997 NeurIPS tutorial on\n",
"Gaussian processes, where he asked “Have we thrown out the baby with the\n",
"bathwater?” The quote below is from his summarization paper.\n",
"\n",
"> According to the hype of 1987, neural networks were meant to be\n",
"> intelligent models which discovered features and patterns in data.\n",
"> Gaussian processes in contrast are simply smoothing devices. How can\n",
"> Gaussian processes possibly replace neural networks? What is going on?\n",
">\n",
"> MacKay (n.d.)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Overfitting\n",
"\n",
"\\[edit\\]\n",
"\n",
"One potential problem is that as the number of nodes in two adjacent\n",
"layers increases, the number of parameters in the affine transformation\n",
"between layers, $\\mathbf{W}$, increases. If there are $k_{i-1}$ nodes in\n",
"one layer, and $k_i$ nodes in the following, then that matrix contains\n",
"$k_i k_{i-1}$ parameters, when we have layer widths in the 1000s that\n",
"leads to millions of parameters.\n",
"\n",
"One proposed solution is known as *dropout* where only a sub-set of the\n",
"neural network is trained at each iteration. An alternative solution\n",
"would be to reparameterize $\\mathbf{W}$ with its *singular value\n",
"decomposition*. $$\n",
" \\mathbf{W}= \\mathbf{U}\\boldsymbol{ \\Lambda}\\mathbf{V}^\\top\n",
" $$ or $$\n",
" \\mathbf{W}= \\mathbf{U}\\mathbf{V}^\\top\n",
" $$ where if $\\mathbf{W}\\in \\Re^{k_1\\times k_2}$ then\n",
"$\\mathbf{U}\\in \\Re^{k_1\\times q}$ and $\\mathbf{V}\\in \\Re^{k_2\\times q}$,\n",
"i.e. we have a low rank matrix factorization for the weights."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import mlai.plot as plot"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot.low_rank_approximation(diagrams='.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: Pictorial representation of the low rank form of the matrix\n",
"$\\mathbf{W}$.\n",
"\n",
"In practice there is evidence that deep models seek these low rank\n",
"solutions where we expect better generalisation. See e.g. Arora et al.\n",
"(2019);Jacot et al. (2021)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Bottleneck Layers in Deep Neural Networks\n",
"\n",
"\\[edit\\]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import mlai.plot as plot"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot.deep_nn_bottleneck(diagrams='./deepgp')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: Inserting the bottleneck layers introduces a new set of\n",
"variables.\n",
"\n",
"Including the low rank decomposition of $\\mathbf{W}$ in the neural\n",
"network, we obtain a new mathematical form. Effectively, we are adding\n",
"additional *latent* layers, $\\mathbf{ z}$, in between each of the\n",
"existing hidden layers. In a neural network these are sometimes known as\n",
"*bottleneck* layers. The network can now be written mathematically as $$\n",
"\\begin{align}\n",
" \\mathbf{ z}_{1} &= \\mathbf{V}^\\top_1 \\mathbf{ x}\\\\\n",
" \\mathbf{ h}_{1} &= \\phi\\left(\\mathbf{U}_1 \\mathbf{ z}_{1}\\right)\\\\\n",
" \\mathbf{ z}_{2} &= \\mathbf{V}^\\top_2 \\mathbf{ h}_{1}\\\\\n",
" \\mathbf{ h}_{2} &= \\phi\\left(\\mathbf{U}_2 \\mathbf{ z}_{2}\\right)\\\\\n",
" \\mathbf{ z}_{3} &= \\mathbf{V}^\\top_3 \\mathbf{ h}_{2}\\\\\n",
" \\mathbf{ h}_{3} &= \\phi\\left(\\mathbf{U}_3 \\mathbf{ z}_{3}\\right)\\\\\n",
" \\mathbf{ y}&= \\mathbf{ w}_4^\\top\\mathbf{ h}_{3}.\n",
"\\end{align}\n",
"$$\n",
"\n",
"$$\n",
"\\begin{align}\n",
" \\mathbf{ z}_{1} &= \\mathbf{V}^\\top_1 \\mathbf{ x}\\\\\n",
" \\mathbf{ z}_{2} &= \\mathbf{V}^\\top_2 \\phi\\left(\\mathbf{U}_1 \\mathbf{ z}_{1}\\right)\\\\\n",
" \\mathbf{ z}_{3} &= \\mathbf{V}^\\top_3 \\phi\\left(\\mathbf{U}_2 \\mathbf{ z}_{2}\\right)\\\\\n",
" \\mathbf{ y}&= \\mathbf{ w}_4 ^\\top \\mathbf{ z}_{3}\n",
"\\end{align}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Cascade of Gaussian Processes\n",
"\n",
"\\[edit\\]\n",
"\n",
"Now if we replace each of these neural networks with a Gaussian process.\n",
"This is equivalent to taking the limit as the width of each layer goes\n",
"to infinity, while appropriately scaling down the outputs.\n",
"\n",
"$$\n",
"\\begin{align}\n",
" \\mathbf{ z}_{1} &= \\mathbf{ f}_1\\left(\\mathbf{ x}\\right)\\\\\n",
" \\mathbf{ z}_{2} &= \\mathbf{ f}_2\\left(\\mathbf{ z}_{1}\\right)\\\\\n",
" \\mathbf{ z}_{3} &= \\mathbf{ f}_3\\left(\\mathbf{ z}_{2}\\right)\\\\\n",
" \\mathbf{ y}&= \\mathbf{ f}_4\\left(\\mathbf{ z}_{3}\\right)\n",
"\\end{align}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Stochastic Process Composition\n",
"\n",
"\\[edit\\]\n",
"\n",
"$$\\mathbf{ y}= \\mathbf{ f}_4\\left(\\mathbf{ f}_3\\left(\\mathbf{ f}_2\\left(\\mathbf{ f}_1\\left(\\mathbf{ x}\\right)\\right)\\right)\\right)$$\n",
"\n",
"Mathematically, a deep Gaussian process can be seen as a composite\n",
"*multivariate* function, $$\n",
" \\mathbf{g}(\\mathbf{ x})=\\mathbf{ f}_5(\\mathbf{ f}_4(\\mathbf{ f}_3(\\mathbf{ f}_2(\\mathbf{ f}_1(\\mathbf{ x}))))).\n",
" $$ Or if we view it from the probabilistic perspective we can see that\n",
"a deep Gaussian process is specifying a factorization of the joint\n",
"density, the standard deep model takes the form of a Markov chain."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from matplotlib import rc\n",
"\n",
"rc(\"font\", **{'family':'sans-serif','sans-serif':['Helvetica'],'size':30})\n",
"rc(\"text\", usetex=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pgm = plot.horizontal_chain(depth=5)\n",
"pgm.render().figure.savefig(\"./deepgp/deep-markov.svg\", transparent=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
" p(\\mathbf{ y}|\\mathbf{ x})= p(\\mathbf{ y}|\\mathbf{ f}_5)p(\\mathbf{ f}_5|\\mathbf{ f}_4)p(\\mathbf{ f}_4|\\mathbf{ f}_3)p(\\mathbf{ f}_3|\\mathbf{ f}_2)p(\\mathbf{ f}_2|\\mathbf{ f}_1)p(\\mathbf{ f}_1|\\mathbf{ x})\n",
" $$\n",
"\n",
"\n",
"\n",
"Figure: Probabilistically the deep Gaussian process can be\n",
"represented as a Markov chain. Indeed they can even be analyzed in this\n",
"way (Dunlop et al., n.d.)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from matplotlib import rc\n",
"rc(\"font\", **{'family':'sans-serif','sans-serif':['Helvetica'], 'size':15})\n",
"rc(\"text\", usetex=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pgm = plot.vertical_chain(depth=5)\n",
"pgm.render().figure.savefig(\"./deepgp/deep-markov-vertical.svg\", transparent=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: More usually deep probabilistic models are written vertically\n",
"rather than horizontally as in the Markov chain."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Why Composition?\n",
"\n",
"\\[edit\\]\n",
"\n",
"If the result of composing many functions together is simply another\n",
"function, then why do we bother? The key point is that we can change the\n",
"class of functions we are modeling by composing in this manner. A\n",
"Gaussian process is specifying a prior over functions, and one with a\n",
"number of elegant properties. For example, the derivative process (if it\n",
"exists) of a Gaussian process is also Gaussian distributed. That makes\n",
"it easy to assimilate, for example, derivative observations. But that\n",
"also might raise some alarm bells. That implies that the *marginal\n",
"derivative distribution* is also Gaussian distributed. If that’s the\n",
"case, then it means that functions which occasionally exhibit very large\n",
"derivatives are hard to model with a Gaussian process. For example, a\n",
"function with jumps in.\n",
"\n",
"A one off discontinuity is easy to model with a Gaussian process, or\n",
"even multiple discontinuities. They can be introduced in the mean\n",
"function, or independence can be forced between two covariance functions\n",
"that apply in different areas of the input space. But in these cases we\n",
"will need to specify the number of discontinuities and where they occur.\n",
"In otherwords we need to *parameterise* the discontinuities. If we do\n",
"not know the number of discontinuities and don’t wish to specify where\n",
"they occur, i.e. if we want a non-parametric representation of\n",
"discontinuities, then the standard Gaussian process doesn’t help."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Stochastic Process Composition\n",
"\n",
"The deep Gaussian process leads to *non-Gaussian* models, and\n",
"non-Gaussian characteristics in the covariance function. In effect, what\n",
"we are proposing is that we change the properties of the functions we\n",
"are considering by *composing stochastic processes*. This is an approach\n",
"to creating new stochastic processes from well known processes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import daft"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pgm = plot.vertical_chain(depth=5, shape=[2, 7])\n",
"pgm.add_node(daft.Node('y_2', r'$\\mathbf{y}_2$', 1.5, 3.5, observed=True))\n",
"pgm.add_edge('f_2', 'y_2')\n",
"pgm.render().figure.savefig(\"./deepgp/deep-markov-vertical-side.svg\", transparent=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Additionally, we are not constrained to the formalism of the chain. For\n",
"example, we can easily add single nodes emerging from some point in the\n",
"depth of the chain. This allows us to combine the benefits of the\n",
"graphical modelling formalism, but with a powerful framework for\n",
"relating one set of variables to another, that of Gaussian processes\n",
"\n",
"\n",
"\n",
"Figure: More generally we aren’t constrained by the Markov chain. We\n",
"can design structures that respect our belief about the underlying\n",
"conditional dependencies. Here we are adding a side note from the\n",
"chain."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Deep Gaussian Processes\n",
"\n",
"\n",
"\n",
"Damianou (2015)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Universe isn’t as Gaussian as it Was\n",
"\n",
"\\[edit\\]\n",
"\n",
"The [Planck space\n",
"craft](https://en.wikipedia.org/wiki/Planck_(spacecraft)) was a European\n",
"Space Agency space telescope that mapped the cosmic microwave background\n",
"(CMB) from 2009 to 2013. The [Cosmic Microwave\n",
"Background](https://en.wikipedia.org/wiki/Cosmic_microwave_background)\n",
"is the first observable echo we have of the big bang. It dates to\n",
"approximately 400,000 years after the big bang, at the time the Universe\n",
"was approximately $10^8$ times smaller and the temperature of the\n",
"Universe was high, around $3 \\times 10^8$ degrees Kelvin. The Universe\n",
"was in the form of a hydrogen plasma. The echo we observe is the moment\n",
"when the Universe was cool enough for Protons and electrons to combine\n",
"to form hydrogen atoms. At this moment, the Universe became transparent\n",
"for the first time, and photons could travel through space.\n",
"\n",
"\n",
"\n",
"Figure: Artist’s impression of the Planck spacecraft which measured\n",
"the Cosmic Microwave Background between 2009 and 2013.\n",
"\n",
"The objective of the Planck spacecraft was to measure the anisotropy and\n",
"statistics of the Cosmic Microwave Background. This was important,\n",
"because if the standard model of the Universe is correct the variations\n",
"around the very high temperature of the Universe of the CMB should be\n",
"distributed according to a Gaussian process.[1] Currently our best\n",
"estimates show this to be the case (Elsner et al., 2016, 2015; Jaffe et\n",
"al., 1998; Pontzen and Peiris, 2010).\n",
"\n",
"To the high degree of precision that we could measure with the Planck\n",
"space telescope, the CMB appears to be a Gaussian process. The\n",
"parameters of its covariance function are given by the fundamental\n",
"parameters of the universe, for example the amount of dark matter and\n",
"matter in the universe\n",
"\n",
"\n",
"\n",
"Figure: The cosmic microwave background is, to a very high degree of\n",
"precision, a Gaussian process. The parameters of its covariance function\n",
"are given by fundamental parameters of the universe, such as the amount\n",
"of dark matter and mass.\n",
"\n",
"[1] Most of my understanding of this is taken from conversations with\n",
"Kyle Cranmer, a physicist who makes extensive use of machine learning\n",
"methods in his work. See e.g. Mishra-Sharma and Cranmer (2020) from Kyle\n",
"and Siddharth Mishra-Sharma. Of course, any errors in the above text are\n",
"mine and do not stem from Kyle."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Simulating a CMB Map\n",
"\n",
"The simulation was created by [Boris\n",
"Leistedt](https://ixkael.github.io/), see the [original Jupyter notebook\n",
"here](https://github.com/ixkael/Prob-tools/blob/master/notebooks/The%20CMB%20as%20a%20Gaussian%20Process.ipynb).\n",
"\n",
"Here we use that code to simulate our own universe and sample from what\n",
"it looks like.\n",
"\n",
"First, we install some specialist software as well as `matplotlib`,\n",
"`scipy`, `numpy` we require\n",
"\n",
"- `camb`: \n",
"- `healpy`: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install camb"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install healpy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%config IPython.matplotlib.backend = 'retina'\n",
"%config InlineBackend.figure_format = 'retina'\n",
"\n",
"import matplotlib\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib import rc\n",
"from cycler import cycler\n",
"\n",
"import numpy as np\n",
"\n",
"rc(\"font\", family=\"serif\", size=14)\n",
"rc(\"text\", usetex=False)\n",
"matplotlib.rcParams['lines.linewidth'] = 2\n",
"matplotlib.rcParams['patch.linewidth'] = 2\n",
"matplotlib.rcParams['axes.prop_cycle'] =\\\n",
" cycler(\"color\", ['k', 'c', 'm', 'y'])\n",
"matplotlib.rcParams['axes.labelsize'] = 16"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import healpy as hp\n",
"\n",
"import camb\n",
"from camb import model, initialpower"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we use the theoretical power spectrum to design the covariance\n",
"function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"nside = 512 # Healpix parameter, giving 12*nside**2 equal-area pixels on the sphere.\n",
"lmax = 3*nside # band-limit. Should be 2*nside < lmax < 4*nside to get information content."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we design our Universe. It is parameterized according to the\n",
"[$\\Lambda$CDM model](https://en.wikipedia.org/wiki/Lambda-CDM_model).\n",
"The variables are as follows. `H0` is the Hubble parameter (in\n",
"Km/s/Mpc). The `ombh2` is Physical Baryon density parameter. The `omch2`\n",
"is the physical dark matter density parameter. `mnu` is the sum of the\n",
"neutrino masses (in electron Volts). `omk` is the $\\Omega_k$ is the\n",
"curvature parameter, which is here set to 0, giving the minimal six\n",
"parameter Lambda-CDM model. `tau` is the reionization optical depth.\n",
"\n",
"Then we set `ns`, the “scalar spectral index.” This was estimated by\n",
"Planck to be 0.96. Then there’s `r`, the ratio of the tensor power\n",
"spectrum to scalar power spectrum. This has been estimated by Planck to\n",
"be under 0.11. Here we set it to zero. These parameters are associated\n",
"[with inflation](https://en.wikipedia.org/wiki/Primordial_fluctuations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Mostly following http://camb.readthedocs.io/en/latest/CAMBdemo.html with parameters from https://en.wikipedia.org/wiki/Lambda-CDM_model\n",
"\n",
"pars = camb.CAMBparams()\n",
"pars.set_cosmology(H0=67.74, ombh2=0.0223, omch2=0.1188, mnu=0.06, omk=0, tau=0.066)\n",
"pars.InitPower.set_params(ns=0.96, r=0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Having set the parameters, we now use the python software “Code for\n",
"Anisotropies in the Microwave Background” to get the results."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pars.set_for_lmax(lmax, lens_potential_accuracy=0);\n",
"results = camb.get_results(pars)\n",
"powers = results.get_cmb_power_spectra(pars)\n",
"totCL = powers['total']\n",
"unlensedCL = powers['unlensed_scalar']\n",
"\n",
"ells = np.arange(totCL.shape[0])\n",
"Dells = totCL[:, 0]\n",
"Cells = Dells * 2*np.pi / ells / (ells + 1) # change of convention to get C_ell\n",
"Cells[0:2] = 0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cmbmap = hp.synfast(Cells, nside, \n",
" lmax=lmax, mmax=None, alm=False, pol=False, \n",
" pixwin=False, fwhm=0.0, sigma=None, new=False, verbose=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"hp.mollview(cmbmap)\n",
"fig = plt.gcf()\n",
"mlai.write_figure('mollweide-sample-cmb.png',\n",
" directory='./physics/')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: A simulation of the Cosmic Microwave Background obtained\n",
"through sampling from the relevant Gaussian process covariance (in polar\n",
"co-ordinates).\n",
"\n",
"The world we see today, of course, is not a Gaussian process. There are\n",
"many discontinuities, for example, in the density of matter, and\n",
"therefore in the temperature of the Universe.\n",
"\n",
"$=f\\Bigg($$\\Bigg)$\n",
"\n",
"Figure: What we observe today is some non-linear function of the\n",
"cosmic microwave background.\n",
"\n",
"We can think of today’s observed Universe, though, as a being a\n",
"consequence of those temperature fluctuations in the CMB. Those\n",
"fluctuations are only order $10^{-6}$ of the scale of the overall\n",
"temperature of the Universe. But minor fluctuations in that density are\n",
"what triggered the pattern of formation of the Galaxies. They determined\n",
"how stars formed and created the elements that are the building blocks\n",
"of our Earth (Vogelsberger et al., 2020)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modern Review\n",
"\n",
"- *A Unifying Framework for Gaussian Process Pseudo-Point\n",
" Approximations using Power Expectation Propagation* Bui et\n",
" al. (2017)\n",
"\n",
"- *Deep Gaussian Processes and Variational Propagation of Uncertainty*\n",
" Damianou (2015)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install gpy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## GPy: A Gaussian Process Framework in Python\n",
"\n",
"\\[edit\\]\n",
"\n",
"Gaussian processes are a flexible tool for non-parametric analysis with\n",
"uncertainty. The GPy software was started in Sheffield to provide a easy\n",
"to use interface to GPs. One which allowed the user to focus on the\n",
"modelling rather than the mathematics.\n",
"\n",
"\n",
"\n",
"Figure: GPy is a BSD licensed software code base for implementing\n",
"Gaussian process models in Python. It is designed for teaching and\n",
"modelling. We welcome contributions which can be made through the GitHub\n",
"repository \n",
"\n",
"GPy is a BSD licensed software code base for implementing Gaussian\n",
"process models in python. This allows GPs to be combined with a wide\n",
"variety of software libraries.\n",
"\n",
"The software itself is available on\n",
"[GitHub](https://github.com/SheffieldML/GPy) and the team welcomes\n",
"contributions.\n",
"\n",
"The aim for GPy is to be a probabilistic-style programming language,\n",
"i.e., you specify the model rather than the algorithm. As well as a\n",
"large range of covariance functions the software allows for non-Gaussian\n",
"likelihoods, multivariate outputs, dimensionality reduction and\n",
"approximations for larger data sets.\n",
"\n",
"The documentation for GPy can be found\n",
"[here](https://gpy.readthedocs.io/en/latest/).\n",
"\n",
"This notebook depends on PyDeepGP. This library can be installed via\n",
"pip."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install --upgrade git+https://github.com/SheffieldML/PyDeepGP.git"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Late bind setup methods to DeepGP object\n",
"from mlai.deepgp_tutorial import initialize\n",
"from mlai.deepgp_tutorial import staged_optimize\n",
"from mlai.deepgp_tutorial import posterior_sample\n",
"from mlai.deepgp_tutorial import visualize\n",
"from mlai.deepgp_tutorial import visualize_pinball\n",
"\n",
"import deepgp\n",
"deepgp.DeepGP.initialize=initialize\n",
"deepgp.DeepGP.staged_optimize=staged_optimize\n",
"deepgp.DeepGP.posterior_sample=posterior_sample\n",
"deepgp.DeepGP.visualize=visualize\n",
"deepgp.DeepGP.visualize_pinball=visualize_pinball"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Olympic Marathon Data\n",
"\n",
"\\[edit\\]\n",
"\n",
"
\n",
"
\n",
"
\n",
"\n",
"- Gold medal times for Olympic Marathon since 1896.\n",
"- Marathons before 1924 didn’t have a standardized distance.\n",
"- Present results using pace per km.\n",
"- In 1904 Marathon was badly organized leading to very slow times.\n",
"\n",
"
\n",
"
\n",
"\n",
"\n",
"Image from Wikimedia Commons \n",
"\n",
"
\n",
"
\n",
"
\n",
"\n",
"The first thing we will do is load a standard data set for regression\n",
"modelling. The data consists of the pace of Olympic Gold Medal Marathon\n",
"winners for the Olympics from 1896 to present. Let’s load in the data\n",
"and plot."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install pods"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import pods"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = pods.datasets.olympic_marathon_men()\n",
"x = data['X']\n",
"y = data['Y']\n",
"\n",
"offset = y.mean()\n",
"scale = np.sqrt(y.var())\n",
"yhat = (y - offset)/scale"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"xlim = (1875,2030)\n",
"ylim = (2.5, 6.5)\n",
"\n",
"fig, ax = plt.subplots(figsize=plot.big_wide_figsize)\n",
"_ = ax.plot(x, y, 'r.',markersize=10)\n",
"ax.set_xlabel('year', fontsize=20)\n",
"ax.set_ylabel('pace min/km', fontsize=20)\n",
"ax.set_xlim(xlim)\n",
"ax.set_ylim(ylim)\n",
"\n",
"mlai.write_figure(filename='olympic-marathon.svg', \n",
" directory='./datasets')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: Olympic marathon pace times since 1896.\n",
"\n",
"Things to notice about the data include the outlier in 1904, in that\n",
"year the Olympics was in St Louis, USA. Organizational problems and\n",
"challenges with dust kicked up by the cars following the race meant that\n",
"participants got lost, and only very few participants completed. More\n",
"recent years see more consistently quick marathons."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Alan Turing\n",
"\n",
"\\[edit\\]\n",
"\n",
"
\n",
"
\n",
"
\n",
"\n",
"\n",
"\n",
"
\n",
"
\n",
"\n",
"\n",
"\n",
"
\n",
"
\n",
"
\n",
"\n",
"Figure: Alan Turing, in 1946 he was only 11 minutes slower than the\n",
"winner of the 1948 games. Would he have won a hypothetical games held in\n",
"1946? Source:\n",
"Alan\n",
"Turing Internet Scrapbook.\n",
"\n",
"If we had to summarise the objectives of machine learning in one word, a\n",
"very good candidate for that word would be *generalization*. What is\n",
"generalization? From a human perspective it might be summarised as the\n",
"ability to take lessons learned in one domain and apply them to another\n",
"domain. If we accept the definition given in the first session for\n",
"machine learning, $$\n",
"\\text{data} + \\text{model} \\stackrel{\\text{compute}}{\\rightarrow} \\text{prediction}\n",
"$$ then we see that without a model we can’t generalise: we only have\n",
"data. Data is fine for answering very specific questions, like “Who won\n",
"the Olympic Marathon in 2012?” because we have that answer stored,\n",
"however, we are not given the answer to many other questions. For\n",
"example, Alan Turing was a formidable marathon runner, in 1946 he ran a\n",
"time 2 hours 46 minutes (just under four minutes per kilometer, faster\n",
"than I and most of the other [Endcliffe Park\n",
"Run](http://www.parkrun.org.uk/sheffieldhallam/) runners can do 5 km).\n",
"What is the probability he would have won an Olympics if one had been\n",
"held in 1946?\n",
"\n",
"To answer this question we need to generalize, but before we formalize\n",
"the concept of generalization let’s introduce some formal representation\n",
"of what it means to generalize in machine learning."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Gaussian Process Fit\n",
"\n",
"\\[edit\\]\n",
"\n",
"Our first objective will be to perform a Gaussian process fit to the\n",
"data, we’ll do this using the [GPy\n",
"software](https://github.com/SheffieldML/GPy)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import GPy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m_full = GPy.models.GPRegression(x,yhat)\n",
"_ = m_full.optimize() # Optimize parameters of covariance function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The first command sets up the model, then `m_full.optimize()` optimizes\n",
"the parameters of the covariance function and the noise level of the\n",
"model. Once the fit is complete, we’ll try creating some test points,\n",
"and computing the output of the GP model in terms of the mean and\n",
"standard deviation of the posterior functions between 1870 and 2030. We\n",
"plot the mean function and the standard deviation at 200 locations. We\n",
"can obtain the predictions using `y_mean, y_var = m_full.predict(xt)`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"xt = np.linspace(1870,2030,200)[:,np.newaxis]\n",
"yt_mean, yt_var = m_full.predict(xt)\n",
"yt_sd=np.sqrt(yt_var)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we plot the results using the helper function in `mlai.plot`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=plot.big_wide_figsize)\n",
"plot.model_output(m_full, scale=scale, offset=offset, ax=ax, xlabel=\"year\", ylabel=\"pace min/km\", fontsize=20, portion=0.2)\n",
"ax.set_xlim(xlim)\n",
"ax.set_ylim(ylim)\n",
"mlai.write_figure(figure=fig,\n",
" filename=\"olympic-marathon-gp.svg\", \n",
" directory = \"./gp\",\n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: Gaussian process fit to the Olympic Marathon data. The error\n",
"bars are too large, perhaps due to the outlier from 1904."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fit Quality\n",
"\n",
"In the fit we see that the error bars (coming mainly from the noise\n",
"variance) are quite large. This is likely due to the outlier point in\n",
"1904, ignoring that point we can see that a tighter fit is obtained. To\n",
"see this make a version of the model, `m_clean`, where that point is\n",
"removed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x_clean=np.vstack((x[0:2, :], x[3:, :]))\n",
"y_clean=np.vstack((yhat[0:2, :], yhat[3:, :]))\n",
"\n",
"m_clean = GPy.models.GPRegression(x_clean,y_clean)\n",
"_ = m_clean.optimize()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=plot.big_wide_figsize)\n",
"plot.model_output(m_clean, scale=scale, offset=offset, ax=ax, xlabel='year', ylabel='pace min/km', fontsize=20, portion=0.2)\n",
"ax.set_xlim(xlim)\n",
"ax.set_ylim(ylim)\n",
"mlai.write_figure(figure=fig,\n",
" filename='./gp/olympic-marathon-gp.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Deep GP Fit\n",
"\n",
"\\[edit\\]\n",
"\n",
"Let’s see if a deep Gaussian process can help here. We will construct a\n",
"deep Gaussian process with one hidden layer (i.e. one Gaussian process\n",
"feeding into another).\n",
"\n",
"Build a Deep GP with an additional hidden layer (one dimensional) to fit\n",
"the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import GPy\n",
"import deepgp"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"hidden = 1\n",
"m = deepgp.DeepGP([y.shape[1],hidden,x.shape[1]],Y=yhat, X=x, inits=['PCA','PCA'], \n",
" kernels=[GPy.kern.RBF(hidden,ARD=True),\n",
" GPy.kern.RBF(x.shape[1],ARD=True)], # the kernels for each layer\n",
" num_inducing=50, back_constraint=False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Call the initalization\n",
"m.initialize()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now optimize the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for layer in m.layers:\n",
" layer.likelihood.variance.constrain_positive(warning=False)\n",
"m.optimize(messages=True,max_iters=10000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.staged_optimize(messages=(True,True,True))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=plot.big_wide_figsize)\n",
"plot.model_output(m, scale=scale, offset=offset, ax=ax, xlabel='year', ylabel='pace min/km', \n",
" fontsize=20, portion=0.2)\n",
"ax.set_xlim(xlim)\n",
"\n",
"ax.set_ylim(ylim)\n",
"mlai.write_figure(figure=fig, filename='./deepgp/olympic-marathon-deep-gp.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Olympic Marathon Data Deep GP\n",
"\n",
"\n",
"\n",
"Figure: Deep GP fit to the Olympic marathon data. Error bars now\n",
"change as the prediction evolves."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=plot.big_wide_figsize)\n",
"plot.model_sample(m, scale=scale, offset=offset, samps=10, ax=ax, \n",
" xlabel='year', ylabel='pace min/km', portion = 0.225)\n",
"ax.set_xlim(xlim)\n",
"ax.set_ylim(ylim)\n",
"mlai.write_figure(figure=fig, filename='./deepgp/olympic-marathon-deep-gp-samples.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Olympic Marathon Data Deep GP\n",
"\n",
"\n",
"\n",
"Figure: Point samples run through the deep Gaussian process show the\n",
"distribution of output locations."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fitted GP for each layer\n",
"\n",
"Now we explore the GPs the model has used to fit each layer. First of\n",
"all, we look at the hidden layer."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.visualize(scale=scale, offset=offset, xlabel='year',\n",
" ylabel='pace min/km',xlim=xlim, ylim=ylim,\n",
" dataset='olympic-marathon',\n",
" diagrams='./deepgp')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import notutils as nu"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"nu.display_plots('olympic-marathon-deep-gp-layer-{sample:0>1}.svg', \n",
" './deepgp', sample=(0,1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: The mapping from input to the latent layer is broadly, with\n",
"some flattening as time goes on. Variance is high across the input\n",
"range.\n",
"\n",
"\n",
"\n",
"Figure: The mapping from the latent layer to the output layer."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=plot.big_wide_figsize)\n",
"m.visualize_pinball(ax=ax, scale=scale, offset=offset, points=30, portion=0.1,\n",
" xlabel='year', ylabel='pace km/min', vertical=True)\n",
"mlai.write_figure(figure=fig, filename='./deepgp/olympic-marathon-deep-gp-pinball.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Olympic Marathon Pinball Plot\n",
"\n",
"\n",
"\n",
"Figure: A pinball plot shows the movement of the ‘ball’ as it passes\n",
"through each layer of the Gaussian processes. Mean directions of\n",
"movement are shown by lines. Shading gives one standard deviation of\n",
"movement position. At each layer, the uncertainty is reset. The overal\n",
"uncertainty is the cumulative uncertainty from all the layers. There is\n",
"some grouping of later points towards the right in the first layer,\n",
"which also injects a large amount of uncertainty. Due to flattening of\n",
"the curve in the second layer towards the right the uncertainty is\n",
"reduced in final output.\n",
"\n",
"The pinball plot shows the flow of any input ball through the deep\n",
"Gaussian process. In a pinball plot a series of vertical parallel lines\n",
"would indicate a purely linear function. For the olypmic marathon data\n",
"we can see the first layer begins to shift from input towards the right.\n",
"Note it also does so with some uncertainty (indicated by the shaded\n",
"backgrounds). The second layer has less uncertainty, but bunches the\n",
"inputs more strongly to the right. This input layer of uncertainty,\n",
"followed by a layer that pushes inputs to the right is what gives the\n",
"heteroschedastic noise."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step Function\n",
"\n",
"\\[edit\\]\n",
"\n",
"Next we consider a simple step function data set."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"num_low=25\n",
"num_high=25\n",
"gap = -.1\n",
"noise=0.0001\n",
"x = np.vstack((np.linspace(-1, -gap/2.0, num_low)[:, np.newaxis],\n",
" np.linspace(gap/2.0, 1, num_high)[:, np.newaxis]))\n",
"y = np.vstack((np.zeros((num_low, 1)), np.ones((num_high,1))))\n",
"scale = np.sqrt(y.var())\n",
"offset = y.mean()\n",
"yhat = (y-offset)/scale"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=plot.big_wide_figsize)\n",
"_ = ax.plot(x, y, 'r.',markersize=10)\n",
"_ = ax.set_xlabel('$x$', fontsize=20)\n",
"_ = ax.set_ylabel('$y$', fontsize=20)\n",
"xlim = (-2, 2)\n",
"ylim = (-0.6, 1.6)\n",
"ax.set_ylim(ylim)\n",
"ax.set_xlim(xlim)\n",
"mlai.write_figure(figure=fig, filename='./datasets/step-function.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step Function Data\n",
"\n",
"\n",
"\n",
"Figure: Simulation study of step function data artificially\n",
"generated. Here there is a small overlap between the two lines."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step Function Data GP\n",
"\n",
"We can fit a Gaussian process to the step function data using `GPy` as\n",
"follows."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m_full = GPy.models.GPRegression(x,yhat)\n",
"_ = m_full.optimize() # Optimize parameters of covariance function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Where `GPy.models.GPRegression()` gives us a standard GP regression\n",
"model with exponentiated quadratic covariance function.\n",
"\n",
"The model is optimized using `m_full.optimize()` which calls an L-BGFS\n",
"gradient based solver in python."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax=plt.subplots(figsize=plot.big_wide_figsize)\n",
"plot.model_output(m_full, scale=scale, offset=offset, ax=ax, fontsize=20, portion=0.5)\n",
"ax.set_ylim(ylim)\n",
"ax.set_xlim(xlim)\n",
"\n",
"mlai.write_figure(figure=fig,filename='./gp/step-function-gp.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: Gaussian process fit to the step function data. Note the\n",
"large error bars and the over-smoothing of the discontinuity. Error bars\n",
"are shown at two standard deviations.\n",
"\n",
"The resulting fit to the step function data shows some challenges. In\n",
"particular, the over smoothing at the discontinuity. If we know how many\n",
"discontinuities there are, we can parameterize them in the step\n",
"function. But by doing this, we form a semi-parametric model. The\n",
"parameters indicate how many discontinuities are, and where they are.\n",
"They can be optimized as part of the model fit. But if new, unforeseen,\n",
"discontinuities arise when the model is being deployed in practice,\n",
"these won’t be accounted for in the predictions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step Function Data Deep GP\n",
"\n",
"\\[edit\\]\n",
"\n",
"First we initialize a deep Gaussian process with three latent layers\n",
"(four layers total). Within each layer we create a GP with an\n",
"exponentiated quadratic covariance (`GPy.kern.RBF`).\n",
"\n",
"At each layer we use 20 inducing points for the variational\n",
"approximation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"layers = [y.shape[1], 1, 1, 1,x.shape[1]]\n",
"inits = ['PCA']*(len(layers)-1)\n",
"kernels = []\n",
"for i in layers[1:]:\n",
" kernels += [GPy.kern.RBF(i)]\n",
" \n",
"m = deepgp.DeepGP(layers,Y=yhat, X=x, \n",
" inits=inits, \n",
" kernels=kernels, # the kernels for each layer\n",
" num_inducing=20, back_constraint=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Once the model is constructed we initialize the parameters, and perform\n",
"the staged optimization which starts by optimizing variational\n",
"parameters with a low noise and proceeds to optimize the whole model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.initialize()\n",
"m.staged_optimize()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We plot the output of the deep Gaussian process fitted to the step data\n",
"as follows."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax=plt.subplots(figsize=plot.big_wide_figsize)\n",
"plot.model_output(m, scale=scale, offset=offset, ax=ax, fontsize=20, portion=0.5)\n",
"ax.set_ylim(ylim)\n",
"ax.set_xlim(xlim)\n",
"mlai.write_figure(filename='./deepgp/step-function-deep-gp.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The deep Gaussian process does a much better job of fitting the data. It\n",
"handles the discontinuity easily, and error bars drop to smaller values\n",
"in the regions of data.\n",
"\n",
"\n",
"\n",
"Figure: Deep Gaussian process fit to the step function data."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step Function Data Deep GP\n",
"\n",
"The samples of the model can be plotted with the helper function from\n",
"`mlai.plot`, `model_sample`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import mlai.plot as plot"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax=plt.subplots(figsize=plot.big_wide_figsize)\n",
"\n",
"plot.model_sample(m, scale=scale, offset=offset, samps=10, ax=ax, portion = 0.5)\n",
"ax.set_ylim(ylim)\n",
"ax.set_xlim(xlim)\n",
"mlai.write_figure(figure=fig, filename='./deepgp/step-function-deep-gp-samples.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The samples from the model show that the error bars, which are\n",
"informative for Gaussian outputs, are less informative for this model.\n",
"They make clear that the data points lie, in output mainly at 0 or 1, or\n",
"occasionally in between.\n",
"\n",
"\n",
"\n",
"Figure: Samples from the deep Gaussian process model for the step\n",
"function fit.\n",
"\n",
"The visualize code allows us to inspect the intermediate layers in the\n",
"deep GP model to understand how it has reconstructed the step function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.visualize(offset=offset, scale=scale, xlim=xlim, ylim=ylim,\n",
" dataset='step-function',\n",
" diagrams='./deepgp')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"\n",
"\n",
"\n",
"Figure: From top to bottom, the Gaussian process mapping function\n",
"that makes up each layer of the resulting deep Gaussian process.\n",
"\n",
"A pinball plot can be created for the resulting model to understand how\n",
"the input is being translated to the output across the different layers."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax=plt.subplots(figsize=plot.big_wide_figsize)\n",
"m.visualize_pinball(offset=offset, ax=ax, scale=scale, xlim=xlim, ylim=ylim, portion=0.1, points=50)\n",
"mlai.write_figure(figure=fig, filename='./deepgp/step-function-deep-gp-pinball.svg', \n",
" transparent=True, frameon=True, ax=ax)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: Pinball plot of the deep GP fitted to the step function data.\n",
"Each layer of the model pushes the ‘ball’ towards the left or right,\n",
"saturating at 1 and 0. This causes the final density to be be peaked at\n",
"0 and 1. Transitions occur driven by the uncertainty of the mapping in\n",
"each layer."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pods"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = pods.datasets.mcycle()\n",
"x = data['X']\n",
"y = data['Y']\n",
"scale=np.sqrt(y.var())\n",
"offset=y.mean()\n",
"yhat = (y - offset)/scale"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai\n",
"import mlai.plot as plot"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=plot.big_wide_figsize)\n",
"_ = ax.plot(x, y, 'r.',markersize=10)\n",
"_ = ax.set_xlabel('time', fontsize=20)\n",
"_ = ax.set_ylabel('acceleration', fontsize=20)\n",
"xlim = (-20, 80)\n",
"ylim = (-175, 125)\n",
"ax.set_xlim(xlim)\n",
"ax.set_ylim(ylim)\n",
"mlai.write_figure(filename='motorcycle-helmet.svg', directory='./datasets/',\n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Motorcycle Helmet Data\n",
"\n",
"\\[edit\\]\n",
"\n",
"\n",
"\n",
"Figure: Motorcycle helmet data. The data consists of acceleration\n",
"readings on a motorcycle helmet undergoing a collision. The data\n",
"exhibits heteroschedastic (time varying) noise levles and\n",
"non-stationarity."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m_full = GPy.models.GPRegression(x,yhat)\n",
"_ = m_full.optimize() # Optimize parameters of covariance function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax=plt.subplots(figsize=plot.big_wide_figsize)\n",
"plot.model_output(m_full, scale=scale, offset=offset, ax=ax, xlabel='time', ylabel='acceleration/$g$', fontsize=20, portion=0.5)\n",
"xlim=(-20,80)\n",
"ylim=(-180,120)\n",
"ax.set_ylim(ylim)\n",
"ax.set_xlim(xlim)\n",
"mlai.write_figure(figure=fig,filename='./gp/motorcycle-helmet-gp.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Motorcycle Helmet Data GP\n",
"\n",
"\\[edit\\]\n",
"\n",
"\n",
"\n",
"Figure: Gaussian process fit to the motorcycle helmet accelerometer\n",
"data."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Motorcycle Helmet Data Deep GP\n",
"\n",
"\\[edit\\]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import deepgp"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"layers = [y.shape[1], 1, x.shape[1]]\n",
"inits = ['PCA']*(len(layers)-1)\n",
"kernels = []\n",
"for i in layers[1:]:\n",
" kernels += [GPy.kern.RBF(i)]\n",
"m = deepgp.DeepGP(layers,Y=yhat, X=x, \n",
" inits=inits, \n",
" kernels=kernels, # the kernels for each layer\n",
" num_inducing=20, back_constraint=False)\n",
"\n",
"\n",
"\n",
"m.initialize()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.staged_optimize(iters=(1000,1000,10000), messages=(True, True, True))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax=plt.subplots(figsize=plot.big_wide_figsize)\n",
"plot.model_output(m, scale=scale, offset=offset, ax=ax, xlabel='time', ylabel='acceleration/$g$', fontsize=20, portion=0.5)\n",
"ax.set_ylim(ylim)\n",
"ax.set_xlim(xlim)\n",
"mlai.write_figure(filename='./deepgp/motorcycle-helmet-deep-gp.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: Deep Gaussian process fit to the motorcycle helmet\n",
"accelerometer data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax=plt.subplots(figsize=plot.big_wide_figsize)\n",
"plot.model_sample(m, scale=scale, offset=offset, samps=10, ax=ax, xlabel='time', ylabel='acceleration/$g$', portion = 0.5)\n",
"ax.set_ylim(ylim)\n",
"ax.set_xlim(xlim)\n",
"\n",
"mlai.write_figure(figure=fig, filename='./deepgp/motorcycle-helmet-deep-gp-samples.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Motorcycle Helmet Data Deep GP\n",
"\n",
"\n",
"\n",
"Figure: Samples from the deep Gaussian process as fitted to the\n",
"motorcycle helmet accelerometer data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.visualize(xlim=xlim, ylim=ylim, scale=scale,offset=offset, \n",
" xlabel=\"time\", ylabel=\"acceleration/$g$\", portion=0.5,\n",
" dataset='motorcycle-helmet',\n",
" diagrams='./deepgp')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Motorcycle Helmet Data Latent 1\n",
"\n",
"\n",
"\n",
"Figure: Mappings from the input to the latent layer for the\n",
"motorcycle helmet accelerometer data."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Motorcycle Helmet Data Latent 2\n",
"\n",
"\n",
"\n",
"Figure: Mappings from the latent layer to the output layer for the\n",
"motorcycle helmet accelerometer data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax=plt.subplots(figsize=plot.big_wide_figsize)\n",
"m.visualize_pinball(ax=ax, xlabel='time', ylabel='acceleration/g', \n",
" points=50, scale=scale, offset=offset, portion=0.1)\n",
"mlai.write_figure(figure=fig, filename='./deepgp/motorcycle-helmet-deep-gp-pinball.svg', \n",
" transparent=True, frameon=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Motorcycle Helmet Pinball Plot\n",
"\n",
"\n",
"\n",
"Figure: Pinball plot for the mapping from input to output layer for\n",
"the motorcycle helmet accelerometer data."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Subsample of the MNIST Data\n",
"\n",
"\\[edit\\]\n",
"\n",
"We will look at a sub-sample of the MNIST digit data set.\n",
"\n",
"First load in the MNIST data set from scikit learn. This can take a\n",
"little while because it’s large to download."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.datasets import fetch_openml"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mnist = fetch_openml('mnist_784')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sub-sample the dataset to make the training faster."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.random.seed(0)\n",
"digits = [0,1,2,3,4]\n",
"N_per_digit = 100\n",
"Y = []\n",
"labels = []\n",
"for d in digits:\n",
" imgs = mnist['data'][mnist['target']==str(d)]\n",
" Y.append(imgs.loc[np.random.permutation(imgs.index)[:N_per_digit]])\n",
" labels.append(np.ones(N_per_digit)*d)\n",
"Y = np.vstack(Y).astype(np.float64)\n",
"labels = np.hstack(labels)\n",
"Y /= 255"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fitting a Deep GP to a the MNIST Digits Subsample\n",
"\n",
"\\[edit\\]\n",
"\n",
"\n",
"\n",
"\n",
"We now look at the deep Gaussian processes’ capacity to perform\n",
"unsupervised learning."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fit a Deep GP\n",
"\n",
"We’re going to fit a Deep Gaussian process model to the MNIST data with\n",
"two hidden layers. Each of the two Gaussian processes (one from the\n",
"first hidden layer to the second, one from the second hidden layer to\n",
"the data) has an exponentiated quadratic covariance."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import deepgp\n",
"import GPy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"num_latent = 2\n",
"num_hidden_2 = 5\n",
"m = deepgp.DeepGP([Y.shape[1],num_hidden_2,num_latent],\n",
" Y,\n",
" kernels=[GPy.kern.RBF(num_hidden_2,ARD=True), \n",
" GPy.kern.RBF(num_latent,ARD=False)], \n",
" num_inducing=50, back_constraint=False, \n",
" encoder_dims=[[200],[200]])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialization\n",
"\n",
"Just like deep neural networks, there are some tricks to intitializing\n",
"these models. The tricks we use here include some early training of the\n",
"model with model parameters constrained. This gives the variational\n",
"inducing parameters some scope to tighten the bound for the case where\n",
"the noise variance is small and the variances of the Gaussian processes\n",
"are around 1."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.obslayer.likelihood.variance[:] = Y.var()*0.01\n",
"for layer in m.layers:\n",
" layer.kern.variance.fix(warning=False)\n",
" layer.likelihood.variance.fix(warning=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We now we optimize for a hundred iterations with the constrained model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.optimize(messages=False,max_iters=100)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we remove the fixed constraint on the kernel variance parameters,\n",
"but keep the noise output constrained, and run for a further 100\n",
"iterations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for layer in m.layers:\n",
" layer.kern.variance.constrain_positive(warning=False)\n",
"m.optimize(messages=False,max_iters=100)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally we unconstrain the layer likelihoods and allow the full model to\n",
"be trained for 1000 iterations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for layer in m.layers:\n",
" layer.likelihood.variance.constrain_positive(warning=False)\n",
"m.optimize(messages=True,max_iters=10000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Visualize the latent space of the top layer\n",
"\n",
"Now the model is trained, let’s plot the mean of the posterior\n",
"distributions in the top latent layer of the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from matplotlib import rc"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"rc(\"font\", **{'family':'sans-serif','sans-serif':['Helvetica'],'size':20})\n",
"fig, ax = plt.subplots(figsize=plot.big_figsize)\n",
"for d in digits:\n",
" ax.plot(m.layer_1.X.mean[labels==d,0],m.layer_1.X.mean[labels==d,1],'.',label=str(d))\n",
"_ = plt.legend()\n",
"mlai.write_figure(figure=fig, filename=\"./deepgp/mnist-digits-subsample-latent.svg\", transparent=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: Latent space for the deep Gaussian process learned through\n",
"unsupervised learning and fitted to a subset of the MNIST digits\n",
"subsample."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Visualize the latent space of the intermediate layer\n",
"\n",
"We can also visualize dimensions of the intermediate layer. First the\n",
"lengthscale of those dimensions is given by"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.obslayer.kern.lengthscale"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=plot.big_figsize)\n",
"for i in range(5):\n",
" for j in range(i):\n",
" dims=[i, j]\n",
" ax.cla()\n",
" for d in digits:\n",
" ax.plot(m.obslayer.X.mean[labels==d,dims[0]],\n",
" m.obslayer.X.mean[labels==d,dims[1]],\n",
" '.', label=str(d))\n",
" plt.legend()\n",
" plt.xlabel('dimension ' + str(dims[0]))\n",
" plt.ylabel('dimension ' + str(dims[1]))\n",
" mlai.write_figure(figure=fig, filename=\"./deepgp/mnist-digits-subsample-hidden-\" + str(dims[0]) + '-' + str(dims[1]) + '.svg', transparent=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: Visualisation of the intermediate layer, plot of dimension 1\n",
"vs dimension 0.\n",
"\n",
"\n",
"\n",
"Figure: Visualisation of the intermediate layer, plot of dimension 1\n",
"vs dimension 0.\n",
"\n",
"\n",
"\n",
"Figure: Visualisation of the intermediate layer, plot of dimension 1\n",
"vs dimension 0.\n",
"\n",
"\n",
"\n",
"Figure: Visualisation of the intermediate layer, plot of dimension 1\n",
"vs dimension 0."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Generate From Model\n",
"\n",
"Now we can take a look at a sample from the model, by drawing a Gaussian\n",
"random sample in the latent space and propagating it through the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"rows = 10\n",
"cols = 20\n",
"t=np.linspace(-1, 1, rows*cols)[:, None]\n",
"kern = GPy.kern.RBF(1,lengthscale=0.05)\n",
"cov = kern.K(t, t)\n",
"x = np.random.multivariate_normal(np.zeros(rows*cols), cov, num_latent).T"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import mlai.plot as plot\n",
"import mlai"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"yt = m.predict(x)\n",
"fig, axs = plt.subplots(rows,cols,figsize=(10,6))\n",
"for i in range(rows):\n",
" for j in range(cols):\n",
" #v = np.random.normal(loc=yt[0][i*cols+j, :], scale=np.sqrt(yt[1][i*cols+j, :]))\n",
" v = yt[0][i*cols+j, :]\n",
" axs[i,j].imshow(v.reshape(28,28), \n",
" cmap='gray', interpolation='none',\n",
" aspect='equal')\n",
" axs[i,j].set_axis_off()\n",
"mlai.write_figure(figure=fig, filename=\"./deepgp/digit-samples-deep-gp.svg\", transparent=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: These digits are produced by taking a tour of the two\n",
"dimensional latent space (as described by a Gaussian process sample) and\n",
"mapping the tour into the data space. We visualize the mean of the\n",
"mapping in the images."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Deep NNs as Point Estimates for Deep GPs\n",
"\n",
"\\[edit\\]\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"Figure: Deep Neural Networks as Point Estimates for Deep Gaussian\n",
"Processes by Dutordoir et al. (2021) shows how deep neural networks can\n",
"represent the mean function of an approximate deep GP.\n",
"\n",
"A very promising idea was recently presented by Dutordoir et al. (2021).\n",
"They note that the ReLU activiation functions we use in the neural\n",
"network can be seen as the consequence of a basis function defined on a\n",
"circle (or a hypersphere in higher dimensions) being projected onto the\n",
"real line (or hyperplane) as show in Figure . This allows them to\n",
"construct a covariance function on the hypersphere that is *stationary*."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ReLU as a Spherical Basis\n",
"\n",
"\n",
"\n",
"Figure: The rectified linear unit can be seen as a basis function\n",
"that lives on a spherical domain being projected onto the real line.\n",
"\n",
"\n",
"\n",
"Figure: The soft ReLU can also be seen as a basis function that lives\n",
"on a spherical domain being projected onto the real line."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Spherical Harmonics\n",
"\n",
"\n",
"\n",
"Figure: The method exploits interdomain inducing variables,\n",
"reinterpreting the ReLU covariance function as a stationary covariance\n",
"on the spherical domain that has been projected to the real line.\n",
"\n",
"Applying variational inference techniques to the resulting model (see\n",
"e.g. Hensman et al. (n.d.),Hensman and Lawrence (2014)) and making use\n",
"of interdomain variational approximations (Lázaro-Gredilla et al.\n",
"(2010),Álvarez et al. (2010),Hensman et al. (2018)) causes the *mean\n",
"function* approximation of the Gaussian process to have the same form as\n",
"a fully connected deep neural network. This inspires the idea to use a\n",
"trained neural network to initialise the deep Gaussian process."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Predictions on Banana Data\n",
"\n",
"\n",
"\n",
"Figure: The banana data is an artificially sampled data set with two\n",
"classes (from Rätsch et al. (2001)).\n",
"\n",
"\n",
"\n",
"Figure: One layer deep GP fit showing the neural network point\n",
"estimate (from Dutordoir et al. (2021)).\n",
"\n",
"\n",
"\n",
"Figure: One layer deep GP fit showing the activated deep Gaussian\n",
"process fit (from Dutordoir et al. (2021)).\n",
"\n",
"The results of doing this on the banana data (Figure Rätsch et al.\n",
"(2001)) can be seen with the neural network solution in Figure and the\n",
"neural network activated deep GP solution given in Figure ."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Deep Health\n",
"\n",
"\\[edit\\]\n",
"\n",
"\n",
"\n",
"Figure: The deep health model uses different layers of abstraction in\n",
"the deep Gaussian process to represent information about diagnostics and\n",
"treatment to model interelationships between a patients different data\n",
"modalities.\n",
"\n",
"From a machine learning perspective, we’d like to be able to interrelate\n",
"all the different modalities that are informative about the state of the\n",
"disease. For deep health, the notion is that the state of the disease is\n",
"appearing at the more abstract levels, as we descend the model, we\n",
"express relationships between the more abstract concept, that sits\n",
"within the physician’s mind, and the data we can measure."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Thanks!\n",
"\n",
"For more information on these subjects and more you might want to check\n",
"the following resources.\n",
"\n",
"- twitter: [@lawrennd](https://twitter.com/lawrennd)\n",
"- podcast: [The Talking Machines](http://thetalkingmachines.com)\n",
"- newspaper: [Guardian Profile\n",
" Page](http://www.theguardian.com/profile/neil-lawrence)\n",
"- blog:\n",
" [http://inverseprobability.com](http://inverseprobability.com/blog.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## References"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Arora, S., Cohen, N., Golowich, N., Hu, W., 2019. A convergence analysis\n",
"of gradient descent for deep linear neural networks, in: International\n",
"Conference on Learning Representations.\n",
"\n",
"Álvarez, M.A., Luengo, D., Titsias, M.K., Lawrence, N.D., 2010.\n",
"Efficient multioutput Gaussian processes through variational inducing\n",
"kernels. pp. 25–32.\n",
"\n",
"Bui, T.D., Yan, J., Turner, R.E., 2017. A unifying framework for\n",
"Gaussian process pseudo-point approximations using power expectation\n",
"propagation. Journal of Machine Learning Research 18, 1–72.\n",
"\n",
"Damianou, A., 2015. Deep Gaussian processes and variational propagation\n",
"of uncertainty (PhD thesis). University of Sheffield.\n",
"\n",
"Dunlop, M.M., Girolami, M.A., Stuart, A.M., Teckentrup, A.L., n.d. How\n",
"deep are deep Gaussian processes? Journal of Machine Learning Research\n",
"19, 1–46.\n",
"\n",
"Dutordoir, V., Hensman, J., Wilk, M. van der, Ek, C.H., Ghahramani, Z.,\n",
"Durrande, N., 2021. Deep neural networks as point estimates for deep\n",
"Gaussian processes, in: Advances in Neural Information Processing\n",
"Systems.\n",
"\n",
"Elsner, F., Leistedt, B., Peiris, H.V., 2016. Unbiased pseudo-$C_\\ell$\n",
"power spectrum estimation with mode projection. Monthly Notices of the\n",
"Royal Astronomical Society 465, 1847–1855.\n",
"\n",
"\n",
"Elsner, F., Leistedt, B., Peiris, H.V., 2015. Unbiased methods for\n",
"removing systematics from galaxy clustering measurements. Monthly\n",
"Notices of the Royal Astronomical Society 456, 2095–2104.\n",
"\n",
"\n",
"Hensman, J., Durrande, N., Solin, A., 2018. Variational fourier features\n",
"for gaussian processes. Journal of Machine Learning Research 18, 1–52.\n",
"\n",
"Hensman, J., Fusi, N., Lawrence, N.D., n.d. Gaussian processes for big\n",
"data.\n",
"\n",
"Hensman, J., Lawrence, N.D., 2014. Nested variational compression in\n",
"deep Gaussian processes. University of Sheffield.\n",
"\n",
"Jacot, A., Ged, F., Gabriel, F., Şimşek, B., Hongler, C., 2021. Deep\n",
"linear networks dynamics: Low-rank biases induced by initialization\n",
"scale and L2 regularization.\n",
"\n",
"Jaffe, A.H., Bond, J.R., Ferreira, P.G., Knox, L.E., 1998. CMB\n",
"likelihood functions for beginners and experts, in: AIP Conf. Proc.\n",
"\n",
"\n",
"Lázaro-Gredilla, M., Quiñonero-Candela, J., Rasmussen, C.E., 2010.\n",
"Sparse spectrum gaussian processes. Journal of Machine Learning Research\n",
"11, 1865–1881.\n",
"\n",
"MacKay, D.J.C., n.d. Introduction to Gaussian processes. pp. 133–166.\n",
"\n",
"Mishra-Sharma, S., Cranmer, K., 2020. Semi-parametric $\\gamma$-ray\n",
"modeling with Gaussian processes and variational inference.\n",
"\n",
"Pontzen, A., Peiris, H.V., 2010. The cut-sky cosmic microwave background\n",
"is not anomalous. Phys. Rev. D 81, 103008.\n",
"\n",
"\n",
"Rätsch, G., Onoda, T., Müller, K.-R., 2001. Soft margins for AdaBoost.\n",
"Machine Learning 42, 287–320.\n",
"\n",
"Taigman, Y., Yang, M., Ranzato, M., Wolf, L., 2014. DeepFace: Closing\n",
"the gap to human-level performance in face verification, in: Proceedings\n",
"of the IEEE Computer Society Conference on Computer Vision and Pattern\n",
"Recognition. \n",
"\n",
"Vogelsberger, M., Marinacci, F., Torrey, P., Puchwei, E., 2020.\n",
"Cosmological simulations of galaxy formation. Nature Reviews Physics 2,\n",
"42–66. "
]
}
],
"nbformat": 4,
"nbformat_minor": 5,
"metadata": {}
}