/
kernel.py
44 lines (35 loc) · 1.37 KB
/
kernel.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
import numpy as np
### Functions for you to fill in ###
def polynomial_kernel(X, Y, c, p):
"""
Compute the polynomial kernel between two matrices X and Y::
K(x, y) = (<x, y> + c)^p
for each pair of rows x in X and y in Y.
Args:
X - (n, d) NumPy array (n datapoints each with d features)
Y - (m, d) NumPy array (m datapoints each with d features)
c - a coefficient to trade off high-order and low-order terms (scalar)
p - the degree of the polynomial kernel
Returns:
kernel_matrix - (n, m) Numpy array containing the kernel matrix
"""
K = X @ Y.T + c
K **= p
return K
def rbf_kernel(X, Y, gamma):
"""
Compute the Gaussian RBF kernel between two matrices X and Y::
K(x, y) = exp(-gamma ||x-y||^2)
for each pair of rows x in X and y in Y.
Args:
X - (n, d) NumPy array (n datapoints each with d features)
Y - (m, d) NumPy array (m datapoints each with d features)
gamma - the gamma parameter of gaussian function (scalar)
Returns:
kernel_matrix - (n, m) Numpy array containing the kernel matrix
"""
Xnorm = np.sum(X**2, axis=1)
Ynorm = np.sum(Y**2, axis=1)
cross = -2 * (X @ Y.T)
K = -gamma * (Xnorm[:, None] + Ynorm[None, :] + cross)
return np.exp(K)