bask.BayesGPR

class bask.BayesGPR(kernel=None, alpha=1e-10, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, normalize_y=False, warp_inputs=False, copy_X_train=True, random_state=None, noise='gaussian')[source]

Gaussian process regressor of which the kernel hyperparameters are inferred in a fully Bayesian framework.

The implementation is based on Algorithm 2.1 of Gaussian Processes for Machine Learning (GPML) by Rasmussen and Williams.

In addition to standard scikit-learn estimator API, GaussianProcessRegressor:
  • allows prediction without prior fitting (based on the GP prior);

  • provides an additional method sample_y(X), which evaluates samples drawn from the GPR (prior or posterior or hyper-posterior) at given inputs;

  • exposes a method log_marginal_likelihood(theta), which can be used externally for other ways of selecting hyperparameters, e.g., via Markov chain Monte Carlo.

  • allows setting the kernel hyperparameters while correctly recalculating the required matrices

  • exposes a method noise_set_to_zero() which can be used as a context manager to temporarily set the prediction noise to zero. This is useful for evaluating acquisition functions for Bayesian optimization

Parameters:
kernelkernel object

The kernel specifying the covariance function of the GP. If None is passed, the kernel “1.0 * RBF(1.0)” is used as default. Note that the kernel’s hyperparameters are set to the geometric median of the Markov chain Monte Carlo samples of the posterior.

alphafloat or array-like, optional (default: 1e-10)

Value added to the diagonal of the kernel matrix during fitting. Larger values correspond to increased noise level in the observations. This can also prevent a potential numerical issue during fitting, by ensuring that the calculated values form a positive definite matrix. If an array is passed, it must have the same number of entries as the data used for fitting and is used as datapoint-dependent noise level. Note that this is equivalent to adding a WhiteKernel with c=alpha. Allowing to specify the noise level directly as a parameter is mainly for convenience and for consistency with Ridge. Also note, that this class adds a WhiteKernel automatically if noise is set.

optimizerstring or callable, optional (default: “fmin_l_bfgs_b”)

Can either be one of the internally supported optimizers for optimizing the kernel’s parameters, specified by a string, or an externally defined optimizer passed as a callable. If a callable is passed, it must have the signature:

def optimizer(obj_func, initial_theta, bounds):
    # * 'obj_func' is the objective function to be minimized, which
    #   takes the hyperparameters theta as parameter and an
    #   optional flag eval_gradient, which determines if the
    #   gradient is returned additionally to the function value
    # * 'initial_theta': the initial value for theta, which can be
    #   used by local optimizers
    # * 'bounds': the bounds on the values of theta
    ....
    # Returned are the best found hyperparameters theta and
    # the corresponding value of the target function.
    return theta_opt, func_min

Per default, the ‘fmin_l_bfgs_b’ algorithm from scipy.optimize is used. If None is passed, the kernel’s parameters are kept fixed. Available internal optimizers are:

'fmin_l_bfgs_b'

Note, that the kernel hyperparameters obtained are only used as the initial position of the Markov chain and will be discarded afterwards.

n_restarts_optimizerint, optional (default: 0)

The number of restarts of the optimizer for finding the kernel’s parameters which maximize the log-marginal likelihood. The first run of the optimizer is performed from the kernel’s initial parameters, the remaining ones (if any) from thetas sampled log-uniform randomly from the space of allowed theta-values. If greater than 0, all bounds must be finite. Note that n_restarts_optimizer == 0 implies that one run is performed.

normalize_yboolean, optional (default: False)

Whether the target values y are normalized, i.e., the mean of the observed target values become zero. This parameter should be set to True if the target values’ mean is expected to differ considerable from zero. When enabled, the normalization effectively modifies the GP’s prior based on the data, which contradicts the likelihood principle.

warp_inputsboolean, optional (default: False)

If True, each input dimension will be warped (internally) using the cumulative distribution function of a beta distribution [1]. The parameters of each beta distribution will be inferred from the data. The input data needs to be in [0, 1].

copy_X_trainbool, optional (default: True)

If True, a persistent copy of the training data is stored in the object. Otherwise, just a reference to the training data is stored, which might cause predictions to change if the data is modified externally.

random_stateint, RandomState instance or None, optional (default: None)

The generator used to initialize the centers. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.

noisestring, optional (default: “gaussian”)

If set to “gaussian”, then it is assumed that y is a noisy estimate of f(x) where the noise is gaussian. A WhiteKernel will be added to the provided kernel.

References

[1]

Snoek, Jasper, Kevin Swersky, Richard Zemel, and Ryan P. Adams. “Input Warping for Bayesian Optimization of Non-Stationary Functions.” In Proceedings of the 31st International Conference on International Conference on Machine Learning - Volume 32, II–1674–II–1682. ICML’14. Beijing, China: JMLR.org, 2014.

