Skip to main content
`Ctrl`+`K`

# `skopt.learning`.GaussianProcessRegressor

class skopt.learning.GaussianProcessRegressor(kernel=None, alpha=1e-10, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, normalize_y=False, copy_X_train=True, random_state=None, noise=None)

  GaussianProcessRegressor that allows noise tunability.

  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) 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.

  Parameters:
    kernel kernel 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 optimized during fitting.

    alpha float 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 and reduce potential numerical issue during fitting. 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.

    optimizer string 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 maximized, 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'

    n_restarts_optimizer int, 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_y boolean, 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; normalization is thus disabled per default.

    copy_X_train bool, 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_state integer or numpy.RandomState, optional

      The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator.

    noise string, “gaussian”, optional

      If set to “gaussian”, then it is assumed that `y` is a noisy estimate of `f(x)` where the noise is gaussian.

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

      Feature values in training data (also required for prediction)

    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”.

  Methods

  `fit`(X, y) | Fit Gaussian process regression model.
  `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.
  `predict`(X[, return_std, return_cov, ...]) | Predict output for X.
  `sample_y`(X[, n_samples, random_state]) | Draw samples from Gaussian process and evaluate at X.
  `score`(X, y[, sample_weight]) | Return coefficient of determination on test data.
  `set_params`(**params) | Set the parameters of this estimator.
  `set_predict_request`(*[, return_cov, ...]) | Configure whether metadata should be requested to be passed to the `predict` method.
  `set_score_request`(*[, sample_weight]) | Configure whether metadata should be requested to be passed to the `score` method.

  __init__(kernel=None, alpha=1e-10, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, normalize_y=False, copy_X_train=True, random_state=None, noise=None)
  fit(X, y)

    Fit Gaussian process regression model.

    Parameters:
      X array-like, shape = (n_samples, n_features)

        Training data

      y array-like, shape = (n_samples, [n_output_dims])

        Target values

    Returns:
      self

        Returns an instance of self.

  get_metadata_routing()

    Get metadata routing of this object.

    Please check User Guide on how the routing mechanism works.

    Returns:
      routing MetadataRequest

        A `MetadataRequest` encapsulating routing information.

  get_params(deep=True)

    Get parameters for this estimator.

    Parameters:
      deep bool, default=True

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

    Returns:
      params dict

        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:
      theta array-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_gradient bool, 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_kernel bool, 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_likelihood float

        Log-marginal likelihood of theta for training data.

      log_likelihood_gradient ndarray 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.

  predict(X, return_std=False, return_cov=False, return_mean_grad=False, return_std_grad=False)

    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:
      X array-like, shape = (n_samples, n_features)

        Query points where the GP is evaluated.

      return_std bool, default: False

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

      return_cov bool, default: False

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

      return_mean_grad bool, default: False

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

      return_std_grad bool, default: False

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

    Returns:
      y_mean array, shape = (n_samples, [n_output_dims])

        Mean of predictive distribution a query points

      y_std array, shape = (n_samples,), optional

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

      y_cov array, shape = (n_samples, n_samples), optional

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

      y_mean_grad shape = (n_samples, n_features)

        The gradient of the predicted mean

      y_std_grad shape = (n_samples, n_features)

        The gradient of the predicted std.

  sample_y(X, n_samples=1, random_state=0)

    Draw samples from Gaussian process and evaluate at X.

    Parameters:
      X array-like of shape (n_samples_X, n_features) or list of object

        Query points where the GP is evaluated.

      n_samples int, default=1

        Number of samples drawn from the Gaussian process per query point.

      random_state int, RandomState instance or None, default=0

        Determines random number generation to randomly draw samples. Pass an int for reproducible results across multiple function calls. See Glossary.

    Returns:
      y_samples ndarray of shape (n_samples_X, n_samples), or (n_samples_X, n_targets, n_samples)

        Values of n_samples samples drawn from Gaussian process and evaluated at query points.

  score(X, y, sample_weight=None)

    Return coefficient of determination on test data.

    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:
      X array-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.

      y array-like of shape (n_samples,) or (n_samples, n_outputs)

        True values for `X`.

      sample_weight array-like of shape (n_samples,), default=None

        Sample weights.

    Returns:
      score float

        \(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_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:
      **params dict

        Estimator parameters.

    Returns:
      self estimator 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$') → GaussianProcessRegressor

    Configure whether metadata should be requested to be passed to the `predict` method.

    Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with `enable_metadata_routing=True` (see `sklearn.set_config()`). Please check the 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.

    Added in version 1.3.

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

        Metadata routing for `return_cov` parameter in `predict`.

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

        Metadata routing for `return_mean_grad` parameter in `predict`.

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

        Metadata routing for `return_std` parameter in `predict`.

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

        Metadata routing for `return_std_grad` parameter in `predict`.

    Returns:
      self object

        The updated object.

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

    Configure whether metadata should be requested to be passed to the `score` method.

    Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with `enable_metadata_routing=True` (see `sklearn.set_config()`). Please check the 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.

    Added in version 1.3.

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

        Metadata routing for `sample_weight` parameter in `score`.

    Returns:
      self object

        The updated object.