MCPcopy
hub / github.com/ddbourgin/numpy-ml / RBFKernel

Class RBFKernel

numpy_ml/utils/kernels.py:184–238  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

182
183
184class RBFKernel(KernelBase):
185 def __init__(self, sigma=None):
186 """
187 Radial basis function (RBF) / squared exponential kernel.
188
189 Notes
190 -----
191 For input vectors :math:`\mathbf{x}` and :math:`\mathbf{y}`, the radial
192 basis function kernel is:
193
194 .. math::
195
196 k(\mathbf{x}, \mathbf{y}) = \exp \left\{ -0.5
197 \left\lVert \\frac{\mathbf{x} -
198 \mathbf{y}}{\sigma} \\right\\rVert_2^2 \\right\}
199
200 The RBF kernel decreases with distance and ranges between zero (in the
201 limit) to one (when **x** = **y**). Notably, the implied feature space
202 of the kernel has an infinite number of dimensions.
203
204 Parameters
205 ----------
206 sigma : float or array of shape `(C,)` or None
207 A scaling parameter for the vectors **x** and **y**, producing an
208 isotropic kernel if a float, or an anistropic kernel if an array of
209 length `C`. Larger values result in higher resolution / greater
210 smoothing. If None, defaults to :math:`\sqrt(C / 2)`. Sometimes
211 referred to as the kernel 'bandwidth'. Default is None.
212 """
213 super().__init__()
214 self.hyperparameters = {"id": "RBFKernel"}
215 self.parameters = {"sigma": sigma}
216
217 def _kernel(self, X, Y=None):
218 """
219 Computes the radial basis function (RBF) kernel between all pairs of
220 rows in `X` and `Y`.
221
222 Parameters
223 ----------
224 X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, C)`
225 Collection of `N` input vectors, each with dimension `C`.
226 Y : :py:class:`ndarray <numpy.ndarray>` of shape `(M, C)`
227 Collection of `M` input vectors. If None, assume `Y` = `X`. Default
228 is None.
229
230 Returns
231 -------
232 out : :py:class:`ndarray <numpy.ndarray>` of shape `(N, M)`
233 Similarity between `X` and `Y` where index (i, j) gives :math:`k(x_i, y_j)`.
234 """
235 P = self.parameters
236 X, Y = kernel_checks(X, Y)
237 sigma = np.sqrt(X.shape[1] / 2) if P["sigma"] is None else P["sigma"]
238 return np.exp(-0.5 * pairwise_l2_distances(X / sigma, Y / sigma) ** 2)
239
240
241class KernelInitializer(object):

Callers 3

test_radial_basis_kernelFunction · 0.90
init_from_strMethod · 0.85
init_from_dictMethod · 0.85

Calls

no outgoing calls

Tested by 1

test_radial_basis_kernelFunction · 0.72