Attributes:
X_train_array-like, shape = (n_samples, n_features)

The training data which was used to train the Gaussian process.

y_train_array-like, shape = (n_samples, [n_output_dims])

Target values in training data (also required for prediction)

kernel_kernel object

The kernel used for prediction. The structure of the kernel is the same as the one passed as parameter but with optimized hyperparameters

L_array-like, shape = (n_samples, n_samples)

Lower-triangular Cholesky decomposition of the kernel in X_train_

alpha_array-like, shape = (n_samples,)

Dual coefficients of training data points in kernel space

log_marginal_likelihood_value_float

The log-marginal-likelihood of self.kernel_.theta

noise_float

Estimate of the gaussian noise. Useful only when noise is set to “gaussian”.

chain_array-like, shape = (n_desired_samples, n_hyperparameters)

Samples from the posterior distribution of the hyperparameters.

pos_array-like, shape = (n_walkers, n_hyperparameters)

Last position of the Markov chain. Useful for continuing sampling when new datapoints arrive. fit(X, y) internally uses an existing pos_ to resume sampling, if no other position is provided.

Methods

create_warpers(alphas, betas)

Create Beta CDFs and inverse CDFs for input (un)warping.

fit(X, y[, noise_vector, n_threads, ...])

Fit the Gaussian process model to the given training data.

get_metadata_routing()

Get metadata routing of this object.

get_params([deep])

Get parameters for this estimator.

log_marginal_likelihood([theta, ...])

Return log-marginal likelihood of theta for training data.

noise_set_to_zero()

Context manager in which the noise of the Gaussian process is 0.

predict(X[, return_std, return_cov, ...])

Predict output for X.

rewarp()

Apply warping again to X_train_ after parameters have changed.

sample([X, y, noise_vector, n_threads, ...])

Sample from the posterior distribution of the hyper-parameters.

sample_y(X[, sample_mean, noise, n_samples, ...])

Sample function realizations of the Gaussian process.

score(X, y[, sample_weight])

Return the coefficient of determination of the prediction.

set_fit_request(*[, n_burnin, ...])

Request metadata passed to the fit method.

set_params(**params)

Set the parameters of this estimator.

set_predict_request(*[, return_cov, ...])

Request metadata passed to the predict method.

set_score_request(*[, sample_weight])

Request metadata passed to the score method.

unwarp(X)

Unwarp the input X back to the original input space.

warp(X)

Warp the input X using the existing warpers.

__init__(kernel=None, alpha=1e-10, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, normalize_y=False, warp_inputs=False, copy_X_train=True, random_state=None, noise='gaussian')[source]
property X_train_

The training data which was used to train the Gaussian process.

If input warping is used, it will return the warped instances.

Returns:
array-like, shape = (n_samples, n_features)

Feature values in training data (also required for prediction). If warp_inputs=True, will contain the warped inputs in [0, 1].

create_warpers(alphas, betas)[source]

Create Beta CDFs and inverse CDFs for input (un)warping.

Parameters:
alphasndarray, shape (n_dims)

Raw alpha parameters of the Beta distributions in log-space.

betasndarray, shape (n_dims)

Raw beta parameters of the Beta distributions in log-space.

fit(X, y, noise_vector=None, n_threads=1, n_desired_samples=100, n_burnin=10, n_walkers_per_thread=100, progress=True, priors=None, warp_priors=None, position=None, **kwargs)[source]

Fit the Gaussian process model to the given training data.

Parameters:
Xndarray, shape (n_points, n_dims)

Points at which the function is evaluated. If None, it will use the saved datapoints.

yndarray, shape (n_points,)

Value(s) of the function at X. If None, it will use the saved values.

noise_vector

Variance(s) of the function at X. If None, no additional noise is applied.

n_threadsint, optional (default: 1)

Number of threads to use during inference. This is currently not implemented.

n_desired_samplesint, optional (default: 100)

Number of hyperposterior samples to collect during inference. Must be a multiple of n_walkers_per_thread.

n_burninint, optional (default: 0)

Number of iterations to discard before collecting hyperposterior samples. Needs to be increased only, if the hyperposterior samples have not reached their typical set yet. Higher values increase the running time.

n_walkers_per_threadint, optional (default: 100)

Number of MCMC ensemble walkers to employ during inference.

progressbool, optional (default: False)

If True, show a progress bar during inference.

priorslist or callable, optional (default: None)

Log prior(s) for the kernel hyperparameters. Remember that the kernel hyperparameters are transformed into log space. Thus your priors need to perform the necessary change-of-variables.

