pairwise_kernels#

cuml.metrics.pairwise_kernels(
X,
Y=None,
metric='linear',
*,
filter_params=False,
**kwds,
)[source]#

Compute the kernel between array X and optional array Y.

This function provides a safe way to take a kernel matrix as input, while preserving compatibility with many other algorithms that take a vector array.

Parameters:
Xarray-like of shape (n_samples_X, n_samples_X) or (n_samples_X, n_features)

Array of pairwise kernels between samples, or a feature array. The shape of the array should be (n_samples_X, n_samples_X) if metric == “precomputed” and (n_samples_X, n_features) otherwise.

Yarray-like of shape (n_samples_Y, n_features), default=None

A second feature array only if X has shape (n_samples_X, n_features). If Y=None, Y=X is used instead.

metricstr or callable, default=”linear”

The metric to use when calculating kernel between instances in a feature array.

Valid metrics are: [‘additive_chi2’, ‘chi2’, ‘cosine’, ‘laplacian’, ‘linear’, ‘poly’, ‘polynomial’, ‘precomputed, ‘rbf’, ‘sigmoid’].

If metric is “precomputed”, X is assumed to be a kernel matrix and is returned directly.

If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should be a numba device function. It should take two rows from X as input and return the corresponding kernel value as a single number. Extra parameters are supported as keyword arguments.

filter_paramsbool, default=False

Whether to filter invalid parameters or not.

**kwdsoptional keyword parameters

Any further parameters are passed directly to the kernel function.

Returns:
Kndarray of shape (n_samples_X, n_samples_X) or (n_samples_X, n_samples_Y)

A kernel matrix K such that K_{i, j} is the kernel between the ith and jth vectors of the given matrix X, if Y is None. If Y is not None, then K_{i, j} is the kernel between the ith array from X and the jth array from Y.

Examples

>>> import cupy as cp
>>> from cuml.metrics import pairwise_kernels
>>> X = cp.array([[2, 3], [3, 5], [5, 8]])
>>> Y = cp.array([[1, 0], [2, 1]])
>>> pairwise_kernels(X, Y, metric='linear')
array([[ 2,  7],
       [ 3, 11],
       [ 5, 18]])

Custom kernels may be provided as numba compiled device functions.

>>> import math
>>> from numba_cuda_mlir import cuda
>>> @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)
>>> pairwise_kernels(X, Y, metric=custom_rbf_kernel)
array([[6.73794700e-03, 1.35335283e-01],
       [5.04347663e-07, 2.03468369e-04],
       [4.24835426e-18, 2.54366565e-13]])