-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMOMoGPstructure.py
397 lines (373 loc) · 17.9 KB
/
MOMoGPstructure.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
"""
Created on June 08, 2021
@author: Zhongjie Yu
@author: Mingye Zhu
"""
import numpy as np
from collections import Counter
import random
class Sum_:
def __init__(self, **kwargs):
self.maxs = kwargs['maxs']
self.mins = kwargs['mins']
self.dimension = dict.get(kwargs, 'dimension', None)
self.children = dict.get(kwargs, 'children', [])
self.depth = dict.get(kwargs, 'depth', 0)
self.n = kwargs['n']
self.scope = dict.get(kwargs, 'scope', [])
self.parent = dict.get(kwargs, 'parent', None)
self.splits = dict.get(kwargs, 'splits', [])
self.idx = dict.get(kwargs, 'idx', [])
self.pop = dict.get(kwargs, 'pop', [])
self.y = dict.get(kwargs, 'y', [])
class Product_x_:
def __init__(self, **kwargs):
self.split = kwargs['split']
self.splits = kwargs['splits']
self.dimension = kwargs['dimension']
self.depth = kwargs['depth']
self.children = kwargs['children']
self.parent = kwargs['parent']
self.maxs = kwargs['maxs']
self.mins = kwargs['mins']
class Product_y_:
def __init__(self, **kwargs):
self.children = kwargs['children']
self.maxs = kwargs['maxsy']
self.mins = kwargs['minsy']
self.scope = dict.get(kwargs, 'scope', None)
self.parent = dict.get(kwargs, 'parent', None)
self.collect = dict.get(kwargs, 'collect', None)
class GPMixture:
def __init__(self, **kwargs):
self.mins = kwargs['mins']
self.maxs = kwargs['maxs']
self.idx = dict.get(kwargs, 'idx', [])
self.parent = kwargs['parent']
self.y = kwargs['y']
def _cached_gp(cache, **kwargs):
min_, max_, y = list(kwargs['mins']), list(kwargs['maxs']), kwargs['y']
cached = dict.get(cache, (*min_, *max_))
if not cached:
cache[(*min_, *max_)] = GPMixture(**kwargs)
return cache[(*min_, *max_)]
def query(X, mins, maxs, skipleft=False):
mask, D = np.full(len(X), True), X.shape[1]
for d_ in range(D):
if skipleft:
mask = mask & (X[:, d_] >= mins[d_]) & (X[:, d_] < maxs[d_])
else:
## consider data at split points to either side or both sides according to the situation
mask = mask & (X[:, d_] >= mins[d_]) & (X[:, d_] <= maxs[d_])
return np.nonzero(mask)[0]
def build_MOMoGP(**kwargs):
"""Bulid the MOMoGP structure.
This function creates the MOMoGP structure
based on Algorithm 1 and Figure 2.
Parameters
----------
**kwargs
Arbitrary keyword arguments.
X: Training data from covariate space in R^D.
Y: Training data from output space in R^P.
qd: Quantiles to split the covariate space, qd = Kpx-1.
max_samples: The threshold M described in paper.
Returns
-------
root_node
The root node of MOMoGP.
gps
The list of GPs.
"""
X = kwargs['X']
Y = kwargs['Y']
ddd = dict.get(kwargs, 'qd', 0)
min_idx = dict.get(kwargs, 'max_samples', 1)
root_mixture_opts = {
'mins': np.min(X, 0),
'maxs': np.max(X, 0),
'n': len(X),
'scope': [i for i in range(Y.shape[1])],
'parent': None,
'dimension': np.argsort(-np.var(X, axis=0))[0],
'idx': X,
'y':Y
}
nsplits = Counter()
root_node = Sum_(**root_mixture_opts)
to_process, cache = [root_node], dict()
count = 0
while len(to_process):
node = to_process.pop()
# try to create children of a Product node for output space
if type(node) is Product_y_:
for i in range(len(node.children)):
node2 = node.children[i]
# the children of a Product node for output space should be Sum nodes or Leaf nodes
if type(node2) is Sum_ :
d = node2.dimension
x_node = node2.idx
scope2 = node2.scope
y2 = node2.y
mins_node, maxs_node = np.min(x_node, 0), np.max(x_node, 0)
scope = node2.scope
d_selected = np.argsort(-np.var(x_node, axis=0))
d2 = d_selected[1]
sum_children = [1, 2]
## take quantiles as split points
quantiles = np.quantile(x_node, np.linspace(0, 1, num = ddd+2), axis=0).T
d = [d_selected[0],d_selected[1]]
m = 0
for split in sum_children:
u = np.unique(quantiles[d[m]]) ##ignore duplicated split points
## put data into different split intervals
loop = []
if len(u) == 1:
loop.append(x_node)
for i in range(len(u)-1):
new_maxs, new_mins = maxs_node.copy(), mins_node.copy()
skipleft = True
if i == 0:
skipleft = False
new_mins[d[m]] = u[i]
new_maxs[d[m]] = u[i + 1]
idx_i = query(x_node, new_mins, new_maxs, skipleft=skipleft)
if len(idx_i)==0:
print("empty children due to data")
continue
loop.append(idx_i)
next_depth = node2.depth + 1
results = []
##create next-layer nodes for current node
for idx in loop:
x_idx = x_node[idx]
maxs_loop = np.max(x_idx, axis=0)
mins_loop = np.min(x_idx, axis=0)
next_dimension = np.argsort(-np.var(x_idx, axis=0))[0]
# if univariate output, check threshold M
if len(scope) == 1:
# if #data smaller than M, create factorization of output
if len(idx) < min_idx and len(idx)>0:
gp = []
prod_opts = {
'minsy': mins_loop,
'maxsy': maxs_loop,
'scope': scope,
'children': gp,
}
prod = Product_y_(**prod_opts)
a = _cached_gp(cache, mins=mins_loop, maxs=maxs_loop, idx=idx, y=scope[0], parent=None)
gp.append(a)
results.append(prod)
# if #data larger than M, create a Sum node and continue splitting
else:
mixture_opts = {
'mins': mins_loop,
'maxs': maxs_loop,
'depth': next_depth,
'dimension': next_dimension,
'n': len(idx),
'scope': scope,
'idx': x_idx,
}
results.append(Sum_(**mixture_opts))
# if multivariate output, randomly split the output dimensions
else:
a = int(len(scope) / 2)
scope1 = random.sample(scope, a)
scope2 = list(set(scope) - set(scope1))
# if #data smaller than M
if len(idx) >= min_idx:
mixture_opts1 = {
'mins': mins_loop,
'maxs': maxs_loop,
'depth': next_depth,
'dimension': next_dimension,
'n': len(idx),
'scope': scope1,
'idx': x_idx,
}
mixture_opts2 = {
'mins': mins_loop,
'maxs': maxs_loop,
'depth': next_depth,
'dimension': next_dimension,
'n': len(idx),
'scope': scope2,
'idx': x_idx,
}
prod_opts = {
'minsy': mins_loop,
'maxsy': maxs_loop,
'scope': scope1 + scope2,
'children': [Sum_(**mixture_opts1), Sum_(**mixture_opts2)]
}
prod = Product_y_(**prod_opts)
results.append(prod)
# if #data larger than M
else:
gp = []
prod_opts = {
'minsy': mins_loop,
'maxsy': maxs_loop,
'scope': scope1+scope2,
'children': gp,
}
prod = Product_y_(**prod_opts)
for yi in prod.scope:
a = _cached_gp(cache, mins=mins_loop, maxs=maxs_loop, idx=idx, y=yi, parent=None)
gp.append(a)
count += 1
results.append(prod)
# if there is still Sum or Product node in the list to split
if len(results) != 1:
to_process.extend(results)
separator_opts = {
'depth': node2.depth,
'mins': mins_node,
'maxs': maxs_node,
'dimension': d[m],
'split': split,
'children': results,
'parent': None,
'splits':u
}
node2.children.append(Product_x_(**separator_opts))
else:
node2.children.extend(results)
to_process.extend(results)
m += 1
# try to create children of a Sum node
elif type(node) is Sum_:
# first find out the two dimensions with largest variance in covariate space
d = node.dimension
x_node = node.idx
mins_node, maxs_node = np.min(x_node, 0), np.max(x_node, 0)
scope = node.scope
d_selected = np.argsort(-np.var(x_node, axis=0))
d2 = d_selected[1]
quantiles = np.quantile(x_node, np.linspace(0, 1, num = ddd+2),axis=0).T
sum_children=[1,2]
d = [d_selected[0], d_selected[1]]
m = 0
for split in sum_children:
u = np.unique(quantiles[d[m]])
loop = []
if len(u) == 1:
loop.append(x_node)
for i in range(len(u)-1):
new_maxs, new_mins = maxs_node.copy(), mins_node.copy()
skipleft = True
if i == 0:
skipleft = False
new_mins[d[m]] = u[i]
new_maxs[d[m]] = u[i + 1]
idx_i = query(x_node, new_mins, new_maxs, skipleft=skipleft)
if len(idx_i)==0:
print("empty children due to data")
continue
loop.append(idx_i)
next_depth = node.depth + 1
results = []
for idx in loop:
x_idx = x_node[idx]
maxs_loop = np.max(x_idx,axis=0)
mins_loop = np.min(x_idx,axis=0)
next_dimension = np.argsort(-np.var(x_idx, axis=0))[0]
# if univariate output, check threshold M
if len(scope) == 1:
# if #data smaller than M, create factorization of output
if len(idx) < min_idx and len(idx) >0:
gp = []
prod_opts = {
'minsy': mins_loop,
'maxsy': maxs_loop,
'scope': scope,
'children': gp,
}
prod = Product_y_(**prod_opts)
a = _cached_gp(cache, mins=mins_loop, maxs=maxs_loop, idx=idx, y=scope[0], parent=None)
gp.append(a)
results.append(prod)
# if #data larger than M, create a Sum node and continue splitting
else:
mixture_opts = {
'mins': mins_loop,
'maxs': maxs_loop,
'depth': next_depth,
'dimension': next_dimension,
'n': len(idx),
'scope': scope,
'idx': x_idx,
}
results.append(Sum_(**mixture_opts))
# if multivariate output, randomly split the output dimensions
else:
a = int(len(scope) / 2)
scope1 = random.sample(scope, a)
scope2 = list(set(scope) - set(scope1))
# if #data smaller than M
if len(idx) >= min_idx:
mixture_opts1 = {
'mins': mins_loop,
'maxs': maxs_loop,
'depth': next_depth,
'dimension': next_dimension,
'n': len(idx),
'scope': scope1,
'idx': x_idx,
}
mixture_opts2 = {
'mins': mins_loop,
'maxs': maxs_loop,
'depth': next_depth,
'dimension': next_dimension,
'n': len(idx),
'scope': scope2,
'idx': x_idx,
}
prod_opts = {
'minsy': mins_loop,
'maxsy': maxs_loop,
'scope': scope1+scope2,
'children': [Sum_(**mixture_opts1),Sum_(**mixture_opts2)]
}
prod = Product_y_(**prod_opts)
results.append(prod)
# if #data larger than M
else:
gp = []
prod_opts = {
'minsy': mins_loop,
'maxsy': maxs_loop,
'scope': scope1+scope2,
'children': gp,
}
prod = Product_y_(**prod_opts)
for yi in prod.scope:
a = _cached_gp(cache, mins=mins_loop, maxs=maxs_loop, idx=idx, y=yi, parent=None)
gp.append(a)
count+=1
results.append(prod)
# if there is still Sum or Product node in the list to split
if len(results) != 1:
to_process.extend(results)
separator_opts = {
'depth': node.depth,
'mins': mins_node,
'maxs': maxs_node,
'dimension': d[m],
'split': split,
'children': results,
'parent': None,
'splits':u
}
node.children.append(Product_x_(**separator_opts))
else:
node.children.extend(results)
to_process.extend(results)
m += 1
gps = list(cache.values())
leaf_len = [len(gp.idx) for gp in gps]
print(f"Leaf observations:\t {leaf_len}\nSum:\t\t\t {sum(leaf_len)} (N={len(X)})")
return root_node, gps