-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgp.py
2170 lines (1680 loc) · 76.5 KB
/
gp.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import numpy as np
import collections
import scipy
import scipy.sparse
import scipy.sparse.linalg
import scikits.sparse.cholmod
import pyublas
import hashlib
import types
import marshal
from features import featurizer_from_string, recover_featurizer
from cover_tree import VectorTree, MatrixTree
from util import mkdir_p
import scipy.weave as weave
from scipy.weave import converters
from gpy_linalg import pdinv, dpotrs
def marshal_fn(f):
if f.func_closure is not None:
raise ValueError("function has non-empty closure %s, cannot marshal!" % repr(f.func_closure))
s = marshal.dumps(f.func_code)
return s
def unmarshal_fn(dumped_code):
f_code = marshal.loads(dumped_code)
f = types.FunctionType(f_code, globals())
return f
def sparse_kernel_from_tree(tree, X, sparse_threshold, identical, noise_var):
max_distance = np.sqrt(-np.log(sparse_threshold)) # assuming a SE kernel
n = len(X)
entries = tree.sparse_training_kernel_matrix(X, max_distance, False)
spK = scipy.sparse.coo_matrix((entries[:,2], (entries[:,0], entries[:,1])), shape=(n,n), dtype=float)
if identical:
spK = spK + noise_var * scipy.sparse.eye(spK.shape[0])
spK = spK + 1e-8 * scipy.sparse.eye(spK.shape[0])
return spK.tocsc()
def prior_ll(params, priors):
ll = 0
for (param, prior) in zip(params, priors):
if prior is not None:
ll += prior.log_p(param)
return ll
def prior_grad(params, priors):
n = len(params)
grad = np.zeros((n,))
for (i, param, prior) in zip(range(n), params, priors):
if prior is not None:
grad[i] = prior.deriv_log_p(param)
return grad
def prior_sample_sparse(X, cov, noise_var, sparse_threshold=1e-20):
n = X.shape[0]
predict_tree = VectorTree(X, 1, cov.dfn_str, cov.dfn_params, cov.wfn_str, cov.wfn_params)
spK = sparse_kernel_from_tree(predict_tree, X, sparse_threshold, True, noise_var)
factor = scikits.sparse.cholmod.cholesky(spK)
L = factor.L()
P = factor.P()
Pinv = np.argsort(P)
z = np.random.randn(n)
y = np.array((L * z)[Pinv]).reshape((-1,))
return y
def mcov(X, cov, noise_var, X2=None):
n = X.shape[0]
predict_tree = VectorTree(X, 1, cov.dfn_str, cov.dfn_params, cov.wfn_str, cov.wfn_params)
if X2 is None:
K = predict_tree.kernel_matrix(X, X, False)
K += np.eye(n) * noise_var
else:
K = predict_tree.kernel_matrix(X, X2, False)
return K
def prior_sample(X, cov, noise_var, sparse_threshold=1e-20, return_K=False):
n = X.shape[0]
K = mcov(X, cov, noise_var)
L = np.linalg.cholesky(K)
z = np.random.randn(n)
y = np.array(np.dot(L, z)).reshape((-1,))
if return_K:
return y, K
else:
return y
def gaussian_logp(y, K):
n = K.shape[0]
L = scipy.linalg.cholesky(K, lower=True)
ld2 = np.log(np.diag(L)).sum() # this computes .5 * log(det(K))
alpha = scipy.linalg.cho_solve((L, True), y)
ll = -.5 * ( np.dot(y.T, alpha) + n * np.log(2*np.pi)) - ld2
grad = -scipy.linalg.cho_solve((L, True), y)
return ll, grad
def ll_under_GPprior(X, y, cov, noise_var, K=None):
n = X.shape[0]
predict_tree = VectorTree(X, 1, cov.dfn_str, cov.dfn_params, cov.wfn_str, cov.wfn_params)
K = predict_tree.kernel_matrix(X, X, False)
K += np.eye(n) * noise_var
ll, grad = gaussian_logp(y, K)
return ll, grad
def dgaussian(r, prec, dcov, dmean=None):
# derivative of gaussian likelihood wrt derivatives of the mean, cov matrices
r = r.reshape((-1, 1))
#dprec = -np.dot(prec, np.dot(dcov, prec))
dprec_r = -np.dot(prec, np.dot(dcov, np.dot(prec, r)))
dll_dcov = -.5*np.dot(r.T, dprec_r)
#dll_dcov -= .5*np.trace(np.dot(prec, dcov))
dll_dcov -= .5*np.trace(np.dot(prec, dcov))
dll = dll_dcov
if dmean is not None:
dmean = dmean.reshape((-1, 1))
dll_dmean = np.dot(r.T, np.dot(prec, dmean))
dll += dll_dmean
return dll
def dgaussian_rank1(r, alpha, prec, dcov_v, p, dmean=None):
# derivative of gaussian likelihood wrt a rank-1 update
# in the cov matrix, where dcov_v is the change in the p'th
# row and column of the cov matrix (and assume dcov_v[p]=0 for symmetry).
# Also optionally dmean is a scalar, the change in the p'th entry of the mean vector
r = r.reshape((-1, 1))
#t1 = -np.dot(prec, dcov)
t1 = -np.outer(prec[p,:], dcov_v)
t1[:, p] = -np.dot(prec, dcov_v)
dll_dcov = -.5*np.dot(r.T, np.dot(t1, alpha))
dll_dcov += .5*np.trace(t1)
dll = dll_dcov
if dmean is not None:
dll_dmean = np.dot(r.T, dmean * prec[:, p])
dll += dll_dmean
return dll
def unpack_gpcov(d, prefix):
try:
wfn_str = d[prefix+'_wfn_str']
wfn_params = d[prefix+'_wfn_params']
dfn_str = d[prefix+'_dfn_str']
dfn_params = d[prefix+'_dfn_params']
try:
Xu = d[prefix+'_Xu']
except KeyError:
Xu = None
return GPCov(wfn_params=wfn_params, dfn_params=dfn_params, wfn_str=wfn_str, dfn_str=dfn_str, Xu=Xu)
except KeyError:
return None
def sort_morton(X, *args):
def cmp_zorder(a, b):
j = 0
k = 0
x = 0
dim = len(a)
for k in range(dim):
y = a[k] ^ b[k]
if less_msb(x, y):
j = k
x = y
return a[j] - b[j]
def less_msb(x, y):
return x < y and x < (x ^ y)
Xint = np.array((X + np.min(X, axis=0)) * 10000, dtype=int)
p = sorted(np.arange(Xint.shape[0]), cmp= lambda i,j : cmp_zorder(Xint[i,:], Xint[j,:]))
returns = [np.array(X[p,:], copy=True)]
for y in args:
returns.append(None if y is None else np.array(y[p], copy=True))
return tuple(returns)
class GPCov(object):
def __init__(self, wfn_params, dfn_params,
wfn_str="se", dfn_str="euclidean",
wfn_priors=None, dfn_priors=None,
Xu=None):
self.wfn_str =str(wfn_str)
self.wfn_params = np.array(wfn_params, dtype=float)
self.dfn_str = str(dfn_str)
self.dfn_params = np.array(dfn_params, dtype=float)
self.Xu = np.asarray(Xu) if Xu is not None else None
self.wfn_priors = wfn_priors
self.dfn_priors = dfn_priors
if self.wfn_priors is None:
self.wfn_priors = [None,] * len(self.wfn_params)
if self.dfn_priors is None:
self.dfn_priors = [None,] * len(self.dfn_params)
def copy(self):
return GPCov(wfn_params = self.wfn_params.copy(), dfn_params=self.dfn_params.copy(),
dfn_str = self.dfn_str, wfn_str=self.wfn_str,
wfn_priors=self.wfn_priors, dfn_priors=self.dfn_priors, Xu= self.Xu.copy() if self.Xu is not None else None)
def tree_params(self):
return (self.dfn_str, self.dfn_params, self.wfn_str, self.wfn_params)
def packed(self, prefix):
return {prefix + "_wfn_str": self.wfn_str,
prefix + "_wfn_params": self.wfn_params,
prefix + "_dfn_str": self.dfn_str,
prefix + "_dfn_params": self.dfn_params,
prefix + "_Xu": self.Xu}
def bounds(self, include_xu=True):
b = [(1e-8,None),] * (len(self.wfn_params) + len(self.dfn_params))
if include_xu and self.Xu is not None:
b += [(None, None),] * self.Xu.size
return b
def flatten(self, include_xu=True):
v = np.concatenate([self.wfn_params, self.dfn_params])
if include_xu and self.Xu is not None:
v = np.concatenate([v, self.Xu.flatten()])
return v
def prior_logp(self):
return prior_ll(self.dfn_params, self.dfn_priors) + prior_ll(self.wfn_params, self.wfn_priors)
def prior_grad(self, include_xu=True):
v = np.concatenate([prior_grad(self.wfn_params, self.wfn_priors) ,
prior_grad(self.dfn_params, self.dfn_priors)])
if include_xu and self.Xu is not None:
v = np.concatenate([v, np.zeros((self.Xu.size,))])
return v
def __repr__(self):
s = self.wfn_str + str(self.wfn_params) + ", " + self.dfn_str + str(self.dfn_params)
return s
class GP(object):
def standardize_input_array(self, c, **kwargs):
assert(len(c.shape) == 2)
return c
def training_kernel_matrix(self, X):
K = self.kernel(X, X, identical=True)
d = np.diag(K).copy() #+ 1e-8
if self.y_obs_variances is not None:
d += self.y_obs_variances
np.fill_diagonal(K, d)
return K
def sparse_training_kernel_matrix(self, X):
K = self.sparse_kernel(X, identical=True)
d = K.diagonal().copy() # + 1e-8
if self.y_obs_variances is not None:
d += self.y_obs_variances
K.setdiag(d)
return K.tocsc()
def invert_kernel_matrix_cheap(self, K):
prec, L, Lprec, logdet = pdinv(K)
Alpha, _ = dpotrs(L, self.y, lower=1)
factor = lambda z : dpotrs(L, z, lower=1)[0]
self.logdet = logdet
return Alpha, factor, L, prec
def invert_kernel_matrix(self, K):
alpha = None
t0 = time.time()
L = scipy.linalg.cholesky(K, lower=True) # c = sqrt(inv(B) + H*K^-1*H.T)
factor = lambda z : scipy.linalg.cho_solve((L, True), z)
t1 = time.time()
self.timings['chol_factor'] = t1-t0
alpha = factor(self.y)
t2 = time.time()
self.timings['solve_alpha'] = t2-t1
Kinv = np.linalg.inv(K)
t3 = time.time()
self.timings['solve_Kinv'] = t3-t2
#I = np.dot(Kinv[0,:], K[:,0])
#if np.abs(I - 1) > 0.01:
# print "WARNING: poorly conditioned inverse (I=%f)" % I
return alpha, factor, L, Kinv
def sparse_invert_kernel_matrix(self, K):
alpha = None
t0 = time.time()
factor = scikits.sparse.cholmod.cholesky(K)
t1 = time.time()
self.timings['chol_factor'] = t1-t0
alpha = factor(self.y)
t2 = time.time()
self.timings['solve_alpha'] = t2-t1
Kinv = factor(scipy.sparse.eye(K.shape[0]).tocsc())
t3 = time.time()
self.timings['solve_Kinv'] = t3-t2
I = (Kinv.getrow(0) * K.getcol(0)).todense()[0,0]
if np.abs(I - 1) > 0.01:
print "WARNING: poorly conditioned inverse (I=%f)" % I
unpermuted_L = factor.L()
P = factor.P()
Pinv = np.argsort(P)
L = unpermuted_L[Pinv,:][:,Pinv]
return alpha, factor, L, Kinv
def sparsify(self, M):
import scipy.sparse
if scipy.sparse.issparse(M):
M = M.copy()
chunksize=1000000
nchunks = len(M.data)/chunksize+1
for i in range(nchunks):
cond = (np.abs(M.data[i*chunksize:(i+1)*chunksize]) < self.sparse_threshold)
M.data[i*chunksize:(i+1)*chunksize][cond] = 0
M.eliminate_zeros()
return M
else:
return scipy.sparse.csc_matrix(np.asarray(M) * np.asarray(np.abs(M) > self.sparse_threshold))
def sort_events(self, X, y):
combined = np.hstack([X, np.reshape(y, (-1, 1))])
combined_sorted = np.array(sorted(combined, key = lambda x: x[0]), dtype=float)
X_sorted = np.array(combined_sorted[:, :-1], copy=True, dtype=float)
y_sorted = combined_sorted[:, -1].flatten()
return X_sorted, y_sorted
##############################################################################
# methods for building / interacting with low-rank additive covariances
def get_data_features(self, X):
# compute the full set of features for a matrix X of test points
features = np.zeros((self.n_features, X.shape[0]))
i = 0
if self.featurizer is not None:
F = self.featurizer(X)
i = F.shape[0]
features[:i,:] = F
if self.predict_tree_fic is not None:
features[i:,:] = self.kernel(self.cov_fic.Xu, X, predict_tree=self.predict_tree_fic)
return features
def combine_lowrank_models(self, H, b, B, K_fic_un, K_fic_uu):
# for training lowrank models: given feature representations
# (H, K_fic_un) and prior covariances (B, K_fic_uu) for two
# additive models, return the combined feature representation,
# combined parameter prior mean (assuming the FIC parameters
# have mean 0) and combined parameter precision matrix (we
# assume the parameters of the two models are independent, so
# this is block diagonal).
N = 0
self.n_features = 0
self.n_param_features = 0
if H is not None:
self.n_param_features = H.shape[0]
self.n_features += self.n_param_features
N = H.shape[1]
if K_fic_un is not None:
self.n_features += K_fic_un.shape[0]
N = K_fic_un.shape[1]
features = np.zeros((self.n_features, N))
mean = np.zeros((self.n_features,))
cov_inv = np.zeros((self.n_features, self.n_features))
if H is not None:
features[0:self.n_param_features, :] = H
mean[0:self.n_param_features] = b
cov_inv[0:self.n_param_features,0:self.n_param_features] = np.linalg.inv(B)
if K_fic_un is not None:
features[self.n_param_features:, :] = K_fic_un
cov_inv[self.n_param_features:,self.n_param_features:] = K_fic_uu
return features, mean, cov_inv
def build_low_rank_model(self, alpha, Kinv_sp, H, b, Binv):
"""
let n be the training size; we'll use an additional rank-m approximation.
the notation here follows section 2.7 in Rasmussen & Williams. For
simplicity, K refers to the observation covariance matrix rather than the
underlying function covariance (i.e. it might really be K+noise_var*I, or
K+diag(y_obs_variances), etc.)
takes:
alpha: n x 1, equal to K^-1 y
Kinv_sp: n x n sparse matrix, equal to K^-1
H: n x m features of training data (this is Qfu for FIC)
b: m x 1 prior mean on feature weights (this is 0 for FIC)
B: m x m prior covariance on feature weights (this is Quu for FIC)
returns:
invc = inv(chol(M)), where M = (B^-1 + H K^-1 H^T)^-1 is the
posterior covariance matrix on feature weights
beta_bar = M (HK^-1y + B^-1 b) gives the weights for the correction
of the low-rank component to the mean prediction
HKinv = HK^-1 comes up in the marginal likelihood computation, so we
go ahead and remember the value we compute now.
"""
# tmp = H * K^-1 * y + B^-1 * b
tmp = np.reshape(np.asarray(np.dot(H, alpha)), (-1,))
if b is not None:
tmp += np.dot(Binv, b)
HKinv = H * Kinv_sp
M_inv = Binv + np.dot(HKinv, H.T)
c = scipy.linalg.cholesky(M_inv, lower=True)
beta_bar = scipy.linalg.cho_solve((c, True), tmp)
invc = scipy.linalg.inv(c)
return c, invc, beta_bar, HKinv
def init_csfic_kernel(self, K_cs):
K_fic_uu = self.kernel(self.cov_fic.Xu, self.cov_fic.Xu, identical=False, predict_tree = self.predict_tree_fic)
Luu = scipy.linalg.cholesky(K_fic_uu, lower=True)
self.Luu = Luu
K_fic_un = self.kernel(self.cov_fic.Xu, self.X, identical=False, predict_tree = self.predict_tree_fic)
dc = self.covariance_diag_correction(self.X)
diag_correction = scipy.sparse.dia_matrix((dc, 0), shape=K_cs.shape)
K_cs = K_cs + diag_correction
return K_cs, K_fic_uu, K_fic_un
def setup_parametric_featurizer(self, X, featurizer_recovery, basis, extract_dim):
# setup featurizer for parametric mean function, if applicable
H = None
self.featurizer = None
self.featurizer_recovery = None
if featurizer_recovery is None:
if basis is not None:
H, self.featurizer, self.featurizer_recovery = featurizer_from_string(X, basis, extract_dim=extract_dim, transpose=True)
else:
self.featurizer, self.featurizer_recovery = recover_featurizer(basis, featurizer_recovery, transpose=True)
H = self.featurizer(X)
return H
###################################################################################
def setup_kernel_matrix(self, sparse_invert=False, build_tree=False):
try:
self.predict_tree
except:
self.predict_tree, self.predict_tree_fic = self.build_initial_single_trees(build_single_trees=sparse_invert)
if sparse_invert:
self._set_max_distance()
self.K = self.sparse_training_kernel_matrix(self.X)
else:
self.K = self.training_kernel_matrix(self.X)
if self.cov_fic is not None:
self.K, self.K_fic_uu, self.K_fic_un = self.init_csfic_kernel(self.K)
else:
self.K_fic_uu, self.K_fic_un = None, None
if sparse_invert:
if type(self.K) == np.ndarray or type(self.K) == np.matrix:
self.K = self.sparsify(self.K)
alpha, self.factor, L, Kinv = self.sparse_invert_kernel_matrix(self.K)
self.Kinv = self.sparsify(Kinv)
#print "Kinv is ", len(self.Kinv.nonzero()[0]) / float(self.Kinv.shape[0]**2), "full (vs diag at", 1.0/self.Kinv.shape[0], ")"
else:
alpha, self.factor, L, Kinv = self.invert_kernel_matrix_cheap(self.K)
if build_tree:
self.Kinv = self.sparsify(Kinv)
#print "Kinv is ", len(self.Kinv.nonzero()[0]) / float(self.Kinv.shape[0]**2), "full (vs diag at", 1.0/self.Kinv.shape[0], ")"
else:
self.Kinv=np.matrix(Kinv)
# not used for anything internally, but store it so that other classes can access
self.L = L
return alpha
def __init__(self, X=None, y=None,
y_obs_variances=None,
fname=None,
noise_var=1.0,
cov_main=None,
cov_fic=None,
basis = None,
extract_dim = None,
param_mean=None,
param_cov=None,
featurizer_recovery=None,
compute_ll=False,
compute_grad=False,
compute_xu_grad=False,
sparse_threshold=1e-10,
K = None,
sort_events=True,
build_tree=False,
compile_tree=None,
sparse_invert=True,
center_mean=False,
ymean=0.0,
leaf_bin_width = 0,
build_dense_Kinv_hack=False): # WARNING: bin sizes > 0 currently lead to memory leaks
self.double_tree = None
if fname is not None:
self.load_trained_model(fname, build_tree=build_tree, leaf_bin_width=leaf_bin_width, build_dense_Kinv_hack=build_dense_Kinv_hack, compile_tree=compile_tree, sparse_invert=sparse_invert)
return
if sort_events:
X, y, y_obs_variances = sort_morton(X, y, y_obs_variances) # arrange events by
# lon/lat, as a
# heuristic to expose
# block structure in the
# kernel matrix
self.cov_main, self.cov_fic, self.noise_var, self.sparse_threshold, self.basis = cov_main, cov_fic, noise_var, sparse_threshold, basis
self.timings = dict()
if X is not None:
self.X = np.matrix(X, dtype=float)
self.y = np.array(y, dtype=float)
if center_mean:
self.ymean = np.mean(y)
self.y -= self.ymean
else:
self.ymean = ymean
self.y -= self.ymean
self.n = X.shape[0]
if y_obs_variances is not None:
self.y_obs_variances = np.array(y_obs_variances, dtype=float).flatten()
else:
self.y_obs_variances = None
else:
self.X = np.reshape(np.array(()), (0,0))
self.y = np.reshape(np.array(()), (0,))
self.n = 0
self.ymean = ymean
self.K = np.reshape(np.array(()), (0,0))
self.Kinv = np.reshape(np.array(()), (0,0))
self.alpha_r = self.y
self.ll = np.float('-inf')
return
# compute sparse training kernel matrix (including
# per-observation noise if appropriate), and invert it.
alpha = self.setup_kernel_matrix(sparse_invert=sparse_invert,
build_tree=build_tree)
# setup the parameteric features, if applicable, and return the feature representation of X
H = self.setup_parametric_featurizer(self.X, featurizer_recovery,
basis, extract_dim)
if H is not None and param_mean is None:
n_features = H.shape[0]
param_mean = np.zeros((n_features,))
param_cov = np.eye(n_features) * 100.0
# if we have any additive low-rank covariances, compute the appropriate terms
if H is not None or cov_fic is not None:
HH, b, Binv = self.combine_lowrank_models(H, param_mean, param_cov, self.K_fic_un, self.K_fic_uu)
self.c, self.invc,self.beta_bar, self.HKinv = self.build_low_rank_model(alpha,
self.Kinv,
HH,
b,
Binv)
r = self.y - np.dot(HH.T, self.beta_bar)
self.alpha_r = np.reshape(np.asarray(self.factor(r)), (-1,))
z = np.dot(HH.T, b) - self.y
else:
self.n_features = 0
self.HKinv = None
self.alpha_r = np.reshape(alpha, (-1,))
r = self.y
z = self.y
Binv = None
HH = None
if build_tree:
self.build_point_tree(HKinv = self.HKinv, Kinv=self.Kinv, alpha_r = self.alpha_r, leaf_bin_width=leaf_bin_width, build_dense_Kinv_hack=build_dense_Kinv_hack, compile_tree=compile_tree)
# precompute training set log likelihood, so we don't need
# to keep L around.
if compute_ll:
self._compute_marginal_likelihood(L=self.L, z=z, Binv=Binv, H=HH, K=self.K, Kinv=self.Kinv)
else:
self.ll = -np.inf
if compute_grad:
self.ll_grad = self._log_likelihood_gradient(z=z, Kinv=self.Kinv, include_xu=compute_xu_grad)
def build_initial_single_trees(self, build_single_trees = False):
if build_single_trees:
tree_X = pyublas.why_not(self.X)
else:
tree_X = np.array([[0.0,] * self.X.shape[1],], dtype=float)
if self.cov_main is not None:
predict_tree = VectorTree(tree_X, 1, *self.cov_main.tree_params())
else:
predict_tree = None
if self.cov_fic is not None:
predict_tree_fic = VectorTree(tree_X, 1, *self.cov_fic.tree_params())
else:
predict_tree_fic = None
return predict_tree, predict_tree_fic
def _set_max_distance(self):
if self.cov_main.wfn_str=="se" and self.sparse_threshold>0:
self.max_distance = np.sqrt(-np.log(self.sparse_threshold))
elif self.cov_main.wfn_str.startswith("compact"):
self.max_distance = 1.0
else:
self.max_distance = 1e300
def build_point_tree(self, HKinv, Kinv, alpha_r, leaf_bin_width, build_dense_Kinv_hack=False, compile_tree=None):
if self.n == 0: return
self._set_max_distance()
fullness = len(self.Kinv.nonzero()[0]) / float(self.Kinv.shape[0]**2)
# print "Kinv is %.1f%% full." % (fullness * 100)
#if fullness > .15:
# raise Exception("not building tree, Kinv is too full!" )
self.predict_tree.set_v(0, alpha_r.astype(np.float))
if HKinv is not None:
self.cov_tree = VectorTree(self.X, self.n_features, *self.cov_main.tree_params())
HKinv = HKinv.astype(np.float)
for i in range(self.n_features):
self.cov_tree.set_v(i, HKinv[i, :])
nzr, nzc = Kinv.nonzero()
vals = np.reshape(np.asarray(Kinv[nzr, nzc]), (-1,))
if build_dense_Kinv_hack:
self.predict_tree.set_Kinv_for_dense_hack(nzr, nzc, vals)
t0 = time.time()
self.double_tree = MatrixTree(self.X, nzr, nzc, *self.cov_main.tree_params())
self.double_tree.set_m_sparse(nzr, nzc, vals)
if leaf_bin_width > 0:
self.double_tree.collapse_leaf_bins(leaf_bin_width)
t1 = time.time()
print "built product tree on %d points in %.3fs" % (self.n, t1-t0)
if compile_tree is not None:
#source_fname = compile_tree + ".cc"
#obj_fname = compile_tree + ".o"
linked_fname = compile_tree + "/main.so"
if not os.path.exists(linked_fname):
mkdir_p(compile_tree)
self.double_tree.compile(compile_tree, 0)
print "generated source files in ", compile_tree
import sys; sys.exit(1)
objfiles = []
for srcfile in os.listdir(compile_tree):
if srcfile.endswith(".cc"):
objfile = os.path.join(compile_tree, srcfile[:-3] + ".o")
objfiles.append(objfile)
os.system("gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -fPIC -I/home/dmoore/.virtualenvs/treegp/local/lib/python2.7/site-packages/pyublas/include -I/home/dmoore/.virtualenvs/treegp/local/lib/python2.7/site-packages/numpy/core/include -I/home/dmoore/local/include/ -I/usr/include/python2.7 -c %s -o %s -O3" % (os.path.join(compile_tree, srcfile), objfile))
os.system("g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro %s -L/ -lboost_python -o %s" % (" ".join(objfiles), linked_fname))
import imp
self.compiled_tree = imp.load_dynamic("compiled_tree", linked_fname)
self.compiled_tree.init_distance_caches()
def predict(self, cond, parametric_only=False, eps=1e-8):
if not self.double_tree: return self.predict_naive(cond, parametric_only)
X1 = self.standardize_input_array(cond).astype(np.float)
if parametric_only:
gp_pred = np.zeros((X1.shape[0],))
else:
gp_pred = np.array([self.predict_tree.weighted_sum(0, np.reshape(x, (1,-1)), eps) for x in X1])
if self.n_features > 0:
H = self.get_data_features(X1)
mean_pred = np.reshape(np.dot(H.T, self.beta_bar), gp_pred.shape)
gp_pred += mean_pred
if len(gp_pred) == 1:
gp_pred = gp_pred[0]
gp_pred += self.ymean
return gp_pred
def predict_naive(self, cond, parametric_only=False, eps=1e-8):
X1 = self.standardize_input_array(cond).astype(np.float)
if parametric_only:
gp_pred = np.zeros((X1.shape[0],))
else:
Kstar = self.kernel(self.X, X1)
gp_pred = np.dot(Kstar.T, self.alpha_r)
if self.n_features > 0:
H = self.get_data_features(X1)
mean_pred = np.reshape(np.dot(H.T, self.beta_bar), gp_pred.shape)
gp_pred += mean_pred
if len(gp_pred) == 1:
gp_pred = gp_pred[0]
gp_pred += self.ymean
return gp_pred
def dKdi(self, X1, X2, i, identical=False):
if (i == 0):
dKdi = np.eye(X1.shape[0]) if identical else np.zeros((X1.shape[0], X2.shape[0]))
elif (i == 1):
if (len(self.cov_main.wfn_params) != 1):
raise ValueError('gradient computation currently assumes just a single scaling parameter for weight function, but currently wfn_params=%s' % self.cov_main.wfn_params)
dKdi = self.kernel(X1, X2, identical=False) / self.cov_main.wfn_params[0]
else:
dc = self.predict_tree.kernel_matrix(X1, X2, True)
dKdi = self.predict_tree.kernel_deriv_wrt_i(X1, X2, i-2, 1 if identical else 0, dc)
return dKdi
def dKdx(self, X1, p, i, X2=None, return_vec=False):
# derivative of kernel(X1, X2) wrt i'th coordinate of p'th point in X1.
if X2 is None:
# consider k(X1, X1)
"""
n = X1.shape[0]
xp = np.array(X1[p:p+1,:], copy=True)
dK = np.zeros((n, n))
kp = self.predict_tree_fic.kernel_deriv_wrt_xi(xp, X1, 0, i)
dK[p,:] = kp
dK[:,p] = kp
"""
if return_vec:
dKv = np.zeros((X1.shape[0]))
self.predict_tree.kernel_deriv_wrt_xi_row(X1, p, i, dKv)
dKv[p] = 0
return dKv
else:
dK = self.predict_tree.kernel_deriv_wrt_xi(X1, X1, p, i)
dK[p,p] = 0
dK = dK + dK.T
else:
dK = self.predict_tree.kernel_deriv_wrt_xi(X1, X2, p, i)
return dK
def grad_prediction(self, cond, i):
"""
Compute the derivative of the predictive distribution (mean and
cov matrix) at a given location with respect to a kernel hyperparameter.
"""
# ONLY WORKS for zero-mean dense GPs with no inducing points or parametric components
X1 = self.standardize_input_array(cond).astype(np.float)
n_main_params = len(self.cov_main.flatten())
nparams = 1 + n_main_params
Kstar = self.kernel(X1, self.X)
dKstar = self.dKdi(X1, self.X, i, identical=False)
dKy = self.dKdi(self.X, self.X, i, identical=True)
dKyinv = -np.dot(self.Kinv, np.dot(dKy, self.Kinv))
Kstar_Kyinv = np.dot(Kstar, self.Kinv)
d_Kstar_Kyinv = np.dot(Kstar, dKyinv) + np.dot(dKstar, self.Kinv)
dmean = np.dot(d_Kstar_Kyinv, self.y)
#Kss = self.kernel(X1, X1)
dKss = self.dKdi(X1, X1, i, identical=True)
dqf = np.dot(d_Kstar_Kyinv, Kstar.T) + np.dot(Kstar_Kyinv, dKstar.T)
dcov = dKss - dqf
return dmean, dcov
def grad_prediction_wrt_source_x(self, cond, p, i):
# ONLY WORKS for zero-mean dense GPs with no inducing points or parametric components
X1 = self.standardize_input_array(cond).astype(np.float)
n_main_params = len(self.cov_main.flatten())
nparams = 1 + n_main_params
# can share Kstar over different vals of p, i
Kstar = self.kernel(X1, self.X)
Kstar_Kyinv = np.dot(Kstar, self.Kinv)
dKstar = self.dKdx(self.X, p, i, X1).T
# does not depend on X1: can be precomputed
# also lots of computation can be shared because only one row(/col) of dKy and dKstar should be nonzero
dKy = self.dKdx(self.X, p, i)
dKyinv = -np.dot(self.Kinv, np.dot(dKy, self.Kinv))
d_Kstar_Kyinv = np.dot(Kstar, dKyinv) + np.dot(dKstar, self.Kinv)
dm = np.dot(d_Kstar_Kyinv, self.y)
dqf = np.dot(d_Kstar_Kyinv, Kstar.T) + np.dot(Kstar_Kyinv, dKstar.T)
dc = -dqf
return dm, dc
def grad_prediction_wrt_target_x(self, cond, p, i):
# ONLY WORKS for zero-mean dense GPs with no inducing points or parametric components
X1 = self.standardize_input_array(cond).astype(np.float)
n_main_params = len(self.cov_main.flatten())
nparams = 1 + n_main_params
# can be shared over p, i
Kstar = self.kernel(X1, self.X)
Kss = self.kernel(X1, X1, identical=True)
# both of these are rank-1
dKss = self.dKdx(X1, p, i)
dKstar = self.dKdx(X1, p, i, X2=self.X)
dm = np.dot(dKstar, self.alpha_r)
dqf = np.dot(dKstar, np.dot(self.Kinv, Kstar.T))
dc = dKss - dqf - dqf.T
return dm, dc
def grad_ll_wrt_X(self):
# ONLY WORKS for zero-mean dense GPs with no inducing points or parametric components
n, d = self.X.shape
llgrad = np.zeros((n, d))
for p in range(n):
for i in range(d):
#dc = self.dKdx(self.X, p, i)
#llgrad2 = dgaussian(self.y, self.Kinv, dc)
dcv = self.dKdx(self.X, p, i, return_vec=True)
llgrad[p,i] = dgaussian_rank1(self.y, self.alpha_r, self.Kinv, dcv, p)
return llgrad
def kernel(self, X1, X2, identical=False, predict_tree=None):
predict_tree = self.predict_tree if predict_tree is None else predict_tree
K = predict_tree.kernel_matrix(X1, X2, False)
if identical:
K += self.noise_var * np.eye(K.shape[0])
return K
def sparse_kernel(self, X, identical=False, predict_tree=None, max_distance=None):
predict_tree = self.predict_tree if predict_tree is None else predict_tree
if max_distance is None:
max_distance = self.max_distance
entries = predict_tree.sparse_training_kernel_matrix(X, max_distance, False)
spK = scipy.sparse.coo_matrix((entries[:,2], (entries[:,1], entries[:,0])), shape=(self.n, len(X)), dtype=float)
if identical:
spK = spK + self.noise_var * scipy.sparse.eye(spK.shape[0])
return spK
def get_query_K_sparse(self, X1, no_R=False):
# avoid recomputing the kernel if we're evaluating at the same
# point multiple times. This is effectively a size-1 cache.
try:
self.querysp_hsh
except AttributeError:
self.querysp_hsh = None
hsh = hashlib.sha1(X1.view(np.uint8)).hexdigest()
if hsh != self.querysp_hsh:
self.querysp_K = self.sparse_kernel(X1)
self.querysp_hsh = hsh
if self.n_features > 0 and not no_R:
H = self.get_data_features(X1)
self.querysp_R = H - np.asmatrix(self.HKinv) * self.querysp_K
# print "cache fail: model %d called with " % (len(self.alpha)), X1
# else:
# print "cache hit!"
return self.querysp_K
def get_query_K(self, X1, no_R=False):
# avoid recomputing the kernel if we're evaluating at the same
# point multiple times. This is effectively a size-1 cache.
try:
self.query_hsh
except AttributeError:
self.query_hsh = None
hsh = hashlib.sha1(X1.view(np.uint8)).hexdigest()
if hsh != self.query_hsh:
self.query_K = self.kernel(self.X, X1)
self.query_hsh = hsh
if self.n_features > 0 and not no_R:
H = self.get_data_features(X1)
self.query_R = H - np.asmatrix(self.HKinv) * self.query_K
# print "cache fail: model %d called with " % (len(self.alpha)), X1
# else:
# print "cache hit!"
return self.query_K
def covariance_diag_correction(self, X):
K_fic_un = self.kernel(self.cov_fic.Xu, X, identical=False, predict_tree = self.predict_tree_fic)
B = scipy.linalg.solve(self.Luu, K_fic_un)
Qvff = np.sum(B*B, axis=0)
return self.cov_fic.wfn_params[0] - Qvff
def covariance_spkernel(self, cond, include_obs=False, parametric_only=False, pad=1e-8):
X1 = self.standardize_input_array(cond)
m = X1.shape[0]
t1 = time.time()
Kstar = self.get_query_K_sparse(X1, no_R=True)
if not parametric_only:
gp_cov = self.kernel(X1,X1, identical=include_obs)
if self.n > 0:
tmp = self.Kinv * Kstar
qf = (Kstar.T * tmp).todense()
gp_cov -= qf
else:
gp_cov = np.zeros((m,m))
t2 = time.time()
self.qf_time = t2-t1
if self.n_features > 0:
t1 = time.time()
H = self.get_data_features(X1)
R = H - np.asmatrix(self.HKinv) * self.querysp_K
#R = self.querysp_R
tmp = np.dot(self.invc, R)
mean_cov = np.dot(tmp.T, tmp)
gp_cov += mean_cov
t2 = time.time()
self.nonqf_time = t2-t1
gp_cov += pad * np.eye(gp_cov.shape[0])
if self.predict_tree_fic is not None:
gp_cov += np.diag(self.covariance_diag_correction(X1))
return gp_cov
def covariance_spkernel_solve(self, cond, include_obs=False, parametric_only=False, pad=1e-8):