# KernelRidge

### *class* cuml.kernel_ridge.KernelRidge(, alpha=1, kernel='linear', gamma=None, degree=3, coef0=1, kernel_params=None, output_type=None, verbose=False)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/kernel_ridge/kernel_ridge.py#L90)

Kernel ridge regression (KRR) performs l2 regularised ridge regression
using the kernel trick. The kernel trick allows the estimator to learn a
linear function in the space induced by the kernel. This may be a
non-linear function in the original feature space (when a non-linear
kernel is used).
This estimator supports multi-output regression (when y is 2 dimensional).
See the sklearn user guide for more information.

* **Parameters:**
  **alpha**
  : Regularization strength; must be a positive float. Regularization
    improves the conditioning of the problem and reduces the variance of
    the estimates. Larger values specify stronger regularization.
    If an array is passed, penalties are assumed to be specific
    to the targets.

  **kernel**
  : Kernel mapping used internally. This parameter is directly passed to
    `pairwise_kernel`.
    If `kernel` is a string, it must be one of the metrics
    in `cuml.metrics.PAIRWISE_KERNEL_FUNCTIONS` or “precomputed”.
    If `kernel` is “precomputed”, X is assumed to be a kernel matrix.
    `kernel` may be a callable numba device function. If so, is called on
    each pair of instances (rows) and the resulting value recorded.

  **gamma**
  : Gamma parameter for the RBF, laplacian, polynomial, exponential chi2
    and sigmoid kernels. Interpretation of the default value is left to
    the kernel; see the documentation for sklearn.metrics.pairwise.
    Ignored by other kernels.

  **degree**
  : Degree of the polynomial kernel. Ignored by other kernels.

  **coef0**
  : Zero coefficient for polynomial and sigmoid kernels.
    Ignored by other kernels.

  **kernel_params**
  : Additional parameters (keyword arguments) for kernel function passed
    as callable object.

  **output_type**
  : Return results and set estimator attributes to the indicated output
    type. If None, the output type set at the module level
    (`cuml.global_settings.output_type`) will be used. See
    [Output Data Type Configuration](../../cuml/index.html.md#output-data-type-configuration) for more info.

  **verbose**
  : Sets logging level. It must be one of `cuml.common.logger.level_*`.
    See [Verbosity Levels](../../cuml/index.html.md#verbosity-levels) for more info.
* **Attributes:**
  **dual_coef_**
  : Representation of weight vector(s) in kernel space

  **X_fit_**
  : Training data, which is also required for prediction. If
    kernel == “precomputed” this is instead the precomputed
    training matrix, of shape (n_samples, n_samples).

### Methods

| [`fit`](#cuml.kernel_ridge.KernelRidge.fit)(X, y[, sample_weight])   |                                       |
|-------------------------------------------------------------------------------|---------------------------------------|
| [`predict`](#cuml.kernel_ridge.KernelRidge.predict)(X)                   | Predict using the kernel ridge model. |

### Examples

```python
>>> import cupy as cp
>>> from cuml.kernel_ridge import KernelRidge
>>> from numba import cuda
>>> import math

>>> n_samples, n_features = 10, 5
>>> rng = cp.random.RandomState(0)
>>> y = rng.randn(n_samples)
>>> X = rng.randn(n_samples, n_features)

>>> model = KernelRidge(kernel="poly").fit(X, y)
>>> pred = model.predict(X)

>>> @cuda.jit(device=True)
... def custom_rbf_kernel(x, y, gamma=None):
...     if gamma is None:
...         gamma = 1.0 / len(x)
...     sum = 0.0
...     for i in range(len(x)):
...         sum += (x[i] - y[i]) ** 2
...     return math.exp(-gamma * sum)

>>> model = KernelRidge(kernel=custom_rbf_kernel,
...                     kernel_params={"gamma": 2.0}).fit(X, y)
>>> pred = model.predict(X)
```

<!-- !! processed by numpydoc !! -->

#### as_sklearn()[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L206)

Convert this estimator into an equivalent scikit-learn (or scikit-learn
extension) estimator.

* **Returns:**
  sklearn.base.BaseEstimator
  : A scikit-learn compatible estimator instance that mirrors the trained
    state of the current estimator.

<!-- !! processed by numpydoc !! -->

#### fit(X, y, sample_weight=None) → [KernelRidge](#cuml.kernel_ridge.KernelRidge)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/kernel_ridge/kernel_ridge.py#L285)

* **Parameters:**
  **X**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.

  **y**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.

  **sample_weight**
  : The weights for each observation in X. If None, all observations
    are assigned equal weight.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.

<!-- !! processed by numpydoc !! -->

#### *classmethod* from_sklearn(model)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L222)

Create a cuml estimator from a scikit-learn estimator.

* **Parameters:**
  **model**
  : A compatible scikit-learn (or scikit-learn extension) estimator.
* **Returns:**
  cls
  : A new instance of this cuml estimator class that mirrors the
    state of the input estimator.

### Notes

`output_type` of the estimator is set to “numpy” by default, as these
cannot be inferred from training arguments. If something different is
required, then please use cuml’s output_type configuration utilities.

<!-- !! processed by numpydoc !! -->

#### get_params(deep=True)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L191)

Returns a dict of all params owned by this class. If the child class
has appropriately overridden the `_get_param_names` method and does not
need anything other than what is there in this method, then it doesn’t
have to override this method

<!-- !! processed by numpydoc !! -->

#### predict(X)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/kernel_ridge/kernel_ridge.py#L317)

Predict using the kernel ridge model.

* **Parameters:**
  **X**
  : Samples. If kernel == “precomputed” this is instead a
    precomputed kernel matrix, shape = [n_samples,
    n_samples_fitted], where n_samples_fitted is the number of
    samples used in the fitting for this estimator.
* **Returns:**
  **C**
  : Returns predicted values.

<!-- !! processed by numpydoc !! -->

#### score(X, y, sample_weight=None, \*\*kwargs)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/mixins.py#L66)

Scoring function for regression estimators

Returns the coefficient of determination R^2 of the prediction.

* **Parameters:**
  **X**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.

  **y**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.

  **sample_weight**
  : The weights for each observation in X. If None, all observations
    are assigned equal weight.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.
* **Returns:**
  **score**
  : R^2 of self.predict(X) wrt. y.

<!-- !! processed by numpydoc !! -->

#### set_params(\*\*params)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L200)

Accepts a dict of params and updates the corresponding ones owned by
this class. If the child class has appropriately overridden the
`_get_param_names` method and does not need anything other than what is,
there in this method, then it doesn’t have to override this method

<!-- !! processed by numpydoc !! -->
