-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathembedding.py
executable file
·487 lines (391 loc) · 14 KB
/
embedding.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
__author__ = "Mojmir Mutny"
__copyright__ = "Copyright (c) 2018 Mojmir Mutny, ETH Zurich"
__credits__ = ["Mojmir Mutny", "Andreas Krause"]
__license__ = "MIT Licence"
__version__ = "0.3"
__email__ = "mojmir.mutny@inf.ethz.ch"
__status__ = "DEV"
"""
This file implements code used in paper:
Mojmir Mutny & Andreas Krause, "Efficient High Dimensional Bayesian Optimization
with Additivity and Quadrature Fourier Features", NIPS 2018
Namely, we implement finite basis approximation to Gaussian processes. The main contribution of this paper
is implementation of the method embed(x) which coincides with \Phi(x) in product approximation
k(x,y) = \Phi(x)^\top \Phi(y)
"""
"""
Copyright (c) 2018 Mojmir Mutny, ETH Zurich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from scipy.stats import norm
from scipy.stats import chi2, chi
import numpy as np
import stpy.helper as helper
import torch
class Embedding():
"""
Base class for Embeddings to approximate kernels with a higher dimensional linear product.
"""
def __init__(self, gamma=0.1, nu=0.5, m=100, d=1, diameter=1.0, groups=None,
kernel="squared_exponential", approx = "rff", **kwargs):
"""
Called to calculate the embedding weights (either via sampling or deterministically)
Args:
gamma: (positional, 0.1) bandwidth of the squared exponential kernel
nu: (positional, 0.5) the parameter of Matern family
m: (positional, 1)
d: dimension of the
Returns:
None
"""
self.gamma = float(gamma)
self.n = nu
self.m = int(m)
self.d = int(d)
self.nu = nu
self.diameter = diameter
self.groups = groups
self.kernel = kernel
self.approx = approx
self.gradient_avail = 0
if self.m % 2 == 1:
raise AssertionError("Number of random features has to be even.")
def sample(self):
"""
Called to calculate the embedding weights (either via sampling or deterministically)
Args:
None
Returns:
None
"""
raise AttributeError("Only derived classes can call this method.")
def embed(self,x):
"""
Called to calculate the embedding weights (either via sampling or deterministically)
Args:
x: numpy array containing the points to be embedded in the format (n,d)
Returns:
y: numpy array containg the embedded points (n,m), where m is the embedding dimension
"""
raise AttributeError("Only derived classes can call this method.")
"""
===============================
Sampling Based Methods
===============================
"""
class RFFEmbedding(Embedding):
"""
Random Fourier Features emebedding
"""
def __init__(self, biased = False,**kwargs):
super().__init__(**kwargs)
self.biased = biased
self.sample()
def sampler(self, size):
"""
Defines the sampler object
Args:
size:
Return:
"""
if self.kernel == "squared_exponential":
distribution = lambda size: np.random.normal(size=size) * (1. / self.gamma)
inv_cum_dist = lambda x: norm.ppf(x) * (1. / self.gamma)
elif self.kernel == "laplace":
distribution = None
inv_cum_dist = lambda x: (np.tan(np.pi * x - np.pi) / self.gamma)
elif self.kernel == "modified_matern":
if self.nu == 2:
distribution = None
inv_cum_dist = None
pdf = lambda x: np.prod(2*(self.gamma)/(np.power((1. + self.gamma**2*x**2),2) * np.pi),axis =1)
elif self.nu == 3:
distribution = None
inv_cum_dist = None
pdf = lambda x: np.prod((8.*self.gamma)/(np.power((1. + self.gamma**2*x**2),3) *3* np.pi),axis =1)
elif self.nu == 4:
distribution = None
inv_cum_dist = None
pdf = lambda x: np.prod((16.*self.gamma)/(np.power((1. + self.gamma**2*x**2),4) *5 * np.pi),axis =1)
# Random Fourier Features
if self.approx == "rff":
if distribution == None:
if inv_cum_dist == None:
self.W = helper.rejection_sampling(pdf,size = size)
else:
self.W = helper.sample_custom(inv_cum_dist, size=size)
else:
self.W = distribution(size)
# Quasi Fourier Features
elif self.approx == "halton":
if inv_cum_dist != None:
self.W = helper.sample_qmc_halton(inv_cum_dist, size=size)
else:
raise AssertionError("Inverse Cumulative Distribution could not be deduced")
elif self.approx == "orf":
distribution = lambda size: np.random.normal(size=size) * (1.)
self.W = distribution(size)
# QR decomposition
self.Q,_ = np.linalg.qr(self.W)
# df and size
self.S = np.diag(chi.rvs(size[1], size=size[0]))
self.W = np.dot(self.S,self.Q)/self.gamma**2
return self.W
def sample(self):
"""
Samples Random Fourier Features
"""
self.W = self.sampler(size = (self.m,self.d))
self.W = torch.from_numpy(self.W)
if self.biased == True:
self.b = 2. * np.pi * np.random.uniform(size=(self.m))
self.bs = self.b.reshape(self.m, 1)
self.b = torch.from_numpy(self.b)
self.bs = torch.from_numpy(self.bs)
def embed(self,x):
"""
:param x: torch array
:return: embeded vector
"""
(times, d) = x.shape
if self.biased == True:
z = np.sqrt(2. / self.m) * torch.t(torch.cos(self.W[:, 0:d].mm(torch.t(x)) + self.b.view(self.m, 1) ))
else:
z = self.W[:, 0:d].mm(torch.t(x))
z[0:int(self.m / 2), :] = np.sqrt(2. / float(self.m)) * torch.cos(z[0:int(self.m / 2), :])
z[int(self.m / 2):self.m, :] = np.sqrt(2. / float(self.m)) * torch.sin(z[int(self.m / 2):self.m, :])
return torch.t(z)
"""
===============================
Quadrature Based Methods
===============================
"""
class QuadratureEmbedding(Embedding):
"""
General quadrature embedding
"""
def __init__(self,scale=1.0,**kwargs):
Embedding.__init__(self,**kwargs)
self.scale = scale
self.compute()
def reorder_complexity(self,omegas,weights):
abs_omegas = np.abs(omegas)
order = np.argsort(abs_omegas)
new_omegas = omegas[order]
new_weights = weights[order]
return new_omegas, new_weights
def compute(self, complexity_reorder = True):
"""
Computes the tensor grid for Fourier features
:return:
"""
self.q = int(np.power(self.m//2, 1. / self.d))
self.m = self.q ** self.d
(omegas, weights) = self.nodesAndWeights(self.q)
if complexity_reorder == True:
(omegas, weights) = self.reorder_complexity(omegas,weights)
self.weights = helper.cartesian([weights for weight in range(self.d)])
self.weights = np.prod(self.weights, axis=1)
v = [omegas for omega in range(self.d)]
self.W = helper.cartesian(v)
self.m = self.m * 2
self.W = torch.from_numpy(self.W)
self.weights = torch.from_numpy(self.weights)
def transform(self):
"""
:return: spectral density of a kernel
"""
if self.kernel == "squared_exponential":
p = lambda omega: np.exp(-np.sum(omega ** 2, axis=1).reshape(-1, 1) / 2 * (self.gamma ** 2)) * np.power(
(self.gamma / np.sqrt(2 * np.pi)), 1.)*np.power(np.pi / 2,1.)
elif self.kernel == "laplace":
p = lambda omega: np.prod(1. / ((self.gamma ** 2) * (omega ** 2) + 1.), axis=1).reshape(-1, 1) * np.power(
self.gamma / 2., 1.)
elif self.kernel == "modified_matern":
if self.nu == 2:
p = lambda omega: np.prod(1. / ((self.gamma ** 2) * (omega ** 2) + 1.) ** self.nu, axis=1).reshape(-1, 1) * np.power(
self.gamma * 1, 1.)
elif self.nu ==3:
p = lambda omega: np.prod(1. / ((self.gamma ** 2) * (omega ** 2) + 1.) ** self.nu, axis=1).reshape(-1, 1) * np.power(
self.gamma * 4/3 , 1.)
elif self.nu ==4:
p = lambda omega: np.prod(1. / ((self.gamma ** 2) * (omega ** 2) + 1.) ** self.nu, axis=1).reshape(-1, 1) * np.power(
self.gamma *8/5, 1.)
return p
def nodesAndWeights(self,q):
"""
Compute nodes and weights of the quadrature scheme in 1D
:param q: degree of quadrature
:return: tuple of (nodes, weights)
"""
# For osciallatory integrands even this has good properties.
#weights = np.ones(self.q) * self.scale * np.pi / (self.q + 1)
#omegas = (np.linspace(0, self.q - 1, self.q)) + 1
#omegas = omegas * (np.pi / (self.q + 1))
(omegas, weights) = np.polynomial.legendre.leggauss(2*q)
omegas = omegas[q:]
weights = 2 * weights[q:]
omegas = ((omegas + 1.) / 2.) * np.pi
sine_scale = (1. / (np.sin(omegas) ** 2))
omegas = self.scale / np.tan(omegas)
prob = self.transform()
weights = self.scale * sine_scale * weights * prob(omegas.reshape(-1, 1)).flatten()
return (omegas,weights)
def embed(self,x):
"""
:param x: torch array
:return: embeding of the x
"""
(times, d) = tuple(x.size())
#z = torch.from_numpy(np.zeros(shape=(self.m, times),dtype=x.dtype))
z = torch.zeros(self.m,times, dtype = x.dtype)
q = torch.mm(self.W[:, 0:d],torch.t(x))
z[0:int(self.m / 2), :] = torch.sqrt(self.weights.view(-1, 1)) * torch.cos(q)
z[int(self.m / 2):self.m, :] = torch.sqrt(self.weights.view(-1, 1)) * torch.sin(q)
return torch.t(z)
def get_sub_indices(self,group):
"""
:param group: group part of the embeding to embed
:return: embeding of x in group
"""
m2 = self.m
mhalf = int(np.power(self.m // 2, 1. / self.d))
m = 2*mhalf
mquater = mhalf//2
if group == 0 :
ind = np.arange(mquater * mhalf, (mquater + 1) * mhalf, 1).tolist() + np.arange(m2 // 2 + (mquater * mhalf),
m2 // 2 + (mquater + 1) * mhalf,
1).tolist()
return ind
else:
ind = np.arange(mquater, m2 // 2, mhalf).tolist() + np.arange(m2 // 2 + mquater, m2, mhalf).tolist()
return ind
def get_sum_sub_indices(self,group):
# idenitfy unique values
arr = self.W[:,group]
values = np.unique(arr)
# find indices of each unique value
ind = []
for value in values:
ind_inside = []
for index,elem in enumerate(arr):
if elem == value:
ind_inside.append(index)
ind.append(ind_inside)
ind_inside2 = [i+self.m//2 for i in ind_inside]
ind.append(ind_inside2)
return ind
class HermiteEmbedding(QuadratureEmbedding):
"""
Hermite Quadrature Fourier Features for squared exponential kernel
"""
def __init__(self,**kwargs):
QuadratureEmbedding.__init__(self,**kwargs)
if self.kernel != "squared_exponential":
raise AssertionError("Hermite Embedding is allowed only with Squared Exponential Kernel")
def nodesAndWeights(self,q):
"""
Compute nodes and weights of the quadrature scheme in 1D
:param q: degree of quadrature
:return: tuple of (nodes, weights)
"""
(nodes, weights) = np.polynomial.hermite.hermgauss(2*q)
nodes = nodes[q:]
weights = 2 * weights[q:]
nodes = np.sqrt(2) * nodes / self.gamma
weights = weights/np.sqrt(np.pi)
return (nodes, weights)
class MaternEmbedding(QuadratureEmbedding):
"""
Matern specific quadrature based Fourier Features
"""
def __init__(self,**kwargs):
super().__init__(**kwargs)
if self.kernel != "modified_matern" and self.kernel !="laplace":
raise AssertionError("Matern Embedding is allowed only with Matern Kernel")
def nodesAndWeights(self,q):
"""
Compute nodes and weights of the quadrature scheme in 1D
:param q: degree of quadrature
:return: tuple of (nodes, weights)
"""
(nodes, weights) = np.polynomial.hermite.hermgauss(q)
nodes = np.sqrt(2) * nodes / self.gamma
weights = weights/np.sqrt(np.pi)
return (nodes, weights)
class QuadPeriodicEmbedding(QuadratureEmbedding):
"""
General class implementing
"""
def __init__(self,**kwargs):
super().__init__(**kwargs)
def nodesAndWeights(self,q):
"""
Compute nodes and weights of the quadrature scheme in 1D
:param q: degree of quadrature
:return: tuple of (nodes, weights)
"""
weights = np.ones(self.q) * self.scale * 2 / (self.q + 1)
omegas = (np.linspace(0, self.q - 1, self.q)) + 1
omegas = omegas * (np.pi / (self.q + 1))
sine_scale = (1. / (np.sin(omegas) ** 2))
omegas = self.scale / np.tan(omegas)
prob = self.transform()
weights = self.scale * sine_scale * weights * prob(omegas.reshape(-1, 1)).flatten()
return (omegas,weights)
class KLEmbedding(QuadratureEmbedding):
"""
General class implementing Karhunen-Loeve expansion
"""
def __init__(self,**kwargs):
super().__init__(**kwargs)
class LatticeEmbedding(QuadratureEmbedding):
"""
Class for standard basis indexed by natural numbers
"""
def __init__(self,**kwargs):
super().__init__(**kwargs)
#if self.kernel != "modified_matern" and self.kernel !="laplace":
# raise AssertionError("Matern Embedding is allowed only with Matern Kernel")
def nodesAndWeights(self,q):
"""
Compute nodes and weights of the quadrature scheme in 1D
:param q: degree of quadrature
:return: tuple of (nodes, weights)
"""
nodes = np.arange(1,q+1,1)
nodes = np.sqrt(2) * nodes / self.gamma
weights = np.ones(q)/(2*q)
return (nodes, weights)
class AdditiveEmbeddings():
def __init__(self, embeddings, m, scaling = None, additive = True):
self.emebeddings = embeddings
if scaling is None:
self.scaling = torch.ones(len(self.emebeddings)).double()
else:
self.scaling = scaling
self.additive = additive
self.m = m
self.no_emb = len(self.emebeddings)
def embed(self,x):
if self.additive:
r = torch.zeros(size = (x.size()[0],self.m*self.no_emb)).double()
for index,embedding in enumerate(self.emebeddings):
r[:,index*self.m:(index+1)*self.m]=embedding.embed(x[:,index].view(-1,1))*self.scaling[index]
return r
else:
pass