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 | class ControlAffineRegressor(DynamicsModel):
"""
Scikit like wrapper around learning and predicting GaussianProcessRegressor
Usage:
F(X), COV(F(X)) = ControlAffineRegressor()
.fit(Xtrain, Utrain, XdotTrain)
.predict(Xtest, return_cov=True)
"""
ground_truth = False
def __init__(self, x_dim, u_dim, device=None, default_device=default_device,
gamma_length_scale_prior=None,
model_class=ControlAffineExactGP):
super().__init__()
self.device = device or default_device()
self.x_dim = x_dim
self.u_dim = u_dim
# Initialize model and likelihood
# Noise model for GPs
self.likelihood = IdentityLikelihood()
# Actual model
self.model_class = model_class
self.model = model_class(
x_dim, u_dim, self.likelihood,
gamma_length_scale_prior=gamma_length_scale_prior
).to(device=self.device)
self._cache = dict()
self._f_func_gp = GaussianProcess(self.f_func_mean, self.f_func_knl, (self.x_dim,), name="f")
@property
def ctrl_size(self):
return self.u_dim
@property
def state_size(self):
return self.x_dim
def _ensure_device_dtype(self, X):
if isinstance(X, np.ndarray):
X = torch.from_numpy(X)
X = X.to(device=self.device, dtype=next(self.model.parameters())[0].dtype)
return X
def fit(self, *args, max_cg_iterations=2000, **kwargs):
with warnings.catch_warnings(), \
gpsettings.max_cg_iterations(max_cg_iterations):
warnings.simplefilter("ignore")
return self._fit_with_warnings(*args, **kwargs)
def _fit_with_warnings(self, Xtrain_in, Utrain_in, XdotTrain_in, training_iter = 50,
lr=0.1):
if Xtrain_in.shape[0] == 0:
# Do nothing if no data
return self
device = self.device
model = self.model
likelihood = self.likelihood
# Convert to torch
Xtrain, Utrain, XdotTrain = [
self._ensure_device_dtype(X)
for X in (Xtrain_in, Utrain_in, XdotTrain_in)]
self.clear_cache()
model.set_train_data(Xtrain, Utrain, XdotTrain)
# Set in train mode
model.train()
likelihood.train()
# Find optimal model hyperparameters
# Use the adam optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer,
milestones=(torch.tensor([0.3, 0.6, 0.8, 0.90])*training_iter).tolist())
# "Loss" for GPs - the marginal log likelihood
# num_data refers to the amount of training data
# mll = VariationalELBO(likelihood, model, Y.numel())
mll = ExactMarginalLogLikelihood(likelihood, model)
for i in range(training_iter):
# Zero backpropped gradients from previous iteration
optimizer.zero_grad()
# Get predictive output
output = model(*model.train_inputs)
for p in model.parameters(recurse=True):
assert not torch.isnan(p).any()
# Calc loss and backprop gradients
loss = -mll(
output,
XdotTrain.reshape(-1) * (
1 + 1e-6 * torch.rand_like(XdotTrain.reshape(-1))))
assert not torch.isnan(loss).any()
assert not torch.isinf(loss).any()
loss.backward()
for p in model.parameters(recurse=True):
if p.grad is not None:
assert not torch.isnan(p.grad).any()
LOG.debug('Iter %d/%d - Loss: %.3f, lr: %.3g' % (i + 1, training_iter,
loss.item(),
scheduler.get_lr()[0]))
optimizer.step()
scheduler.step()
return self
def zero_grad(self):
for p in self.model.parameters():
if p.grad is not None:
p.grad.detach_()
p.grad.zero_()
def predict(self, Xtest_in, return_cov=True):
Xtest = self._ensure_device_dtype(Xtest_in)
# Switch back to eval mode
if self.model is None or self.likelihood is None:
raise RuntimeError("Call fit() with training data before calling predict")
# Set in eval mode
self.model.eval()
self.likelihood.eval()
# Concatenate the test set
_, MXUHtest = self.model.encode_from_XU(Xtest)
output = self.model(MXUHtest)
mean, cov = (output.mean.reshape(-1, *self.model.matshape),
output.covariance_matrix)
#mean_np, cov_np = [arr.detach().cpu().numpy() for arr in (mean, cov)]
mean = mean.to(device=Xtest_in.device, dtype=Xtest_in.dtype)
cov = cov.to(device=Xtest_in.device, dtype=Xtest_in.dtype)
return (mean, cov) if return_cov else mean
#return mean, cov
def _perturbed_cholesky_compute(self, k, B, Xtrain, UHtrain,
cholesky_tries=10,
cholesky_perturb_init=1e-5,
cholesky_perturb_scale=10):
KXX = k(Xtrain, Xtrain)
uBu = UHtrain @ B @ UHtrain.T
Kb = KXX * uBu
# Kb can be singular because of repeated datasamples
# Add diagonal jitter
Kbp, Kb_sqrt = make_psd(Kb)
return Kb_sqrt
def _perturbed_cholesky(self, k, B, Xtrain, UHtrain,
cache_key="perturbed_cholesky" ):
if cache_key not in self._cache:
self._cache[cache_key] = self._perturbed_cholesky_compute(
k, B, Xtrain, UHtrain)
return self._cache[cache_key]
def clear_cache(self):
self._cache = dict()
def custom_predict(self, Xtest_in, Utest_in=None, UHfill=1, Xtestp_in=None,
Utestp_in=None, UHfillp=1,
compute_cov=True,
grad_gp=False,
grad_check=False,
scalar_var_only=False):
"""
Gpytorch is complicated. It uses terminology like fantasy something,
something. Even simple exact prediction strategy uses Laczos. I do not
understand Laczos and Gpytorch code.
Let the training be handled by Gpytorch. After that i take things in my
own hands and predict myself.
Vector variate GP (preffered):
Kᶠ(u, u') = uᵀBu' ⊗ A = (uᵀBu)A = bᶠ(u, u') A
ẋ = f(x;u)
cov(f(x;u), f(x';u')) = k(x,x')Kᶠ(u, u') = k(x,x')bᶠ(u, u') ⊗ A
f(x; u) ~ 𝔾ℙ(μ(x)u, k(x, x')bᶠ(u, u') ⊗ A)
Kb⁻¹:= [k(xᵢ,xⱼ)uᵢᵀBuⱼ]ᵢⱼ
kb* := [k(xᵢ,xⱼ)uᵢᵀBuⱼ]ᵢⱼ
f*(x*; u) ~ 𝔾ℙ( {[(kb*ᵀK_b⁻¹) ⊗ Iₙ]}(Y-μ(x)u),
[kb(x*,x*) - k*bᵀKb⁻¹kb*] ⊗ A)
Algorithm (Rasmussen and Williams 2006)
1. L := cholesky(K)
2. α := Lᵀ \ ( L \ Y )
3. μ := kb*ᵀ α
4. v := L \ kb*
5. k* := k(x*,x*) - vᵀv
6. log p(y|X) := -0.5 yᵀ α - ∑ log Lᵢᵢ - 0.5 n log(2π)
"""
Xtest = self._ensure_device_dtype(Xtest_in)
Xtestp = (self._ensure_device_dtype(Xtestp_in) if Xtestp_in is not None
else Xtest)
if Utest_in is None:
UHtest = Xtest.new_zeros(Xtest.shape[0], self.model.matshape[0])
UHtest[:, 0] = 1
else:
Utest = self._ensure_device_dtype(Utest_in)
UHtest = torch.cat((Utest.new_full((Utest.shape[0], 1), UHfill),
Utest), dim=-1)
if Utestp_in is None:
UHtestp = UHtest
else:
Utestp = self._ensure_device_dtype(Utestp_in)
UHtestp = torch.cat((Utest.new_full((Utestp.shape[0], 1), UHfillp),
Utestp), dim=-1)
k_xx = lambda x, xp: self.model.covar_module.data_covar_module(
x, xp).evaluate()
if not grad_gp:
k_ss = k_xs = k_sx = k_xx
mean_s = self.model.mean_module
else:
def grad_mean_s(xs):
with variable_required_grad(xs):
# allow_unused=True because the mean_module can be ConstantMean
mean_xs = self.model.mean_module(xs)
grad_mean_xs = torch.autograd.grad(
list(mean_xs.flatten()),
xs, allow_unused=True)[0]
if grad_mean_xs is None:
return xs.new_zeros(xs.shape[0], *self.model.matshape,
xs.shape[-1])
else:
return grad_mean_xs.reshape(xs.shape[0],
*self.model.matshape,
xs.shape[-1])
mean_s = grad_mean_s
def grad_ksx(xs, xx):
with variable_required_grad(xs):
return torch.autograd.grad(list(k_xx(xs, xx)), xs)[0]
def grad_kxs(xx, xs):
with variable_required_grad(xs):
return torch.autograd.grad(list(k_xx(xx, xs)), xs)[0]
k_sx = grad_ksx
k_xs = grad_kxs
def Hessian_kxx(xs, xsp):
if xs is xsp:
xsp = xsp.detach().clone()
return t_hessian(k_xx, xs, xsp)
k_ss = Hessian_kxx
A = self.model.covar_module.task_covar_module.U.covar_matrix.evaluate()
B = self.model.covar_module.task_covar_module.V.covar_matrix.evaluate()
# Output of mean_s(Xtest) is (B, (1+m)n)
# Make it (B, (1+m), n, 1) then transpose
# (B, n, 1, (1+m)) and multiply with UHtest (B, (1+m)) to get
# (B, n, 1)
fX_mean_test = mean_s(Xtest)
fu_mean_test = (
fX_mean_test
.reshape(Xtest.shape[0], *self.model.matshape, -1) # (B, 1+m, n, n or 1)
.permute(0, 2, 3, 1) # (B, n, n or 1, 1+m)
.reshape(Xtest.shape[0], -1, self.model.matshape[0]) # (B, n(n or 1), 1+m)
.bmm(UHtest.unsqueeze(-1)) # (B, n(n or 1), 1)
.squeeze(-1) # (B, n(n or 1))
)
if self.model.train_inputs is None:
# We do not have training data just return the mean and prior covariance
if fX_mean_test.ndim == 4:
fu_mean_test = fu_mean_test.reshape(Xtest.shape[0], *self.model.matshape[1:], -1)
else:
fu_mean_test = fu_mean_test.reshape(Xtest.shape[0], *self.model.matshape[1:])
# Compute k(x*,x*) uᵀBu
kb_star_starp = k_ss(Xtest, Xtestp) * (UHtest @ B @ UHtestp.t())
# 5. k* := k(x*,x*) uᵀBu
scalar_var = kb_star_starp
return fu_mean_test, torch_kron(scalar_var.unsqueeze(0), A.unsqueeze(0))
MXUHtrain = self.model.train_inputs[0]
Mtrain, Xtrain, UHtrain = self.model.decoder.decode(MXUHtrain)
nsamples = Xtrain.size(0)
if grad_check and not grad_gp:
with variable_required_grad(Xtest):
old_dtype = self.dtype
self.double_()
torch.autograd.gradcheck(
lambda X: self.model.covar_module.data_covar_module(
Xtrain.double(), X).evaluate(),
Xtest.double())
gradgradcheck(
partial(lambda s, X, Xp: s.model.covar_module.data_covar_module(
X, Xp).evaluate(), self),
Xtest[:1, :].double())
self.to(dtype=old_dtype)
Y = (
self.model.train_targets.reshape(nsamples, -1)
- self.model.mean_module(Xtrain).reshape(nsamples,
*self.model.matshape)
.transpose(-2,-1)
.bmm(UHtrain.unsqueeze(-1))
.squeeze(-1)
)
# 1. L := cholesky(K)
Kb_sqrt = self._perturbed_cholesky(k_xx, B, Xtrain, UHtrain)
kb_star = k_xs(Xtrain, Xtest) * (UHtrain @ B @ UHtest.t())
if grad_check:
old_dtype = self.dtype
self.double_()
kb_star_func = lambda X: k_xs(Xtrain.double(), X) * (UHtrain.double() @ B.double() @ UHtest.double().t())
with variable_required_grad(Xtest):
torch.autograd.gradcheck(kb_star_func, Xtest.double())
self.to(dtype=old_dtype)
# 2. α := Lᵀ \ ( L \ Y )
α = torch.cholesky_solve(Y, Kb_sqrt) # check the shape of Y
# 3. μ := μ(x) + kb*ᵀ α
mean = fu_mean_test + kb_star.t() @ α
if compute_cov:
kb_star_p = (k_xs(Xtrain, Xtestp) * (UHtrain @ B @ UHtestp.t())
if Xtestp_in is not None
else kb_star)
kb_star_starp = k_ss(Xtest, Xtestp) * (UHtest @ B @ UHtestp.t())
if grad_check:
old_dtype = self.dtype
self.double_()
kb_star_starp_func = lambda X: k_ss(X, Xtestp.double()) * (UHtest @ B @ UHtestp.t()).double()
with variable_required_grad(Xtest):
torch.autograd.gradcheck(kb_star_starp_func, Xtest.double())
kb_star_star_func = lambda X, Xp: k_ss(X, Xp) * (UHtest @ B @ UHtestp.t()).double()
gradgradcheck(kb_star_star_func, Xtest.double())
self.to(dtype=old_dtype)
# 4. v := L \ kb*
v = torch.linalg.solve(Kb_sqrt, kb_star)
if grad_check:
old_dtype = self.dtype
self.double_()
v_func = lambda X: torch.linalg.solve(Kb_sqrt.double(), kb_star_func(X))
with variable_required_grad(Xtest):
torch.autograd.gradcheck(v_func, Xtest.double())
self.to(dtype=old_dtype)
vp = torch.linalg.solve(Kb_sqrt, kb_star_p) if Xtestp_in is not None else v
if grad_check:
old_dtype = self.dtype
self.double_()
v_func = lambda X: torch.linalg.solve(Kb_sqrt.double(), kb_star_func(X))
with variable_required_grad(Xtest):
torch.autograd.gradcheck(v_func, Xtest.double())
self.to(dtype=old_dtype)
# 5. k* := k(x*,x*) - vᵀv
scalar_var = kb_star_starp - v.t() @ vp
if grad_check:
old_dtype = self.dtype
self.double_()
scalar_var_func = lambda X: (
kb_star_starp_func(X)
- v_func(X).t() @ v_func(Xtestp.double()))
with variable_required_grad(Xtest):
torch.autograd.gradcheck(scalar_var_func, Xtest.double())
scalar_var_XX_func = lambda X, Xp: (
kb_star_star_func(X, Xp)
- v_func(X).t() @ v_func(Xp))
gradgradcheck(scalar_var_XX_func, Xtest.double())
self.model.float()
self.to(dtype=old_dtype)
covar_mat = torch_kron(scalar_var.unsqueeze(0), A.unsqueeze(0))
if grad_check:
old_dtype = self.dtype
self.double_()
covar_mat_func = lambda X: (scalar_var_func(X).reshape(-1, 1, 1) * A.double())[0,0]
with variable_required_grad(Xtest):
torch.autograd.gradcheck(covar_mat_func, Xtest.double())
self.model.float()
self.to(dtype=old_dtype)
else: # if not compute_cov
covar_mat = 0 * A
return mean, (scalar_var if scalar_var_only else covar_mat)
@property
def dtype(self):
return next(self.model.parameters())[0].dtype
def to(self, dtype=torch.float64):
if dtype is torch.float64:
self.double_()
else:
self.float_()
def double_(self):
self.model.double()
assert self.dtype is torch.float64
self.model.train_inputs = tuple([
inp.double()
for inp in self.model.train_inputs])
self.model.train_targets = self.model.train_targets.double()
for k, v in self._cache.items():
self._cache[k] = v.double()
def float_(self):
self.model.float()
assert self.dtype is torch.float32
self.model.train_inputs = tuple([
inp.float()
for inp in self.model.train_inputs])
self.model.train_targets = self.model.train_targets.float()
for k, v in self._cache.items():
self._cache[k] = v.float()
def _predict_flatten(self, Xtest_in, Utest_in):
"""
Directly predict
f(x, u) = f(x) + g(x) @ u
If you need f only, put Utest = [1, 0]
"""
device = self.device
if isinstance(Xtest_in, np.ndarray):
Xtest = torch.from_numpy(Xtest_in)
else:
Xtest = Xtest_in
Xtest = Xtest.to(device=device, dtype=self.dtype)
if isinstance(Utest_in, np.ndarray):
Utest = torch.from_numpy(Utest_in)
else:
Utest = Utest_in
Utest = Utest.to(device=device, dtype=self.dtype)
# Switch back to eval mode
if self.model is None or self.likelihood is None:
raise RuntimeError("Call fit() with training data before calling predict")
# Set in eval mode
self.model.eval()
self.likelihood.eval()
# Concatenate the test set
_, MXUHtest = self.model.encode_from_XU(Xtest, Utrain=Utest, M=1)
output = self.model(MXUHtest)
mean = output.mean.reshape(Xtest.shape[0], -1)
cov = output.covariance_matrix.reshape(Xtest.shape[0],
mean.shape[-1], mean.shape[-1],
Xtest.shape[0])
return (mean.to(device=Xtest_in.device, dtype=Xtest_in.dtype),
cov.to(device=Xtest_in.device, dtype=Xtest_in.dtype))
def f_func(self, Xtest_in, return_cov=False):
Xtest = (Xtest_in.unsqueeze(0)
if Xtest_in.ndim == 1
else Xtest_in)
Utest = Xtest.new_zeros((Xtest.shape[0], self.u_dim))
#mean_fx, cov_fx = self._predict_flatten(Xtest, Utest)
mean_fx, cov_fx = self.custom_predict(Xtest, Utest)
if return_cov:
if Xtest_in.ndim == 1:
cov_fx = cov_fx.squeeze(0)
cov_fx = cov_fx.to(dtype=Xtest_in.dtype, device=Xtest_in.device)
if Xtest_in.ndim == 1:
mean_fx = mean_fx.squeeze(0)
mean_fx = mean_fx.to(dtype=Xtest_in.dtype, device=Xtest_in.device)
return (mean_fx, cov_fx) if return_cov else mean_fx
def _A_mat(self):
return self.model.covar_module.task_covar_module.U.covar_matrix.evaluate()
def _B_mat(self):
return self.model.covar_module.task_covar_module.V.covar_matrix.evaluate()
def f_func_mean(self, Xtest_in):
Xtest = (Xtest_in.unsqueeze(0)
if Xtest_in.ndim == 1
else Xtest_in)
mean_f, _ = self.custom_predict(Xtest, compute_cov=False)
if Xtest_in.ndim == 1:
mean_f = mean_f.squeeze(0)
return mean_f.to(dtype=Xtest_in.dtype, device=Xtest_in.device)
def f_func_knl(self, Xtest_in, Xtestp_in, grad_check=False):
Xtest = (Xtest_in.unsqueeze(0)
if Xtest_in.ndim == 1
else Xtest_in)
Xtestp = (Xtestp_in.unsqueeze(0)
if Xtestp_in.ndim == 1
else Xtestp_in)
_, var_f = self.custom_predict(Xtest, Xtestp_in=Xtestp, compute_cov=True)
if Xtest_in.ndim == 1:
var_f = var_f.squeeze(0)
var_f_out = var_f.to(dtype=Xtest_in.dtype, device=Xtest_in.device)
if grad_check:
old_dtype = self.dtype
self.double_()
var_f_func = lambda X: self.custom_predict(
X, Xtestp_in=Xtestp, compute_cov=True)[1][0,0,0]
with variable_required_grad(Xtest):
torch.autograd.gradcheck(var_f_func, Xtest.double())
var_f_func_2 = lambda X, Xp: self.custom_predict(
X, Xtestp_in=Xp, compute_cov=True)[1][0,0,0]
gradgradcheck(var_f_func_2, Xtest.double())
self.model.float()
self.to(dtype=old_dtype)
return var_f_out
def f_func_gp(self):
#return GaussianProcess(self.f_func_mean, self.f_func_knl, (self.x_dim,))
return self._f_func_gp
def fu_func_mean(self, Utest_in, Xtest_in):
Xtest = (Xtest_in.unsqueeze(0)
if Xtest_in.ndim == 1
else Xtest_in)
Utest = (Utest_in.unsqueeze(0)
if Utest_in.ndim == 1
else Utest_in)
mean_f, _ = self.custom_predict(Xtest, Utest, compute_cov=False)
if Xtest_in.ndim == 1:
mean_f = mean_f.squeeze(0)
mean_f = mean_f.to(dtype=Xtest_in.dtype, device=Xtest_in.device)
return mean_f
def _grad_fu_func_mean(self, Xtest_in, Utest_in=None):
Xtest = (Xtest_in.unsqueeze(0)
if Xtest_in.ndim == 1
else Xtest_in)
Utest = (Utest_in.unsqueeze(0)
if Utest_in is not None and Utest_in.ndim == 1
else Utest_in)
mean_f, _ = self.custom_predict(Xtest, Utest, compute_cov=False,
grad_gp=True)
if Xtest_in.ndim == 1:
mean_f = mean_f.squeeze(0)
mean_f = mean_f.to(dtype=Xtest_in.dtype, device=Xtest_in.device)
return mean_f
def fu_func_knl(self, Utest_in, Xtest_in, Xtestp_in):
Xtest = (Xtest_in.unsqueeze(0)
if Xtest_in.ndim == 1
else Xtest_in)
Utest = (Utest_in.unsqueeze(0)
if Utest_in.ndim == 1
else Utest_in)
Xtestp = (Xtestp_in.unsqueeze(0)
if Xtestp_in.ndim == 1
else Xtestp_in)
_, var_f = self.custom_predict(Xtest, Utest,
Xtestp_in=Xtestp,
compute_cov=True)
if Xtest_in.ndim == 1:
var_f = var_f.squeeze(0)
var_f = var_f.to(dtype=Xtest_in.dtype, device=Xtest_in.device)
return var_f
def fu_func_gp(self, Utest_in):
gp = GaussianProcess(mean=partial(self.fu_func_mean, Utest_in),
knl=partial(self.fu_func_knl, Utest_in),
shape=(self.x_dim,),
name="F(.)u")
gp.register_covar(self._f_func_gp, partial(self.covar_fu_f, Utest_in))
return gp
def covar_fu_f(self, Utest_in, Xtest_in, Xtestp_in):
Xtest = (Xtest_in.unsqueeze(0)
if Xtest_in.ndim == 1
else Xtest_in)
Utest = (Utest_in.unsqueeze(0)
if Utest_in.ndim == 1
else Utest_in)
Xtestp = (Xtestp_in.unsqueeze(0)
if Xtestp_in.ndim == 1
else Xtestp_in)
Utestp = torch.zeros_like(Utest)
mean_f, var_f = self.custom_predict(Xtest, Utest,
Xtestp_in=Xtestp,
Utestp_in=Utestp,
compute_cov=True)
if Xtest_in.ndim == 1:
var_f = var_f.squeeze(0)
var_f = var_f.to(dtype=Xtest_in.dtype, device=Xtest_in.device)
return var_f
def g_func(self, Xtest_in, return_cov=False):
assert not return_cov, "Don't know what matrix covariance looks like"
Xtest = (Xtest_in.unsqueeze(0)
if Xtest_in.ndim == 1
else Xtest_in)
mean_Fx = self.predict(Xtest, return_cov=return_cov)
mean_gx = mean_Fx[:, 1:, :]
if Xtest_in.ndim == 1:
mean_gx = mean_gx.squeeze(0)
mean_gx = mean_gx.to(dtype=Xtest_in.dtype, device=Xtest_in.device)
return mean_gx.transpose(-2, -1)
def _gu_func(self, Xtest_in, Utest_in=None, return_cov=False, Xtestp_in=None):
Xtest = (Xtest_in.unsqueeze(0)
if Xtest_in.ndim == 1
else Xtest_in)
if Utest_in is not None:
Utest = (Utest_in.unsqueeze(0)
if Utest_in.ndim == 1
else Utest_in)
else:
Utest = Xtest_in.new_ones(Xtest.shape[0], self.u_dim)
mean_gu, var_gu = self.custom_predict(Xtest, Utest, UHfill=0,
Xtestp_in=Xtestp_in,
compute_cov=True)
if Xtest_in.ndim == 1 and Utest_in.ndim == 1:
mean_gu = mean_gu.squeeze(0)
var_gu = var_gu.squeeze(0)
return (mean_gu, var_gu) if return_cov else mean_gu
def g_func_mean(self, Xtest_in):
return self._gu_func(Xtest_in, return_cov=False)
def _cbf_func(self, Xtest, grad_htest, return_cov=False):
if return_cov:
mean_Fx, cov_Fx = self.predict(Xtest, return_cov=True)
cov_hFT = grad_htest.T @ cov_Fx @ grad_htest
else:
mean_Fx, cov_Fx = self.predict(Xtest, return_cov=False)
mean_hFT = grad_htest @ mean_Fx
return mean_hFT, cov_hFT
def state_dict(self):
return dict(model=self.model.state_dict(),
likelihood=self.likelihood.state_dict())
def load_state_dict(self, state_dict):
self.model.load_state_dict(state_dict['model'])
self.likelihood.load_state_dict(state_dict['likelihood'])
def save(self, path='/tmp/saved.pickle'):
torch.save(self.state_dict(), path)
def load(self, path='/tmp/saved.pickle'):
self.load_state_dict(torch.load(path))
def get_kernel_param(self, name):
if name == 'A':
return self._A_mat()
elif name == 'B':
return self._B_mat()
elif name == 'scalefactor':
assert isinstance(self.model.input_covar, ScaleKernel)
return self.model.input_covar.outputscale
elif name == 'lengthscale':
assert isinstance(self.model.input_covar.base_kernel, RBFKernel)
return self.model.input_covar.base_kernel.lengthscale
else:
raise ValueError('Unknown param %s' % name)
|