forked from charles92/autogpc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflexible_function.py
More file actions
2255 lines (1814 loc) · 79.4 KB
/
Copy pathflexible_function.py
File metadata and controls
2255 lines (1814 loc) · 79.4 KB
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
"""
Defines wrappers for mean, covariance and likelihood functions.
Also defines kernel manipulation routines.
Created November 2012
@authors: James Robert Lloyd (jrl44@cam.ac.uk)
David Duvenaud (dkd23@cam.ac.uk)
Roger Grosse (rgrosse@mit.edu)
--
Modified by Qiurui He (qh219@cam.ac.uk)
May 2016
"""
from __future__ import division
import itertools
from numpy import nan, inf
import numpy as np
import re
import operator
from utils import psd_matrices
import utils.misc
from utils.misc import colored, format_if_possible
from scipy.special import i0 # 0th order Bessel function of the first kind
##############################################
# #
# Base classes #
# #
##############################################
class FunctionWrapper:
"""Base class for mean / kernel / likelihood functions."""
# Properties - these are read-only and immutable
# e.g. @covSEiso
@property
def gpml_function(self): raise RuntimeError('This property must be overriden')
@property
def is_operator(self): return False
@property
def is_abelian(self):
if not self.is_operator:
return None # Not applicable
else:
raise RuntimeError('Operators must override this property')
# Identification used internally
@property
def id(self): raise RuntimeError('This property must be overriden')
# Parameters in the order defined by GPML
@property
def param_vector(self): raise RuntimeError('This property must be overriden')
@property
def num_params(self): return len(self.param_vector)
# Used by information criteria that count optimised parameters
@property
def effective_params(self):
if not self.is_operator:
'''This is true of all base functions, hence definition here'''
return len(self.param_vector)
else:
raise RuntimeError('Operators must override this property')
# LaTeX representation of function
@property
def latex(self): raise RuntimeError('This property must be overriden')
# Depth up the expression tree - leaves = 0
@property
def depth(self):
if not self.is_operator:
return 0
else:
raise RuntimeError('Operators must override this property')
# String representation of function without any parameters
@property
def syntax(self): raise RuntimeError('This property must be overriden')
# Hidden methods
def __repr__(self): return 'FunctionWrapper()'
# NOTE : This hash is defined for convenience but must be used with caution since this class is mutable
def __hash__(self): return hash(self.__repr__())
def __cmp__(self, other):
if cmp(self.__class__, other.__class__):
return cmp(self.__class__, other.__class__)
else:
# QUESTION : Is comparing strings very slow?
# If so this should be overidden for speed
return cmp(self.__repr__(), other.__repr__())
# Methods returning objects of the same type as self
def copy(self): raise RuntimeError('This method must be overriden')
# Returns a function with any syntactic redundancy removed (e.g. idempotency, zero elements...)
def simplified(self): return self.copy()
# Returns the canonical form of an object
def canonical(self): return self.copy()
def additive_form(self): return self.copy()
# Returns a list of summands
def break_into_summands(self): return [self.copy()]
# Methods returning different types
def initialise_params(self, sd=1, data_shape=None): raise RuntimeError('This method must be overriden')
def pretty_print(self): return RuntimeError('This method must be overriden')
def out_of_bounds(self, constraints): return False
def load_param_vector(self, params): return RuntimeError('This method must be overriden')
class MeanFunction(FunctionWrapper):
"""Base mean function class with default properties and methods."""
# Syntactic sugar e.g. f1 + f2
# Returns copies of involved functions - ensured by canonical operation
def __add__(self, other):
assert isinstance(other, MeanFunction)
if isinstance(other, SumFunction):
if isinstance(self, SumFunction):
new_f = self.copy()
new_f.operands = self.operands + other.operands
return new_f.canonical()
else:
new_f = self.copy()
new_f.operands = [self] + other.operands
return new_f.canonical()
else:
return SumFunction([self, other]).canonical()
# Syntactic sugar e.g. f1 * f2
# Returns copies of involved functions - ensured by canonical operation
def __mul__(self, other):
assert isinstance(other, MeanFunction)
if isinstance(other, ProductFunction):
if isinstance(self, ProductFunction):
new_f = self.copy()
new_f.operands = self.operands + other.operands
return new_f.canonical()
else:
new_f = self.copy()
new_f.operands = [self] + other.operands
return new_f.canonical()
else:
return ProductFunction([self, other]).canonical()
# Properties
@property
def is_thunk(self): return False
# Methods
def get_gpml_expression(self, dimensions):
if not self.is_operator:
if self.is_thunk or (dimensions == 1):
return self.gpml_function
else:
# Need to screen out dimensions
assert (self.dimension < dimensions) and (not self.dimension is None)
dim_vec = np.zeros(dimensions, dtype=int)
dim_vec[self.dimension] = 1
dim_vec_str = '[' + ' '.join(map(str, dim_vec)) + ']'
return '{@meanMask, {%s, %s}}' % (dim_vec_str, self.gpml_function)
else:
raise RuntimeError('Operators must override this method')
def __repr__(self): return 'MeanFunction()'
class Kernel(FunctionWrapper):
"""Base kernel class with default properties and methods"""
# Syntactic sugar e.g. k1 + k2
# Returns copies of involved functions - ensured by canonical operation
def __add__(self, other):
assert isinstance(other, Kernel)
if isinstance(other, SumKernel):
if isinstance(self, SumKernel):
new_f = self.copy()
new_f.operands = self.operands + other.operands
return new_f.canonical()
else:
new_f = self.copy()
new_f.operands = [self] + other.operands
return new_f.canonical()
else:
return SumKernel([self, other]).canonical()
# Syntactic sugar e.g. k1 * k2
# Returns copies of involved functions - ensured by canonical operation
def __mul__(self, other):
assert isinstance(other, Kernel)
if isinstance(other, ProductKernel):
if isinstance(self, ProductKernel):
new_f = self.copy()
new_f.operands = self.operands + other.operands
return new_f.canonical()
else:
new_f = self.copy()
new_f.operands = [self] + other.operands
return new_f.canonical()
else:
return ProductKernel([self, other]).canonical()
# Properties
@property
def is_stationary(self): return True
@property
def sf(self): raise RuntimeError('This must be overriden')
#### TODO - this only happens when a kernel is dimensionless?
@property
def is_thunk(self): return False
# Methods
def get_gpml_expression(self, dimensions):
if not self.is_operator:
if self.is_thunk or (dimensions == 1):
return self.gpml_function
else:
# Need to screen out dimensions
assert (self.dimension < dimensions) and (not self.dimension is None)
dim_vec = np.zeros(dimensions, dtype=int)
dim_vec[self.dimension] = 1
dim_vec_str = '[' + ' '.join(map(str, dim_vec)) + ']'
return '{@covMask, {%s, %s}}' % (dim_vec_str, self.gpml_function)
else:
raise RuntimeError('Operators must override this method')
def multiply_by_const(self, sf):
if not self.is_operator:
if hasattr(self, 'sf'):
self.sf += sf
else:
raise RuntimeError('Kernels without a scale factor must overide this method')
else:
raise RuntimeError('Operators must override this method')
def simplified(self):
k = self.copy()
k_prev = None
while not k_prev == k:
k_prev = k.copy()
k = k.collapse_additive_idempotency()
k = k.collapse_multiplicative_idempotency()
k = k.collapse_multiplicative_identity()
k = k.collapse_multiplicative_zero()
k = k.canonical()
return k
def __repr__(self): return 'Kernel()'
def canonical(self):
'''Sorts a kernel tree into a canonical form.'''
#### TODO - This can be abstracted to mean functions and likelihood functions by defining a None wrapper
if not self.is_operator:
return self.copy()
else:
new_ops = []
for op in self.operands:
op_canon = op.canonical()
if isinstance(op_canon, self.__class__) and (self.arity=='n'):
new_ops += op_canon.operands
elif not isinstance(op_canon, NoneKernel):
new_ops.append(op_canon)
if len(new_ops) == 0:
return NoneKernel()
elif len(new_ops) == 1:
return new_ops[0]
else:
canon = self.copy()
if self.is_abelian:
canon.operands = sorted(new_ops)
else:
canon.operands = new_ops
return canon
def additive_form(self):
'''
Converts a kernel into a sum of products and with changepoints percolating to the top
Output is always in canonical form
'''
#### TODO - currently implemented for a subset of changepoint operators - to be extended or operators to be abstracted
k = self.canonical()
if isinstance(k, ProductKernel):
# Convert operands into additive form
additive_ops = sorted([op.additive_form() for op in k.operands])
# Initialise the new kernel
new_kernel = additive_ops[0]
# Build up the product, iterating over the other components
for additive_op in additive_ops[1:]:
if isinstance(new_kernel, ChangePointKernel) or isinstance(new_kernel, ChangeWindowKernel):
# Changepoints take priority - nest the products within this operator
new_kernel.operands = [(op*additive_op.copy()).canonical().additive_form() for op in new_kernel.operands]
elif isinstance(additive_op, ChangePointKernel) or isinstance(additive_op, ChangeWindowKernel):
# Nest within the next operator
old_kernel = new_kernel.copy()
new_kernel = additive_op
new_kernel.operands = [(op*old_kernel.copy()).canonical().additive_form() for op in new_kernel.operands]
elif isinstance(new_kernel, SumKernel):
# Nest the products within this sum
new_kernel.operands = [(op*additive_op.copy()).canonical().additive_form() for op in new_kernel.operands]
elif isinstance(additive_op, SumKernel):
# Nest within the next operator
old_kernel = new_kernel.copy()
new_kernel = additive_op
new_kernel.operands = [(op*old_kernel.copy()).canonical().additive_form() for op in new_kernel.operands]
else:
# Both base kernels - just multiply
new_kernel = new_kernel*additive_op
# Make sure still in canonical form - useful mostly for detecting duplicates
new_kernel = new_kernel.canonical()
return new_kernel
elif k.is_operator:
# This operator is additive - make all operands additive
new_kernel = k.copy()
new_kernel.operands = [op.additive_form() for op in k.operands]
return new_kernel.canonical()
else:
#### TODO - Place a check here that the kernel is not a binary or higher operator
# Base case - return self
return k.canonical() # Just to make it clear that the output is always canonical
#### TODO - this can be abstracted to function wrapper level
def break_into_summands(self):
'''Takes a kernel, expands it into a polynomial, and breaks terms up into a list.
Mutually Recursive with distribute_products_k().
Always returns a list.
'''
k = self.copy()
# First, recursively distribute all products within the kernel.
k_dist = k.distribute_products()
if isinstance(k_dist, SumKernel):
# Break the summands into a list of kernels.
return list(k_dist.operands)
else:
return [k_dist]
def distribute_products(self):
"""Distributes products to get a polynomial.
Mutually recursive with break_kernel_into_summands().
Always returns a sumkernel.
"""
k = self.copy()
if isinstance(k, ProductKernel):
# Recursively distribute each of the terms to be multiplied.
distributed_ops = [op.break_into_summands() for op in k.operands]
# Now produce a sum of all combinations of terms in the products. Itertools is awesome.
new_prod_ks = [ProductKernel( operands=prod ) for prod in itertools.product(*distributed_ops)]
return SumKernel(operands=new_prod_ks)
elif isinstance(k, SumKernel):
# Recursively distribute each the operands to be summed, then combine them back into a new SumKernel.
return SumKernel([subop for op in k.operands for subop in op.break_into_summands()])
elif k.is_operator:
if k.arity == 2:
summands = []
operands_list = [[op, ZeroKernel()] for op in k.operands[0].break_into_summands()]
for ops in operands_list:
k_new = k.copy()
k_new.operands = ops
summands.append(k_new)
operands_list = [[ZeroKernel(), op] for op in k.operands[1].break_into_summands()]
for ops in operands_list:
k_new = k.copy()
k_new.operands = ops
summands.append(k_new)
return SumKernel(operands=summands)
else:
raise RuntimeError('Not sure how to distribute products of this operator')
else:
# Base case: A kernel that's just, like, a kernel, man.
return k
def collapse_additive_idempotency(self):
# TODO - abstract this behaviour
k = self.copy()
k = k.canonical()
if not k.is_operator:
return k
elif isinstance(k, SumKernel):
ops = [o.collapse_additive_idempotency() for o in k.operands]
# Count the number of white noises
sf = 0
WN_count = 0
not_WN_ops = []
for op in ops:
if isinstance(op, NoiseKernel):
WN_count += 1
sf += np.exp(2*op.sf)
else:
not_WN_ops.append(op)
# Compactify if necessary
if WN_count > 0:
ops = not_WN_ops + [NoiseKernel(sf=0.5*np.log(sf))]
# Now count the number of constants
sf = 0
const_count = 0
not_const_ops = []
for op in ops:
if isinstance(op, ConstKernel):
const_count += 1
sf += np.exp(2*op.sf)
else:
not_const_ops.append(op)
# Compactify if necessary
if (const_count > 0):
ops = not_const_ops + [ConstKernel(sf=0.5*np.log(sf))]
# Finish
k.operands = ops
return k.canonical()
else:
new_ops = []
for o in k.operands:
new_ops.append(o.collapse_additive_idempotency())
k.operands = new_ops
return k
def collapse_multiplicative_idempotency(self):
# TODO - abstract this behaviour
k = self.copy()
k = k.canonical()
if not k.is_operator:
return k
elif isinstance(k, ProductKernel):
ops = [o.collapse_multiplicative_idempotency() for o in k.operands]
# Count the number of SEs in different dimensions
lengthscales = {}
sfs = {}
not_SE_ops = []
for op in ops:
if isinstance(op, SqExpKernel):
if not lengthscales.has_key(op.dimension):
lengthscales[op.dimension] = np.Inf
sfs[op.dimension] = 0
lengthscales[op.dimension] = -0.5 * np.log(np.exp(-2*lengthscales[op.dimension]) + np.exp(-2*op.lengthscale))
sfs[op.dimension] += op.sf
else:
not_SE_ops.append(op)
# Compactify if necessary
ops = not_SE_ops
for dimension in lengthscales:
ops += [SqExpKernel(dimension=dimension, lengthscale=lengthscales[dimension], sf=sfs[dimension])]
# Count the number of white noises
sf = 0
WN_count = 0
not_WN_ops = []
for op in ops:
if isinstance(op, NoiseKernel):
WN_count += 1
sf += op.sf
else:
not_WN_ops.append(op)
# Compactify if necessary
if WN_count > 0:
ops = not_WN_ops + [NoiseKernel(sf=sf)]
# Now count the number of constants
sf = 0
const_count = 0
not_const_ops = []
for op in ops:
if isinstance(op, ConstKernel):
const_count += 1
sf += op.sf
else:
not_const_ops.append(op)
# Compactify if necessary
if const_count > 0:
ops = not_const_ops + [ConstKernel(sf=sf)]
# Finish
k.operands = ops
return k.canonical()
else:
new_ops = []
for o in k.operands:
new_ops.append(o.collapse_multiplicative_idempotency())
k.operands = new_ops
return k
def collapse_multiplicative_zero(self):
# TODO - abstract this behaviour
k = self.copy()
k = k.canonical()
if not k.is_operator:
return k
elif isinstance(k, ProductKernel):
ops = [o.collapse_multiplicative_zero() for o in k.operands]
sf = 0
WN_count = 0
not_WN_ops = []
for op in ops:
if isinstance(op, NoiseKernel):
WN_count += 1
sf += op.sf
elif op.is_stationary:
sf += op.sf
else:
not_WN_ops.append(op)
# Compactify if necessary
if WN_count > 0:
ops = not_WN_ops + [NoiseKernel(sf=sf)]
# Finish
k.operands = ops
return k.canonical()
else:
new_ops = []
for o in k.operands:
new_ops.append(o.collapse_multiplicative_zero())
k.operands = new_ops
return k
def collapse_multiplicative_identity(self):
# TODO - abstract this behaviour
k = self.copy()
k = k.canonical()
if not k.is_operator:
return k
elif isinstance(k, ProductKernel):
ops = [o.collapse_multiplicative_identity() for o in k.operands]
sf = 0
const_count = 0
not_const_ops = []
for op in ops:
if isinstance(op, ConstKernel):
const_count += 1
sf += op.sf
else:
not_const_ops.append(op)
# Compactify if necessary
if const_count > 0:
ops = not_const_ops
ops[0].multiply_by_const(sf=sf)
# Finish
k.operands = ops
return k.canonical()
else:
new_ops = []
for o in k.operands:
new_ops.append(o.collapse_multiplicative_identity())
k.operands = new_ops
return k
def cp_structure(self):
# Replaces most things with constants - useful for understanding structure of changepoints
k = self.copy()
if isinstance(k, ZeroKernel) or isinstance(k, NoneKernel): # TODO - can this be abstracted?
return k
elif not k.is_operator:
return ConstKernel(sf=0)
else:
k.operands = [op.cp_structure() for op in k.operands]
return k
class Likelihood(FunctionWrapper):
"""Base likelihood function class with default properties and methods"""
# Syntactic sugar e.g. l1 + l2
# Returns copies of involved functions - ensured by canonical operation
def __add__(self, other):
assert isinstance(other, Likelihood)
if isinstance(other, SumLikelihood):
if isinstance(self, SumLikelihood):
new_f = self.copy()
new_f.operands = self.operands + other.operands
return new_f.canonical()
else:
new_f = self.copy()
new_f.operands = [self] + other.operands
return new_f.canonical()
else:
return SumLikelihood([self, other]).canonical()
# Syntactic sugar e.g. l1 * l2
# Returns copies of involved functions - ensured by canonical operation
def __mul__(self, other):
assert isinstance(other, Likelihood)
if isinstance(other, ProductLikelihood):
if isinstance(self, ProductLikelihood):
new_f = self.copy()
new_f.operands = self.operands + other.operands
return new_f.canonical()
else:
new_f = self.copy()
new_f.operands = [self] + other.operands
return new_f.canonical()
else:
return ProductLikelihood([self, other]).canonical()
# Properties
@property
def gpml_inference_method(self): return '@infExact'
# Methods
def get_gpml_expression(self, dimensions):
if not self.is_operator:
if self.is_thunk or (dimensions == 1):
return self.gpml_function
else:
# Need to screen out dimensions
assert self.dimension < dimensions
dim_vec = np.zeros(dimensions, dtype=int)
dim_vec[self.dimension] = 1
dim_vec_str = '[' + ' '.join(map(str, dim_vec)) + ']'
return '{@meanMask, {%s, %s}}' % (dim_vec_str, self.gpml_function)
else:
raise RuntimeError('Operators must override this method')
def __repr__(self): return 'Likelihood()'
class GPModel:
"""Model class - keeps track of a mean function, kernel, likelihood function,
and optionally a score."""
def __init__(self, mean=None, kernel=None, likelihood=None, nll=None, ndata=None):
assert isinstance(mean, MeanFunction) or (mean is None)
assert isinstance(kernel, Kernel) or (kernel is None)
assert isinstance(likelihood, Likelihood) or (likelihood is None)
self.mean = mean
self.kernel = kernel
self.likelihood = likelihood
self.nll = nll
self.ndata = ndata
def __hash__(self): return hash(self.__repr__())
def __repr__(self):
# Remember all the various scoring criteria
return 'GPModel(mean=%s, kernel=%s, likelihood=%s, nll=%s, ndata=%s)' % \
(self.mean.__repr__(), self.kernel.__repr__(), self.likelihood.__repr__(), self.nll, self.ndata)
def __cmp__(self, other):
if cmp(self.__class__, other.__class__):
return cmp(self.__class__, other.__class__)
else:
return cmp(self.__repr__(), other.__repr__())
def copy(self):
m = self.mean.copy() if not self.mean is None else None
k = self.kernel.copy() if not self.kernel is None else None
l = self.likelihood.copy() if not self.likelihood is None else None
return GPModel(mean=m, kernel=k, likelihood=l, nll=self.nll, ndata=self.ndata)
def pretty_print(self):
return 'GPModel(mean=%s, kernel=%s, likelihood=%s)' % \
(self.mean.pretty_print(), self.kernel.pretty_print(), self.likelihood.pretty_print())
def out_of_bounds(self, constraints):
return any([self.mean.out_of_bounds(constraints), \
self.kernel.out_of_bounds(constraints), \
self.likelihood.out_of_bounds(constraints)])
@property
def bic(self):
return 2 * self.nll + self.kernel.effective_params * np.log(self.ndata)
@property
def aic(self):
return 2 * self.nll + self.kernel.effective_params * 2
@property
def pl2(self):
return self.nll / self.ndata + self.kernel.effective_params / (2 * self.ndata)
@staticmethod
def score(self, criterion='bic'):
return {'bic': self.bic,
'aic': self.aic,
'pl2': self.pl2,
'nll': self.nll
}[criterion.lower()]
@staticmethod
def from_printed_outputs(nll=None, ndata=None, noise=None, mean=None, kernel=None, likelihood=None):
return GPModel(mean=mean, kernel=kernel, likelihood=likelihood, nll=nll, ndata=ndata)
@staticmethod
def from_matlab_output(output, model, ndata):
model.mean.load_param_vector(output.mean_hypers)
model.kernel.load_param_vector(output.kernel_hypers)
model.likelihood.load_param_vector(output.lik_hypers)
return GPModel(mean=model.mean, kernel=model.kernel, likelihood=model.likelihood, nll=output.nll, ndata=ndata)
def simplified(self):
simple = self.copy()
simple.mean = simple.mean.simplified()
simple.kernel = simple.kernel.simplified()
simple.likelihood = simple.likelihood.simplified()
return simple
def canonical(self):
canon = self.copy()
canon.mean = canon.mean.canonical()
canon.kernel = canon.kernel.canonical()
canon.likelihood = canon.likelihood.canonical()
return canon
def additive_form(self):
# This will need to be more cunning when using compound mean and lik
additive = self.copy()
additive.kernel = additive.kernel.additive_form()
return additive
def break_into_summands(self):
mean_list = self.mean.break_into_summands()
kernel_list = self.kernel.break_into_summands()
likelihood_list = self.likelihood.break_into_summands()
model_list = []
for a_mean in mean_list:
model_list.append(GPModel(mean=a_mean, kernel=ZeroKernel(), likelihood=LikGauss(sf=-np.Inf)))
for a_kernel in kernel_list:
model_list.append(GPModel(mean=MeanZero(), kernel=a_kernel, likelihood=LikGauss(sf=-np.Inf)))
for a_likelihood in likelihood_list:
model_list.append(GPModel(mean=MeanZero(), kernel=ZeroKernel(), likelihood=a_likelihood))
null_model = GPModel(ean=MeanZero(), kernel=ZeroKernel(), likelihood=LikGauss(sf=-np.Inf))
model_list = [model for model in model_list if not model == null_model]
return model_list
##############################################
# #
# Mean functions #
# #
##############################################
class MeanZero(MeanFunction):
def __init__(self):
pass
# Properties
@property
def gpml_function(self): return '{@meanZero}'
@property
def is_thunk(self): return True
@property
def id(self): return 'Zero'
@property
def param_vector(self): return np.array([])
@property
def latex(self): return '{\\emptyset}'
@property
def syntax(self): return colored('MZ', self.depth)
# Methods
def copy(self): return MeanZero()
def initialise_params(self, sd=1, data_shape=None):
pass
def __repr__(self):
return 'MeanZero()'
def pretty_print(self):
return colored('MZ', self.depth)
def load_param_vector(self, params):
assert len(params) == 0
class MeanConst(MeanFunction):
def __init__(self, c=None):
self.c = c
# Properties
@property
def gpml_function(self): return '{@meanConst}'
@property
def is_thunk(self): return True
@property
def id(self): return 'Const'
@property
def param_vector(self): return np.array([self.c])
@property
def latex(self): return '{\\sc C}'
@property
def syntax(self): return colored('C', self.depth)
# Methods
def copy(self): return MeanConst(c=self.c)
def initialise_params(self, sd=1, data_shape=None):
if self.c == None:
# Set offset with data
if np.random.rand() < 0.5:
self.c = np.random.normal(loc=data_shape['y_mean'], scale=sd*np.exp(data_shape['y_sd']))
else:
self.c = np.random.normal(loc=0, scale=sd*np.exp(data_shape['y_sd']))
def __repr__(self):
return 'MeanConst(c=%s)' % (self.c)
def pretty_print(self):
return colored('C(c=%s)' % (format_if_possible('%1.1f', self.c)), self.depth)
def load_param_vector(self, params):
c, = params # N.B. - expects list input
self.c = c
##############################################
# #
# Kernel functions #
# #
##############################################
# I hope this class can be deleted one day
class NoneKernel(Kernel):
def __init__(self):
pass
def copy(self): return NoneKernel()
def __repr__(self):
return 'NoneKernel()'
def multiply_by_const(self, sf):
pass
@property
def param_vector(self): return np.array([])
class ZeroKernel(Kernel):
def __init__(self):
pass
# Properties
@property
def gpml_function(self): return '{@covZero}'
@property
def is_thunk(self): return True
@property
def id(self): return 'Zero'
@property
def param_vector(self): return np.array([])
@property
def latex(self): return '{\\sc Z}'
@property
def syntax(self): return colored('Z', self.depth)
# Methods
def copy(self): return ZeroKernel()
def initialise_params(self, sd=1, data_shape=None):
pass
def __repr__(self):
return 'ZeroKernel()'
def pretty_print(self):
return colored('Z', self.depth)
def load_param_vector(self, params):
pass
def multiply_by_const(self, sf):
pass
class NoiseKernel(Kernel):
def __init__(self, sf=None):
self.sf = sf
# Properties
@property
def gpml_function(self): return '{@covNoise}'
@property
def is_thunk(self): return True
@property
def id(self): return 'Noise'
@property
def param_vector(self): return np.array([self.sf])
@property
def latex(self): return '{\\sc WN}'
@property
def syntax(self): return colored('WN', self.depth)
# Methods
def copy(self): return NoiseKernel(sf=self.sf)
def initialise_params(self, sd=1, data_shape=None):
if self.sf == None:
# Set scale factor with 1/10 data std or neutrally
if np.random.rand() < 0.5:
self.sf = np.random.normal(loc=data_shape['y_sd']-np.log(10), scale=sd)
else:
self.sf = np.random.normal(loc=0, scale=sd)
def __repr__(self):
return 'NoiseKernel(sf=%s)' % (self.sf)
def pretty_print(self):
return colored('WN(sf=%s)' % (format_if_possible('%1.1f', self.sf)), self.depth)
def load_param_vector(self, params):
sf, = params # N.B. - expects list input
self.sf = sf
class ConstKernel(Kernel):
def __init__(self, sf=None):
self.sf = sf
# Properties
@property
def gpml_function(self): return '{@covConst}'
@property
def is_thunk(self): return True
@property
def id(self): return 'Const'
@property
def param_vector(self): return np.array([self.sf])
@property
def latex(self): return '{\\sc C}'
@property
def syntax(self): return colored('C', self.depth)
# Methods
def copy(self): return ConstKernel(sf=self.sf)
def initialise_params(self, sd=1, data_shape=None):
if self.sf == None:
# Set scale factor with output location, scale or neutrally
if np.random.rand() < 1.0 / 3:
self.sf = np.random.normal(loc=np.log(np.abs(data_shape['y_mean'])), scale=sd)
elif np.random.rand() < 1.0 / 2:
self.sf = np.random.normal(loc=data_shape['y_sd'], scale=sd)
else:
self.sf = np.random.normal(loc=0, scale=sd)
def __repr__(self):
return 'ConstKernel(sf=%s)' % (self.sf)
def pretty_print(self):
return colored('C(sf=%s)' % (format_if_possible('%1.1f', self.sf)), self.depth)
def load_param_vector(self, params):