positionndarray, shape (n_walkers, n_kernel_dims), optional (default: None)

Starting position of the Markov chain. If None, it will use the current position. If this is None as well, it will try to initialize in a small ball.

kwargsdict

Additional keyword arguments for BayesGPR.sample

get_metadata_routing()

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:
routingMetadataRequest

A MetadataRequest encapsulating routing information.

get_params(deep=True)

Get parameters for this estimator.

Parameters:
deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:
paramsdict

Parameter names mapped to their values.

log_marginal_likelihood(theta=None, eval_gradient=False, clone_kernel=True)

Return log-marginal likelihood of theta for training data.

Parameters:
thetaarray-like of shape (n_kernel_params,) default=None

Kernel hyperparameters for which the log-marginal likelihood is evaluated. If None, the precomputed log_marginal_likelihood of self.kernel_.theta is returned.

eval_gradientbool, default=False

If True, the gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta is returned additionally. If True, theta must not be None.

clone_kernelbool, default=True

If True, the kernel attribute is copied. If False, the kernel attribute is modified, but may result in a performance improvement.

Returns:
log_likelihoodfloat

Log-marginal likelihood of theta for training data.

log_likelihood_gradientndarray of shape (n_kernel_params,), optional

Gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta. Only returned when eval_gradient is True.

noise_set_to_zero()[source]

Context manager in which the noise of the Gaussian process is 0.

This is useful when you want to predict the epistemic uncertainty of the Gaussian process without the noise.

predict(X, return_std=False, return_cov=False, return_mean_grad=False, return_std_grad=False)[source]

Predict output for X.

In addition to the mean of the predictive distribution, also its standard deviation (return_std=True) or covariance (return_cov=True), the gradient of the mean and the standard-deviation with respect to X can be optionally provided.

Parameters:
Xarray-like, shape = (n_samples, n_features)

Query points where the GP is evaluated.

return_stdbool, default: False

If True, the standard-deviation of the predictive distribution at the query points is returned along with the mean.

return_covbool, default: False

If True, the covariance of the joint predictive distribution at the query points is returned along with the mean.

return_mean_gradbool, default: False

Whether or not to return the gradient of the mean. Only valid when X is a single point.

return_std_gradbool, default: False

Whether or not to return the gradient of the std. Only valid when X is a single point.

Returns:
y_meanarray, shape = (n_samples, [n_output_dims])

Mean of predictive distribution a query points

y_stdarray, shape = (n_samples,), optional

Standard deviation of predictive distribution at query points. Only returned when return_std is True.

y_covarray, shape = (n_samples, n_samples), optional

Covariance of joint predictive distribution a query points. Only returned when return_cov is True.

y_mean_gradshape = (n_samples, n_features)

The gradient of the predicted mean

y_std_gradshape = (n_samples, n_features)

The gradient of the predicted std.

rewarp()[source]

Apply warping again to X_train_ after parameters have changed.

Does nothing if warp_inputs=False or if no warpers have been fit yet.

sample(X=None, y=None, noise_vector=None, n_threads=1, n_desired_samples=100, n_burnin=0, n_thin=1, n_walkers_per_thread=100, progress=False, priors=None, warp_priors=None, position=None, add=False, **kwargs)[source]

Sample from the posterior distribution of the hyper-parameters.

Parameters:
Xndarray, shape (n_points, n_dims), optional (default: None)

Points at which the function is evaluated. If None, it will use the saved datapoints.

yndarray, shape (n_points,), optional (default: None)

Value(s) of the function at X. If None, it will use the saved values.

noise_vector

Variance(s) of the function at X. If None, no additional noise is applied.

n_threadsint, optional (default: 1)

Number of threads to use during inference. This is currently not implemented.

n_desired_samplesint, optional (default: 100)

Number of hyperposterior samples to collect during inference. Must be a multiple of n_walkers_per_thread.

n_burninint, optional (default: 0)

Number of iterations to discard before collecting hyperposterior samples. Needs to be increased only, if the hyperposterior samples have not reached their typical set yet. Higher values increase the running time.

n_thinint, optional (default: 1)

Only collect hyperposterior samples every k-th iteration. This can help reducing the autocorrelation of the collected samples, but reduces the total number of samples.

n_walkers_per_threadint, optional (default: 100)

Number of MCMC ensemble walkers to employ during inference.

progressbool, optional (default: False)

If True, show a progress bar during inference.

priorslist or callable, optional (default: None)

Log prior(s) for the kernel hyperparameters. Remember that the kernel hyperparameters are transformed into log space. Thus your priors need to perform the necessary change-of-variables.

