1.7. Gaussian Processes
Gaussian Processes (GP) are a generic supervised learning method designedto solve regression and probabilistic classification problems.
The advantages of Gaussian processes are:
The prediction interpolates the observations (at least for regularkernels).
The prediction is probabilistic (Gaussian) so that one can computeempirical confidence intervals and decide based on those if one shouldrefit (online fitting, adaptive fitting) the prediction in someregion of interest.
Versatile: different kernels can be specified. Common kernels are provided, butit is also possible to specify custom kernels.
The disadvantages of Gaussian processes include:
They are not sparse, i.e., they use the whole samples/features information toperform the prediction.
They lose efficiency in high dimensional spaces – namely when the numberof features exceeds a few dozens.
1.7.1. Gaussian Process Regression (GPR)
The GaussianProcessRegressor
implements Gaussian processes (GP) forregression purposes. For this, the prior of the GP needs to be specified. Theprior mean is assumed to be constant and zero (for normalize_y=False
) or thetraining data’s mean (for normalize_y=True
). The prior’scovariance is specified by passing a kernel object. Thehyperparameters of the kernel are optimized during fitting ofGaussianProcessRegressor by maximizing the log-marginal-likelihood (LML) basedon the passed optimizer
. As the LML may have multiple local optima, theoptimizer can be started repeatedly by specifying n_restarts_optimizer
. Thefirst run is always conducted starting from the initial hyperparameter valuesof the kernel; subsequent runs are conducted from hyperparameter valuesthat have been chosen randomly from the range of allowed values.If the initial hyperparameters should be kept fixed, None
can be passed asoptimizer.
The noise level in the targets can be specified by passing it via theparameter alpha
, either globally as a scalar or per datapoint.Note that a moderate noise level can also be helpful for dealing with numericissues during fitting as it is effectively implemented as Tikhonovregularization, i.e., by adding it to the diagonal of the kernel matrix. Analternative to specifying the noise level explicitly is to include aWhiteKernel component into the kernel, which can estimate the global noiselevel from the data (see example below).
The implementation is based on Algorithm 2.1 of [RW2006]. In addition tothe API of standard scikit-learn estimators, GaussianProcessRegressor:
allows prediction without prior fitting (based on the GP prior)
provides an additional method
sample_y(X)
, which evaluates samplesdrawn from the GPR (prior or posterior) at given inputsexposes a method
log_marginal_likelihood(theta)
, which can be usedexternally for other ways of selecting hyperparameters, e.g., viaMarkov chain Monte Carlo.
1.7.2. GPR examples
1.7.2.1. GPR with noise-level estimation
This example illustrates that GPR with a sum-kernel including a WhiteKernel canestimate the noise level of data. An illustration of thelog-marginal-likelihood (LML) landscape shows that there exist two localmaxima of LML.
The first corresponds to a model with a high noise level and alarge length scale, which explains all variations in the data by noise.
The second one has a smaller noise level and shorter length scale, which explainsmost of the variation by the noise-free functional relationship. The secondmodel has a higher likelihood; however, depending on the initial value for thehyperparameters, the gradient-based optimization might also converge to thehigh-noise solution. It is thus important to repeat the optimization severaltimes for different initializations.
1.7.2.2. Comparison of GPR and Kernel Ridge Regression
Both kernel ridge regression (KRR) and GPR learna target function by employing internally the “kernel trick”. KRR learns alinear function in the space induced by the respective kernel which correspondsto a non-linear function in the original space. The linear function in thekernel space is chosen based on the mean-squared error loss withridge regularization. GPR uses the kernel to define the covariance ofa prior distribution over the target functions and uses the observed trainingdata to define a likelihood function. Based on Bayes theorem, a (Gaussian)posterior distribution over target functions is defined, whose mean is usedfor prediction.
A major difference is that GPR can choose the kernel’s hyperparameters basedon gradient-ascent on the marginal likelihood function while KRR needs toperform a grid search on a cross-validated loss function (mean-squared errorloss). A further difference is that GPR learns a generative, probabilisticmodel of the target function and can thus provide meaningful confidenceintervals and posterior samples along with the predictions while KRR onlyprovides predictions.
The following figure illustrates both methods on an artificial dataset, whichconsists of a sinusoidal target function and strong noise. The figure comparesthe learned model of KRR and GPR based on a ExpSineSquared kernel, which issuited for learning periodic functions. The kernel’s hyperparameters controlthe smoothness (length_scale) and periodicity of the kernel (periodicity).Moreover, the noise levelof the data is learned explicitly by GPR by an additional WhiteKernel componentin the kernel and by the regularization parameter alpha of KRR.
The figure shows that both methods learn reasonable models of the targetfunction. GPR correctly identifies the periodicity of the function to beroughly
(6.28), while KRR chooses the doubled periodicity . Besidesthat, GPR provides reasonable confidence bounds on the prediction which are notavailable for KRR. A major difference between the two methods is the timerequired for fitting and predicting: while fitting KRR is fast in principle,the grid-search for hyperparameter optimization scales exponentially with thenumber of hyperparameters (“curse of dimensionality”). The gradient-basedoptimization of the parameters in GPR does not suffer from this exponentialscaling and is thus considerable faster on this example with 3-dimensionalhyperparameter space. The time for predicting is similar; however, generatingthe variance of the predictive distribution of GPR takes considerable longerthan just predicting the mean.
1.7.2.3. GPR on Mauna Loa CO2 data
This example is based on Section 5.4.3 of [RW2006].It illustrates an example of complex kernel engineering andhyperparameter optimization using gradient ascent on thelog-marginal-likelihood. The data consists of the monthly average atmosphericCO2 concentrations (in parts per million by volume (ppmv)) collected at theMauna Loa Observatory in Hawaii, between 1958 and 1997. The objective is tomodel the CO2 concentration as a function of the time t.
The kernel is composed of several terms that are responsible for explainingdifferent properties of the signal:
a long term, smooth rising trend is to be explained by an RBF kernel. TheRBF kernel with a large length-scale enforces this component to be smooth;it is not enforced that the trend is rising which leaves this choice to theGP. The specific length-scale and the amplitude are free hyperparameters.
a seasonal component, which is to be explained by the periodicExpSineSquared kernel with a fixed periodicity of 1 year. The length-scaleof this periodic component, controlling its smoothness, is a free parameter.In order to allow decaying away from exact periodicity, the product with anRBF kernel is taken. The length-scale of this RBF component controls thedecay time and is a further free parameter.
smaller, medium term irregularities are to be explained by aRationalQuadratic kernel component, whose length-scale and alpha parameter,which determines the diffuseness of the length-scales, are to be determined.According to [RW2006], these irregularities can better be explained bya RationalQuadratic than an RBF kernel component, probably because it canaccommodate several length-scales.
a “noise” term, consisting of an RBF kernel contribution, which shallexplain the correlated noise components such as local weather phenomena,and a WhiteKernel contribution for the white noise. The relative amplitudesand the RBF’s length scale are further free parameters.
Maximizing the log-marginal-likelihood after subtracting the target’s meanyields the following kernel with an LML of -83.214:
- 34.4**2 * RBF(length_scale=41.8)
- + 3.27**2 * RBF(length_scale=180) * ExpSineSquared(length_scale=1.44,
- periodicity=1)
- + 0.446**2 * RationalQuadratic(alpha=17.7, length_scale=0.957)
- + 0.197**2 * RBF(length_scale=0.138) + WhiteKernel(noise_level=0.0336)
Thus, most of the target signal (34.4ppm) is explained by a long-term risingtrend (length-scale 41.8 years). The periodic component has an amplitude of3.27ppm, a decay time of 180 years and a length-scale of 1.44. The long decaytime indicates that we have a locally very close to periodic seasonalcomponent. The correlated noise has an amplitude of 0.197ppm with a lengthscale of 0.138 years and a white-noise contribution of 0.197ppm. Thus, theoverall noise level is very small, indicating that the data can be very wellexplained by the model. The figure shows also that the model makes veryconfident predictions until around 2015
1.7.3. Gaussian Process Classification (GPC)
The GaussianProcessClassifier
implements Gaussian processes (GP) forclassification purposes, more specifically for probabilistic classification,where test predictions take the form of class probabilities.GaussianProcessClassifier places a GP prior on a latent function
,which is then squashed through a link function to obtain the probabilisticclassification. The latent function is a so-called nuisance function,whose values are not observed and are not relevant by themselves.Its purpose is to allow a convenient formulation of the model, andis removed (integrated out) during prediction. GaussianProcessClassifierimplements the logistic link function, for which the integral cannot becomputed analytically but is easily approximated in the binary case.
In contrast to the regression setting, the posterior of the latent function
is not Gaussian even for a GP prior since a Gaussian likelihood isinappropriate for discrete class labels. Rather, a non-Gaussian likelihoodcorresponding to the logistic link function (logit) is used.GaussianProcessClassifier approximates the non-Gaussian posterior with aGaussian based on the Laplace approximation. More details can be found inChapter 3 of [RW2006].
The GP prior mean is assumed to be zero. The prior’scovariance is specified by passing a kernel object. Thehyperparameters of the kernel are optimized during fitting ofGaussianProcessRegressor by maximizing the log-marginal-likelihood (LML) basedon the passed optimizer
. As the LML may have multiple local optima, theoptimizer can be started repeatedly by specifying n_restarts_optimizer
. Thefirst run is always conducted starting from the initial hyperparameter valuesof the kernel; subsequent runs are conducted from hyperparameter valuesthat have been chosen randomly from the range of allowed values.If the initial hyperparameters should be kept fixed, None
can be passed asoptimizer.
GaussianProcessClassifier
supports multi-class classificationby performing either one-versus-rest or one-versus-one based training andprediction. In one-versus-rest, one binary Gaussian process classifier isfitted for each class, which is trained to separate this class from the rest.In “one_vs_one”, one binary Gaussian process classifier is fitted for each pairof classes, which is trained to separate these two classes. The predictions ofthese binary predictors are combined into multi-class predictions. See thesection on multi-class classification for more details.
In the case of Gaussian process classification, “one_vs_one” might becomputationally cheaper since it has to solve many problems involving only asubset of the whole training set rather than fewer problems on the wholedataset. Since Gaussian process classification scales cubically with the sizeof the dataset, this might be considerably faster. However, note that“one_vs_one” does not support predicting probability estimates but only plainpredictions. Moreover, note that GaussianProcessClassifier
does not(yet) implement a true multi-class Laplace approximation internally, butas discussed above is based on solving several binary classification tasksinternally, which are combined using one-versus-rest or one-versus-one.
1.7.4. GPC examples
1.7.4.1. Probabilistic predictions with GPC
This example illustrates the predicted probability of GPC for an RBF kernelwith different choices of the hyperparameters. The first figure shows thepredicted probability of GPC with arbitrarily chosen hyperparameters and withthe hyperparameters corresponding to the maximum log-marginal-likelihood (LML).
While the hyperparameters chosen by optimizing LML have a considerable largerLML, they perform slightly worse according to the log-loss on test data. Thefigure shows that this is because they exhibit a steep change of the classprobabilities at the class boundaries (which is good) but have predictedprobabilities close to 0.5 far away from the class boundaries (which is bad)This undesirable effect is caused by the Laplace approximation usedinternally by GPC.
The second figure shows the log-marginal-likelihood for different choices ofthe kernel’s hyperparameters, highlighting the two choices of thehyperparameters used in the first figure by black dots.
1.7.4.2. Illustration of GPC on the XOR dataset
This example illustrates GPC on XOR data. Compared are a stationary, isotropickernel (RBF
) and a non-stationary kernel (DotProduct
). Onthis particular dataset, the DotProduct
kernel obtains considerablybetter results because the class-boundaries are linear and coincide with thecoordinate axes. In practice, however, stationary kernels such as RBF
often obtain better results.
1.7.4.3. Gaussian process classification (GPC) on iris dataset
This example illustrates the predicted probability of GPC for an isotropicand anisotropic RBF kernel on a two-dimensional version for the iris-dataset.This illustrates the applicability of GPC to non-binary classification.The anisotropic RBF kernel obtains slightly higher log-marginal-likelihood byassigning different length-scales to the two feature dimensions.
1.7.5. Kernels for Gaussian Processes
Kernels (also called “covariance functions” in the context of GPs) are a crucialingredient of GPs which determine the shape of prior and posterior of the GP.They encode the assumptions on the function being learned by defining the “similarity”of two datapoints combined with the assumption that similar datapoints shouldhave similar target values. Two categories of kernels can be distinguished:stationary kernels depend only on the distance of two datapoints and not on theirabsolute values
and are thus invariant totranslations in the input space, while non-stationary kernelsdepend also on the specific values of the datapoints. Stationary kernels can furtherbe subdivided into isotropic and anisotropic kernels, where isotropic kernels arealso invariant to rotations in the input space. For more details, we refer toChapter 4 of [RW2006].
1.7.5.1. Gaussian Process Kernel API
The main usage of a Kernel
is to compute the GP’s covariance betweendatapoints. For this, the method call
of the kernel can be called. Thismethod can either be used to compute the “auto-covariance” of all pairs ofdatapoints in a 2d array X, or the “cross-covariance” of all combinationsof datapoints of a 2d array X with datapoints in a 2d array Y. The followingidentity holds true for all kernels k (except for the WhiteKernel
):k(X) == K(X, Y=X)
If only the diagonal of the auto-covariance is being used, the method diag()
of a kernel can be called, which is more computationally efficient than theequivalent call to call
: np.diag(k(X, X)) == k.diag(X)
Kernels are parameterized by a vector
of hyperparameters. Thesehyperparameters can for instance control length-scales or periodicity of akernel (see below). All kernels support computing analytic gradientsof the kernel’s auto-covariance with respect to via settingevalgradient=True
in the _call
method. This gradient is used by theGaussian process (both regressor and classifier) in computing the gradientof the log-marginal-likelihood, which in turn is used to determine thevalue of, which maximizes the log-marginal-likelihood, viagradient ascent. For each hyperparameter, the initial value and thebounds need to be specified when creating an instance of the kernel. Thecurrent value of can be get and set via the propertytheta
of the kernel object. Moreover, the bounds of the hyperparameters can beaccessed by the property bounds
of the kernel. Note that both properties(theta and bounds) return log-transformed values of the internally used valuessince those are typically more amenable to gradient-based optimization.The specification of each hyperparameter is stored in the form of an instance ofHyperparameter
in the respective kernel. Note that a kernel using ahyperparameter with name “x” must have the attributes self.x and self.x_bounds.
The abstract base class for all kernels is Kernel
. Kernel implements asimilar interface as Estimator
, providing the methods getparams()
,setparams()
, and clone()
. This allows setting kernel values also viameta-estimators such as Pipeline
or GridSearch
. Note that due to the nestedstructure of kernels (by applying kernel operators, see below), the names ofkernel parameters might become relatively complicated. In general, for abinary kernel operator, parameters of the left operand are prefixed with k1__
and parameters of the right operand with k2
. An additional conveniencemethod is clone_with_theta(theta)
, which returns a cloned version of thekernel but with the hyperparameters set to theta
. An illustrative example:
>>>
- >>> from sklearn.gaussian_process.kernels import ConstantKernel, RBF
- >>> kernel = ConstantKernel(constant_value=1.0, constant_value_bounds=(0.0, 10.0)) * RBF(length_scale=0.5, length_scale_bounds=(0.0, 10.0)) + RBF(length_scale=2.0, length_scale_bounds=(0.0, 10.0))
- >>> for hyperparameter in kernel.hyperparameters: print(hyperparameter)
- Hyperparameter(name='k1__k1__constant_value', value_type='numeric', bounds=array([[ 0., 10.]]), n_elements=1, fixed=False)
- Hyperparameter(name='k1__k2__length_scale', value_type='numeric', bounds=array([[ 0., 10.]]), n_elements=1, fixed=False)
- Hyperparameter(name='k2__length_scale', value_type='numeric', bounds=array([[ 0., 10.]]), n_elements=1, fixed=False)
- >>> params = kernel.get_params()
- >>> for key in sorted(params): print("%s : %s" % (key, params[key]))
- k1 : 1**2 * RBF(length_scale=0.5)
- k1__k1 : 1**2
- k1__k1__constant_value : 1.0
- k1__k1__constant_value_bounds : (0.0, 10.0)
- k1__k2 : RBF(length_scale=0.5)
- k1__k2__length_scale : 0.5
- k1__k2__length_scale_bounds : (0.0, 10.0)
- k2 : RBF(length_scale=2)
- k2__length_scale : 2.0
- k2__length_scale_bounds : (0.0, 10.0)
- >>> print(kernel.theta) # Note: log-transformed
- [ 0. -0.69314718 0.69314718]
- >>> print(kernel.bounds) # Note: log-transformed
- [[ -inf 2.30258509]
- [ -inf 2.30258509]
- [ -inf 2.30258509]]
All Gaussian process kernels are interoperable with sklearn.metrics.pairwise
and vice versa: instances of subclasses of Kernel
can be passed asmetric
to pairwise_kernels
from sklearn.metrics.pairwise
. Moreover,kernel functions from pairwise can be used as GP kernels by using the wrapperclass PairwiseKernel
. The only caveat is that the gradient ofthe hyperparameters is not analytic but numeric and all those kernels supportonly isotropic distances. The parameter gamma
is considered to be ahyperparameter and may be optimized. The other kernel parameters are setdirectly at initialization and are kept fixed.
1.7.5.2. Basic kernels
The ConstantKernel
kernel can be used as part of a Product
kernel where it scales the magnitude of the other factor (kernel) or as partof a Sum
kernel, where it modifies the mean of the Gaussian process.It depends on a parameter
. It is defined as:
The main use-case of the WhiteKernel
kernel is as part of asum-kernel where it explains the noise-component of the signal. Tuning itsparameter
corresponds to estimating the noise-level.It is defined as:
1.7.5.3. Kernel operators
Kernel operators take one or two base kernels and combine them into a newkernel. The Sum
kernel takes two kernels
andand combines them via.The Product
kernel takes two kernels andand combines them via.The Exponentiation
kernel takes one base kernel and a scalar parameter and combines them via.
1.7.5.4. Radial-basis function (RBF) kernel
The RBF
kernel is a stationary kernel. It is also known as the “squaredexponential” kernel. It is parameterized by a length-scale parameter
, whichcan either be a scalar (isotropic variant of the kernel) or a vector with the samenumber of dimensions as the inputs (anisotropic variant of the kernel).The kernel is given by:
This kernel is infinitely differentiable, which implies that GPs with thiskernel as covariance function have mean square derivatives of all orders, and are thusvery smooth. The prior and posterior of a GP resulting from an RBF kernel are shown inthe following figure:
1.7.5.5. Matérn kernel
The Matern
kernel is a stationary kernel and a generalization of theRBF
kernel. It has an additional parameter
which controlsthe smoothness of the resulting function. It is parameterized by a length-scale parameter, which can either be a scalar (isotropic variant of the kernel) or a vector with the same number of dimensions as the inputs (anisotropic variant of the kernel). The kernel is given by:
As
, the Matérn kernel converges to the RBF kernel.When, the Matérn kernel becomes identical to the absoluteexponential kernel, i.e.,
In particular,
:
and
:
are popular choices for learning functions that are not infinitelydifferentiable (as assumed by the RBF kernel) but at least once (
) or twice differentiable ().
The flexibility of controlling the smoothness of the learned function via
allows adapting to the properties of the true underlying functional relation.The prior and posterior of a GP resulting from a Matérn kernel are shown inthe following figure:
See [RW2006], pp84 for further details regarding thedifferent variants of the Matérn kernel.
1.7.5.6. Rational quadratic kernel
The RationalQuadratic
kernel can be seen as a scale mixture (an infinite sum)of RBF
kernels with different characteristic length-scales. It is parameterizedby a length-scale parameter
and a scale mixture parameterOnly the isotropic variant where is a scalar is supported at the moment.The kernel is given by:
The prior and posterior of a GP resulting from a RationalQuadratic
kernel are shown inthe following figure:
1.7.5.7. Exp-Sine-Squared kernel
The ExpSineSquared
kernel allows modeling periodic functions.It is parameterized by a length-scale parameter
and a periodicity parameter. Only the isotropic variant where is a scalar is supported at the moment.The kernel is given by:
The prior and posterior of a GP resulting from an ExpSineSquared kernel are shown inthe following figure:
1.7.5.8. Dot-Product kernel
The DotProduct
kernel is non-stationary and can be obtained from linear regressionby putting
priors on the coefficients of anda prior of on the bias. The DotProduct
kernel is invariant to a rotationof the coordinates about the origin, but not translations.It is parameterized by a parameter. For, the kernelis called the homogeneous linear kernel, otherwise it is inhomogeneous. The kernel is given by
The DotProduct
kernel is commonly combined with exponentiation. An example with exponent 2 isshown in the following figure: