-
Notifications
You must be signed in to change notification settings - Fork 1
/
kernels.py
69 lines (61 loc) · 2.11 KB
/
kernels.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import numpy as np
import math
from sklearn.metrics.pairwise import check_pairwise_arrays,manhattan_distances
from sklearn.utils import gen_even_slices
from sklearn.externals.joblib import delayed, Parallel
def LaplacianKernel(X, Y=None, gamma=None):
return GeneralizedNormalKernel(X, Y=Y, gamma=gamma)
def GeneralizedNormalKernel(X, Y=None, gamma = None, beta = 1):
"""Compute the generalized normal kernel between X and Y.
The generalized normal kernel is defined as::
K(x, y) = exp(-gamma ||x-y||_1^beta)
for each pair of rows x in X and y in Y.
Parameters
----------
X : array of shape (n_samples_X, n_features)
Y : array of shape (n_samples_Y, n_features)
gamma : float
Returns
-------
kernel_matrix : array of shape (n_samples_X, n_samples_Y)
"""
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
if beta == 1:
K = -gamma * manhattan_distances(X, Y)
else:
K = -gamma * manhattan_distances(X, Y) ** beta
np.exp(K, K) # exponentiate K in-place
return K
def MaternKernel(X, Y=None, gamma = None, p = 0):
"""Compute the generalized normal kernel between X and Y.
The generalized normal kernel is defined as::
K(x, y) = exp(-gamma ||x-y||_1^beta)
for each pair of rows x in X and y in Y.
Parameters
----------
X : array of shape (n_samples_X, n_features)
Y : array of shape (n_samples_Y, n_features)
gamma : float
Returns
-------
kernel_matrix : array of shape (n_samples_X, n_samples_Y)
"""
assert(p == int(p))
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
r = manhattan_distances(X, Y)
if p == 0:
K = -gamma * r
np.exp(K, K) # exponentiate K in-place
if p == 1:
K = -gamma * r * math.sqrt(3)
np.exp(K, K) # exponentiate K in-place
K *= (1+gamma * r * math.sqrt(3))
if p == 1:
K = -gamma * r * math.sqrt(5)
np.exp(K, K) # exponentiate K in-place
K *= (1+gamma * r * math.sqrt(5) + 5./3. * (r*gamma)**2)
return K