warp_priorslist or callable, optional (default: None)

Log prior(s) for the parameters of the Beta distribution used to warp each dimension. Only used, if warp_inputs=True. By default uses a log-normal distribution with mean 0 and standard deviation of 0.5 for each parameter of the Beta distribution. This prior favors the identity transformation and sufficient data is needed to shift towards a stronger warping function.

positionndarray, shape (n_walkers, n_kernel_dims), optional (default: None)

Starting position of the Markov chain. If None, it will use the current position. If this is None as well, it will try to initialize in a small ball.

addbool, optional (default: False)

If True, all collected hyperposterior samples will be added to the existing samples in BayesGPR.chain_. Otherwise they will be replaced.

kwargsdict

Additional keyword arguments for emcee.EnsembleSampler

sample_y(X, sample_mean=False, noise=False, n_samples=1, random_state=0)[source]

Sample function realizations of the Gaussian process.

Parameters:
Xndarray, shape (n_points, n_dims)

Points at which to evaluate the functions.

sample_meanbool, optional (default: False)

If True, the geometric median of the hyperposterior samples is used as the Gaussian process to sample from. If False, a new set of hyperposterior is used for each new sample.

noisebool, optional (default: False)

If True, Gaussian noise is added to the samples.

n_samplesint, optional (default: 1)

Number of samples to draw from the Gaussian process(es).

random_stateint or RandomState or None, optional, default=None

Pseudo random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions.

Returns:
resultndarray, shape (n_points, n_samples)

Samples from the Gaussian process(es)

Raises:
ValueError

If warp_inputs=True and the entries of X are not all between 0 and 1.

score(X, y, sample_weight=None)

Return the coefficient of determination of the prediction.

The coefficient of determination \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)** 2).sum() and \(v\) is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.

Parameters:
Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

Returns:
scorefloat

\(R^2\) of self.predict(X) w.r.t. y.

Notes

The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score(). This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_fit_request(*, n_burnin: bool | None | str = '$UNCHANGED$', n_desired_samples: bool | None | str = '$UNCHANGED$', n_threads: bool | None | str = '$UNCHANGED$', n_walkers_per_thread: bool | None | str = '$UNCHANGED$', noise_vector: bool | None | str = '$UNCHANGED$', position: bool | None | str = '$UNCHANGED$', priors: bool | None | str = '$UNCHANGED$', progress: bool | None | str = '$UNCHANGED$', warp_priors: bool | None | str = '$UNCHANGED$') BayesGPR

Request metadata passed to the fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

New in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a pipeline.Pipeline. Otherwise it has no effect.

Parameters:
n_burninstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for n_burnin parameter in fit.

n_desired_samplesstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for n_desired_samples parameter in fit.

n_threadsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for n_threads parameter in fit.

n_walkers_per_threadstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for n_walkers_per_thread parameter in fit.

noise_vectorstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for noise_vector parameter in fit.

positionstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for position parameter in fit.

priorsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for priors parameter in fit.

progressstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for progress parameter in fit.

warp_priorsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for warp_priors parameter in fit.

Returns:
selfobject

The updated object.

set_params(**params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.

set_predict_request(*, return_cov: bool | None | str = '$UNCHANGED$', return_mean_grad: bool | None | str = '$UNCHANGED$', return_std: bool | None | str = '$UNCHANGED$', return_std_grad: bool | None | str = '$UNCHANGED$') BayesGPR

Request metadata passed to the predict method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

New in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a pipeline.Pipeline. Otherwise it has no effect.

Parameters:
return_covstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for return_cov parameter in predict.

return_mean_gradstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for return_mean_grad parameter in predict.

return_stdstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for return_std parameter in predict.

return_std_gradstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for return_std_grad parameter in predict.

Returns:
selfobject

The updated object.

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') BayesGPR

Request metadata passed to the score method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

New in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a pipeline.Pipeline. Otherwise it has no effect.

Parameters:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for sample_weight parameter in score.

Returns:
selfobject

The updated object.

property theta

The current geometric median of the kernel hyperparameter distribution.

The returned values are located in log space. Call BayesGPR.kernel_ to obtain the values their original space.

Returns:
ndarray

Array containing the kernel hyperparameters in log space.

unwarp(X)[source]

Unwarp the input X back to the original input space.

Returns X if warp_inputs=False or if no warpers have been fit yet.

Parameters:
Xndarray, shape (n_points, n_dims)

Points in the warped space which should be transformed back to the input space.

warp(X)[source]

Warp the input X using the existing warpers.

Returns X if warp_inputs=False or if no warpers have been fit yet.

Parameters:
Xndarray, shape (n_points, n_dims)

Points in the original space which should be warped.