| Title: | Gaussian Processes from First Principles |
|---|---|
| Description: | Gaussian process regression, classification, and count models with explicit covariance kernels, exact Gaussian inference, Laplace approximations for non-Gaussian likelihoods, sparse approximations, marginal-likelihood optimization, derivatives, posterior sampling, calibration diagnostics, and time-series workflows. The implementation follows the core methodology of Rasmussen and Williams (2006) <doi:10.7551/mitpress/3206.001.0001> and emphasizes numerical stability, transparent assumptions, and reproducible statistical workflows. |
| Authors: | Diogo Ribeiro [aut, cre] (ORCID: <https://orcid.org/0009-0001-2022-7072>, affiliation: Faculty of Media Arts and Design of the Technical University of Porto) |
| Maintainer: | Diogo Ribeiro <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.0.0.9000 |
| Built: | 2026-10-22 10:33:15 UTC |
| Source: | https://gitlab.com/diogoribeiro7/gaussian-processes-r |
Measures exact GP fit time and retained model size over increasing training sizes using seeded RBF simulations. This function is intended for local empirical scaling studies rather than CI performance gating.
benchmark_exact_gp_scaling( sizes = c(50L, 100L, 200L, 400L), repeats = 3L, seed = 1729L )benchmark_exact_gp_scaling( sizes = c(50L, 100L, 200L, 400L), repeats = 3L, seed = 1729L )
sizes |
Positive integer vector of training sizes. |
repeats |
Number of timing repetitions per size. |
seed |
Base non-negative integer seed. |
A data frame with one row per requested size.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
# A deliberately small run; larger sizes show the cubic cost. benchmark_exact_gp_scaling(sizes = c(20, 40), repeats = 1)# A deliberately small run; larger sizes show the cubic cost. benchmark_exact_gp_scaling(sizes = c(20, 40), repeats = 1)
Runs both models with identical fixed kernel and noise parameters, then compares retained model size, elapsed fitting/prediction time, posterior mean RMSE, and latent-variance MAE. The exact GP is treated as the numerical reference, not as ground truth.
benchmark_sparse_gp( x, y, kernel, n_inducing, prediction_x = x, noise_variance = 1e-06, mean = zero_mean(), selection = c("farthest", "quantile", "variance"), observation_noise_variance = NULL )benchmark_sparse_gp( x, y, kernel, n_inducing, prediction_x = x, noise_variance = 1e-06, mean = zero_mean(), selection = c("farthest", "quantile", "variance"), observation_noise_variance = NULL )
x |
Numeric vector or matrix of training inputs. |
y |
Numeric response vector. |
kernel |
Fixed kernel specification shared by both models. |
n_inducing |
Number of inducing points for FITC. |
prediction_x |
Optional prediction inputs; defaults to |
noise_variance |
Non-negative observation-noise variance: a scalar, or one value per training observation. Both models use the same noise. |
mean |
Mean specification shared by both models. |
selection |
Inducing-point selection method. |
observation_noise_variance |
Optional noise variance at
|
The benchmark reports retained R object size, not peak process memory. Elapsed timings are simple wall-clock measurements intended for local comparison, not publication-grade benchmarking.
A list containing a comparison data frame and both prediction objects.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
x <- seq(-3, 3, length.out = 200) y <- sin(x) + 0.1 * cos(7 * x) benchmark <- benchmark_sparse_gp( x, y, kernel = rbf_kernel(length_scale = 0.8), n_inducing = 15, noise_variance = 0.01 ) benchmark$comparisonx <- seq(-3, 3, length.out = 200) y <- sin(x) + 0.1 * cos(7 * x) benchmark <- benchmark_sparse_gp( x, y, kernel = rbf_kernel(length_scale = 0.8), n_inducing = 15, noise_variance = 0.01 ) benchmark$comparison
Switches from one covariance to another along one input column, smoothly around an estimable location: a structural break in a time series, or a regime change in space.
changepoint_kernel(before, after, location = 0, steepness = 1, column = 1L)changepoint_kernel(before, after, location = 0, steepness = 1, column = 1L)
before, after
|
Kernel specifications that hold before and after the change. |
location |
Finite location |
steepness |
Positive steepness |
column |
The input column along which the change happens. |
With the sigmoid along column
,
where is before and is after. Each term has the
form , so the kernel is positive semidefinite.
The two regimes are independent processes: as , the
covariance between points on opposite sides of tends to 0.
location is a real-valued parameter, optimized on the identity scale,
and steepness a positive one, optimized on the log scale. Parameter
paths are location and steepness for the change itself, and
before. and after. for the two kernels, so nested changepoints model
several changes. optimize_gp() bounds every changepoint location by the
training range of its column and, because the likelihood is often
multimodal in the location, starts it at evenly spaced quantiles of that
column.
The kernel is as smooth as its two components, so it supports
kernel_input_gradient(), predict_gradient_gp(), and derivative
observations when they do.
A composite kernel specification.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
time_series_kernel(), whose changepoint argument adds a
change to the time-series kernel.
kernel <- changepoint_kernel( before = rbf_kernel(variance = 1, length_scale = 2), after = rbf_kernel(variance = 0.2, length_scale = 0.5), location = 5, steepness = 4 ) kernel names(kernel_parameters(kernel, flatten = TRUE)) # Points on opposite sides of a steep change are nearly uncorrelated. evaluate_kernel(kernel, c(4, 6))kernel <- changepoint_kernel( before = rbf_kernel(variance = 1, length_scale = 2), after = rbf_kernel(variance = 0.2, length_scale = 0.5), location = 5, steepness = 4 ) kernel names(kernel_parameters(kernel, flatten = TRUE)) # Points on opposite sides of a steep change are nearly uncorrelated. evaluate_kernel(kernel, c(4, 6))
coef() returns the coefficients of a model's mean function,
and vcov() their covariance given the hyperparameters.
## S3 method for class 'gaussianprocesses_latent_model' coef(object, ...) ## S3 method for class 'gaussianprocesses_model' coef(object, ...) ## S3 method for class 'gaussianprocesses_model' vcov(object, ...)## S3 method for class 'gaussianprocesses_latent_model' coef(object, ...) ## S3 method for class 'gaussianprocesses_model' coef(object, ...) ## S3 method for class 'gaussianprocesses_model' vcov(object, ...)
object |
A fitted |
... |
Unused. |
For estimated coefficients, coef() is the generalized least-squares
estimate and vcov() its covariance
. For marginalized coefficients they are the
posterior mean and covariance
. Fixed coefficients have zero
covariance. Both treat the kernel and noise parameters as known. The zero
mean has no coefficients.
For latent models (fit_latent_gp()), coef() returns the fixed
coefficients, the estimate that maximizes the approximate marginal
likelihood, or, under a Gaussian prior , the approximate
posterior mean with . They have no vcov() method.
coef(): a named numeric vector. vcov(): a matrix with matching
row and column names.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
mean_coefficients, linear_mean().
x <- seq(0, 4, length.out = 25) model <- fit_gp(x, 1 + 0.5 * x + sin(2 * x), rbf_kernel(length_scale = 0.5), noise_variance = 0.01, mean = linear_mean()) coef(model) vcov(model)x <- seq(0, 4, length.out = 25) model <- fit_gp(x, 1 + 0.5 * x + sin(2 * x), rbf_kernel(length_scale = 0.5), noise_variance = 0.01, mean = linear_mean()) coef(model) vcov(model)
Compare two GP posterior predictions numerically
compare_gp_predictions(reference, candidate)compare_gp_predictions(reference, candidate)
reference |
Reference prediction object with |
candidate |
Candidate prediction object with matching lengths. |
A named list of numerical accuracy differences.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
x <- seq(-3, 3, length.out = 100) y <- sin(x) kernel <- rbf_kernel(length_scale = 0.8) exact <- predict_gp(fit_gp(x, y, kernel, noise_variance = 0.01), x) sparse <- predict_sparse_gp( fit_sparse_gp(x, y, kernel, noise_variance = 0.01, n_inducing = 10), x ) compare_gp_predictions(exact, sparse)x <- seq(-3, 3, length.out = 100) y <- sin(x) kernel <- rbf_kernel(length_scale = 0.8) exact <- predict_gp(fit_gp(x, y, kernel, noise_variance = 0.01), x) sparse <- predict_sparse_gp( fit_sparse_gp(x, y, kernel, noise_variance = 0.01, n_inducing = 10), x ) compare_gp_predictions(exact, sparse)
A coregionalization kernel acts on one input column that holds an output
index and gives the covariance between
outputs, with
which is positive semidefinite by construction. Multiplied by a kernel
on the other inputs it gives the intrinsic coregionalization model (ICM),
; a sum of
such products is the linear model of coregionalization (LMC).
coregionalization_kernel(n_outputs, rank = 1L, W = NULL, kappa = NULL)coregionalization_kernel(n_outputs, rank = 1L, W = NULL, kappa = NULL)
n_outputs |
Number of outputs |
rank |
Number of columns |
W |
|
kappa |
Positive output-specific variances, one per output; the default is 1. |
The kernel needs exactly one input column, so in a model with other
inputs it is restricted to the output-index column with
select_dimensions(). With inputs in column 1 and the output index in
column 2, an ICM kernel is
product_kernel(select_dimensions(rbf_kernel(), 1), select_dimensions(coregionalization_kernel(P), 2)). gp_stack_outputs()
builds such inputs from one response column per output, and
initialize_coregionalization() gives a starting and
.
The optimizer works on directly and on . Two
cautions apply:
is identified only up to rotation and sign: gives the
same for any orthogonal . Report , with
coregionalization_matrix(), not .
is a stationary point of the likelihood, where the gradient
with respect to is zero, so an optimization started there keeps
; start from initialize_coregionalization() instead.
The overall scale of an ICM term is shared by and the variance of
the input kernel; fixing the latter at 1 removes the redundancy only if
that parameter is not optimized, so expect the two to trade off.
A gaussianprocesses_kernel.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Bonilla, E. V., Chai, K. M. A., and Williams, C. K. I. (2008). Multi-task Gaussian process prediction. Advances in Neural Information Processing Systems, 20.
Alvarez, M. A., Rosasco, L., and Lawrence, N. D. (2012). Kernels for vector-valued functions: a review. Foundations and Trends in Machine Learning, 4(3), 195–266.
gp_stack_outputs(), initialize_coregionalization(),
coregionalization_matrix().
kernel <- coregionalization_kernel( n_outputs = 2, rank = 1, W = c(1, 0.5), kappa = c(0.1, 0.2) ) coregionalization_matrix(kernel) evaluate_kernel(kernel, matrix(c(1, 2, 2))) # An ICM kernel for inputs in column 1 and the output index in column 2. icm <- product_kernel( select_dimensions(rbf_kernel(length_scale = 0.5), 1), select_dimensions(kernel, 2) )kernel <- coregionalization_kernel( n_outputs = 2, rank = 1, W = c(1, 0.5), kappa = c(0.1, 0.2) ) coregionalization_matrix(kernel) evaluate_kernel(kernel, matrix(c(1, 2, 2))) # An ICM kernel for inputs in column 1 and the output index in column 2. icm <- product_kernel( select_dimensions(rbf_kernel(length_scale = 0.5), 1), select_dimensions(kernel, 2) )
Returns for every
coregionalization kernel in a kernel, such as the fitted kernel of a
multi-output model.
coregionalization_matrix(kernel)coregionalization_matrix(kernel)
kernel |
A kernel specification. |
is identified, while is not: gives the same
for any orthogonal . In an ICM term , the
scale of also trades off with the variance of the input kernel
; the correlations stats::cov2cor(B) do not.
A named list with one matrix per
coregionalization kernel, named by its parameter path ("" for a
coregionalization kernel itself).
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
kernel <- sum_kernel( product_kernel( select_dimensions(rbf_kernel(), 1), select_dimensions(coregionalization_kernel(2, W = c(1, 1)), 2) ), select_dimensions(coregionalization_kernel(2, kappa = c(0.5, 2)), 2) ) coregionalization_matrix(kernel)kernel <- sum_kernel( product_kernel( select_dimensions(rbf_kernel(), 1), select_dimensions(coregionalization_kernel(2, W = c(1, 1)), 2) ), select_dimensions(coregionalization_kernel(2, kappa = c(0.5, 2)), 2) ) coregionalization_matrix(kernel)
The package offers two ways to compute a covariance matrix. Kernel
specifications, such as rbf_kernel(), are objects: they can be combined
with sum_kernel(), product_kernel(), and scale_kernel(), their
parameters can be read, updated, and optimized, and models store them.
evaluate_kernel() computes their covariance. The covariance functions,
such as kernel_rbf(), take the parameter values as arguments and return
one matrix directly. Both use the same formulas.
evaluate_kernel(kernel, x, y = NULL)evaluate_kernel(kernel, x, y = NULL)
kernel |
A Gaussian-process kernel specification. |
x |
Numeric vector or matrix of observations. |
y |
Optional numeric vector or matrix. If |
A numeric covariance matrix.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel <- sum_kernel(rbf_kernel(length_scale = 0.5), white_noise_kernel(0.1)) x <- c(0, 0.5, 1) evaluate_kernel(kernel, x) # Cross-covariance between training and new inputs. evaluate_kernel(kernel, x, c(0.25, 2))kernel <- sum_kernel(rbf_kernel(length_scale = 0.5), white_noise_kernel(0.1)) x <- c(0, 0.5, 1) evaluate_kernel(kernel, x) # Cross-covariance between training and new inputs. evaluate_kernel(kernel, x, c(0.25, 2))
Computes and its first three derivatives with
respect to the latent values , the quantities that Laplace and
related approximations need.
evaluate_likelihood(likelihood, y, f, exposure = NULL)evaluate_likelihood(likelihood, y, f, exposure = NULL)
likelihood |
A likelihood specification (gp_likelihoods). |
y |
Responses, as the likelihood accepts them. |
f |
Numeric vector of latent values, one per response. |
exposure |
Optional positive exposure for Poisson likelihoods: one value or one per response. |
A data frame with one row per response: y in the internal coding
(0/1 for binary responses), f, log_density, and the derivatives
first, second, and third.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
f <- c(-40, -2, 0, 2, 40) evaluate_likelihood(bernoulli_likelihood("probit"), rep(1, 5), f) evaluate_likelihood(poisson_likelihood(), c(0, 1, 2, 3, 4), f = log(1:5), exposure = 2)f <- c(-40, -2, 0, 2, 40) evaluate_likelihood(bernoulli_likelihood("probit"), rep(1, 5), f) evaluate_likelihood(poisson_likelihood(), c(0, 1, 2, 3, 4), f = log(1:5), exposure = 2)
Evaluate a Gaussian-process mean function
evaluate_mean(mean, x)evaluate_mean(mean, x)
mean |
A Gaussian-process mean specification. |
x |
Numeric vector or matrix of observations. |
Means with fixed coefficients evaluate to . A mean
whose coefficients have a Gaussian prior evaluates to its prior mean
. Estimated coefficients, and those with a vague prior,
have no value before a model is fitted; predict_gp() and coef() use
the fitted values.
A numeric vector with one mean value per observation.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
evaluate_mean(constant_mean(1), matrix(0, nrow = 4, ncol = 2)) evaluate_mean(linear_mean(c(1, 2)), c(0, 0.5, 1))evaluate_mean(constant_mean(1), matrix(0, nrow = 4, ncol = 2)) evaluate_mean(linear_mean(c(1, 2)), c(0, 0.5, 1))
Fits a Gaussian-process regression model by conditioning a Gaussian prior on observed responses. The implementation uses a Cholesky factorization and triangular solves; it never forms an explicit matrix inverse.
fit_gp( x, y, kernel, noise_variance = 1e-06, mean = zero_mean(), initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), derivative = NULL )fit_gp( x, y, kernel, noise_variance = 1e-06, mean = zero_mean(), initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), derivative = NULL )
x |
Numeric vector or matrix of training inputs. Matrix rows are observations and columns are input dimensions. |
y |
Numeric response vector with one value per training observation. |
kernel |
A Gaussian-process kernel specification. |
noise_variance |
Non-negative scalar observation-noise variance or a non-negative vector with one known variance per training observation. |
mean |
Gaussian-process mean specification: |
initial_jitter |
Non-negative jitter tried first, relative to the covariance scale (see Numerical jitter). |
fallback_jitter |
Positive relative jitter tried after the first failed factorization. |
jitter_multiplier |
Multiplicative increase applied to jitter after each failed factorization. |
max_attempts |
Maximum number of Cholesky attempts. |
symmetry_tolerance |
Relative tolerance for checking that the covariance matrix is symmetric. |
derivative |
Optional observation types, one per observation: 0
if |
A scalar noise_variance gives the usual homoscedastic model. A vector
adds a known diagonal observation-noise variance for each training point.
Observation noise and numerical jitter are always stored separately.
An object of class gaussianprocesses_model.
Differentiation is linear, so derivatives of a Gaussian process are
jointly Gaussian with its values, and observing them is exact
conditioning. With values at and derivatives at ,
where each derivative row uses its own direction . The blocks come
from the kernel's input derivatives (kernel_input_gradient()), so the
kernel must be mean-square differentiable; otherwise an error of class
gaussianprocesses_smoothness_error is raised. Parametric means
contribute their input derivatives. noise_variance may differ between
value and derivative observations.
Conditioning, prediction, log_marginal_likelihood(), its gradient, and
optimize_gp() work unchanged with this covariance;
predict_gp() and predict_gradient_gp() predict values and
derivatives at new inputs. Derivative blocks scale with
, so gp_numerical_diagnostics() reports the
conditioning of each observation type separately.
If does not factorize, the factorization
is retried with , where and
is the covariance scale, the mean of the diagonal of . The
relative jitter starts at initial_jitter (if positive),
then takes the values fallback_jitter, fallback_jitter * jitter_multiplier, and so on, for at most max_attempts attempts.
Because is proportional to , results do not depend
on the units of y: multiplying y by and every variance
parameter by multiplies the jitter by . The fitted
model reports the absolute jitter in jitter, and
gp_numerical_diagnostics() also reports and .
Stable: from version 1.0.0 this interface changes incompatibly only in a
major release, after a deprecation period. Results and options that
concern an experimental model class, kernel, or argument follow that
interface's tier. See gaussianprocesses-package for the
policy. The derivative argument (derivative observations) is experimental.
gaussianprocesses_model for the structure, versioning, and persistence of fitted models.
x <- seq(-2, 2, length.out = 15) y <- sin(2 * x) model <- fit_gp(x, y, kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01) model # Known, observation-specific noise variances. fit_gp( x, y, kernel = rbf_kernel(length_scale = 0.6), noise_variance = seq(0.01, 0.1, length.out = 15) )x <- seq(-2, 2, length.out = 15) y <- sin(2 * x) model <- fit_gp(x, y, kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01) model # Known, observation-specific noise variances. fit_gp( x, y, kernel = rbf_kernel(length_scale = 0.6), noise_variance = seq(0.01, 0.1, length.out = 15) )
Fits two coupled Gaussian processes: one for the latent regression function and one for the logarithm of input-dependent observation-noise variance. Noise targets are constructed from exact leave-one-out residuals of the current mean GP, standardized by their leave-one-out variance so that the latent function's uncertainty is not counted as noise, and corrected for the known mean of a log chi-squared variable with one degree of freedom.
fit_heteroscedastic_gp( x, y, kernel, noise_kernel, mean = zero_mean(), initial_noise_variance = NULL, noise_floor = 1e-06, noise_ceiling = Inf, damping = 0.5, max_iterations = 50L, convergence_tolerance = 0.001, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )fit_heteroscedastic_gp( x, y, kernel, noise_kernel, mean = zero_mean(), initial_noise_variance = NULL, noise_floor = 1e-06, noise_ceiling = Inf, damping = 0.5, max_iterations = 50L, convergence_tolerance = 0.001, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )
x |
Numeric vector or matrix of training inputs. |
y |
Numeric response vector. |
kernel |
Kernel specification for the latent regression function. |
noise_kernel |
Kernel specification for log observation-noise variance. |
mean |
Mean specification for the latent regression function, with fixed coefficients. |
initial_noise_variance |
Optional positive scalar used for the initial
homoscedastic mean fit. If |
noise_floor |
Strictly positive lower bound for estimated noise variances. |
noise_ceiling |
Optional upper bound for estimated noise variances. |
damping |
Value in |
max_iterations |
Maximum number of mean/noise refinement iterations. In a simulation study every fit that converged did so within 50 iterations, and most within 15. |
convergence_tolerance |
Convergence tolerance on the maximum absolute log change in training noise variance. |
initial_jitter |
Non-negative jitter tried first, relative to the covariance scale (the mean of its diagonal). |
fallback_jitter |
Positive relative jitter tried after the first failed factorization. |
jitter_multiplier |
Multiplicative jitter escalation factor. |
max_attempts |
Maximum Cholesky attempts. |
symmetry_tolerance |
Relative tolerance for checking that covariance matrices are symmetric. |
This is a deterministic plug-in approximation inspired by most-likely heteroscedastic GP methods. It is not full joint Bayesian inference over the latent function and noise process.
For a Gaussian residual , has
additive log-chi-squared noise with known mean and
variance . The implementation uses these known moments
when constructing and fitting the log-noise GP.
A leave-one-out residual has variance ,
where is the leave-one-out variance of the latent function, so
alone overestimates the noise. The target is therefore
, with
the current noise estimate, which is unbiased at a fixed point
of the iteration. The research note
system.file("notes", "heteroscedastic-gp.md", package = "gaussianprocesses") derives the correction and reports a simulation
study of its bias and convergence.
The approach alternates plug-in estimates rather than integrating jointly
over the latent function and noise process. If the estimate has not
converged after max_iterations iterations, the function warns with class
gaussianprocesses_convergence_warning and returns the last iterate with
converged = FALSE.
An object of class
gaussianprocesses_heteroscedastic_model.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
gaussianprocesses_model for the structure, versioning, and persistence of fitted models.
simulation <- gp_simulation_scenario("heteroscedastic_1d", n = 60) model <- fit_heteroscedastic_gp( simulation$x, simulation$observed, kernel = matern52_kernel(length_scale = 0.2), noise_kernel = rbf_kernel(length_scale = 0.4), max_iterations = 30 ) model # The estimated noise variance rises with x, as in the simulation. rows <- c(1, 20, 40, 60) cbind( x = simulation$x[rows], true = simulation$noise_variance[rows], estimated = model$training_noise_variance[rows] )simulation <- gp_simulation_scenario("heteroscedastic_1d", n = 60) model <- fit_heteroscedastic_gp( simulation$x, simulation$observed, kernel = matern52_kernel(length_scale = 0.2), noise_kernel = rbf_kernel(length_scale = 0.4), max_iterations = 30 ) model # The estimated noise variance rises with x, as in the simulation. rows <- c(1, 20, 40, 60) cbind( x = simulation$x[rows], true = simulation$noise_variance[rows], estimated = model$training_noise_variance[rows] )
Fits a Gaussian process observed through a
likelihood , such as Bernoulli responses for
classification or Poisson counts, with the Laplace approximation to the
posterior of . With gaussian_likelihood() the approximation is
exact and the model equals fit_gp().
fit_latent_gp( x, y, kernel, likelihood, mean = zero_mean(), exposure = NULL, method = "laplace", max_iterations = 100L, convergence_tolerance = 1e-14, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )fit_latent_gp( x, y, kernel, likelihood, mean = zero_mean(), exposure = NULL, method = "laplace", max_iterations = 100L, convergence_tolerance = 1e-14, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )
x |
Numeric vector or matrix of training inputs. Matrix rows are observations and columns are input dimensions. |
y |
Responses, one per row of |
kernel |
A Gaussian-process kernel specification. |
likelihood |
A likelihood specification (gp_likelihoods). It must be log-concave. |
mean |
Gaussian-process mean specification, with fixed
coefficients, coefficients estimated by maximum likelihood, or
coefficients with a Gaussian |
exposure |
Optional positive exposure for Poisson likelihoods: one
value or one per observation (see |
method |
The approximation: |
max_iterations |
Maximum number of Newton iterations. |
convergence_tolerance |
The Newton iterations stop when the Newton decrement is at most this value (see Details). |
initial_jitter, fallback_jitter, jitter_multiplier, max_attempts
|
The
jitter policy for the factorization of |
symmetry_tolerance |
Relative tolerance for checking that |
The posterior of is proportional to
. The Laplace approximation replaces it by
, where maximizes
and is diagonal. For a
log-concave likelihood is strictly concave, so the mode is
unique; other likelihoods raise an error of class
gaussianprocesses_log_concavity_error.
Newton's method finds the mode (Rasmussen and Williams, 2006, Algorithm
3.1) in the parameterization . Each iteration factorizes
whose eigenvalues are at least 1, so it is well conditioned even when
is nearly singular; the factorization follows the jitter policy
of fit_gp(). A step-halving line search on prevents
overshooting. The iterations stop when the Newton decrement
which is twice the increase of that the next Newton step
predicts, is at most convergence_tolerance. is about the
distance to the mode measured in posterior standard deviations, so the
default of places the mode within about
standard deviations. $laplace records the number of iterations and step
halvings, the final decrement, the largest component of , the last
change of , and whether the iterations converged; if they did
not, a warning of class gaussianprocesses_convergence_warning is
raised.
The approximate log marginal likelihood is
reported by log_marginal_likelihood() and logLik(), with its gradient
in log_marginal_likelihood_gradient().
A mean with fixed coefficients contributes . Coefficients with
a Gaussian prior are integrated out: the prior becomes
with covariance
. Coefficients estimated by
maximum likelihood (estimate_coefficients("ml"), the default of
linear_mean()) maximize at the
given hyperparameters, by BFGS with the analytical gradient
, where is the
derivative of in , starting from the
generalized linear model without the latent process. The estimate is
plugged in, like the hyperparameters; coef() returns it and $mean_fit
records it. A constant mean estimated this way is the usual mean level of
a count or classification model. Restricted likelihoods and vague priors
are not supported.
An object of class gaussianprocesses_latent_model with fields
x, y (responses in the internal coding), response_levels (the
levels of a factor response), exposure, kernel, mean,
likelihood, method, mode (), alpha (),
curvature (the diagonal of ), b_cholesky ( with
), jitter (),
log_marginal_likelihood, laplace, n_observations, n_features,
schema_version, and package_version. Other fields are internal.
For a few observations the exact marginal likelihood
can be computed by tensor-product Gauss-Hermite
quadrature. With an RBF kernel (variance 2, length scale 1) and the first
of the inputs and of the responses below, the
error of the Laplace approximation is:
| Likelihood | Responses | |
|
|
| logit | 1, 1, 0 | -0.0171 | -0.0192 | -0.0387 |
| probit | 1, 1, 0 | -0.0196 | -0.0298 | -0.0450 |
| Poisson | 0, 2, 7 | 0.0125 | -0.0101 | -0.0197 |
| Poisson, mean 5 | 120, 150, 200 | -0.000681 | -0.00118 | -0.00158 |
For binary responses and small counts the error is a few hundredths and
grows with ; the approximation can over- or underestimate. For counts in the hundreds, where the likelihood is nearly
Gaussian in , it is ten times smaller. The test suite reproduces
these values.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian Processes for Machine Learning. MIT Press. Chapters 3 and 5.
predict_latent_gp(), optimize_latent_gp(),
sample_gp_posterior().
x <- seq(-3, 3, length.out = 30) y <- as.numeric(sin(x) + 0.3 * cos(5 * x) > 0) model <- fit_latent_gp(x, y, rbf_kernel(variance = 4), bernoulli_likelihood()) model predict_latent_gp(model, c(-2, 0, 2))$probabilityx <- seq(-3, 3, length.out = 30) y <- as.numeric(sin(x) + 0.3 * cos(5 * x) > 0) model <- fit_latent_gp(x, y, rbf_kernel(variance = 4), bernoulli_likelihood()) model predict_latent_gp(model, c(-2, 0, 2))$probability
Fits a sparse approximation with fixed inducing locations: the Fully Independent Training Conditional (FITC) approximation or the collapsed variational free energy (VFE) of Titsias (2009). Exact GP regression remains the reference model; these provide a lower-cost path when the number of inducing points is much smaller than the number of observations.
fit_sparse_gp( x, y, kernel, noise_variance = 1e-06, mean = zero_mean(), n_inducing = NULL, inducing_points = NULL, selection = c("farthest", "quantile", "variance"), method = c("fitc", "vfe"), fitc_diagonal_floor = 1e-10, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )fit_sparse_gp( x, y, kernel, noise_variance = 1e-06, mean = zero_mean(), n_inducing = NULL, inducing_points = NULL, selection = c("farthest", "quantile", "variance"), method = c("fitc", "vfe"), fitc_diagonal_floor = 1e-10, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )
x |
Numeric vector or matrix of training inputs. |
y |
Numeric response vector. |
kernel |
Gaussian-process kernel specification. |
noise_variance |
Non-negative scalar or one non-negative value per training observation. |
mean |
Gaussian-process mean specification with fixed coefficients. |
n_inducing |
Optional number of inducing points selected from |
inducing_points |
Optional explicit inducing locations. If supplied,
|
selection |
Inducing-point selection method used when explicit points
are not supplied: |
method |
The approximation: |
fitc_diagonal_floor |
Strictly positive numerical floor applied to the FITC diagonal term before inversion. |
initial_jitter |
Non-negative jitter tried first in the inducing-system Cholesky factorizations, relative to the scale of each factorized matrix (the mean of its diagonal). |
fallback_jitter |
Positive relative jitter tried after the first failed factorization. |
jitter_multiplier |
Multiplicative jitter escalation factor. |
max_attempts |
Maximum Cholesky attempts. |
symmetry_tolerance |
Relative tolerance for checking that covariance matrices are symmetric. |
Let be the number of inducing points and the number of
training observations. FITC replaces the full training covariance with a
low-rank inducing covariance plus a diagonal correction. The dominant
training cost is rather than the exact GP's
, with . The implementation stores an
cross covariance rather than an training
covariance.
FITC preserves each training point's prior marginal variance through the diagonal correction, unlike simpler deterministic training conditional approximations. It is still an approximation: inducing locations and their number can affect posterior means, variances, and the approximate marginal likelihood.
If the inducing covariance needs numerical jitter, the jittered matrix is used consistently in the low-rank term, the posterior, and the approximate log marginal likelihood. The inducing posterior is factorized in whitened form, whose eigenvalues are bounded below by one.
An object of class gaussianprocesses_sparse_model.
With and noise
, the collapsed variational
bound of Titsias (2009) is
It is a lower bound on the exact log marginal likelihood, reported as
log_marginal_likelihood, so maximizing it over the hyperparameters
cannot overfit the way FITC can: FITC's diagonal correction
can absorb noise, and FITC tends to
underestimate the noise variance (Bauer, van der Wilk, and Rasmussen,
2016). VFE predicts with the deterministic training conditional, which
has the same form as the FITC prediction with .
Both models report the trace term
in
trace_term: the prior variance that the inducing points do not explain,
in units of noise variance. A trace term much larger than 1 means that
the inducing points do not cover the data well: VFE's bound is loose by at
least and FITC leans on its diagonal correction. More or better
placed inducing points reduce it.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Titsias, M. (2009). Variational learning of inducing variables in sparse Gaussian processes. Proceedings of the 12th International Conference on Artificial Intelligence and Statistics, 567–574.
Bauer, M., van der Wilk, M., and Rasmussen, C. E. (2016). Understanding probabilistic sparse Gaussian process approximations. Advances in Neural Information Processing Systems, 29.
gaussianprocesses_model for the structure, versioning, and persistence of fitted models.
x <- seq(-3, 3, length.out = 200) y <- sin(x) + 0.1 * cos(7 * x) model <- fit_sparse_gp( x, y, kernel = rbf_kernel(length_scale = 0.8), noise_variance = 0.01, n_inducing = 15 ) modelx <- seq(-3, 3, length.out = 200) y <- sin(x) + 0.1 * cos(7 * x) model <- fit_sparse_gp( x, y, kernel = rbf_kernel(length_scale = 0.8), noise_variance = 0.01, n_inducing = 15 ) model
Fit a GP to ordered time-series observations
fit_time_series_gp( time, y, kernel, unit = "auto", method = c("exact", "state_space"), ... )fit_time_series_gp( time, y, kernel, unit = "auto", method = c("exact", "state_space"), ... )
time |
Numeric, Date, or POSIXt vector in strictly increasing order. |
y |
Numeric response vector. |
kernel |
Gaussian-process kernel specification. |
unit |
Time unit passed to |
method |
|
... |
Additional arguments passed to |
This function was called fit_gp_time() in version 0.1.0.
A fitted model containing explicit time-index metadata used by
forecast_gp(): a gaussianprocesses_model for method = "exact" and
a gaussianprocesses_state_space_model for method = "state_space".
On one input, a Matérn process with is the first
component of the state of the linear
stochastic differential equation , with
the companion matrix of ,
, and white noise of spectral
density (Hartikainen and Särkkä, 2010). The stationary state
covariance solves
, and
for
with . Sums of kernels stack their states, and
scaled kernels scale and . Between consecutive
times the state moves by , which has a closed
form because is nilpotent, with process noise
.
The Kalman filter (with Joseph-form updates) gives the log marginal
likelihood by the prediction-error decomposition, the Rauch-Tung-Striebel
smoother gives the posterior at the training times, and forecast_gp()
interleaves the requested times as unobserved steps. The results equal
those of the exact GP up to rounding, at cost instead of
, and no numerical jitter is used. sample_gp_posterior()
draws by forward filtering, backward sampling. Kernels without an exact
finite-dimensional state (RBF, rational quadratic, periodic, linear, and
products) raise an error of class gaussianprocesses_state_space_error.
Stable: from version 1.0.0 this interface changes incompatibly only in a
major release, after a deprecation period. Results and options that
concern an experimental model class, kernel, or argument follow that
interface's tier. See gaussianprocesses-package for the
policy. method = "state_space" is experimental.
Hartikainen, J., and Särkkä, S. (2010). Kalman filtering and smoothing solutions to temporal Gaussian process regression models. IEEE International Workshop on Machine Learning for Signal Processing, 379–384.
Särkkä, S., and Solin, A. (2019). Applied Stochastic Differential Equations. Cambridge University Press.
optimize_time_series_gp() to estimate the hyperparameters.
time <- as.Date("2026-01-01") + 0:23 y <- sin(2 * pi * (0:23) / 12) model <- fit_time_series_gp( time, y, kernel = time_series_kernel(period = 12), noise_variance = 0.05 ) model$time[c("origin", "unit")] # The same posterior by Kalman smoothing, for a Matern kernel. kernel <- matern32_kernel(length_scale = 3) exact <- fit_time_series_gp(time, y, kernel, noise_variance = 0.05) kalman <- fit_time_series_gp(time, y, kernel, noise_variance = 0.05, method = "state_space") c(logLik(exact), logLik(kalman))time <- as.Date("2026-01-01") + 0:23 y <- sin(2 * pi * (0:23) / 12) model <- fit_time_series_gp( time, y, kernel = time_series_kernel(period = 12), noise_variance = 0.05 ) model$time[c("origin", "unit")] # The same posterior by Kalman smoothing, for a Matern kernel. kernel <- matern32_kernel(length_scale = 3) exact <- fit_time_series_gp(time, y, kernel, noise_variance = 0.05) kalman <- fit_time_series_gp(time, y, kernel, noise_variance = 0.05, method = "state_space") c(logLik(exact), logLik(kalman))
Converts future time values using the training model's original time origin and units, then evaluates the GP posterior: exactly, or by Kalman smoothing for state-space models. Each requested point is labelled as interpolation, backward extrapolation, or forward forecast.
forecast_gp( model, future_time, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps), observation_noise_variance = NULL )forecast_gp( model, future_time, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps), observation_noise_variance = NULL )
model |
A model fitted by |
future_time |
Numeric, Date, or POSIXt values matching the training time type and supplied in strictly increasing order. |
interval_level |
Probability level for posterior intervals. |
include_covariance |
If |
variance_tolerance |
Relative tolerance for posterior variances. |
observation_noise_variance |
Optional non-negative scalar or vector of
observation-noise variances at |
An object of class gaussianprocesses_time_forecast.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
time <- as.Date("2026-01-01") + 0:23 model <- fit_time_series_gp( time, sin(2 * pi * (0:23) / 12), kernel = time_series_kernel(period = 12), noise_variance = 0.05 ) forecast <- forecast_gp(model, as.Date("2026-01-01") + c(10.5, 25, 30)) data.frame( region = forecast$region, mean = forecast$mean, forecast$prediction_interval )time <- as.Date("2026-01-01") + 0:23 model <- fit_time_series_gp( time, sin(2 * pi * (0:23) / 12), kernel = time_series_kernel(period = 12), noise_variance = 0.05 ) forecast <- forecast_gp(model, as.Date("2026-01-01") + c(10.5, 25, 30)) data.frame( region = forecast$region, mean = forecast$mean, forecast$prediction_interval )
Summarizes a rolling-origin GP backtest with both point and probabilistic forecast metrics.
forecast_metrics(backtest)forecast_metrics(backtest)
backtest |
A |
A named list containing RMSE, MAE, standardized RMSE, empirical interval coverage, mean interval width, and mean log predictive density.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
time <- 0:23 backtest <- rolling_origin_gp( time, sin(2 * pi * time / 12), kernel = time_series_kernel(period = 12), initial_window = 12, horizon = 3, step = 3, noise_variance = 0.05 ) forecast_metrics(backtest)time <- 0:23 backtest <- rolling_origin_gp( time, sin(2 * pi * time / 12), kernel = time_series_kernel(period = 12), initial_window = 12, horizon = 3, step = 3, noise_variance = 0.05 ) forecast_metrics(backtest)
The structure, versioning, and persistence of the models returned by
fit_gp(), optimize_gp(), fit_time_series_gp(), fit_sparse_gp(),
fit_heteroscedastic_gp(), fit_latent_gp(), optimize_latent_gp(), and
optimize_sparse_gp().
Objects of class gaussianprocesses_model, from fit_gp(),
optimize_gp(), and fit_time_series_gp(), document these fields:
x, y
Training inputs as a matrix and responses.
derivativeFor derivative observations, the type of each
observation: 0 for a function value and for
. NULL when every observation is a
function value.
kernel, mean
The kernel and mean specifications. A polynomial mean records the centring and scaling of its inputs.
mean_fitFor estimated or marginalized mean coefficients, a
list with treatment, method ("ml", "reml", "gaussian", or
"vague"), the coefficients , the basis matrix
basis (), and coefficient_factor, an upper-triangular
with plus under a
Gaussian prior. NULL for other means. Use coef() and vcov() to
read the coefficients.
noise_variance, training_noise_variance, noise_structure
The
noise variance as supplied, one value per training observation, and
"homoscedastic" or "known_heteroscedastic".
choleskyUpper-triangular with
, where and
is jitter.
alpha, with
for estimated or marginalized coefficients.
jitterDiagonal jitter that the factorization
needed; usually 0. It is a multiple of the mean diagonal of
(see fit_gp()).
n_observations, n_features
Training size and input dimension.
optimizationOptimizer diagnostics, for optimize_gp()
models.
timeTime metadata, for fit_time_series_gp() models.
schema_version, package_version
See below.
The kernel matrix and the observation covariance are not
stored, because they can be recomputed exactly:
evaluate_kernel(model$kernel, model$x) is , and adding
diag(model$training_noise_variance) gives . Storing only
keeps a model with observations at about
bytes. Other fields, such as centered_y, prior_mean,
cholesky_attempts, and numerical_policy, are internal and may change
without notice.
Sparse models (gaussianprocesses_sparse_model) document x, y,
kernel, mean, noise_variance, inducing_points, n_inducing,
method ("fitc" or "vfe"), approximation ("FITC" or "VFE"),
log_marginal_likelihood (the FITC objective or the VFE bound),
trace_term, and, for optimize_sparse_gp() models, optimization;
their other fields are internal. Heteroscedastic models
(gaussianprocesses_heteroscedastic_model) document x, y, kernel,
noise_kernel, training_noise_variance, converged, iterations, and
history, and contain two exact models, mean_model and noise_model.
Both record schema_version and package_version.
Latent models (gaussianprocesses_latent_model) document the fields
listed in fit_latent_gp(). Like exact models, they store the Cholesky
factor of but not , and record
schema_version and package_version; they were added at schema 3.
State-space models (gaussianprocesses_state_space_model), from
fit_time_series_gp() with method = "state_space", store the training
data, kernel, mean, noise, log marginal likelihood, and the smoothed
fitted means and variances, but no covariance matrix or factor: every
prediction filters and smooths again. They were added at schema 4.
schema_version identifies the structure of a model, and
package_version is the version of gaussianprocesses that created it.
The current schema is 4: schema 2 added mean_fit, schema 3 added
derivative, and schema 4 added the method and trace_term of sparse
models. Schema 4 is the format of version 1.0. Models saved by
versions that predate schema versions, which stored and ,
are schema 0, and models saved before parametric means were added are
schema 1. Every function
that accepts a model first converts older schemas to schema 4; the
converted model gives the same results, and a converted sparse model is
a FITC model. A converted schema-0 model has
package_version NA, because the creating version is unknown.
A model with a newer or unknown schema, or without the fields its class
requires, raises an error of class
gaussianprocesses_model_format_error. The condition object has fields
found_schema, supported_schemas, and package_version.
Models can be saved with saveRDS() and restored with readRDS(); a
restored model gives the same predictions, likelihoods, gradients,
diagnostics, and seeded draws as the original.
Every 1.x release reads models saved by any earlier version, back to
0.1.0. A 1.x release may introduce a new schema only together with an
upgrade from schema 4, so models saved by version 1.0 stay readable and
give the same results. A model saved by a newer version than the one
reading it raises gaussianprocesses_model_format_error rather than
giving wrong results. The tests read models saved by the 0.1.0 release
and schema-4 models written before 1.0, and check that they give the
results they were saved with. Keeping the training data with the kernel,
mean, and noise also reproduces a model exactly: refitting them with the
same numerical settings gives the same model.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
x <- seq(-2, 2, length.out = 10) model <- fit_gp(x, sin(x), rbf_kernel(), noise_variance = 0.01) model$schema_version # C is recomputed from the kernel, and R'R reproduces it. C <- evaluate_kernel(model$kernel, model$x) + diag(model$training_noise_variance) all.equal(crossprod(model$cholesky), C + diag(model$jitter, nrow(C))) # A saved model gives identical predictions. path <- tempfile(fileext = ".rds") saveRDS(model, path) identical(predict_gp(readRDS(path), 0.5), predict_gp(model, 0.5))x <- seq(-2, 2, length.out = 10) model <- fit_gp(x, sin(x), rbf_kernel(), noise_variance = 0.01) model$schema_version # C is recomputed from the kernel, and R'R reproduces it. C <- evaluate_kernel(model$kernel, model$x) + diag(model$training_noise_variance) all.equal(crossprod(model$cholesky), C + diag(model$jitter, nrow(C))) # A saved model gives identical predictions. path <- tempfile(fileext = ".rds") saveRDS(model, path) identical(predict_gp(readRDS(path), 0.5), predict_gp(model, 0.5))
Summarizes exact LOO predictive diagnostics. The returned statistics are descriptive diagnostics rather than a pass/fail calibration test.
gp_calibration_diagnostics(model, interval_level = 0.95)gp_calibration_diagnostics(model, interval_level = 0.95)
model |
A fitted |
interval_level |
Probability level for LOO prediction intervals. |
PIT values should be assessed as a distribution rather than individually. Under a correctly specified continuous predictive distribution they are uniform in repeated sampling.
A named list of calibration summaries.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
x <- seq(-2, 2, length.out = 20) model <- fit_gp( x, sin(2 * x), kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01 ) gp_calibration_diagnostics(model, interval_level = 0.9)x <- seq(-2, 2, length.out = 20) model <- fit_gp( x, sin(2 * x), kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01 ) gp_calibration_diagnostics(model, interval_level = 0.9)
Scores predicted class probabilities against binary responses with proper
scoring rules (log loss and Brier score), discrimination (ROC AUC), and
calibration (reliability diagram data and the expected calibration
error). gp_holdout_scores() returns these scores for latent models with
a Bernoulli likelihood.
gp_classification_scores( observed, probability, n_bins = 10L, log_density = NULL )gp_classification_scores( observed, probability, n_bins = 10L, log_density = NULL )
observed |
Binary responses: 0/1 numbers, logical values, or a
two-level factor whose second level is the event coded 1, as in
|
probability |
Forecast probabilities |
n_bins |
Number of equal-width probability bins of the reliability diagram and the expected calibration error. |
log_density |
Optional log predictive probabilities of the observed
responses, for the log loss. They default to |
, the negative mean log
predictive probability. Proper; lower is better; for .
. Proper; lower is
better; 0.25 for .
The probability that a random event receives a higher
forecast than a random non-event, with ties counted as one half: the
Mann-Whitney statistic from mid-ranks. 0.5 for uninformative forecasts;
NA without both classes. It measures discrimination only and ignores
calibration.
The forecasts are grouped into n_bins equal-width
bins of . For calibrated forecasts the observed frequency
of each bin is close to its mean probability, within about
standard_error .
The expected calibration error
. It depends on the
binning, and even calibrated forecasts have a positive ECE of the order
of the bin standard errors.
An object of class gaussianprocesses_classification_scores with
summaryNamed numeric vector: n, log_loss, brier_score,
auc, ece, base_rate (the mean response), and mean_probability.
reliabilityData frame with one row per non-empty bin: bin,
lower, upper, n, mean_probability, observed_frequency, and
standard_error.
pointwiseData frame with observed (0/1), probability,
log_density, and squared_error.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Gneiting, T. and Raftery, A. E. (2007). Strictly proper scoring rules, prediction, and estimation. Journal of the American Statistical Association, 102(477), 359–378.
gp_scores() for Gaussian predictions, predict_latent_gp().
set.seed(1) x <- runif(80, 0, 6) y <- rbinom(80, 1, plogis(2 * sin(x))) training <- 1:50 model <- fit_latent_gp(x[training], y[training], rbf_kernel(4, 1), bernoulli_likelihood()) scores <- gp_holdout_scores(model, x[-training], y[-training], n_bins = 5) scores scores$reliabilityset.seed(1) x <- runif(80, 0, 6) y <- rbinom(80, 1, plogis(2 * sin(x))) training <- 1:50 model <- fit_latent_gp(x[training], y[training], rbf_kernel(4, 1), bernoulli_likelihood()) scores <- gp_holdout_scores(model, x[-training], y[-training], n_bins = 5) scores scores$reliability
Scores Poisson-lognormal predictive distributions of counts, those of
latent Gaussian-process models with a poisson_likelihood(), with proper
scores, a dispersion check, interval coverage, and randomized probability
integral transform (PIT) values. gp_holdout_scores() returns these
scores for latent Poisson models.
gp_count_scores( observed, latent_mean, latent_variance, exposure = NULL, interval_levels = c(0.5, 0.8, 0.9, 0.95), seed = NULL, quadrature_order = 40L )gp_count_scores( observed, latent_mean, latent_variance, exposure = NULL, interval_levels = c(0.5, 0.8, 0.9, 0.95), seed = NULL, quadrature_order = 40L )
observed |
Non-negative integer counts. |
latent_mean, latent_variance
|
Mean and variance of the latent log
rate |
exposure |
Optional positive exposure: one value or one per count. |
interval_levels |
Levels of the equal-tailed prediction intervals whose coverage is reported. |
seed |
Optional seed for the randomization of the PIT values. The caller's random state is restored afterwards. |
quadrature_order |
Number of Gauss-Hermite nodes. |
Given , a count has the Poisson-lognormal predictive
distribution, with mean and probabilities,
distribution function, and quantiles computed by Gauss-Hermite
quadrature.
The mean log predictive probability of the counts. Proper; higher is better.
with the
predictive mean and standard deviation ; proper for the
first two moments and recommended for counts by Czado, Gneiting, and
Held (2009). Lower is better.
The mean squared Pearson residual
. It is about 1 when the predictive variance is
right; clearly larger values mean that the counts are overdispersed
relative to the model.
Of the equal-tailed prediction intervals at each level. Counts are discrete, so the intervals cover at least their level: their coverage is conservative, by up to the probability of their end points.
with
: uniform on when the forecasts are
calibrated, unlike the plain PIT of a discrete
distribution. The summary reports their mean (1/2), variance (1/12),
and the p-value of a Kolmogorov-Smirnov test of uniformity.
An object of class gaussianprocesses_count_scores with
summaryNamed numeric vector: n, log_score,
dawid_sebastiani, dispersion, pit_mean, pit_variance, and
pit_ks_p_value.
calibrationData frame with one row per interval level: the
level, empirical coverage, and mean width (upper minus lower
count).
pointwiseData frame with observed, predictive_mean,
predictive_variance, log_score, dawid_sebastiani,
pearson_residual, and pit.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Czado, C., Gneiting, T., and Held, L. (2009). Predictive model assessment for count data. Biometrics, 65(4), 1254–1261.
gp_scores(), gp_classification_scores(),
predict_latent_gp().
set.seed(1) x <- seq(0, 10, length.out = 60) counts <- rpois(60, exp(1 + sin(x))) training <- seq(1, 60, by = 2) model <- fit_latent_gp(x[training], counts[training], rbf_kernel(0.5, 1.5), poisson_likelihood(), mean = constant_mean(1)) gp_holdout_scores(model, x[-training], counts[-training], seed = 1)set.seed(1) x <- seq(0, 10, length.out = 60) counts <- rpois(60, exp(1 + sin(x))) training <- seq(1, 60, by = 2) model <- fit_latent_gp(x[training], counts[training], rbf_kernel(0.5, 1.5), poisson_likelihood(), mean = constant_mean(1)) gp_holdout_scores(model, x[-training], counts[-training], seed = 1)
Combines exact leave-one-out predictive diagnostics, uncertainty-calibration summaries, and numerical-conditioning diagnostics. The components are kept separate so predictive misfit is not automatically attributed to numerical instability, and numerical instability is not mistaken for model misfit.
gp_diagnostics( model, interval_level = 0.95, condition_tolerance = sqrt(.Machine$double.eps) )gp_diagnostics( model, interval_level = 0.95, condition_tolerance = sqrt(.Machine$double.eps) )
model |
A fitted |
interval_level |
Probability level for LOO prediction intervals. |
condition_tolerance |
Positive reciprocal-condition threshold used by the numerical diagnostic summary. |
An object of class gaussianprocesses_diagnostics.
Stable: from version 1.0.0 this interface changes incompatibly only in a
major release, after a deprecation period. Results and options that
concern an experimental model class, kernel, or argument follow that
interface's tier. See gaussianprocesses-package for the
policy. Its numerical component comes from the experimental gp_numerical_diagnostics().
x <- seq(-2, 2, length.out = 20) model <- fit_gp( x, sin(2 * x), kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01 ) gp_diagnostics(model)x <- seq(-2, 2, length.out = 20) model <- fit_gp( x, sin(2 * x), kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01 ) gp_diagnostics(model)
Approximates the uncertainty of a model's hyperparameters from the curvature of the log marginal likelihood at its optimum, and flags hyperparameters that the data identify poorly.
gp_hyperparameter_uncertainty( model, step = 1e-04, interval_level = 0.95, condition_threshold = 1e+06, log_scale_threshold = log(2) )gp_hyperparameter_uncertainty( model, step = 1e-04, interval_level = 0.95, condition_threshold = 1e+06, log_scale_threshold = log(2) )
model |
A fitted |
step |
Step of the central differences of the gradient, on the optimizer's coordinate scale. |
interval_level |
Level of the approximate intervals. |
condition_threshold |
Condition number of the observed information above which the hyperparameters are flagged as poorly identified. |
log_scale_threshold |
Standard deviation, on the log scale, of the
least determined combination of log-scale parameters above which they
are flagged as poorly identified. The default, |
The hyperparameters are those optimize_gp() estimated (all kernel
parameters and the noise for other models), on its coordinate scale
: logarithms of positive parameters and real parameters
themselves. The observed information
is computed by central differences of the analytical gradient
(log_marginal_likelihood_gradient()), one refit per displaced
coordinate. Its inverse is the covariance of the Laplace approximation
with a flat prior on the coordinate scale:
Standard errors and correlations are reported on the coordinate scale,
and approximate intervals are mapped back
to the natural scale, so that intervals for positive parameters stay
positive. Estimated mean coefficients are profiled out (the likelihood
is the profile, restricted, or marginal likelihood of the mean), and the
approximation conditions on them.
The approximation needs a maximum: gradient reports the gradient at the
estimate, which should be close to zero. Some combinations of
hyperparameters can be nearly unidentifiable: under infill asymptotics,
only is consistently estimable for a Matérn
kernel of smoothness (Zhang, 2004). The likelihood is then
nearly flat along a ridge: the information is nearly singular in
absolute terms, though not always in relative ones, because the
curvature across the ridge can be small too. poorly_identified is
therefore TRUE when the information is not positive definite, when its
condition number exceeds condition_threshold, or when the standard
deviation along the least determined combination of the log-scale
parameters, weakest_log_scale_sd, exceeds log_scale_threshold.
weakest_direction is the eigenvector of the smallest eigenvalue, the
direction along the ridge; for a Matérn kernel under infill it is close
to in (log variance, log length
scale). Real-valued parameters, such as changepoint locations, have no
common scale with the others and enter only the first two criteria.
gp_profile_likelihood() shows the likelihood along one parameter
without the quadratic approximation.
An object of class gaussianprocesses_hyperparameter_uncertainty
with
parametersData frame: parameter, estimate, coordinate
("log" or "identity"), coordinate_estimate, standard_error on
the coordinate scale, and lower and upper on the natural scale.
covariance, correlation
On the coordinate scale; NULL when
the information is not positive definite.
information, eigenvalues, condition_number,
weakest_log_scale_sd, poorly_identified, weakest_direction
The observed information and its diagnostics.
gradientThe gradient at the estimate.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Zhang, H. (2004). Inconsistent estimation and asymptotically equal interpolations in model-based geostatistics. Journal of the American Statistical Association, 99(465), 250–261.
gp_profile_likelihood(), and the article on hyperparameter
uncertainty on the documentation site.
set.seed(1) x <- seq(0, 10, length.out = 60) y <- sin(x) + rnorm(60, sd = 0.2) model <- optimize_gp(x, y, rbf_kernel(), noise_variance = 0.1, n_starts = 1) uncertainty <- gp_hyperparameter_uncertainty(model) uncertainty uncertainty$correlationset.seed(1) x <- seq(0, 10, length.out = 60) y <- sin(x) + rnorm(60, sd = 0.2) model <- optimize_gp(x, y, rbf_kernel(), noise_variance = 0.1, n_starts = 1) uncertainty <- gp_hyperparameter_uncertainty(model) uncertainty uncertainty$correlation
Observation models that link the latent Gaussian
process to the responses. Like kernel specifications, they are
plain data with a class, a print method, and constrained parameters.
gaussian_likelihood(variance = 1) bernoulli_likelihood(link = c("logit", "probit")) poisson_likelihood(link = "log")gaussian_likelihood(variance = 1) bernoulli_likelihood(link = c("logit", "probit")) poisson_likelihood(link = "log")
variance |
Positive noise variance of the Gaussian likelihood. |
link |
Link function: |
gaussian_likelihood(), the
observation model of fit_gp() with noise_variance .
bernoulli_likelihood() with
the logistic function, , or
with the probit link. Responses may be 0/1 numbers,
logical values (TRUE is 1), or a two-level factor whose second level
is 1, as in stats::glm(). Multi-class (softmax) likelihoods are not
supported.
poisson_likelihood() with exposure , so
. The exposure is data,
supplied where the likelihood is used, not part of the specification.
Counts more variable than a Poisson process with a smooth rate allows
need negative-binomial or zero-inflated likelihoods, which are not yet
supported; gp_count_scores() checks for such overdispersion.
Every likelihood provides, vectorized over observations, the log density
and its first three derivatives in (evaluate_likelihood()),
derivatives in its parameters, the predictive distribution of a new
response when is Gaussian (likelihood_predictive()), and
whether the log density is concave in . All three are
log-concave, which makes Laplace approximations well behaved. Gaussian
expectations without a closed form use Gauss-Hermite quadrature: nodes
from the Golub-Welsch eigenvalue method, weights from Christoffel sums,
cached by order.
The probit derivatives use the inverse Mills ratio
computed in log space, with
. For , where grows like
and cancels, they use the continued fraction of the
Mills ratio instead. The logistic derivatives compute and
separately. All derivatives stay finite and accurate for
large .
Latent models with any of these likelihoods are fitted with
fit_latent_gp() and optimize_latent_gp(); fit_gp() remains the
exact Gaussian model.
An object of class gaussianprocesses_likelihood.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Golub, G. H. and Welsch, J. H. (1969). Calculation of Gauss quadrature rules. Mathematics of Computation, 23(106), 221–230.
Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian Processes for Machine Learning. MIT Press. Chapter 3.
evaluate_likelihood(), likelihood_predictive(),
fit_latent_gp().
gaussian_likelihood(variance = 0.1) bernoulli_likelihood("probit") poisson_likelihood() evaluate_likelihood(bernoulli_likelihood(), c(TRUE, FALSE), f = c(1, 1))gaussian_likelihood(variance = 0.1) bernoulli_likelihood("probit") poisson_likelihood() evaluate_likelihood(bernoulli_likelihood(), c(TRUE, FALSE), f = c(1, 1))
Mean specifications separate the deterministic part of the model from the
covariance kernel. zero_mean() is zero everywhere and constant_mean()
is a constant, fixed or with an estimated or marginalized value. For
regression trends see linear_mean(), polynomial_mean(), and
basis_mean().
zero_mean() constant_mean(value = 0)zero_mean() constant_mean(value = 0)
value |
A finite number that fixes the constant, or
|
An object of class gaussianprocesses_mean.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
zero_mean() constant_mean(2.5) evaluate_mean(constant_mean(2.5), 1:3) # Estimate the constant instead. x <- seq(0, 3, length.out = 15) model <- fit_gp(x, 4 + sin(2 * x), rbf_kernel(), noise_variance = 0.01, mean = constant_mean(estimate_coefficients())) coef(model)zero_mean() constant_mean(2.5) evaluate_mean(constant_mean(2.5), 1:3) # Estimate the constant instead. x <- seq(0, 3, length.out = 15) model <- fit_gp(x, 4 + sin(2 * x), rbf_kernel(), noise_variance = 0.01, mean = constant_mean(estimate_coefficients())) coef(model)
Methods for stats::predict(), stats::logLik(), stats::nobs(),
stats::fitted(), stats::residuals(), and summary() on exact
(gaussianprocesses_model), sparse (gaussianprocesses_sparse_model),
heteroscedastic (gaussianprocesses_heteroscedastic_model), latent
(gaussianprocesses_latent_model), and state-space
(gaussianprocesses_state_space_model) models.
## S3 method for class 'gaussianprocesses_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_sparse_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_state_space_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_latent_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_latent_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_latent_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_latent_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_model' residuals(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' residuals(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' residuals(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' residuals(object, ...) ## S3 method for class 'gaussianprocesses_model' summary(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' summary(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' summary(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' summary(object, ...) ## S3 method for class 'gaussianprocesses_latent_model' summary(object, ...) ## S3 method for class 'summary.gaussianprocesses_model' print(x, ...)## S3 method for class 'gaussianprocesses_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_sparse_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_state_space_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_latent_model' predict(object, newdata, ...) ## S3 method for class 'gaussianprocesses_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_latent_model' logLik(object, ...) ## S3 method for class 'gaussianprocesses_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_latent_model' nobs(object, ...) ## S3 method for class 'gaussianprocesses_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_latent_model' fitted(object, ...) ## S3 method for class 'gaussianprocesses_model' residuals(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' residuals(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' residuals(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' residuals(object, ...) ## S3 method for class 'gaussianprocesses_model' summary(object, ...) ## S3 method for class 'gaussianprocesses_sparse_model' summary(object, ...) ## S3 method for class 'gaussianprocesses_state_space_model' summary(object, ...) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' summary(object, ...) ## S3 method for class 'gaussianprocesses_latent_model' summary(object, ...) ## S3 method for class 'summary.gaussianprocesses_model' print(x, ...)
object |
A fitted model. |
newdata |
Prediction inputs. If missing, the training inputs (or, for time-series models, the training times) are used. |
... |
Further arguments passed to the package's prediction function:
|
x |
A summary object. |
predict() returns exactly what the package's prediction function for the
model returns. For models from fit_time_series_gp(), newdata are time
values and predict() calls forecast_gp(); this includes every
state-space model with time metadata.
logLik() returns the log marginal likelihood
: log_marginal_likelihood() for exact
and state-space models and, for sparse models, the FITC approximate
marginal likelihood or the VFE lower bound. This is a
type-II likelihood, with the latent function integrated out and the
hyperparameters plugged in. Its df attribute counts the
hyperparameters estimated from the data: the parameters optimized by
optimize_gp() or optimize_sparse_gp(), and 0 for models whose
hyperparameters were supplied,
plus the mean coefficients when they are estimated. For restricted
likelihoods (REML estimates and vague coefficient priors) the nobs
attribute is , as for restricted likelihoods elsewhere in R,
and such likelihoods are comparable only between models with the same
mean.
stats::AIC() and stats::BIC() therefore work, but comparing kernels
by them is a heuristic: it is not an ordinary maximum-likelihood
comparison, and the penalty does not account for the flexibility of the
kernel. Heteroscedastic models have no logLik() method, because their
noise function is a plug-in estimate rather than a likelihood maximizer.
For latent models it is the Laplace approximation to the marginal
likelihood, and df counts the parameters optimized by
optimize_latent_gp() or the mean coefficients estimated by
fit_latent_gp(). For state-space models df counts the parameters
optimized by optimize_time_series_gp().
fitted() returns the posterior mean of the latent function at the
training inputs, and residuals() returns the observed responses minus
those fitted values. For exact models the fitted values are
, which equals
without forming ; is the
numerical jitter. For state-space models they are the Kalman-smoother
means. For latent models fitted() returns the posterior mode
of the latent function, and there is no residuals()
method, because the responses are not on the scale of .
summary() collects the training size and dimension, kernel, mean, noise,
log marginal likelihood, optimization status, and numerical status, and
prints them compactly.
predict(): a prediction object. logLik(): an object of class
logLik. nobs(): the number of training observations. fitted()
and residuals(): numeric vectors with one value per training
observation. summary(): an object of class
summary.gaussianprocesses_model.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
x <- seq(-2, 2, length.out = 20) y <- sin(2 * x) + 0.1 * cos(7 * x) model <- optimize_gp( x, y, kernel = rbf_kernel(), noise_variance = 0.05, n_starts = 1 ) summary(model) predict(model, c(-1, 0.5))$mean logLik(model) AIC(model) head(residuals(model))x <- seq(-2, 2, length.out = 20) y <- sin(2 * x) + 0.1 * cos(7 * x) model <- optimize_gp( x, y, kernel = rbf_kernel(), noise_variance = 0.05, n_starts = 1 ) summary(model) predict(model, c(-1, 0.5))$mean logLik(model) AIC(model) head(residuals(model))
Reports numerical quantities separately from statistical fit diagnostics. In particular, observation-noise variance and numerical jitter remain distinct.
gp_numerical_diagnostics( model, condition_tolerance = sqrt(.Machine$double.eps) )gp_numerical_diagnostics( model, condition_tolerance = sqrt(.Machine$double.eps) )
model |
A fitted |
condition_tolerance |
Positive reciprocal-condition threshold used only to flag a potentially ill-conditioned stabilized covariance matrix. |
A named list of numerical diagnostics, including:
observation_noise_varianceThe statistical noise variance.
numerical_jitterThe diagonal jitter that the
factorization of the training covariance needed.
covariance_scaleThe mean of the diagonal of .
relative_jitternumerical_jitter / covariance_scale.
cholesky_attemptsFactorization attempts, 1 if no jitter was needed.
reciprocal_condition_number, condition_number
The 1-norm
condition estimate of and its reciprocal.
potentially_ill_conditionedWhether the reciprocal condition
number is below condition_tolerance.
observation_typesA data frame with one row per observation
type ("value", or "derivative x1", ... for derivative
observations): the number of observations, the mean diagonal of their
block of , and the reciprocal condition number of that block
with the jitter. Derivative blocks scale with , so
their conditioning can differ from that of the values.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
# Duplicated inputs without observation noise need numerical jitter, which is # reported separately from the (zero) noise variance. model <- fit_gp(c(0, 0, 1), c(1, 1, 0), kernel = rbf_kernel(), noise_variance = 0) diagnostics <- gp_numerical_diagnostics(model) diagnostics[c( "observation_noise_variance", "numerical_jitter", "relative_jitter", "cholesky_attempts" )]# Duplicated inputs without observation noise need numerical jitter, which is # reported separately from the (zero) noise variance. model <- fit_gp(c(0, 0, 1), c(1, 1, 0), kernel = rbf_kernel(), noise_variance = 0) diagnostics <- gp_numerical_diagnostics(model) diagnostics[c( "observation_noise_variance", "numerical_jitter", "relative_jitter", "cholesky_attempts" )]
Fixes one estimated hyperparameter at each of a grid of values and maximizes the log marginal likelihood over the others.
gp_profile_likelihood( model, parameter, values = NULL, n_values = 11L, step = 1e-04 )gp_profile_likelihood( model, parameter, values = NULL, n_values = 11L, step = 1e-04 )
model |
A fitted |
parameter |
Path of the parameter, as in
|
values |
Values of the parameter on its natural scale. If |
n_values |
Number of grid points when |
step |
Step of the central differences of the gradient, on the optimizer's coordinate scale. |
At each value the other estimated hyperparameters start from their
estimates and are re-optimized with L-BFGS-B and the analytical gradient,
within the bounds that optimize_gp() used. deviance is twice the drop
in log marginal likelihood from the estimate, and converged whether the
other parameters reached a stationary point: the optimizer converged, or
the gradient there is below . Under the usual asymptotics
values with deviance below qchisq(0.95, 1) form an approximate 95%
interval. A flat profile shows a poorly identified parameter directly.
A data frame of class gaussianprocesses_profile_likelihood with
one row per value: value, log_marginal_likelihood, deviance, and
converged.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
set.seed(1) x <- seq(0, 10, length.out = 40) model <- optimize_gp(x, sin(x) + rnorm(40, sd = 0.2), rbf_kernel(), noise_variance = 0.1, n_starts = 1) gp_profile_likelihood(model, "length_scale", n_values = 5)set.seed(1) x <- seq(0, 10, length.out = 40) model <- optimize_gp(x, sin(x) + rnorm(40, sd = 0.2), rbf_kernel(), noise_variance = 0.1, n_starts = 1) gp_profile_likelihood(model, "length_scale", n_values = 5)
Scores Gaussian predictive distributions against observations with proper
scoring rules, interval scores and coverage across a grid of levels, and
the probability integral transform. gp_holdout_scores() scores a fitted
model on held-out data and gp_loo_scores() on its exact leave-one-out
predictions.
gp_scores( observed, mean, sd, interval_levels = c(0.5, 0.8, 0.9, 0.95), reference_mean = NULL, reference_variance = NULL ) gp_holdout_scores( model, x, y, interval_levels = c(0.5, 0.8, 0.9, 0.95), n_bins = 10L, seed = NULL, ... ) gp_loo_scores(model, interval_levels = c(0.5, 0.8, 0.9, 0.95))gp_scores( observed, mean, sd, interval_levels = c(0.5, 0.8, 0.9, 0.95), reference_mean = NULL, reference_variance = NULL ) gp_holdout_scores( model, x, y, interval_levels = c(0.5, 0.8, 0.9, 0.95), n_bins = 10L, seed = NULL, ... ) gp_loo_scores(model, interval_levels = c(0.5, 0.8, 0.9, 0.95))
observed |
Numeric vector of observations. |
mean, sd
|
Predictive means and standard deviations, one per observation; the standard deviations must be positive. |
interval_levels |
Levels of the central prediction intervals whose coverage and interval score are reported: the calibration curve. |
reference_mean, reference_variance
|
Mean and variance of the
reference Gaussian for the MSLL, usually those of the training
responses. Without them the MSLL is |
model |
A fitted model of any class. |
x |
Held-out inputs, as accepted by the model's |
y |
Held-out observations, one per row of |
n_bins |
Number of probability bins for the reliability of
classification scores ( |
seed |
Optional seed for the randomized PIT values of count scores
( |
... |
Further arguments to |
With , the scores are
, the log
predictive density. Higher is better.
, the continuous ranked probability score of
Gneiting and Raftery (2007), in closed form. Lower is better; it is in
the units of .
for the
central interval of level . Lower is better.
, uniform on when the forecasts
are calibrated.
The mean squared error divided by the variance of the observations (Rasmussen and Williams, 2006, section 2.5).
The mean of minus the same under the
reference Gaussian; negative values beat that reference.
The log score, CRPS, and interval score are proper: in expectation they are optimized by the true predictive distribution.
gp_holdout_scores() predicts with stats::predict(), so it accepts
every model class, and scores the observation predictive distribution,
including noise. Its MSLL reference is the mean and variance of the
training responses. gp_loo_scores() scores the exact leave-one-out
predictions of loo_gp() against the same reference.
For latent models (fit_latent_gp()), gp_holdout_scores() scores the
predictive distribution of new responses: with a Gaussian likelihood as
above, with a Bernoulli likelihood by gp_classification_scores(), whose
log loss uses the predictive log probabilities of
likelihood_predictive(), and with a Poisson likelihood by
gp_count_scores(), with the exposure of the predictions.
An object of class gaussianprocesses_scores with
summaryNamed numeric vector: n, log_score (mean log
predictive density), crps (mean), smse, msll, pit_mean, and
pit_variance (1/12 for uniform PIT values).
calibrationData frame with one row per interval level: the
level, empirical coverage, mean width, and mean
interval_score.
pointwiseData frame with one row per observation:
observed, mean, sd, standardized_error, pit, log_score, and
crps.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
Gneiting, T. and Raftery, A. E. (2007). Strictly proper scoring rules, prediction, and estimation. Journal of the American Statistical Association, 102(477), 359–378.
Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian Processes for Machine Learning. MIT Press. Section 2.5.
gp_calibration_diagnostics(), forecast_metrics().
x <- seq(0, 6, length.out = 40) y <- sin(x) + rnorm(40, sd = 0.1) training <- seq(1, 40, by = 2) model <- fit_gp(x[training], y[training], rbf_kernel(), noise_variance = 0.01) scores <- gp_holdout_scores(model, x[-training], y[-training]) scores scores$calibration gp_loo_scores(model)$summaryx <- seq(0, 6, length.out = 40) y <- sin(x) + rnorm(40, sd = 0.1) training <- seq(1, 40, by = 2) model <- fit_gp(x[training], y[training], rbf_kernel(), noise_variance = 0.01) scores <- gp_holdout_scores(model, x[-training], y[-training]) scores scores$calibration gp_loo_scores(model)$summary
Creates deterministic input designs and seeded observations for common validation cases used throughout the benchmark suite.
gp_simulation_scenario( scenario = c("smooth_1d", "near_singular", "ard_2d", "heteroscedastic_1d"), n = 60L, seed = 1729L )gp_simulation_scenario( scenario = c("smooth_1d", "near_singular", "ard_2d", "heteroscedastic_1d"), n = 60L, seed = 1729L )
scenario |
One of |
n |
Number of observations. |
seed |
Non-negative integer seed. |
A gaussianprocesses_simulation with a scenario element.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
simulation <- gp_simulation_scenario("ard_2d", n = 40) simulation simulation$kernelsimulation <- gp_simulation_scenario("ard_2d", n = 40) simulation simulation$kernel
Converts inputs and one response column per output into the long format of multi-output models: one row per observed (input, output) pair, with the output index as the last input column.
gp_stack_outputs(x, y = NULL, outputs = NULL)gp_stack_outputs(x, y = NULL, outputs = NULL)
x |
Numeric vector or matrix of inputs, one row per observation. |
y |
Numeric matrix or data frame with one column per output and one
row per row of |
outputs |
Output indices to stack when |
A list with x, the stacked input matrix whose last column,
output, holds the output index; y, the stacked responses (only when
y is given); output, the output index of each row; and row, the
row of the original x. Rows are ordered by output, then by row.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
x <- c(0, 1, 2) y <- cbind(c(1.0, NA, 0.4), c(0.2, 0.3, NA)) stacked <- gp_stack_outputs(x, y) stacked$x stacked$y gp_stack_outputs(c(0.5, 1.5), outputs = 1:2)$xx <- c(0, 1, 2) y <- cbind(c(1.0, NA, 0.4), c(0.2, 0.3, NA)) stacked <- gp_stack_outputs(x, y) stacked$x stacked$y gp_stack_outputs(c(0.5, 1.5), outputs = 1:2)$x
Converts numeric, Date, or POSIXt values to elapsed numeric time while retaining origin, unit, and input-class metadata. Input order is never changed: non-increasing time values are rejected.
gp_time_index(time, unit = "auto")gp_time_index(time, unit = "auto")
time |
Numeric, Date, or POSIXt vector in strictly increasing order. |
unit |
Time unit for Date or POSIXt inputs. |
Time values are never sorted silently. Non-increasing input is rejected so the temporal order supplied by the user remains explicit.
A numeric vector of elapsed time with class
gaussianprocesses_time_index and time metadata in attributes.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
gp_time_index(as.Date("2026-01-01") + c(0, 1, 7)) gp_time_index( as.POSIXct("2026-01-01 00:00", tz = "UTC") + c(0, 3600, 7200), unit = "hours" )gp_time_index(as.Date("2026-01-01") + c(0, 1, 7)) gp_time_index( as.POSIXct("2026-01-01 00:00", tz = "UTC") + c(0, 3600, 7200), unit = "hours" )
Builds a coregionalization_kernel() whose is the empirical
covariance between the outputs, a starting point from which optimization
can move .
initialize_coregionalization(output, y, x = NULL, rank = 1L, n_outputs = NULL)initialize_coregionalization(output, y, x = NULL, rank = 1L, n_outputs = NULL)
output |
Output index of each observation, from 1 to |
y |
Numeric response of each observation. |
x |
Optional inputs of each observation, a vector or matrix without
the output-index column. Covariances between two outputs are estimated
from the inputs at which both are observed; without |
rank |
Rank |
n_outputs |
Number of outputs; by default the largest index in
|
The empirical covariance of the centred responses is made
positive semidefinite by setting negative eigenvalues to zero. is
taken from its leading eigenvectors, scaled by the square roots of
their eigenvalues, and from what remains on the diagonal,
with at least 5% of each output's variance. The empirical variances
include the observation noise, so starts too large on the
diagonal; optimization corrects that.
A gaussianprocesses_kernel.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
coregionalization_kernel(), gp_stack_outputs().
set.seed(1) x <- seq(0, 5, length.out = 20) y <- cbind(sin(x), 2 * sin(x) + 0.1) + rnorm(40, sd = 0.1) stacked <- gp_stack_outputs(x, y) kernel <- initialize_coregionalization(stacked$output, stacked$y, x = stacked$x[, 1]) coregionalization_matrix(kernel)set.seed(1) x <- seq(0, 5, length.out = 20) y <- cbind(sin(x), 2 * sin(x) + 0.1) + rnorm(40, sd = 0.1) stacked <- gp_stack_outputs(x, y) kernel <- initialize_coregionalization(stacked$output, stacked$y, x = stacked$x[, 1]) coregionalization_matrix(kernel)
Builds a spectral_mixture_kernel() whose components sit at the main
peaks of the empirical spectrum of one-dimensional data, a starting point
for optimize_gp().
initialize_spectral_mixture(x, y, n_components = 2L)initialize_spectral_mixture(x, y, n_components = 2L)
x |
Numeric vector of inputs, regularly or irregularly spaced. |
y |
Numeric vector of responses. |
n_components |
Number of components |
The spectrum of the centred responses is the periodogram
(stats::spec.pgram(), without taper) when the inputs are regularly
spaced, and the Lomb-Scargle periodogram otherwise, computed on a grid
four times finer than the frequency resolution , for an input
range , up to half the reciprocal median spacing. A mixture of
Gaussians and a uniform background is fitted to the spectrum, as
a density over frequency weighted by the power, by EM, starting from the
largest local maxima. The background absorbs the flat spectrum of
observation noise, which would otherwise widen the components.
Component takes the mean and variance of Gaussian as its
frequency and spectral variance, and the share of the variance of
that the Gaussian explains as its weight; the background share is
left to the noise. Spectral variances are at least
, the order of a spectral peak's width.
The likelihood of a spectral mixture is strongly multimodal, and this
initialisation is only a starting point: optimize with several starts,
for example n_starts = 5, which displace each frequency by one
resolution bin in turn.
A spectral-mixture kernel specification with n_components
components.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
set.seed(1) x <- 0:199 y <- 2 * sin(2 * pi * 0.1 * x) + sin(2 * pi * 0.27 * x) + rnorm(200, sd = 0.5) kernel <- initialize_spectral_mixture(x, y, n_components = 2) kernelset.seed(1) x <- 0:199 y <- 2 * sin(2 * pi * 0.1 * x) + sin(2 * pi * 0.27 * x) + rnorm(200, sd = 0.5) kernel <- initialize_spectral_mixture(x, y, n_components = 2) kernel
Computes diag(K(x, x)) without constructing the full covariance matrix.
This is particularly useful in sparse Gaussian-process approximations.
kernel_diagonal(kernel, x)kernel_diagonal(kernel, x)
kernel |
A Gaussian-process kernel specification. |
x |
Numeric vector or matrix of observations. |
A numeric vector with one prior variance per observation.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel <- sum_kernel(rbf_kernel(variance = 2), linear_kernel()) x <- cbind(1:3, 0:2) kernel_diagonal(kernel, x) all.equal(kernel_diagonal(kernel, x), diag(evaluate_kernel(kernel, x)))kernel <- sum_kernel(rbf_kernel(variance = 2), linear_kernel()) x <- cbind(1:3, 0:2) kernel_diagonal(kernel, x) all.equal(kernel_diagonal(kernel, x), diag(evaluate_kernel(kernel, x)))
Computes analytical derivatives of the covariance matrix
with respect to the logarithm of every kernel
parameter, . These are the
building blocks for gradient-based marginal-likelihood optimization, which
works in log-parameter space.
kernel_gradient(kernel, x, y = NULL)kernel_gradient(kernel, x, y = NULL)
kernel |
A Gaussian-process kernel specification. |
x |
Numeric vector or matrix of observations. |
y |
Optional numeric vector or matrix. If |
Every kernel parameter is strictly positive, so derivatives are taken with
respect to . The derivative with respect to the
parameter on its natural scale is
.
Elements are named and ordered exactly like
kernel_parameters(kernel, flatten = TRUE), including indexed ARD paths
such as kernel1.length_scale[2], so they can be matched to optimizer
parameters by name. A scalar length scale shared by several input
dimensions has a single derivative.
Leaf derivatives are closed-form expressions in the covariance matrix and
the scaled input differences. Sums differentiate term by term, products use
the product rule (without dividing by any factor, so exact zeros are safe),
and scaled kernels use the chain rule. The derivations are in
vignette("v07-kernel-derivatives", package = "gaussianprocesses").
A named list with one numeric matrix per flattened kernel
parameter. Each matrix has nrow(x) rows and nrow(y) columns (or
nrow(x) columns when y is NULL).
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel_input_gradient() for derivatives with respect to the
inputs.
kernel <- sum_kernel( rbf_kernel(variance = 1.5, length_scale = c(0.5, 2)), white_noise_kernel(variance = 0.1) ) x <- cbind(c(0, 0.5, 1.5), c(1, 0, 2)) gradient <- kernel_gradient(kernel, x) names(gradient) # Natural-scale derivative with respect to the first ARD length scale. gradient[["kernel1.length_scale[1]"]] / 0.5kernel <- sum_kernel( rbf_kernel(variance = 1.5, length_scale = c(0.5, 2)), white_noise_kernel(variance = 0.1) ) x <- cbind(c(0, 0.5, 1.5), c(1, 0, 2)) gradient <- kernel_gradient(kernel, x) names(gradient) # Natural-scale derivative with respect to the first ARD length scale. gradient[["kernel1.length_scale[1]"]] / 0.5
Computes for every input
dimension : the covariance between the derivative of the process
at and its value at .
kernel_input_gradient(kernel, x, y = NULL)kernel_input_gradient(kernel, x, y = NULL)
kernel |
A Gaussian-process kernel specification. |
x |
Numeric vector or matrix of inputs; the derivatives are taken with respect to these. |
y |
Optional numeric vector or matrix. If |
Input derivatives exist only for mean-square differentiable kernels. The
Matérn-1/2 and white-noise kernels, and any sum or product that contains
one, are not, and raise an error of class
gaussianprocesses_smoothness_error. The Matérn-3/2 process is
differentiable once, the Matérn-5/2 process twice, and the RBF,
rational-quadratic, periodic, and linear processes infinitely often.
Derivatives are closed-form expressions for every kernel, written so that
coincident inputs need no limit; sums, products, and scaled kernels follow
the sum and product rules. predict_gradient_gp() uses them to predict
the gradient of the latent function. The derivations are in
vignette("v07-kernel-derivatives", package = "gaussianprocesses").
A list with one numeric matrix per input dimension. Element d
has nrow(x) rows and nrow(y) columns and holds
.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
kernel_gradient() for derivatives with respect to the
hyperparameters.
kernel <- rbf_kernel(variance = 1, length_scale = 0.5) x <- c(0, 0.25, 1) gradient <- kernel_input_gradient(kernel, x) gradient[[1]] # Compare with a central difference in the first input. h <- 1e-6 (evaluate_kernel(kernel, x + h, x) - evaluate_kernel(kernel, x - h, x)) / (2 * h)kernel <- rbf_kernel(variance = 1, length_scale = 0.5) x <- c(0, 0.25, 1) gradient <- kernel_input_gradient(kernel, x) gradient[[1]] # Compare with a central difference in the first input. h <- 1e-6 (evaluate_kernel(kernel, x + h, x) - evaluate_kernel(kernel, x - h, x)) / (2 * h)
Computes a linear kernel from inner products between observations.
kernel_linear(x, y = NULL, variance = 1)kernel_linear(x, y = NULL, variance = 1)
x |
Numeric vector or matrix. Matrix rows are observations and columns are input dimensions. |
y |
Optional numeric vector or matrix with the same number of input
dimensions as |
variance |
Positive marginal variance. |
A numeric covariance matrix.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
linear_kernel() creates the same kernel as a reusable
specification, which can be combined, optimized, and used in models.
x <- cbind(c(1, 2, 3), c(0, 1, 0)) kernel_linear(x, variance = 0.5)x <- cbind(c(1, 2, 3), c(0, 1, 0)) kernel_linear(x, variance = 0.5)
Computes Matérn kernels for smoothness parameters
, , and . A scalar length scale gives an
isotropic distance; one length scale per input dimension gives ARD.
kernel_matern12(x, y = NULL, variance = 1, length_scale = 1) kernel_matern32(x, y = NULL, variance = 1, length_scale = 1) kernel_matern52(x, y = NULL, variance = 1, length_scale = 1)kernel_matern12(x, y = NULL, variance = 1, length_scale = 1) kernel_matern32(x, y = NULL, variance = 1, length_scale = 1) kernel_matern52(x, y = NULL, variance = 1, length_scale = 1)
x |
Numeric vector or matrix. Matrix rows are observations and columns are input dimensions. |
y |
Optional numeric vector or matrix with the same number of input
dimensions as |
variance |
Positive marginal variance. |
length_scale |
Positive scalar or numeric vector with one value per input dimension. A vector enables ARD. |
A numeric covariance matrix.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
matern_kernel_specs for the same kernels as reusable specifications, which can be combined, optimized, and used in models.
x <- seq(0, 2, by = 0.5) # Smoothness increases from nu = 1/2 to nu = 5/2. kernel_matern12(x, length_scale = 0.7)[1, ] kernel_matern32(x, length_scale = 0.7)[1, ] kernel_matern52(x, length_scale = 0.7)[1, ]x <- seq(0, 2, by = 0.5) # Smoothness increases from nu = 1/2 to nu = 5/2. kernel_matern12(x, length_scale = 0.7)[1, ] kernel_matern32(x, length_scale = 0.7)[1, ] kernel_matern52(x, length_scale = 0.7)[1, ]
Extract kernel parameters
kernel_parameters(kernel, flatten = FALSE)kernel_parameters(kernel, flatten = FALSE)
kernel |
A Gaussian-process kernel specification. |
flatten |
If |
Flat parameter names encode the position of each nested kernel. Scalar
parameters use paths such as kernel1.variance; vector-valued ARD
parameters use paths such as kernel1.length_scale[1] and
kernel1.length_scale[2]. These names remain stable when parameter values
are updated and can be passed directly to optimization routines.
A large ARD length scale means covariance changes slowly along that input dimension, while a small value means covariance changes more rapidly. This is a model sensitivity parameterization and should not be interpreted as a causal importance measure.
A nested list or named numeric vector.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel <- sum_kernel( rbf_kernel(length_scale = c(1, 2)), white_noise_kernel(variance = 0.1) ) str(kernel_parameters(kernel)) kernel_parameters(kernel, flatten = TRUE)kernel <- sum_kernel( rbf_kernel(length_scale = c(1, 2)), white_noise_kernel(variance = 0.1) ) str(kernel_parameters(kernel)) kernel_parameters(kernel, flatten = TRUE)
Computes a periodic kernel with a shared period and either an isotropic length scale or one ARD length scale per input dimension.
kernel_periodic(x, y = NULL, variance = 1, length_scale = 1, period = 1)kernel_periodic(x, y = NULL, variance = 1, length_scale = 1, period = 1)
x |
Numeric vector or matrix. Matrix rows are observations and columns are input dimensions. |
y |
Optional numeric vector or matrix with the same number of input
dimensions as |
variance |
Positive marginal variance. |
length_scale |
Positive scalar or numeric vector with one value per input dimension. A vector enables ARD. |
period |
Positive period shared across input dimensions. |
A numeric covariance matrix.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
periodic_kernel() creates the same kernel as a reusable
specification, which can be combined, optimized, and used in models.
x <- c(0, 0.25, 1, 2) covariance <- kernel_periodic(x, length_scale = 0.8, period = 1) # Inputs a whole number of periods apart are perfectly correlated. covariance[1, ]x <- c(0, 0.25, 1, 2) covariance <- kernel_periodic(x, length_scale = 0.8, period = 1) # Inputs a whole number of periods apart are perfectly correlated. covariance[1, ]
The rational-quadratic kernel can be interpreted as a scale mixture of squared-exponential kernels with different length scales. Scalar and ARD length-scale parameterizations are both supported.
kernel_rational_quadratic( x, y = NULL, variance = 1, length_scale = 1, alpha = 1 )kernel_rational_quadratic( x, y = NULL, variance = 1, length_scale = 1, alpha = 1 )
x |
Numeric vector or matrix. Matrix rows are observations and columns are input dimensions. |
y |
Optional numeric vector or matrix with the same number of input
dimensions as |
variance |
Positive marginal variance. |
length_scale |
Positive scalar or numeric vector with one value per input dimension. A vector enables ARD. |
alpha |
Positive scale-mixture parameter. |
A numeric covariance matrix.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
rational_quadratic_kernel() creates the same kernel as a reusable
specification, which can be combined, optimized, and used in models.
x <- seq(0, 2, by = 0.5) kernel_rational_quadratic(x, length_scale = 0.7, alpha = 0.5) # As alpha grows, the kernel approaches the RBF kernel. all.equal( kernel_rational_quadratic(x, alpha = 1e6), kernel_rbf(x), tolerance = 1e-5 )x <- seq(0, 2, by = 0.5) kernel_rational_quadratic(x, length_scale = 0.7, alpha = 0.5) # As alpha grows, the kernel approaches the RBF kernel. all.equal( kernel_rational_quadratic(x, alpha = 1e6), kernel_rbf(x), tolerance = 1e-5 )
Computes the squared-exponential (radial basis function) kernel between rows
of x and y. A scalar length scale gives an isotropic kernel; one
length scale per input dimension gives automatic relevance determination
(ARD).
kernel_rbf(x, y = NULL, variance = 1, length_scale = 1)kernel_rbf(x, y = NULL, variance = 1, length_scale = 1)
x |
Numeric vector or matrix. Matrix rows are observations and columns are input dimensions. |
y |
Optional numeric vector or matrix with the same number of input
dimensions as |
variance |
Positive marginal variance. |
length_scale |
Positive scalar or numeric vector with one value per input dimension. A vector enables ARD. |
A numeric covariance matrix with nrow(x) rows and nrow(y)
columns. Numeric vectors are treated as one-dimensional observations.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
rbf_kernel() creates the same kernel as a reusable
specification, which can be combined, optimized, and used in models.
x <- seq(0, 2, by = 0.5) kernel_rbf(x, variance = 2, length_scale = 0.7) # ARD: one length scale per input dimension. x2 <- cbind(c(0, 1, 2), c(0, 0, 1)) kernel_rbf(x2, length_scale = c(0.5, 3)) # Cross-covariance between two sets of inputs. kernel_rbf(x, c(0.25, 1.75))x <- seq(0, 2, by = 0.5) kernel_rbf(x, variance = 2, length_scale = 0.7) # ARD: one length scale per input dimension. x2 <- cbind(c(0, 1, 2), c(0, 0, 1)) kernel_rbf(x2, length_scale = c(0.5, 3)) # Cross-covariance between two sets of inputs. kernel_rbf(x, c(0.25, 1.75))
Returns variance when two observations are exactly identical and zero
otherwise. For kernel_white_noise(x), the diagonal therefore equals the
requested white-noise variance.
kernel_white_noise(x, y = NULL, variance = 1)kernel_white_noise(x, y = NULL, variance = 1)
x |
Numeric vector or matrix. Matrix rows are observations and columns are input dimensions. |
y |
Optional numeric vector or matrix with the same number of input
dimensions as |
variance |
Positive marginal variance. |
A numeric covariance matrix.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
white_noise_kernel() creates the same kernel as a reusable
specification, which can be combined, optimized, and used in models.
# Only coincident inputs covary. kernel_white_noise(c(0, 0, 1), variance = 0.1)# Only coincident inputs covary. kernel_white_noise(c(0, 0, 1), variance = 0.1)
Integrates a likelihood against a Gaussian distribution of the latent
value, : the
predictive distribution of a new response given the posterior of the
latent function at its input.
likelihood_predictive( likelihood, mean, variance, observed = NULL, exposure = NULL, quadrature_order = 40L )likelihood_predictive( likelihood, mean, variance, observed = NULL, exposure = NULL, quadrature_order = 40L )
likelihood |
A likelihood specification (gp_likelihoods). |
mean, variance
|
Mean and variance of the latent value, one per prediction. |
observed |
Optional responses whose log predictive density is returned. |
exposure |
Optional positive exposure for Poisson likelihoods: one value or one per response. |
quadrature_order |
Number of Gauss-Hermite nodes for integrals without a closed form. |
Closed forms are used where they exist: the Gaussian likelihood adds its
variance, the probit link gives , and the Poisson mean and variance are
those of a Poisson with a lognormal rate,
and
.
The logistic probability and the Poisson and logistic predictive
densities use adaptive Gauss-Hermite quadrature (Liu and Pierce, 1994).
With the mode of , found by Newton's method, and
,
computed in logs. Centring the nodes on the integrand rather than on
matters when the observation lies in the tail of the latent
distribution, as for large counts.
Quadrature converges more slowly as grows, because the
logistic function has poles at . With the default 40
nodes, the logistic probability is accurate to for
up to 3; increase quadrature_order for wider latent
distributions.
A list with the predictive mean and variance of ,
probability, , for Bernoulli likelihoods, and
log_density of observed when it is given.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Liu, Q. and Pierce, D. A. (1994). A note on Gauss-Hermite quadrature. Biometrika, 81(3), 624–629.
likelihood_predictive(bernoulli_likelihood("probit"), mean = c(-1, 0, 2), variance = c(0.5, 1, 4))$probability likelihood_predictive(poisson_likelihood(), mean = log(3), variance = 0.2, observed = 4, exposure = 2)likelihood_predictive(bernoulli_likelihood("probit"), mean = c(-1, 0, 2), variance = c(0.5, 1, 4))$probability likelihood_predictive(poisson_likelihood(), mean = log(3), variance = 0.2, observed = 4, exposure = 2)
Create a linear kernel specification
linear_kernel(variance = 1)linear_kernel(variance = 1)
variance |
Positive variance multiplier. |
An object of class gaussianprocesses_kernel.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel_linear() computes the same covariance directly from
parameter values, without a kernel specification.
# A linear trend component. evaluate_kernel(linear_kernel(variance = 0.1), 1:4)# A linear trend component. evaluate_kernel(linear_kernel(variance = 0.1), 1:4)
Computes the exact Gaussian log marginal likelihood from a fitted model using its stored Cholesky factor and solve vector.
log_marginal_likelihood(model)log_marginal_likelihood(model)
model |
A fitted |
If numerical jitter was required during fitting, the stored Cholesky factor corresponds to the jitter-stabilized covariance used by the numerical calculation. Jitter remains distinct from statistical observation noise.
For a mean with estimated coefficients, the value is the profile
likelihood, at the generalized least-squares estimate
(estimate_coefficients("ml")), or the restricted likelihood
(estimate_coefficients("reml")). For coefficients with a Gaussian prior
it is the marginal likelihood of the Gaussian process with covariance
, and for a vague prior it is the
restricted likelihood. mean_coefficients gives the formulas.
For a latent model from fit_latent_gp() or optimize_latent_gp() the
value is the Laplace approximation . For
a state-space model from fit_time_series_gp() it is the exact log
marginal likelihood from the Kalman filter's prediction errors.
A single finite numeric log marginal likelihood.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
x <- seq(-2, 2, length.out = 15) y <- sin(2 * x) # Compare candidate length scales by their marginal likelihood. sapply(c(0.2, 0.6, 2), function(length_scale) { log_marginal_likelihood( fit_gp(x, y, rbf_kernel(length_scale = length_scale), noise_variance = 0.01) ) })x <- seq(-2, 2, length.out = 15) y <- sin(2 * x) # Compare candidate length scales by their marginal likelihood. sapply(c(0.2, 0.6, 2), function(length_scale) { log_marginal_likelihood( fit_gp(x, y, rbf_kernel(length_scale = length_scale), noise_variance = 0.01) ) })
Computes the exact gradient of log_marginal_likelihood() with respect to
the logarithm of every kernel parameter and, for models with a single
homoscedastic noise variance, the logarithm of that noise variance.
log_marginal_likelihood_gradient(model)log_marginal_likelihood_gradient(model)
model |
A fitted |
Let be the observation covariance and
. For ,
For kernel parameters, is given by
kernel_gradient(); for the noise variance it is
.
The trace requires every entry of the precision matrix . They
are computed once from the stored Cholesky factor with chol2inv(), the
Cholesky solve of ; is never passed to solve() or a
general-purpose inverse, and the precision matrix is not used to solve
linear systems. The alternative, two triangular solves per parameter,
never forms ; against an exact reference it was equally
accurate for condition numbers up to and 4 to 18 times
slower (inst/benchmarks/gradient-numerics.R). As in
log_marginal_likelihood(), any numerical jitter used during fitting is
part of the factorized covariance and is treated as a constant.
Models fitted with observation-specific noise variances have no noise parameter, so only kernel derivatives are returned for them.
For a latent model the gradient is that of the Laplace approximation,
including the implicit dependence of the mode on the parameters
(optimize_latent_gp()), in the optimizer coordinates of the kernel
parameters and of the likelihood parameters.
A named numeric vector. Names follow
kernel_parameters(model$kernel, flatten = TRUE), followed by
noise_variance for homoscedastic models, or by
likelihood.<name> for the parameters of the likelihood of a latent
model.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
x <- seq(-2, 2, length.out = 15) model <- fit_gp( x, sin(x), kernel = rbf_kernel(length_scale = 0.8), noise_variance = 0.01 ) log_marginal_likelihood_gradient(model)x <- seq(-2, 2, length.out = 15) model <- fit_gp( x, sin(x), kernel = rbf_kernel(length_scale = 0.8), noise_variance = 0.01 ) log_marginal_likelihood_gradient(model)
Computes exact leave-one-out (LOO) predictive summaries from a fitted exact Gaussian-process model without refitting the model once per observation. The calculation uses the fitted precision diagonal implied by the stored Cholesky factor.
loo_gp(model, interval_level = 0.95)loo_gp(model, interval_level = 0.95)
model |
A fitted |
interval_level |
Probability level for LOO prediction intervals. |
When numerical jitter was required during fitting, the LOO calculation
necessarily reflects the stabilized covariance used in that factorization;
the amount of jitter is reported separately by gp_numerical_diagnostics().
Estimated mean coefficients stay at their full-data estimate, as in
predict_gp(). Marginalized coefficients are integrated out as in the
posterior: the precision diagonal is that of
,
so with a vague prior each prediction re-estimates the coefficients
without the left-out observation.
A data frame with observed values, LOO predictive means and variances, residuals, standardized residuals, probability integral transform (PIT) values, interval bounds, coverage indicators, and pointwise log predictive densities.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
x <- seq(-2, 2, length.out = 20) model <- fit_gp( x, sin(2 * x), kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01 ) loo <- loo_gp(model) head(loo[, c("observed", "mean", "sd", "pit", "covered")])x <- seq(-2, 2, length.out = 20) model <- fit_gp( x, sin(2 * x), kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01 ) loo <- loo_gp(model) head(loo[, c("observed", "mean", "sd", "pit", "covered")])
Create Matérn kernel specifications
matern12_kernel(variance = 1, length_scale = 1) matern32_kernel(variance = 1, length_scale = 1) matern52_kernel(variance = 1, length_scale = 1)matern12_kernel(variance = 1, length_scale = 1) matern32_kernel(variance = 1, length_scale = 1) matern52_kernel(variance = 1, length_scale = 1)
variance |
Positive marginal variance. |
length_scale |
Positive scalar or numeric vector. A vector supplies one ARD length scale per input dimension and is validated against the data when the kernel is evaluated. |
An object of class gaussianprocesses_kernel.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel_matern12(), kernel_matern32(), and
kernel_matern52() compute the same covariances directly from
parameter values.
matern52_kernel(variance = 1, length_scale = 0.8) # ARD length scales become indexed parameter paths. kernel_parameters(matern32_kernel(length_scale = c(1, 2)), flatten = TRUE)matern52_kernel(variance = 1, length_scale = 0.8) # ARD length scales become indexed parameter paths. kernel_parameters(matern32_kernel(length_scale = c(1, 2)), flatten = TRUE)
A parametric mean has coefficients
that are fixed, estimated, or marginalized. Pass the result of
these functions as the coefficients argument of linear_mean(),
polynomial_mean(), basis_mean(), or as the value of
constant_mean(); a numeric vector fixes the coefficients instead.
estimate_coefficients(method = c("ml", "reml")) coefficient_prior(mean = 0, covariance = NULL)estimate_coefficients(method = c("ml", "reml")) coefficient_prior(mean = 0, covariance = NULL)
method |
|
mean |
Prior mean |
covariance |
Prior covariance |
Write for the matrix of basis rows ,
for the observation covariance, and for the
number of coefficients.
Estimated. The coefficients are the generalized least-squares estimate
, which maximizes
the likelihood for given hyperparameters. Predictions plug in
and do not include its uncertainty. With method = "ml"
the likelihood is the profile likelihood, the Gaussian likelihood at
. With method = "reml" it is the restricted likelihood
with ,
which accounts for the degrees of freedom used by
and so estimates variances with less bias.
Marginalized. With the prior , the model is
exactly a Gaussian process with mean and covariance
(Rasmussen and Williams, 2006,
section 2.7). Predictions use the posterior mean
and add the coefficient uncertainty
,
, to the predictive covariance; posterior
draws include it too. The likelihood is the marginal likelihood of that
Gaussian process. In the vague limit and the
likelihood, up to a constant, is the restricted likelihood above.
Rank-deficient bases make estimated coefficients, and those with a vague
prior, unidentifiable, and raise an error of class
gaussianprocesses_rank_deficiency_error. A proper prior identifies them.
An object of class gaussianprocesses_coefficients.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian Processes for Machine Learning. MIT Press. Section 2.7.
linear_mean(), and the universal-kriging section of
vignette("v03-marginal-likelihood-and-prediction").
x <- seq(0, 4, length.out = 25) y <- 1 + 0.5 * x + sin(2 * x) estimated <- fit_gp(x, y, rbf_kernel(length_scale = 0.5), noise_variance = 0.01, mean = linear_mean()) coef(estimated) # A vague prior gives the same coefficients and adds their uncertainty to # predictions away from the data. marginalized <- fit_gp(x, y, rbf_kernel(length_scale = 0.5), noise_variance = 0.01, mean = linear_mean(coefficient_prior())) predict_gp(estimated, 8)$latent_sd predict_gp(marginalized, 8)$latent_sdx <- seq(0, 4, length.out = 25) y <- 1 + 0.5 * x + sin(2 * x) estimated <- fit_gp(x, y, rbf_kernel(length_scale = 0.5), noise_variance = 0.01, mean = linear_mean()) coef(estimated) # A vague prior gives the same coefficients and adds their uncertainty to # predictions away from the data. marginalized <- fit_gp(x, y, rbf_kernel(length_scale = 0.5), noise_variance = 0.01, mean = linear_mean(coefficient_prior())) predict_gp(estimated, 8)$latent_sd predict_gp(marginalized, 8)$latent_sd
Estimates kernel parameters and, optionally, observation-noise variance by maximizing the exact log marginal likelihood. Optimization is performed in log-parameter space with deterministic multiple starts.
optimize_gp( x, y, kernel, noise_variance = 1e-06, mean = zero_mean(), optimize_noise = TRUE, n_starts = 3L, start_spread = 1, lower = 1e-08, upper = 1e+08, control = list(maxit = 500), initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), gradient = c("analytical", "numerical"), derivative = NULL, noise_groups = NULL )optimize_gp( x, y, kernel, noise_variance = 1e-06, mean = zero_mean(), optimize_noise = TRUE, n_starts = 3L, start_spread = 1, lower = 1e-08, upper = 1e+08, control = list(maxit = 500), initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), gradient = c("analytical", "numerical"), derivative = NULL, noise_groups = NULL )
x |
Numeric vector or matrix of training inputs. |
y |
Numeric response vector. |
kernel |
Initial Gaussian-process kernel specification. |
noise_variance |
Non-negative observation-noise variance: a scalar,
or one value per observation. With |
mean |
Gaussian-process mean specification. Estimated or marginalized coefficients are not optimizer parameters: for each value of the hyperparameters they are computed in closed form, and the objective is the profile, restricted, or marginal likelihood (mean_coefficients). |
optimize_noise |
If |
n_starts |
Number of deterministic optimization starts. |
start_spread |
Log-space displacement used to construct additional deterministic starts around the supplied parameters. |
lower |
Strictly positive lower bound applied to all optimized parameters on the natural scale. |
upper |
Strictly positive upper bound applied to all optimized parameters on the natural scale. |
control |
List passed to |
initial_jitter |
Non-negative jitter tried first, relative to the covariance scale (the mean of its diagonal). |
fallback_jitter |
Positive relative jitter tried after the first failed factorization. |
jitter_multiplier |
Multiplicative jitter escalation factor. |
max_attempts |
Maximum Cholesky attempts per objective evaluation. |
symmetry_tolerance |
Relative tolerance for checking that the covariance matrix is symmetric. |
gradient |
How L-BFGS-B obtains the gradient of the objective.
|
derivative |
Optional observation types for derivative observations,
as in |
noise_groups |
Optional group of each observation, such as the output
of a multi-output model ( |
Kernel parameters are identified through the stable paths returned by
kernel_parameters(kernel, flatten = TRUE). Every parameter is optimized
on an unconstrained coordinate determined by its constraint. Positive
parameters, including the noise variance, are optimized on the log scale
and stay positive. Real-valued parameters, such as the location of a
changepoint_kernel(), are optimized on the identity scale.
$optimization$coordinates records the coordinate of each parameter. The
deterministic starts do not depend on gradient.
A changepoint location is bounded by the training range of its input
column, and the starts after the first place it at evenly spaced
quantiles of that column, because the likelihood is often multimodal in
the location. A spectral-mixture frequency is bounded by 0 and the
Nyquist frequency of its column, and later starts displace it by one
frequency-resolution bin (spectral_mixture_kernel()).
The objective is the likelihood that log_marginal_likelihood() reports
for the mean: $optimization$likelihood records which, and
$optimization$mean_coefficients the coefficients at the optimum.
The returned diagnostics retain every start, convergence code, objective
value, final parameters, and the gradient method. Evaluation counts are
reported per start in start_results and summed over all starts:
function_evaluationsEvaluations of the negative log marginal
likelihood, including those stats::optim() makes to approximate
gradients by finite differences.
gradient_evaluationsAnalytical gradient evaluations, or the number of finite-difference gradient approximations.
model_fitsGP fits, the dominant cost. With analytical gradients the value and gradient at the same point share one fit.
counts is the unmodified stats::optim() result for the best start;
with numerical gradients it excludes the finite-difference evaluations.
$optimization$optima groups the starts by the optimum they reached:
starts whose log marginal likelihoods differ by at most and
whose coordinates differ by at most share one. It reports,
for each distinct optimum, its starts, log marginal likelihood, and gap to
the best. Several optima with large gaps mean that the starts matter;
several with nearly equal likelihoods but different parameters suggest a
ridge of poorly identified parameters (gp_hyperparameter_uncertainty()).
summary() reports them.
A fitted gaussianprocesses_model with optimized kernel and noise
parameters. Optimization diagnostics are stored in $optimization.
Stable: from version 1.0.0 this interface changes incompatibly only in a
major release, after a deprecation period. Results and options that
concern an experimental model class, kernel, or argument follow that
interface's tier. See gaussianprocesses-package for the
policy. The noise_groups argument (one noise variance per group) is experimental.
x <- seq(-2, 2, length.out = 20) y <- sin(2 * x) + 0.1 * cos(9 * x) model <- optimize_gp(x, y, kernel = rbf_kernel(), noise_variance = 0.05, n_starts = 1) model kernel_parameters(model$kernel, flatten = TRUE) model$noise_variancex <- seq(-2, 2, length.out = 20) y <- sin(2 * x) + 0.1 * cos(9 * x) model <- optimize_gp(x, y, kernel = rbf_kernel(), noise_variance = 0.05, n_starts = 1) model kernel_parameters(model$kernel, flatten = TRUE) model$noise_variance
Estimates kernel parameters and, optionally, likelihood parameters by
maximizing the Laplace approximation to the log marginal likelihood, with
the optimizer of optimize_gp(): L-BFGS-B on unconstrained coordinates,
deterministic multiple starts, and analytical gradients.
optimize_latent_gp( x, y, kernel, likelihood, mean = zero_mean(), exposure = NULL, optimize_likelihood = TRUE, n_starts = 3L, start_spread = 1, lower = 1e-08, upper = 1e+08, control = list(maxit = 500), method = "laplace", max_iterations = 100L, convergence_tolerance = 1e-14, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), gradient = c("analytical", "numerical") )optimize_latent_gp( x, y, kernel, likelihood, mean = zero_mean(), exposure = NULL, optimize_likelihood = TRUE, n_starts = 3L, start_spread = 1, lower = 1e-08, upper = 1e+08, control = list(maxit = 500), method = "laplace", max_iterations = 100L, convergence_tolerance = 1e-14, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), gradient = c("analytical", "numerical") )
x |
Numeric vector or matrix of training inputs. Matrix rows are observations and columns are input dimensions. |
y |
Responses, one per row of |
kernel |
Initial kernel specification. |
likelihood |
Likelihood specification; its parameters, if any, are the starting values of the likelihood parameters. |
mean |
Gaussian-process mean specification, with fixed
coefficients, coefficients estimated by maximum likelihood, or
coefficients with a Gaussian |
exposure |
Optional positive exposure for Poisson likelihoods: one
value or one per observation (see |
optimize_likelihood |
If |
n_starts, start_spread, lower, upper, control, gradient
|
As in
|
method |
The approximation: |
max_iterations |
Maximum number of Newton iterations. |
convergence_tolerance |
The Newton iterations stop when the Newton decrement is at most this value (see Details). |
initial_jitter, fallback_jitter, jitter_multiplier, max_attempts
|
The
jitter policy for the factorization of |
symmetry_tolerance |
Relative tolerance for checking that |
The objective is of fit_latent_gp(). Its
gradient (Rasmussen and Williams, 2006, Algorithm 5.1) has an explicit
part, with the mode held fixed, and an implicit part through
the dependence of on :
which needs the third derivatives of the log likelihood
(evaluate_likelihood()). Likelihood parameters are named
likelihood.<name>, for example likelihood.variance.
Mean coefficients estimated by maximum likelihood
(estimate_coefficients("ml")) are optimized jointly with the other
parameters, on the real line, as mean.<name> (for example
mean.intercept), starting from the generalized linear model fitted
without the latent process. Their gradient is
plus the implicit part through
.
Each evaluation starts the Newton iterations from the previous mode when
that is better than the prior mean, which saves most of the iterations
once the optimizer takes small steps. The returned model is refitted at
the optimum from the prior mean, so it equals fit_latent_gp() with the
optimized parameters.
$optimization has the fields of optimize_gp(), with
optimize_likelihood and approximation in place of the noise fields,
and at_bound, the parameters that ended at lower or upper (on the
natural scale) or at the limits that optimize_gp() describes for
changepoint locations and spectral frequencies.
A fitted gaussianprocesses_latent_model with optimized
parameters and optimizer diagnostics in $optimization.
Every positive parameter is searched within [lower, upper]. If any
parameter ends at a bound, a warning of class
gaussianprocesses_bound_warning names it, because the likelihood may
still increase beyond the bound and the bound, not the data, then
determines the estimate. With binary responses this happens when the
classes are separable: larger signal variances let the latent function
separate them more sharply, and the approximate marginal likelihood
keeps increasing up to very large variances. On twenty separable points
on a line it peaks only near a variance of 1800, with a nearly flat
maximum, and a smaller upper ends the search at the bound with this
warning. Setting upper to the largest plausible variance makes the
limit explicit.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
x <- seq(0, 10, length.out = 40) counts <- c(1, 0, 2, 1, 3, 2, 4, 5, 3, 6, 7, 5, 8, 6, 9, 7, 6, 8, 5, 6, 4, 5, 3, 4, 2, 3, 2, 1, 2, 1, 1, 0, 1, 2, 1, 3, 2, 4, 3, 5) model <- optimize_latent_gp(x, counts, rbf_kernel(), poisson_likelihood(), n_starts = 1) kernel_parameters(model$kernel, flatten = TRUE)x <- seq(0, 10, length.out = 40) counts <- c(1, 0, 2, 1, 3, 2, 4, 5, 3, 6, 7, 5, 8, 6, 9, 7, 6, 8, 5, 6, 4, 5, 3, 4, 2, 3, 2, 1, 2, 1, 1, 0, 1, 2, 1, 3, 2, 4, 3, 5) model <- optimize_latent_gp(x, counts, rbf_kernel(), poisson_likelihood(), n_starts = 1) kernel_parameters(model$kernel, flatten = TRUE)
Estimates kernel parameters, optionally the noise, and optionally the
inducing inputs of a sparse model (fit_sparse_gp()) by maximizing the
VFE bound or the FITC approximate marginal likelihood, with the optimizer
of optimize_gp(): L-BFGS-B on unconstrained coordinates, deterministic
multiple starts, and analytical gradients.
optimize_sparse_gp( x, y, kernel, noise_variance = 1e-06, mean = zero_mean(), n_inducing = NULL, inducing_points = NULL, selection = c("farthest", "quantile", "variance"), method = c("vfe", "fitc"), optimize_inducing = FALSE, optimize_noise = TRUE, n_starts = 3L, start_spread = 1, lower = 1e-08, upper = 1e+08, control = list(maxit = 500), fitc_diagonal_floor = 1e-10, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), gradient = c("analytical", "numerical") )optimize_sparse_gp( x, y, kernel, noise_variance = 1e-06, mean = zero_mean(), n_inducing = NULL, inducing_points = NULL, selection = c("farthest", "quantile", "variance"), method = c("vfe", "fitc"), optimize_inducing = FALSE, optimize_noise = TRUE, n_starts = 3L, start_spread = 1, lower = 1e-08, upper = 1e+08, control = list(maxit = 500), fitc_diagonal_floor = 1e-10, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), gradient = c("analytical", "numerical") )
x |
Numeric vector or matrix of training inputs. |
y |
Numeric response vector. |
kernel |
Initial kernel specification. |
noise_variance |
Noise variance: a scalar starting value, or one value
per observation forming a known pattern whose scale is estimated, as in
|
mean |
Gaussian-process mean specification with fixed coefficients. |
n_inducing |
Optional number of inducing points selected from |
inducing_points |
Optional explicit inducing locations. If supplied,
|
selection |
Inducing-point selection method used when explicit points
are not supplied: |
method |
The approximation: |
optimize_inducing |
If |
optimize_noise, n_starts, start_spread, lower, upper, control, gradient
|
As in |
fitc_diagonal_floor |
Strictly positive numerical floor applied to the FITC diagonal term before inversion. |
initial_jitter |
Non-negative jitter tried first in the inducing-system Cholesky factorizations, relative to the scale of each factorized matrix (the mean of its diagonal). |
fallback_jitter |
Positive relative jitter tried after the first failed factorization. |
jitter_multiplier |
Multiplicative jitter escalation factor. |
max_attempts |
Maximum Cholesky attempts. |
symmetry_tolerance |
Relative tolerance for checking that covariance matrices are symmetric. |
VFE is the default because its objective is a lower bound on the exact log marginal likelihood: maximizing it fits the hyperparameters of the exact model as well as the inducing points allow, and pays for poor coverage through the trace term. FITC's objective is not a bound; its diagonal correction can absorb noise, and maximizing it tends to underestimate the noise variance (Bauer, van der Wilk, and Rasmussen, 2016). The research note on sparse approximations compares the two.
The gradient is analytical for both approximations, with the inducing
points fixed: with and
,
where follows from the derivatives of
and , plus the derivative of the VFE trace term.
It is computed in time without forming an
matrix, processing the observations in blocks.
A fitted gaussianprocesses_sparse_model with optimizer
diagnostics in $optimization, which has the fields of optimize_gp().
With optimize_inducing = TRUE the inducing inputs
are optimized as well, on the real line, as parameters named
inducing.<j>.<d>. Their gradient follows from the same terms:
changes only row of and row and
column of ,
with the kernel input derivatives of kernel_input_gradient() and the
sensitivities and of the objective to
and , at the same cost.
Optimizing is recommended with VFE: the bound can only move
towards the exact marginal likelihood, so better inducing inputs make the
approximation better. With FITC it is prone to overfitting: the inducing
inputs can move or collapse so that FITC's diagonal correction absorbs the
noise, and the noise variance is then underestimated (Bauer, van der Wilk,
and Rasmussen, 2016). Inducing points that become nearly identical under
the kernel are reported in $inducing_collapse with a warning of class
gaussianprocesses_inducing_collapse_warning; is factorized
with the package's jitter policy, so the fit stays defined. Greedy
variance selection (selection = "variance") gives a good starting point.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
fit_sparse_gp(), optimize_gp().
set.seed(1) x <- seq(-3, 3, length.out = 300) y <- sin(2 * x) + rnorm(300, sd = 0.2) model <- optimize_sparse_gp(x, y, rbf_kernel(), noise_variance = 0.1, n_inducing = 20, n_starts = 1) model model$noise_varianceset.seed(1) x <- seq(-3, 3, length.out = 300) y <- sin(2 * x) + rnorm(300, sd = 0.2) model <- optimize_sparse_gp(x, y, rbf_kernel(), noise_variance = 0.1, n_inducing = 20, n_starts = 1) model model$noise_variance
Estimates the kernel parameters and the noise of a GP on ordered
time-series observations by maximizing the log marginal likelihood, with
the optimizer of optimize_gp().
optimize_time_series_gp( time, y, kernel, unit = "auto", method = c("exact", "state_space"), ... )optimize_time_series_gp( time, y, kernel, unit = "auto", method = c("exact", "state_space"), ... )
time |
Numeric, Date, or POSIXt vector in strictly increasing order. |
y |
Numeric response vector. |
kernel |
Initial kernel specification. |
unit |
Time unit passed to |
method |
|
... |
Additional arguments passed to |
With method = "state_space" each objective value is one Kalman filter
pass, in time (fit_time_series_gp() describes the method).
Gradients are finite-difference approximations by L-BFGS-B
(gradient = "numerical" in optimize_gp()); analytical sensitivity
recursions are not implemented yet.
A fitted model as returned by fit_time_series_gp(), with
optimizer diagnostics in $optimization.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
set.seed(1) time <- sort(runif(200, 0, 50)) y <- sin(time / 3) + rnorm(200, sd = 0.2) model <- optimize_time_series_gp(time, y, matern52_kernel(), noise_variance = 0.1, n_starts = 1, method = "state_space") model$optimization$optimized_parametersset.seed(1) time <- sort(runif(200, 0, 50)) y <- sin(time / 3) + rnorm(200, sd = 0.2) model <- optimize_time_series_gp(time, y, matern52_kernel(), noise_variance = 0.1, n_starts = 1, method = "state_space") model$optimization$optimized_parameters
Regression trends , the mean of universal
kriging, with fixed, estimated, or marginalized coefficients.
linear_mean(coefficients = estimate_coefficients()) polynomial_mean( degree = 2L, coefficients = estimate_coefficients(), center = NULL, scale = NULL ) basis_mean(basis, coefficients = estimate_coefficients())linear_mean(coefficients = estimate_coefficients()) polynomial_mean( degree = 2L, coefficients = estimate_coefficients(), center = NULL, scale = NULL ) basis_mean(basis, coefficients = estimate_coefficients())
coefficients |
|
degree |
Non-negative integer polynomial degree. |
center, scale
|
Optional centring and scaling of the inputs for
|
basis |
A function of the input matrix that returns a numeric matrix with one row per input and one column per coefficient. |
The bases are:
linear_mean(), on the raw
inputs, so the coefficients are an intercept and slopes. Coefficients
are named intercept, x1, ..., xD.
polynomial_mean()An intercept and the powers
of each standardized input
, without interactions. Powers of raw
inputs make badly conditioned bases, so by default is the
midpoint and half the range of the training inputs, which
maps them to . A fitted model stores these values in its
mean specification and uses them for prediction, and the coefficients,
named intercept, x1, x1^2, ..., refer to the standardized
inputs. polynomial_mean(0) is an unknown constant.
basis_mean()The columns returned by basis, named by its
column names or h1, h2, ....
mean_coefficients describes the three treatments of .
coef() and vcov() return the coefficients of a fitted model and
their covariance.
Parametric means are supported by exact models: fit_gp(),
optimize_gp(), and the functions that use them. Sparse and
heteroscedastic models accept them only with fixed coefficients.
An object of class gaussianprocesses_mean.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
x <- cbind(seq(0, 4, length.out = 30), rep(c(-1, 1), 15)) y <- 2 + 0.5 * x[, 1] - x[, 2] + sin(2 * x[, 1]) model <- fit_gp(x, y, rbf_kernel(length_scale = c(0.5, 5)), noise_variance = 0.01, mean = linear_mean()) coef(model) sqrt(diag(vcov(model))) # A quadratic trend in one input; coefficients refer to inputs scaled to # [-1, 1]. x1 <- seq(-3, 3, length.out = 30) quadratic <- fit_gp(x1, x1^2 + sin(3 * x1), rbf_kernel(length_scale = 0.4), noise_variance = 0.01, mean = polynomial_mean(2)) coef(quadratic) quadratic$mean$scale # Any basis, here a periodic one with fixed coefficients. seasonal <- basis_mean( function(x) cbind(sin = sin(x[, 1]), cos = cos(x[, 1])), coefficients = c(1, 0.5) ) evaluate_mean(seasonal, c(0, pi / 2))x <- cbind(seq(0, 4, length.out = 30), rep(c(-1, 1), 15)) y <- 2 + 0.5 * x[, 1] - x[, 2] + sin(2 * x[, 1]) model <- fit_gp(x, y, rbf_kernel(length_scale = c(0.5, 5)), noise_variance = 0.01, mean = linear_mean()) coef(model) sqrt(diag(vcov(model))) # A quadratic trend in one input; coefficients refer to inputs scaled to # [-1, 1]. x1 <- seq(-3, 3, length.out = 30) quadratic <- fit_gp(x1, x1^2 + sin(3 * x1), rbf_kernel(length_scale = 0.4), noise_variance = 0.01, mean = polynomial_mean(2)) coef(quadratic) quadratic$mean$scale # Any basis, here a periodic one with fixed coefficients. seasonal <- basis_mean( function(x) cbind(sin = sin(x[, 1]), cos = cos(x[, 1])), coefficients = c(1, 0.5) ) evaluate_mean(seasonal, c(0, pi / 2))
Create a periodic kernel specification
periodic_kernel(variance = 1, length_scale = 1, period = 1)periodic_kernel(variance = 1, length_scale = 1, period = 1)
variance |
Positive marginal variance. |
length_scale |
Positive scalar or numeric vector. A vector supplies one ARD length scale per input dimension and is validated against the data when the kernel is evaluated. |
period |
Positive period. |
An object of class gaussianprocesses_kernel.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel_periodic() computes the same covariance directly from
parameter values, without a kernel specification.
# Monthly data with a yearly cycle. kernel <- periodic_kernel(length_scale = 0.8, period = 12) evaluate_kernel(kernel, c(0, 6, 12))# Monthly data with a yearly cycle. kernel <- periodic_kernel(length_scale = 0.8, period = 12) evaluate_kernel(kernel, c(0, 6, 12))
Computes the posterior mean and uncertainty at new input locations. Latent function uncertainty and future-observation uncertainty are reported separately. The stored Cholesky factor from model fitting is reused; no covariance-matrix inverse is formed.
predict_gp( model, x, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps), observation_noise_variance = NULL, block_size = NULL )predict_gp( model, x, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps), observation_noise_variance = NULL, block_size = NULL )
model |
A fitted |
x |
Numeric vector or matrix of prediction inputs. Matrix rows are observations and columns must match the fitted input dimension. |
interval_level |
Probability level for latent credible intervals and noisy-observation prediction intervals. |
include_covariance |
If |
variance_tolerance |
Relative tolerance used when deciding whether a small negative posterior variance is floating-point error or a material numerical failure. |
observation_noise_variance |
Optional non-negative scalar or vector giving observation-noise variance at the prediction inputs. It defaults to the fitted scalar noise variance for homoscedastic models. Models fitted with observation-specific training noise require this argument. |
block_size |
Number of prediction inputs processed together when
|
With training and prediction inputs,
the factorized training covariance, and
, the latent posterior variance at
prediction input is
This is exact. The default marginal prediction evaluates only the
cross-covariance , in blocks of block_size prediction
inputs, and the prior variances with
kernel_diagonal(). It takes time and memory
for blocks of inputs, beyond the fitted factor.
include_covariance = TRUE also forms the prior
covariance and the latent and observation posterior covariances, which
takes time and memory. Each
matrix takes bytes, 512 MB for 8000 inputs,
and several are held at once. It is opt-in because pointwise means,
variances, and intervals do not need it; joint quantities such as
function draws (sample_gp_posterior()) do.
A parametric mean contributes with its fixed,
estimated, or posterior-mean coefficients. Estimated coefficients are
plugged in. Marginalized coefficients add their uncertainty,
with
, to the latent variances and
covariances (mean_coefficients).
An object of class gaussianprocesses_prediction. Its fields
are shared by every prediction in the package: predict_sparse_gp(),
predict_heteroscedastic_gp(), and forecast_gp() return the same
fields with the same meaning, and may add their own.
xThe prediction inputs as a matrix.
meanThe posterior mean of the latent function.
latent_variance, latent_sd
The posterior variance and standard deviation of the latent function.
observation_noise_varianceThe noise variance of a new observation.
observation_variance, observation_sd
The variance and
standard deviation of a new noisy observation:
latent_variance + observation_noise_variance.
interval_level, latent_interval,
prediction_interval
The interval level and the intervals for the latent function and for a new observation.
latent_covariance, observation_covariance
The full
covariance matrices, only with include_covariance = TRUE.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
x <- seq(-2, 2, length.out = 15) model <- fit_gp( x, sin(2 * x), kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01 ) prediction <- predict_gp(model, c(0, 3)) # Latent-function and noisy-observation uncertainty are reported separately; # both grow away from the data. prediction$latent_sd prediction$observation_sd prediction$prediction_intervalx <- seq(-2, 2, length.out = 15) model <- fit_gp( x, sin(2 * x), kernel = rbf_kernel(length_scale = 0.6), noise_variance = 0.01 ) prediction <- predict_gp(model, c(0, 3)) # Latent-function and noisy-observation uncertainty are reported separately; # both grow away from the data. prediction$latent_sd prediction$observation_sd prediction$prediction_interval
Computes the posterior mean and variance of each partial derivative
of the latent function of an exact
Gaussian-process model. Differentiation is linear, so these derivatives
are jointly Gaussian with the observations and the posterior is exact.
predict_gradient_gp( model, x, interval_level = 0.95, variance_tolerance = sqrt(.Machine$double.eps), block_size = NULL )predict_gradient_gp( model, x, interval_level = 0.95, variance_tolerance = sqrt(.Machine$double.eps), block_size = NULL )
model |
A fitted |
x |
Numeric vector or matrix of prediction inputs. |
interval_level |
Probability level for the credible intervals. |
variance_tolerance |
Relative tolerance used when deciding whether a small negative posterior variance is floating-point error. |
block_size |
Number of prediction inputs processed together; |
With the factorized training covariance and
,
The kernel derivatives come from kernel_input_gradient() and its
second-order counterpart. Only mean-square differentiable kernels have a
gradient process; others raise an error of class
gaussianprocesses_smoothness_error.
The variances are marginal: covariances between partial derivatives, or between points, are not returned.
Parametric means add
to the mean. Marginalized coefficients add their uncertainty to the
variance, as in predict_gp(), with and
replaced by their derivatives. basis_mean() has no input derivatives
and raises an error.
An object of class gaussianprocesses_gradient_prediction with
the prediction inputs x and, as matrices with one row per input and one
column per input dimension, the posterior mean, variance, and sd
of the partial derivatives and the credible-interval bounds lower and
upper at interval_level.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
x <- seq(0, 2 * pi, length.out = 25) model <- fit_gp( x, sin(x), rbf_kernel(length_scale = 1), noise_variance = 1e-4 ) gradient <- predict_gradient_gp(model, c(0, pi / 2, pi)) # The derivative of sin is cos. cbind(estimate = gradient$mean[, 1], truth = cos(c(0, pi / 2, pi))) gradient$sdx <- seq(0, 2 * pi, length.out = 25) model <- fit_gp( x, sin(x), rbf_kernel(length_scale = 1), noise_variance = 1e-4 ) gradient <- predict_gradient_gp(model, c(0, pi / 2, pi)) # The derivative of sin is cos. cbind(estimate = gradient$mean[, 1], truth = cos(c(0, pi / 2, pi))) gradient$sd
The latent-function posterior and the input-dependent noise process are predicted separately. Observation variance is the sum of latent posterior variance and the plug-in estimated noise variance. Uncertainty about the log-noise process is returned separately and is not folded into the observation variance.
predict_heteroscedastic_gp( model, x, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps) )predict_heteroscedastic_gp( model, x, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps) )
model |
A fitted heteroscedastic GP model. |
x |
Numeric vector or matrix of prediction inputs. |
interval_level |
Probability level for returned intervals. |
include_covariance |
If |
variance_tolerance |
Relative tolerance for latent posterior variances. |
An object of class
gaussianprocesses_heteroscedastic_prediction. It has the fields that
every prediction in the package shares (see predict_gp()), with the
plug-in noise estimate as observation_noise_variance, and in addition
noise_log_variance, its posterior variance
noise_log_variance_uncertainty, and noise_variance_interval from the
log-noise GP.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
simulation <- gp_simulation_scenario("heteroscedastic_1d", n = 60) model <- fit_heteroscedastic_gp( simulation$x, simulation$observed, kernel = matern52_kernel(length_scale = 0.2), noise_kernel = rbf_kernel(length_scale = 0.4), max_iterations = 30 ) prediction <- predict_heteroscedastic_gp(model, c(0.1, 0.9)) # Observation variance = latent variance + estimated noise variance. cbind( latent = prediction$latent_variance, noise = prediction$observation_noise_variance, observation = prediction$observation_variance )simulation <- gp_simulation_scenario("heteroscedastic_1d", n = 60) model <- fit_heteroscedastic_gp( simulation$x, simulation$observed, kernel = matern52_kernel(length_scale = 0.2), noise_kernel = rbf_kernel(length_scale = 0.4), max_iterations = 30 ) prediction <- predict_heteroscedastic_gp(model, c(0.1, 0.9)) # Observation variance = latent variance + estimated noise variance. cbind( latent = prediction$latent_variance, noise = prediction$observation_noise_variance, observation = prediction$observation_variance )
Computes the approximate posterior of the latent function at new inputs and the predictive distribution of new responses through the likelihood: class probabilities for Bernoulli likelihoods and predictive means and variances for every likelihood.
predict_latent_gp( model, x, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps), exposure = NULL, quadrature_order = 40L, block_size = NULL )predict_latent_gp( model, x, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps), exposure = NULL, quadrature_order = 40L, block_size = NULL )
model |
A fitted |
x |
Numeric vector or matrix of prediction inputs. |
interval_level |
Probability level of the latent credible intervals. |
include_covariance |
If |
variance_tolerance |
Relative tolerance used when deciding whether a small negative posterior variance is floating-point error or a material numerical failure. |
exposure |
Optional positive exposure of the new responses for Poisson likelihoods: one value or one per prediction input. It defaults to 1. |
quadrature_order |
Number of Gauss-Hermite nodes for predictive
integrals without a closed form ( |
block_size |
Number of prediction inputs processed together when
|
Under the Laplace approximation the latent values at new inputs are Gaussian (Rasmussen and Williams, 2006, Algorithm 3.2), with
where , , and
. The predictive distribution of a new response
integrates the likelihood against this Gaussian with
likelihood_predictive().
An object of class gaussianprocesses_latent_prediction with the
shared latent fields of predict_gp(), x, mean, latent_variance,
latent_sd, interval_level, and latent_interval (and
latent_covariance with include_covariance = TRUE), and the
predictive distribution of a new response: response_mean,
response_variance, probability and
probability_interval for Bernoulli likelihoods, rate_interval,
prediction_interval, and exposure for Poisson likelihoods, and
prediction_interval for Gaussian likelihoods. A non-Gaussian response
has no observation-noise variance, so the observation fields of
predict_gp() are replaced by these; prediction_interval has its
meaning there, an interval for a new response.
For a Bernoulli likelihood, probability is
for the response coded 1: the second level of a factor response
(model$response_levels), or TRUE. It averages the link over the
latent posterior,
which for the probit link is
exactly and for the logistic link is computed by Gauss-Hermite
quadrature. It is not : the plug-in probability ignores
the latent uncertainty and is too confident, by up to 0.04 at
and 0.11 at . MacKay's
approximation with
is closer but still off by
up to 0.005 at and 0.01 at , so
it is not used.
probability_interval describes the uncertainty of the class probability
itself: because the link is increasing, the
interval_level quantiles of are the link applied to the
latent interval, exactly under the Gaussian approximation. Joint
uncertainty, for example of a difference of probabilities, comes from
the probability draws of sample_gp_posterior().
Multi-class (softmax) classification is not supported.
For a Poisson likelihood the rate is
lognormal: its mean is
(response_mean, also the mean of the count) and its quantiles are
exactly, because the exponential is
increasing (rate_interval). A new count has the Poisson-lognormal
predictive distribution; prediction_interval gives its equal-tailed
quantiles at interval_level, computed by quadrature
(gp_count_scores()). Counts are discrete, so these intervals cover at
least interval_level: their coverage is conservative.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
fit_latent_gp(), sample_gp_posterior().
x <- seq(-3, 3, length.out = 30) y <- as.numeric(sin(x) + 0.3 * cos(5 * x) > 0) model <- fit_latent_gp(x, y, rbf_kernel(variance = 4), bernoulli_likelihood()) prediction <- predict_latent_gp(model, c(-2, 0, 2, 6)) # Far from the data the latent variance grows and the probability moves # towards 1/2, unlike the logistic function of the latent mean. cbind(prediction$probability, plogis(prediction$mean))x <- seq(-3, 3, length.out = 30) y <- as.numeric(sin(x) + 0.3 * cos(5 * x) > 0) model <- fit_latent_gp(x, y, rbf_kernel(variance = 4), bernoulli_likelihood()) prediction <- predict_latent_gp(model, c(-2, 0, 2, 6)) # Far from the data the latent variance grows and the probability moves # towards 1/2, unlike the logistic function of the latent mean. cbind(prediction$probability, plogis(prediction$mean))
Computes the posterior of the latent function and of new observations
under a FITC or VFE model (fit_sparse_gp()).
predict_sparse_gp( model, x, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps), observation_noise_variance = NULL, block_size = NULL )predict_sparse_gp( model, x, interval_level = 0.95, include_covariance = FALSE, variance_tolerance = sqrt(.Machine$double.eps), observation_noise_variance = NULL, block_size = NULL )
model |
A fitted sparse GP model. |
x |
Numeric vector or matrix of prediction inputs. |
interval_level |
Probability level for intervals. |
include_covariance |
If |
variance_tolerance |
Relative tolerance for posterior variances. |
observation_noise_variance |
Optional prediction-time observation-noise variance. Required when the sparse model was fitted with observation- specific training noise. |
block_size |
Number of prediction inputs processed together when
|
With , where
is the FITC diagonal or, for VFE, the noise, the latent
posterior at new inputs is
computed through the Cholesky factors of and
. For VFE these are the predictive
equations of the deterministic training conditional.
An object of class gaussianprocesses_sparse_prediction, with the
shared prediction fields of predict_gp() and approximation.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
x <- seq(-3, 3, length.out = 200) y <- sin(x) + 0.1 * cos(7 * x) kernel <- rbf_kernel(length_scale = 0.8) sparse <- fit_sparse_gp(x, y, kernel, noise_variance = 0.01, n_inducing = 15) exact <- fit_gp(x, y, kernel, noise_variance = 0.01) x_new <- c(-1, 0, 1) cbind( exact = predict_gp(exact, x_new)$mean, sparse = predict_sparse_gp(sparse, x_new)$mean )x <- seq(-3, 3, length.out = 200) y <- sin(x) + 0.1 * cos(7 * x) kernel <- rbf_kernel(length_scale = 0.8) sparse <- fit_sparse_gp(x, y, kernel, noise_variance = 0.01, n_inducing = 15) exact <- fit_gp(x, y, kernel, noise_variance = 0.01) x_new <- c(-1, 0, 1) cbind( exact = predict_gp(exact, x_new)$mean, sparse = predict_sparse_gp(sparse, x_new)$mean )
The covariance matrices generated by all supplied kernels are multiplied element-wise.
product_kernel(...)product_kernel(...)
... |
Two or more Gaussian-process kernel specifications. |
A composite kernel specification.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
# A locally periodic kernel: a periodic pattern whose shape drifts slowly. kernel <- product_kernel( periodic_kernel(period = 12), rbf_kernel(length_scale = 24) ) evaluate_kernel(kernel, c(0, 12, 48))[1, ]# A locally periodic kernel: a periodic pattern whose shape drifts slowly. kernel <- product_kernel( periodic_kernel(period = 12), rbf_kernel(length_scale = 24) ) evaluate_kernel(kernel, c(0, 12, 48))[1, ]
Create a rational-quadratic kernel specification
rational_quadratic_kernel(variance = 1, length_scale = 1, alpha = 1)rational_quadratic_kernel(variance = 1, length_scale = 1, alpha = 1)
variance |
Positive marginal variance. |
length_scale |
Positive scalar or numeric vector. A vector supplies one ARD length scale per input dimension and is validated against the data when the kernel is evaluated. |
alpha |
Positive scale-mixture parameter. |
An object of class gaussianprocesses_kernel.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel_rational_quadratic() computes the same covariance
directly from parameter values, without a kernel specification.
kernel <- rational_quadratic_kernel(length_scale = 0.8, alpha = 2) evaluate_kernel(kernel, c(0, 0.5, 1))kernel <- rational_quadratic_kernel(length_scale = 0.8, alpha = 2) evaluate_kernel(kernel, c(0, 0.5, 1))
Kernel specifications are reusable objects that store covariance parameters separately from the observations on which they are evaluated. They are the building blocks for composite kernels and later Gaussian-process fitting.
rbf_kernel(variance = 1, length_scale = 1)rbf_kernel(variance = 1, length_scale = 1)
variance |
Positive marginal variance. |
length_scale |
Positive scalar or numeric vector. A vector supplies one ARD length scale per input dimension and is validated against the data when the kernel is evaluated. |
An object of class gaussianprocesses_kernel.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel_rbf() computes the same covariance directly from
parameter values, without a kernel specification.
kernel <- rbf_kernel(variance = 1.5, length_scale = c(0.5, 2)) kernel evaluate_kernel(kernel, cbind(c(0, 1), c(0, 1)))kernel <- rbf_kernel(variance = 1.5, length_scale = c(0.5, 2)) kernel evaluate_kernel(kernel, cbind(c(0, 1), c(0, 1)))
Performs expanding-window rolling-origin evaluation with fixed kernel and noise hyperparameters. Each split is fitted using only observations available at that origin, preventing look-ahead leakage.
rolling_origin_gp( time, y, kernel, initial_window, horizon = 1L, step = 1L, noise_variance = 1e-06, mean = zero_mean(), unit = "auto", interval_level = 0.95, ... )rolling_origin_gp( time, y, kernel, initial_window, horizon = 1L, step = 1L, noise_variance = 1e-06, mean = zero_mean(), unit = "auto", interval_level = 0.95, ... )
time |
Numeric, Date, or POSIXt vector in strictly increasing order. |
y |
Numeric response vector. |
kernel |
Fixed Gaussian-process kernel specification. |
initial_window |
Number of observations in the first training window. |
horizon |
Number of future observations predicted at each origin. |
step |
Number of observations between consecutive origins. |
noise_variance |
Non-negative observation-noise variance: a scalar, or one value per observation. With one value per observation, each training window uses the values of its rows and each forecast uses the values of its target rows. |
mean |
Gaussian-process mean specification. |
unit |
Time unit passed to |
interval_level |
Probability level for prediction intervals. |
... |
Additional arguments passed to |
Fixed hyperparameters prevent future observations from influencing earlier origins through repeated whole-series hyperparameter tuning. Hyperparameters can be selected separately using an appropriate training period.
A data frame with class gaussianprocesses_backtest.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
time <- 0:23 y <- sin(2 * pi * time / 12) backtest <- rolling_origin_gp( time, y, kernel = time_series_kernel(period = 12), initial_window = 12, horizon = 3, step = 3, noise_variance = 0.05 ) head(backtest[, c("origin_index", "horizon", "observed", "mean", "covered")])time <- 0:23 y <- sin(2 * pi * time / 12) backtest <- rolling_origin_gp( time, y, kernel = time_series_kernel(period = 12), initial_window = 12, horizon = 3, step = 3, noise_variance = 0.05 ) head(backtest[, c("origin_index", "horizon", "observed", "mean", "covered")])
Runs seeded synthetic scenarios through exact and FITC regression. Accuracy, performance, and numerical stability are returned as separate tables so faster execution is never conflated with better numerical agreement.
run_gp_benchmark_suite( scenarios = c("smooth_1d", "near_singular", "ard_2d", "heteroscedastic_1d"), n = 60L, n_inducing = 15L, repeats = 3L, seed = 1729L )run_gp_benchmark_suite( scenarios = c("smooth_1d", "near_singular", "ard_2d", "heteroscedastic_1d"), n = 60L, n_inducing = 15L, repeats = 3L, seed = 1729L )
scenarios |
Character vector of standard scenario names. |
n |
Number of observations per scenario. |
n_inducing |
Number of FITC inducing points. |
repeats |
Number of timing repetitions. Medians are reported. |
seed |
Base non-negative integer seed. Scenario-specific offsets are applied deterministically. |
Timing results use median elapsed wall-clock time and are intended for
local comparison, not CI gating. Retained memory is measured with
utils::object.size() and is not a peak-allocation measurement.
The exact Gaussian process is used as the numerical reference when assessing FITC approximation error. Synthetic scenarios also retain their latent draw so both exact and sparse posterior means can be compared against the same known simulation truth.
An object of class gaussianprocesses_benchmark_suite containing
separate accuracy, performance, and stability data frames.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
# A deliberately small run; see inst/benchmarks/run-suite.R for a full one. suite <- run_gp_benchmark_suite( scenarios = "smooth_1d", n = 30, n_inducing = 8, repeats = 1 ) suite$accuracy# A deliberately small run; see inst/benchmarks/run-suite.R for a full one. suite <- run_gp_benchmark_suite( scenarios = "smooth_1d", n = 30, n_inducing = 8, repeats = 1 ) suite$accuracy
Draws latent function values from the posterior of a fitted model and, optionally, noisy observations from the posterior predictive distribution.
## S3 method for class 'gaussianprocesses_latent_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), seed = NULL, exposure = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), ... ) sample_gp_posterior(model, x, n_draws = 1L, ...) ## Default S3 method: sample_gp_posterior(model, x, n_draws = 1L, ...) ## S3 method for class 'gaussianprocesses_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), observation_noise_variance = NULL, seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), ... ) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), ... ) ## S3 method for class 'gaussianprocesses_sparse_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), observation_noise_variance = NULL, seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), ... ) ## S3 method for class 'gaussianprocesses_state_space_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), observation_noise_variance = NULL, seed = NULL, ... )## S3 method for class 'gaussianprocesses_latent_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), seed = NULL, exposure = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), ... ) sample_gp_posterior(model, x, n_draws = 1L, ...) ## Default S3 method: sample_gp_posterior(model, x, n_draws = 1L, ...) ## S3 method for class 'gaussianprocesses_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), observation_noise_variance = NULL, seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), ... ) ## S3 method for class 'gaussianprocesses_heteroscedastic_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), ... ) ## S3 method for class 'gaussianprocesses_sparse_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), observation_noise_variance = NULL, seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps), ... ) ## S3 method for class 'gaussianprocesses_state_space_model' sample_gp_posterior( model, x, n_draws = 1L, type = c("latent", "observation"), observation_noise_variance = NULL, seed = NULL, ... )
model |
A fitted |
x |
Numeric vector or matrix of prediction inputs. For models fitted
with |
n_draws |
Number of independent draws. |
type |
|
seed |
Optional non-negative integer seed. The caller's random state is restored afterwards. |
exposure |
For latent Poisson models, optional exposure of the
observation draws, as in |
initial_jitter |
Non-negative jitter tried first, relative to the covariance scale (the mean of its diagonal). |
fallback_jitter |
Positive relative jitter tried after the first failed factorization. |
jitter_multiplier |
Multiplicative jitter escalation factor. |
max_attempts |
Maximum Cholesky attempts. |
symmetry_tolerance |
Relative tolerance for checking that the covariance matrix is symmetric. |
... |
Further arguments passed to methods. |
observation_noise_variance |
For exact and sparse models, optional
non-negative scalar or vector of noise variances at |
The posterior mean and latent covariance come from
predict_gp() (or predict_heteroscedastic_gp()), which uses triangular
solves with the fitted Cholesky factor; no covariance matrix is inverted.
Latent draws are with and
. Posterior covariances are often nearly
singular, for example at closely spaced or repeated inputs; the factor then
uses the package's jitter policy, and the jitter is reported.
Observation draws add independent noise,
with , so their covariance is
.
For heteroscedastic models, the latent draws come from the mean GP and the
noise variances are the plug-in estimates of
predict_heteroscedastic_gp(). The draws are therefore conditional on the
estimated noise function: uncertainty in the noise process is not
propagated, consistent with the approximation being a plug-in method rather
than full Bayesian inference.
For latent models, the latent draws come from the Gaussian (Laplace)
approximation of predict_latent_gp(), and observation draws are drawn
from the likelihood given each latent draw: Bernoulli, Poisson (with
exposure), or Gaussian responses. Their observation_noise_variance is
NULL. For Bernoulli likelihoods the samples also contain probability,
the class probability of each latent draw, whose mean over
draws is the predictive probability of predict_latent_gp(); for Poisson
likelihoods they contain rate, the rate of each latent
draw.
For sparse models (FITC or VFE, fit_sparse_gp()), the draws use the
sparse posterior covariance
of predict_sparse_gp() at
the sampling inputs. It costs time for
inducing points, and its factorization time and
memory, as for exact models. The number of inducing points
enters only through cross-covariances, so the limit is
the number of sampling inputs, a few thousand, rather than .
Observation draws need observation_noise_variance for models fitted with
observation-specific noise.
An object of class gaussianprocesses_samples with one row per
input point and one column per draw in latent and, for
type = "observation", in observation. It also contains the posterior
mean, the latent_covariance that was sampled, the
observation_noise_variance used for observation draws, the numerical
jitter with its relative_jitter and covariance_scale, and the
cholesky_attempts.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
x <- c(-2, -1, 0, 1.5) y <- sin(2 * x) model <- fit_gp(x, y, rbf_kernel(length_scale = 0.7), noise_variance = 0.01) x_new <- seq(-3, 3, length.out = 100) draws <- sample_gp_posterior(model, x_new, n_draws = 5, seed = 1) draws matplot(x_new, draws$latent, type = "l", lty = 1, ylab = "f(x)") points(x, y, pch = 19) # Noisy observation draws are generated from the same latent draws. noisy <- sample_gp_posterior( model, x_new, n_draws = 1, type = "observation", seed = 2 ) head(cbind(latent = noisy$latent[, 1], observation = noisy$observation[, 1]))x <- c(-2, -1, 0, 1.5) y <- sin(2 * x) model <- fit_gp(x, y, rbf_kernel(length_scale = 0.7), noise_variance = 0.01) x_new <- seq(-3, 3, length.out = 100) draws <- sample_gp_posterior(model, x_new, n_draws = 5, seed = 1) draws matplot(x_new, draws$latent, type = "l", lty = 1, ylab = "f(x)") points(x, y, pch = 19) # Noisy observation draws are generated from the same latent draws. noisy <- sample_gp_posterior( model, x_new, n_draws = 1, type = "observation", seed = 2 ) head(cbind(latent = noisy$latent[, 1], observation = noisy$observation[, 1]))
Draws latent function values
at the supplied inputs. Use simulate_gp_data() for a single prior draw
with added observation noise.
sample_gp_prior( x, kernel, mean = zero_mean(), n_draws = 1L, seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )sample_gp_prior( x, kernel, mean = zero_mean(), n_draws = 1L, seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )
x |
Numeric vector or matrix of inputs. Matrix rows are input points. |
kernel |
A Gaussian-process kernel specification, including ARD and composite kernels. |
mean |
Gaussian-process mean specification. Its coefficients must
be fixed or have a Gaussian |
n_draws |
Number of independent function draws. |
seed |
Optional non-negative integer seed. The caller's random state is restored afterwards. |
initial_jitter |
Non-negative jitter tried first, relative to the covariance scale (the mean of its diagonal). |
fallback_jitter |
Positive relative jitter tried after the first failed factorization. |
jitter_multiplier |
Multiplicative jitter escalation factor. |
max_attempts |
Maximum Cholesky attempts. |
symmetry_tolerance |
Relative tolerance for checking that the covariance matrix is symmetric. |
Each draw is with and
. Prior covariances on closely spaced inputs
are often numerically singular; the Cholesky factor then uses the package's
jitter policy, and the jitter is reported in the result. A single draw
with the same seed equals the latent values of simulate_gp_data().
An object of class gaussianprocesses_samples. Its latent
element is a matrix with one row per input point and one column per draw.
It also contains the prior mean, the latent_covariance that was
sampled, the numerical jitter, the relative_jitter and
covariance_scale it was computed from (jitter is relative jitter times
the mean diagonal of the covariance), and the cholesky_attempts.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
x <- seq(0, 5, length.out = 100) draws <- sample_gp_prior(x, rbf_kernel(length_scale = 0.8), n_draws = 3, seed = 1) draws matplot(x, draws$latent, type = "l", lty = 1, ylab = "f(x)")x <- seq(0, 5, length.out = 100) draws <- sample_gp_prior(x, rbf_kernel(length_scale = 0.8), n_draws = 3, seed = 1) draws matplot(x, draws$latent, type = "l", lty = 1, ylab = "f(x)")
Multiplies a covariance kernel by a positive scalar. The scalar is retained as a named parameter and can therefore be optimized together with parameters of nested kernels.
scale_kernel(kernel, scale = 1)scale_kernel(kernel, scale = 1)
kernel |
A Gaussian-process kernel specification. |
scale |
Positive scalar multiplier. |
A composite kernel specification.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel <- scale_kernel(rbf_kernel(), scale = 3) all.equal( evaluate_kernel(kernel, 1:3), 3 * evaluate_kernel(rbf_kernel(), 1:3) )kernel <- scale_kernel(rbf_kernel(), scale = 3) all.equal( evaluate_kernel(kernel, 1:3), 3 * evaluate_kernel(rbf_kernel(), 1:3) )
Makes a kernel act on some input columns only:
for the selected columns . Sums of
restricted kernels give additive models such as
.
select_dimensions(kernel, columns)select_dimensions(kernel, columns)
kernel |
A Gaussian-process kernel specification. |
columns |
Positive integer indices of the input columns the kernel acts on, without duplicates. |
A restricted kernel is positive semidefinite whenever kernel is, because
it is kernel composed with a linear projection. A sum
is the covariance of
with independent components .
The selection is not a hyperparameter. It adds no parameter and no level
to parameter paths: select_dimensions(rbf_kernel(), 2) has the paths
variance and length_scale, like rbf_kernel(). ARD parameters of
kernel have one value per selected column.
Columns index the inputs the kernel receives. The number of input columns is not known when a specification is built, so column indices and ARD lengths are checked when the kernel is evaluated and when a model is fitted. Derivatives with respect to unselected input columns are zero.
A composite kernel specification.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
# An additive model f(x) = f1(x1) + f2(x2, x3). kernel <- sum_kernel( select_dimensions(rbf_kernel(length_scale = 0.5), 1), select_dimensions(matern52_kernel(length_scale = c(1, 2)), 2:3) ) kernel names(kernel_parameters(kernel, flatten = TRUE)) x <- cbind(c(0, 0.5, 1), c(1, 0, -1), c(2, 2, 0)) all.equal( evaluate_kernel(kernel, x), evaluate_kernel(rbf_kernel(length_scale = 0.5), x[, 1]) + evaluate_kernel(matern52_kernel(length_scale = c(1, 2)), x[, 2:3]) )# An additive model f(x) = f1(x1) + f2(x2, x3). kernel <- sum_kernel( select_dimensions(rbf_kernel(length_scale = 0.5), 1), select_dimensions(matern52_kernel(length_scale = c(1, 2)), 2:3) ) kernel names(kernel_parameters(kernel, flatten = TRUE)) x <- cbind(c(0, 0.5, 1), c(1, 0, -1), c(2, 2, 0)) all.equal( evaluate_kernel(kernel, x), evaluate_kernel(rbf_kernel(length_scale = 0.5), x[, 1]) + evaluate_kernel(matern52_kernel(length_scale = c(1, 2)), x[, 2:3]) )
Select inducing points deterministically
select_inducing_points( x, n_inducing, method = c("farthest", "quantile", "variance"), kernel = NULL )select_inducing_points( x, n_inducing, method = c("farthest", "quantile", "variance"), kernel = NULL )
x |
Numeric vector or matrix of candidate inputs. |
n_inducing |
Number of inducing points to select. |
method |
Selection method. |
kernel |
Kernel specification, needed by |
Repeated input rows are offered as candidates only once, so the selected
inducing locations are always distinct. n_inducing therefore cannot
exceed the number of distinct rows in x.
Greedy conditional-variance selection (Burt, Rasmussen, and van der Wilk,
2019, 2020) adds, one at a time, the input whose prior variance is least
explained by the points chosen so far: the largest residual
with the Nyström approximation from the
chosen points. This is the pivot order of a pivoted Cholesky
decomposition of , computed incrementally without forming
in time and memory. It
minimizes the trace term greedily, so
it is the natural choice for VFE, whose bound loses half that trace over
the noise variance. If the prior variance is explained, to a relative
, before n_inducing points are chosen, the selection stops
with a warning of class gaussianprocesses_inducing_warning and returns
fewer points.
A numeric matrix with one inducing point per row. The selected
training-row indices are stored in the indices attribute.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Burt, D. R., Rasmussen, C. E., and van der Wilk, M. (2019). Rates of convergence for sparse variational Gaussian process regression. Proceedings of the 36th International Conference on Machine Learning, 862–871.
Burt, D. R., Rasmussen, C. E., and van der Wilk, M. (2020). Convergence of sparse variational inference in Gaussian processes regression. Journal of Machine Learning Research, 21(131), 1–63.
x <- seq(0, 10, length.out = 101) inducing <- select_inducing_points(x, n_inducing = 5, method = "quantile") inducing[, 1] attr(inducing, "indices")x <- seq(0, 10, length.out = 101) inducing <- select_inducing_points(x, n_inducing = 5, method = "quantile") inducing[, 1] attr(inducing, "indices")
Draws a latent Gaussian-process realization at supplied inputs and then adds independent Gaussian observation noise. The kernel, mean, noise variances, and numerical jitter used for simulation are retained in the result.
simulate_gp_data( x, kernel, mean = zero_mean(), noise_variance = 0, seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )simulate_gp_data( x, kernel, mean = zero_mean(), noise_variance = 0, seed = NULL, initial_jitter = 0, fallback_jitter = 1e-10, jitter_multiplier = 10, max_attempts = 8L, symmetry_tolerance = sqrt(.Machine$double.eps) )
x |
Numeric vector or matrix of simulation inputs. |
kernel |
Gaussian-process kernel specification. |
mean |
Gaussian-process mean specification. Its coefficients must
be fixed or have a Gaussian |
noise_variance |
Non-negative scalar or one non-negative value per observation. |
seed |
Optional non-negative integer seed. The caller's global random state is restored after simulation. |
initial_jitter |
Non-negative jitter tried first, relative to the covariance scale (the mean of its diagonal). |
fallback_jitter |
Positive relative jitter tried after the first failed factorization. |
jitter_multiplier |
Multiplicative jitter escalation factor. |
max_attempts |
Maximum Cholesky attempts. |
symmetry_tolerance |
Relative tolerance for checking that the covariance matrix is symmetric. |
An object of class gaussianprocesses_simulation.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
simulation <- simulate_gp_data( seq(0, 1, length.out = 30), kernel = rbf_kernel(length_scale = 0.2), noise_variance = 0.01, seed = 1 ) simulation head(cbind(latent = simulation$latent, observed = simulation$observed))simulation <- simulate_gp_data( seq(0, 1, length.out = 30), kernel = rbf_kernel(length_scale = 0.2), noise_variance = 0.01, seed = 1 ) simulation head(cbind(latent = simulation$latent, observed = simulation$observed))
A spectral-mixture kernel (Wilson and Adams, 2013) is a sum of
components with Gaussian spectral densities. With enough
components it approximates any stationary covariance.
spectral_mixture_kernel( n_components = 1L, weights = 1/n_components, frequencies = 0, spectral_variances = 1 )spectral_mixture_kernel( n_components = 1L, weights = 1/n_components, frequencies = 0, spectral_variances = 1 )
n_components |
Number of components |
weights |
Positive component weights |
frequencies |
Frequencies |
spectral_variances |
Positive spectral variances |
By Bochner's theorem a stationary kernel is the Fourier transform of a
non-negative spectral density. The spectral mixture uses
,
whose transform is
So . A component with is an RBF
kernel with variance and length scale
; a component with a small spectral
variance is a long-lived oscillation with period .
Each component is a kernel with parameters weight, frequency, and
spectral_variance, and the mixture is their sum_kernel(), so parameter
paths are kernel1.weight, kernel1.frequency, and so on; a single
component has no prefix. Frequencies are real-valued and optimized on the
identity scale, the others on the log scale. Because is even,
and give the same kernel. optimize_gp() bounds
every frequency by 0 and the Nyquist frequency of its
input column, with the smallest spacing between distinct
inputs, and displaces it in later starts by one frequency-resolution
bin, the reciprocal of the input range.
The likelihood is strongly multimodal: components can swap, merge, or
settle on harmonics. Start from the data's spectrum with
initialize_spectral_mixture(), and use several starts; the examples use
n_starts = 5.
A kernel specification: one spectral component, or the sum of
n_components of them.
Experimental: this interface may change in a minor release, and every change is listed in NEWS. See gaussianprocesses-package for the policy.
Wilson, A. G. and Adams, R. P. (2013). Gaussian process kernels for pattern discovery and extrapolation. Proceedings of the 30th International Conference on Machine Learning, 1067–1075.
initialize_spectral_mixture().
kernel <- spectral_mixture_kernel( n_components = 2, weights = c(1, 0.5), frequencies = c(0, 0.25), spectral_variances = c(0.01, 0.001) ) kernel # k(0) is the sum of the weights. evaluate_kernel(kernel, 0) # A component with frequency 0 is an RBF kernel. all.equal( evaluate_kernel(spectral_mixture_kernel(1, 2, 0, 1 / (4 * pi^2)), 0:3), evaluate_kernel(rbf_kernel(variance = 2, length_scale = 1), 0:3) )kernel <- spectral_mixture_kernel( n_components = 2, weights = c(1, 0.5), frequencies = c(0, 0.25), spectral_variances = c(0.01, 0.001) ) kernel # k(0) is the sum of the weights. evaluate_kernel(kernel, 0) # A component with frequency 0 is an RBF kernel. all.equal( evaluate_kernel(spectral_mixture_kernel(1, 2, 0, 1 / (4 * pi^2)), 0:3), evaluate_kernel(rbf_kernel(variance = 2, length_scale = 1), 0:3) )
The covariance matrices generated by all supplied kernels are added element-wise.
sum_kernel(...)sum_kernel(...)
... |
Two or more Gaussian-process kernel specifications. |
A composite kernel specification.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel <- sum_kernel(linear_kernel(variance = 0.1), periodic_kernel(period = 12)) kernel names(kernel_parameters(kernel, flatten = TRUE))kernel <- sum_kernel(linear_kernel(variance = 0.1), periodic_kernel(period = 12)) kernel names(kernel_parameters(kernel, flatten = TRUE))
Constructs a transparent additive example consisting of a nonstationary linear covariance component, a periodic covariance component, and a local Matérn-3/2 component. The components are explicit so stationarity is never implied for the full model.
time_series_kernel( period, trend_variance = 1, periodic_variance = 1, periodic_length_scale = 1, local_variance = 1, local_length_scale = 1, changepoint = NULL, changepoint_steepness = 1 )time_series_kernel( period, trend_variance = 1, periodic_variance = 1, periodic_length_scale = 1, local_variance = 1, local_length_scale = 1, changepoint = NULL, changepoint_steepness = 1 )
period |
Positive period in the same units as the time index. |
trend_variance |
Positive variance of the linear trend component. |
periodic_variance |
Positive variance of the periodic component. |
periodic_length_scale |
Positive periodic length scale. |
local_variance |
Positive variance of the local Matérn component. |
local_length_scale |
Positive local Matérn length scale. |
changepoint |
Optional location of a structural break, on the time
index scale of |
changepoint_steepness |
Positive steepness of the break. |
With a changepoint, the kernel is a changepoint_kernel() between two
independent copies of the trend-periodic-local kernel, so every component
can change at the break; the copies start from the same parameter values
and are estimated separately. To place a break at a date, convert it with
the training times: gp_time_index(c(time[1], date), unit)[2].
A composite gaussianprocesses_kernel.
Stable: from version 1.0.0 this interface changes incompatibly only in a
major release, after a deprecation period. Results and options that
concern an experimental model class, kernel, or argument follow that
interface's tier. See gaussianprocesses-package for the
policy. The changepoint argument, which builds a changepoint_kernel(), is experimental.
kernel <- time_series_kernel(period = 12) kernel # A structural break 30 time units after the first observation. names(kernel_parameters( time_series_kernel(period = 12, changepoint = 30), flatten = TRUE ))kernel <- time_series_kernel(period = 12) kernel # A structural break 30 time units after the first observation. names(kernel_parameters( time_series_kernel(period = 12, changepoint = 30), flatten = TRUE ))
Parameters are identified by the names returned by
kernel_parameters(kernel, flatten = TRUE). Partial updates are supported,
which allows an optimizer or tuning routine to modify selected parameters
without manually unpacking nested kernel objects.
update_kernel_parameters(kernel, parameters)update_kernel_parameters(kernel, parameters)
kernel |
A Gaussian-process kernel specification. |
parameters |
Named numeric vector of parameter updates. |
A new kernel specification with updated parameters.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel <- sum_kernel( rbf_kernel(length_scale = c(1, 2)), white_noise_kernel(variance = 0.1) ) updated <- update_kernel_parameters( kernel, c("kernel1.length_scale[2]" = 5, "kernel2.variance" = 0.01) ) kernel_parameters(updated, flatten = TRUE)kernel <- sum_kernel( rbf_kernel(length_scale = c(1, 2)), white_noise_kernel(variance = 0.1) ) updated <- update_kernel_parameters( kernel, c("kernel1.length_scale[2]" = 5, "kernel2.variance" = 0.01) ) kernel_parameters(updated, flatten = TRUE)
Create a white-noise kernel specification
white_noise_kernel(variance = 1)white_noise_kernel(variance = 1)
variance |
Positive white-noise variance. |
An object of class gaussianprocesses_kernel.
Stable: from version 1.0.0 this interface changes incompatibly only in a major release, after a deprecation period. Results and options that concern an experimental model class, kernel, or argument follow that interface's tier. See gaussianprocesses-package for the policy.
kernel_white_noise() computes the same covariance directly from
parameter values, without a kernel specification.
# Add an independent nugget to a smooth kernel. kernel <- sum_kernel(rbf_kernel(), white_noise_kernel(variance = 0.05)) evaluate_kernel(kernel, c(0, 0.5))# Add an independent nugget to a smooth kernel. kernel <- sum_kernel(rbf_kernel(), white_noise_kernel(variance = 0.05)) evaluate_kernel(kernel, c(0, 0.5))