forked from EigenPro/EigenPro-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkernel.py
92 lines (73 loc) · 2.36 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
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'''Implementation of kernel functions.'''
import torch
def euclidean_distances(samples, centers, squared=True):
'''Calculate the pointwise distance.
Args:
samples: of shape (n_sample, n_feature).
centers: of shape (n_center, n_feature).
squared: boolean.
Returns:
pointwise distances (n_sample, n_center).
'''
samples_norm = torch.sum(samples**2, dim=1, keepdim=True)
if samples is centers:
centers_norm = samples_norm
else:
centers_norm = torch.sum(centers**2, dim=1, keepdim=True)
centers_norm = torch.reshape(centers_norm, (1, -1))
distances = samples.mm(torch.t(centers))
distances.mul_(-2)
distances.add_(samples_norm)
distances.add_(centers_norm)
if not squared:
distances.clamp_(min=0)
distances.sqrt_()
return distances
def gaussian(samples, centers, bandwidth):
'''Gaussian kernel.
Args:
samples: of shape (n_sample, n_feature).
centers: of shape (n_center, n_feature).
bandwidth: kernel bandwidth.
Returns:
kernel matrix of shape (n_sample, n_center).
'''
assert bandwidth > 0
kernel_mat = euclidean_distances(samples, centers)
kernel_mat.clamp_(min=0)
gamma = 1. / (2 * bandwidth ** 2)
kernel_mat.mul_(-gamma)
kernel_mat.exp_()
return kernel_mat
def laplacian(samples, centers, bandwidth):
'''Laplacian kernel.
Args:
samples: of shape (n_sample, n_feature).
centers: of shape (n_center, n_feature).
bandwidth: kernel bandwidth.
Returns:
kernel matrix of shape (n_sample, n_center).
'''
assert bandwidth > 0
kernel_mat = euclidean_distances(samples, centers, squared=False)
kernel_mat.clamp_(min=0)
gamma = 1. / bandwidth
kernel_mat.mul_(-gamma)
kernel_mat.exp_()
return kernel_mat
def dispersal(samples, centers, bandwidth, gamma):
'''Dispersal kernel.
Args:
samples: of shape (n_sample, n_feature).
centers: of shape (n_center, n_feature).
bandwidth: kernel bandwidth.
gamma: dispersal factor.
Returns:
kernel matrix of shape (n_sample, n_center).
'''
assert bandwidth > 0
kernel_mat = euclidean_distances(samples, centers)
kernel_mat.pow_(gamma / 2.)
kernel_mat.mul_(-1. / bandwidth)
kernel_mat.exp_()
return kernel_mat