-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpla_e.m
2301 lines (2015 loc) · 95.3 KB
/
gpla_e.m
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
function [e, edata, eprior, param] = gpla_e(w, gp, varargin)
%GPLA_E Do Laplace approximation and return marginal log posterior estimate
%
% Description
% E = GPLA_E(W, GP, X, Y, OPTIONS) takes a GP structure GP
% together with a matrix X of input vectors and a matrix Y of
% target vectors, and finds the Laplace approximation for the
% conditional posterior p(Y | X, th), where th is the
% parameters. Returns the energy at th (see below). Each
% row of X corresponds to one input vector and each row of Y
% corresponds to one target vector.
%
% [E, EDATA, EPRIOR] = GPLA_E(W, GP, X, Y, OPTIONS) returns also
% the data and prior components of the total energy.
%
% The energy is minus log posterior cost function for th:
% E = EDATA + EPRIOR
% = - log p(Y|X, th) - log p(th),
% where th represents the parameters (lengthScale,
% magnSigma2...), X is inputs and Y is observations.
%
% OPTIONS is optional parameter-value pair
% z - optional observed quantity in triplet (x_i,y_i,z_i)
% Some likelihoods may use this. For example, in case of
% Poisson likelihood we have z_i=E_i, that is, expected
% value for ith case.
%
% References
%
% Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian
% Processes for Machine Learning. The MIT Press.
%
% Jarno Vanhatalo, Pasi Jylänki and Aki Vehtari (2009). Gaussian
% process regression with Student-t likelihood. In Y. Bengio et al,
% editors, Advances in Neural Information Processing Systems 22,
% pp. 1910-1918
%
% See also
% GP_SET, GP_E, GPLA_G, GPLA_PRED
% Description 2
% Additional properties meant only for internal use.
%
% GP = GPLA_E('init', GP) takes a GP structure GP and
% initializes required fields for the Laplace approximation.
%
% GP = GPLA_E('clearcache', GP) takes a GP structure GP and clears the
% internal cache stored in the nested function workspace.
%
% [e, edata, eprior, f, L, a, La2, p] = GPLA_E(w, gp, x, y, varargin)
% returns many useful quantities produced by EP algorithm.
%
% The Newton's method is implemented as described in Rasmussen
% and Williams (2006).
%
% The stabilized Newton's method is implemented as suggested by
% Hannes Nickisch (personal communication).
%
% Copyright (c) 2007-2010 Jarno Vanhatalo
% Copyright (c) 2010 Aki Vehtari
% Copyright (c) 2010 Pasi Jylänki
% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.
% parse inputs
ip=inputParser;
ip.FunctionName = 'GPLA_E';
ip.addRequired('w', @(x) ...
isempty(x) || ...
(ischar(x) && strcmp(w, 'init')) || ...
isvector(x) && isreal(x) && all(isfinite(x)) ...
|| all(isnan(x)));
ip.addRequired('gp',@isstruct);
ip.addOptional('x', @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))
ip.addOptional('y', @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))
ip.addParamValue('z', [], @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))
ip.parse(w, gp, varargin{:});
x=ip.Results.x;
y=ip.Results.y;
z=ip.Results.z;
if strcmp(w, 'init')
% Initialize cache
ch = [];
% set function handle to the nested function laplace_algorithm
% this way each gp has its own peristent memory for EP
gp.fh.ne = @laplace_algorithm;
% set other function handles
gp.fh.e=@gpla_e;
gp.fh.g=@gpla_g;
gp.fh.pred=@gpla_pred;
gp.fh.jpred=@gpla_jpred;
gp.fh.looe=@gpla_looe;
gp.fh.loog=@gpla_loog;
gp.fh.loopred=@gpla_loopred;
e = gp;
% remove clutter from the nested workspace
clear w gp varargin ip x y z
elseif strcmp(w, 'clearcache')
% clear the cache
gp.fh.ne('clearcache');
else
% call laplace_algorithm using the function handle to the nested function
% this way each gp has its own peristent memory for Laplace
%[e, edata, eprior, f, L, a, La2, p] = gp.fh.ne(w, gp, x, y, z);
[e, edata, eprior, param] = gp.fh.ne(w, gp, x, y, z);
end
function [e, edata, eprior, param] = laplace_algorithm(w, gp, x, y, z)
if strcmp(w, 'clearcache')
ch=[];
return
end
% code for the Laplace algorithm
% check whether saved values can be used
if isempty(z)
datahash=hash_sha512([x y]);
else
datahash=hash_sha512([x y z]);
end
if ~isempty(ch) && all(size(w)==size(ch.w)) && all(abs(w-ch.w)<1e-8) && ...
isequal(datahash,ch.datahash)
% The covariance function parameters or data haven't changed so we
% can return the energy and the site parameters that are
% saved in the cache
e = ch.e;
edata = ch.edata;
eprior = ch.eprior;
param.f = ch.f;
param.L = ch.L;
param.La2 = ch.La2;
param.a = ch.a;
param.p = ch.p;
else
% The parameters or data have changed since
% the last call for gpla_e. In this case we need to
% re-evaluate the Laplace approximation
gp=gp_unpak(gp, w);
ncf = length(gp.cf);
n = size(x,1);
p = [];
maxiter = gp.latent_opt.maxiter;
tol = gp.latent_opt.tol;
% Initialize latent values
% zero seems to be a robust choice (Jarno)
% with mean functions, initialize to mean function values
if ~isfield(gp,'meanf')
% f = zeros(size(y));
% f = (y - mean(y))/std(y) + mean(y);
else
[H,b_m,B_m]=mean_prep(gp,x,[]);
f = H'*b_m;
end
% =================================================
% First Evaluate the data contribution to the error
switch gp.type
% ============================================================
% FULL
% ============================================================
case 'FULL'
if ~isfield(gp.lik, 'nondiagW')
K = gp_trcov(gp, x);
if isfield(gp,'meanf')
K=K+H'*B_m*H;
end
% If K is sparse, permute all the inputs so that evaluations are more efficient
if issparse(K) % Check if compact support covariance is used
p = analyze(K);
y = y(p);
K = K(p,p);
if ~isempty(z)
z = z(p,:);
end
end
switch gp.latent_opt.optim_method
% --------------------------------------------------------------------------------
% find the posterior mode of latent variables by Newton method
case 'newton'
a = f;
if isfield(gp,'meanf')
a = a-H'*b_m;
end
W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);
dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);
lp_new = gp.lik.fh.ll(gp.lik, y, f, z);
lp_old = -Inf;
if issparse(K)
speyen=speye(n);
end
iter=0;
while abs(lp_new - lp_old) > tol && iter < maxiter
iter = iter + 1;
lp_old = lp_new; a_old = a;
sW = sqrt(W);
if issparse(K)
sW = sparse(1:n, 1:n, sW, n, n);
[L,notpositivedefinite] = ldlchol(speyen+sW*K*sW );
else
%L = chol(eye(n)+sW*sW'.*K); % L'*L=B=eye(n)+sW*K*sW
L=bsxfun(@times,bsxfun(@times,sW,K),sW');
L(1:n+1:end)=L(1:n+1:end)+1;
[L, notpositivedefinite] = chol(L);
end
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
if ~isfield(gp,'meanf')
b = W.*f+dlp;
else
b = W.*f+K\(H'*b_m)+dlp;
end
if issparse(K)
a = b - sW*ldlsolve(L,sW*(K*b));
else
a = b - sW.*(L\(L'\(sW.*(K*b))));
end
if any(isnan(a))
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
f = K*a;
lp = gp.lik.fh.ll(gp.lik, y, f, z);
if ~isfield(gp,'meanf')
lp_new = -a'*f/2 + lp;
else
lp_new = -(f-H'*b_m)'*(a-K\(H'*b_m))/2 + lp; %f^=f-H'*b_m,
end
i = 0;
while i < 10 && (lp_new < lp_old || isnan(sum(f)))
% reduce step size by half
a = (a_old+a)/2;
f = K*a;
lp = gp.lik.fh.ll(gp.lik, y, f, z);
if ~isfield(gp,'meanf')
lp_new = -a'*f/2 + lp;
else
lp_new = -(f-H'*b_m)'*(a-K\(H'*b_m))/2 + lp;
end
i = i+1;
end
W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);
dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);
end
% --------------------------------------------------------------------------------
% find the posterior mode of latent variables by stabilized Newton method.
% This is implemented as suggested by Hannes Nickisch (personal communication)
case 'stabilized-newton'
% Gaussian initialization
% sigma=gp.lik.sigma;
% W = ones(n,1)./sigma.^2;
% sW = sqrt(W);
% %B = eye(n) + siV*siV'.*K;
% L=bsxfun(@times,bsxfun(@times,sW,K),sW');
% L(1:n+1:end)=L(1:n+1:end)+1;
% L = chol(L,'lower');
% a=sW.*(L'\(L\(sW.*y)));
% f = K*a;
% initialize to observations
%f=y;
switch gp.lik.type
% should be handled inside lik_*
case 'Student-t'
nu=gp.lik.nu;
sigma2=gp.lik.sigma2;
Wmax=(nu+1)/nu/sigma2;
case 'Negbinztr'
r=gp.lik.disper;
Wmax=1./((1+r)./(1*r));
otherwise
Wmax=100;
end
Wlim=0;
W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);
dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);
lp = -(f'*(K\f))/2 +gp.lik.fh.ll(gp.lik, y, f, z);
lp_old = -Inf;
f_old = f+1;
ge = Inf; %max(abs(a-dlp));
if issparse(K)
speyen=speye(n);
end
iter=0;
% begin Newton's iterations
while (lp - lp_old > tol || max(abs(f-f_old)) > tol) && iter < maxiter
iter=iter+1;
W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);
dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);
W(W<Wlim)=Wlim;
sW = sqrt(W);
if issparse(K)
sW = sparse(1:n, 1:n, sW, n, n);
[L, notpositivedefinite] = ldlchol(speyen+sW*K*sW );
else
%L = chol(eye(n)+sW*sW'.*K); % L'*L=B=eye(n)+sW*K*sW
L=bsxfun(@times,bsxfun(@times,sW,K),sW');
L(1:n+1:end)=L(1:n+1:end)+1;
[L, notpositivedefinite] = chol(L);
end
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
b = W.*f+dlp;
if issparse(K)
a = b - sW*ldlsolve(L,sW*(K*b));
else
a = b - sW.*(L\(L'\(sW.*(K*b))));
end
f_new = K*a;
lp_new = -(a'*f_new)/2 + gp.lik.fh.ll(gp.lik, y, f_new, z);
ge_new=max(abs(a-dlp));
d=lp_new-lp;
if (d<-1e-6 || (abs(d)<1e-6 && ge_new>ge) ) && Wlim<Wmax*0.5
%fprintf('%3d, p(f)=%.12f, max|a-g|=%.12f, %.3f \n',i1,lp,ge,Wlim)
Wlim=Wlim+Wmax*0.05; %Wmax*0.01
else
Wlim=0;
ge=ge_new;
lp_old = lp;
lp = lp_new;
f_old = f;
f = f_new;
%fprintf('%3d, p(f)=%.12f, max|a-g|=%.12f, %.3f \n',i1,lp,ge,Wlim)
end
if Wlim>Wmax
%fprintf('\n%3d, p(f)=%.12f, max|a-g|=%.12f, %.3f \n',i1,lp,ge,Wlim)
break
end
end
% --------------------------------------------------------------------------------
% find the posterior mode of latent variables by fminunc
case 'fminunc_large'
if issparse(K)
[LD,notpositivedefinite] = ldlchol(K);
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
fhm = @(W, f, varargin) (ldlsolve(LD,f) + repmat(W,1,size(f,2)).*f); % W*f; %
else
[LD,notpositivedefinite] = chol(K);
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
fhm = @(W, f, varargin) (LD\(LD'\f) + repmat(W,1,size(f,2)).*f); % W*f; %
end
defopts=struct('GradObj','on','Hessian','on','HessMult', fhm,'TolX', tol,'TolFun', tol,'LargeScale', 'on','Display', 'off');
if ~isfield(gp.latent_opt, 'fminunc_opt')
opt = optimset(defopts);
else
opt = optimset(defopts,gp.latent_opt.fminunc_opt);
end
if issparse(K)
fe = @(f, varargin) (0.5*f*(ldlsolve(LD,f')) - gp.lik.fh.ll(gp.lik, y, f', z));
fg = @(f, varargin) (ldlsolve(LD,f') - gp.lik.fh.llg(gp.lik, y, f', 'latent', z))';
fh = @(f, varargin) (-gp.lik.fh.llg2(gp.lik, y, f', 'latent', z)); %inv(K) + diag(g2(f', gp.lik)) ; %
else
fe = @(f, varargin) (0.5*f*(LD\(LD'\f')) - gp.lik.fh.ll(gp.lik, y, f', z));
fg = @(f, varargin) (LD\(LD'\f') - gp.lik.fh.llg(gp.lik, y, f', 'latent', z))';
fh = @(f, varargin) (-gp.lik.fh.llg2(gp.lik, y, f', 'latent', z)); %inv(K) + diag(g2(f', gp.lik)) ; %
end
mydeal = @(varargin)varargin{1:nargout};
[f,fval,exitflag,output] = fminunc(@(ww) mydeal(fe(ww), fg(ww), fh(ww)), f', opt);
f = f';
if issparse(K)
a = ldlsolve(LD,f);
else
a = LD\(LD'\f);
end
% --------------------------------------------------------------------------------
% find the posterior mode of latent variables with likelihood specific algorithm
% For example, with Student-t likelihood this mean EM-algorithm which is coded in the
% lik_t file.
case 'lik_specific'
[f, a] = gp.lik.fh.optimizef(gp, y, K);
if isnan(f)
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
otherwise
error('gpla_e: Unknown optimization method ! ')
end
% evaluate the approximate log marginal likelihood
W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);
if ~isfield(gp,'meanf')
logZ = 0.5 *f'*a - gp.lik.fh.ll(gp.lik, y, f, z);
else
logZ = 0.5 *((f-H'*b_m)'*(a-K\(H'*b_m))) - gp.lik.fh.ll(gp.lik, y, f, z);
end
if min(W) >= 0
% This is the usual case where likelihood is log concave
% for example, Poisson and probit
if issparse(K)
W = sparse(1:n,1:n, -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z), n,n);
sqrtW = sqrt(W);
B = sparse(1:n,1:n,1,n,n) + sqrtW*K*sqrtW;
[L, notpositivedefinite] = ldlchol(B);
% Note that here we use LDL cholesky
edata = logZ + 0.5.*sum(log(diag(L))); % 0.5*log(det(eye(size(K)) + K*W)) ; %
else
sW = sqrt(W);
L=bsxfun(@times,bsxfun(@times,sW,K),sW');
L(1:n+1:end)=L(1:n+1:end)+1;
[L, notpositivedefinite] = chol(L, 'lower');
edata = logZ + sum(log(diag(L))); % 0.5*log(det(eye(size(K)) + K*W)) ; %
end
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
else
% We may end up here if the likelihood is not log concave
% For example Student-t likelihood.
[W2,I] = sort(W, 1, 'descend');
if issparse(K)
error(['gpla_e: Unfortunately the compact support covariance (CS) functions do not work if'...
'the second gradient of negative likelihood is negative. This happens for example '...
'with Student-t likelihood. Please use non-CS functions instead (e.g. gpcf_sexp) ']);
end
[L, notpositivedefinite] = chol(K);
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
L1 = L;
for jj=1:size(K,1)
i = I(jj);
ll = sum(L(:,i).^2);
l = L'*L(:,i);
upfact = W(i)./(1 + W(i).*ll);
% Check that Cholesky factorization will remain positive definite
if 1./ll + W(i) < 0 %1 + W(i).*ll <= 0 | abs(upfact) > abs(1./ll) %upfact > 1./ll
warning('gpla_e: 1./Sigma(i,i) + W(i) < 0')
if ~isfield(gp.lik.fh,'upfact')
% log-concave likelihood, this should not happen
% let's just return NaN
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
% non-log-concave likelihood, this may happen
% let's try to do something about it
ind = 1:i-1;
if isempty(z)
mu = K(i,ind)*gp.lik.fh.llg(gp.lik, y(I(ind)), f(I(ind)), 'latent', z);
upfact = gp.lik.fh.upfact(gp, y(I(i)), mu, ll);
else
mu = K(i,ind)*gp.lik.fh.llg(gp.lik, y(I(ind)), f(I(ind)), 'latent', z(I(ind)));
upfact = gp.lik.fh.upfact(gp, y(I(i)), mu, ll, z(I(i)));
end
end
if upfact > 0
[L,notpositivedefinite] = cholupdate(L, l.*sqrt(upfact), '-');
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
else
L = cholupdate(L, l.*sqrt(-upfact));
end
end
edata = logZ + sum(log(diag(L1))) - sum(log(diag(L)));
end
La2 = W;
else
% Likelihoods with non-diagonal Hessian
[n,nout] = size(y);
if isfield(gp, 'comp_cf') % own covariance for each ouput component
multicf = true;
if length(gp.comp_cf) ~= nout && nout > 1
error('GPLA_ND_E: the number of component vectors in gp.comp_cf must be the same as number of outputs.')
end
else
multicf = false;
end
p=[];
switch gp.lik.type
case {'LGP', 'LGPC'}
nl=n;
% Initialize latent values
% zero seems to be a robust choice (Jarno)
% with mean functions, initialize to mean function values
if ~isfield(gp,'meanf')
f = zeros(sum(nl),1);
else
[H,b_m,B_m]=mean_prep(gp,x,[]);
Hb_m=H'*b_m;
f = Hb_m;
end
if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1
% Use Kronecker product kron(Ka,Kb) instead of K
gptmp=gp; gptmp.jitterSigma2=0;
ls=gptmp.cf{1}.lengthScale;
if numel(ls)>1
gptmp.cf{1}.lengthScale=ls(1);
end
Ka = gp_trcov(gptmp, unique(x(:,1)));
% fix the magnitude sigma to 1 for Kb matrix
wtmp=gp_pak(gptmp); wtmp(1)=0; gptmp=gp_unpak(gptmp,wtmp);
if numel(ls)>1
gptmp.cf{1}.lengthScale=ls(2);
end
Kb = gp_trcov(gptmp, unique(x(:,2)));
clear gptmp
n1=size(Ka,1);
n2=size(Kb,1);
[Va,Da]=eig(Ka); [Vb,Db]=eig(Kb);
% eigenvalues of K matrix
Dtmp=kron(diag(Da),diag(Db));
[sDtmp,istmp]=sort(Dtmp,'descend');
% Form the low-rank approximation. Exclude eigenvalues
% smaller than gp.latent_opt.eig_tol or take
% gp.latent_opt.eig_prct*n eigenvalues at most.
nlr=min([sum(sDtmp>gp.latent_opt.eig_tol) round(gp.latent_opt.eig_prct*n)]);
sDtmp=sDtmp+gp.jitterSigma2;
itmp1=meshgrid(1:n1,1:n2);
itmp2=meshgrid(1:n2,1:n1)';
ind=[itmp1(:) itmp2(:)];
% included eigenvalues
Dlr=sDtmp(1:nlr);
% included eigenvectors
Vlr=zeros(n,nlr);
for i1=1:nlr
Vlr(:,i1)=kron(Va(:,ind(istmp(i1),1)),Vb(:,ind(istmp(i1),2)));
end
%L=[];
% diag(K)-diag(Vlr*diag(Dlr)*Vlr')
Lb=gp_trvar(gp,x)-sum(bsxfun(@times,Vlr.*Vlr,Dlr'),2);
if isfield(gp,'meanf')
Dt=[Dlr; diag(B_m)];
Vt=[Vlr H'];
else
Dt=Dlr;
Vt=Vlr;
end
Dtsq=sqrt(Dt);
elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1
% unique values from covariance matrix
K1 = gp_cov(gp, x(1,:), x);
K1(1)=K1(1)+gp.jitterSigma2;
if size(x,2)==1
% form circulant matrix to avoid border effects
Kcirc=[K1 0 K1(end:-1:2)];
fftKcirc = fft(Kcirc);
elseif size(x,2)==2
n1=gp.latent_opt.gridn(1);
n2=gp.latent_opt.gridn(2);
Ktmp=reshape(K1,n2,n1);
% form circulant matrix to avoid border effects
Ktmp=[Ktmp; zeros(1,n1); flipud(Ktmp(2:end,:))];
fftKcirc=fft2([Ktmp zeros(2*n2,1) fliplr(Ktmp(:,2:end))]);
else
error('FFT speed-up implemented only for 1D and 2D cases.')
end
else
K = gp_trcov(gp, x);
end
% Mean function contribution to K
if isfield(gp,'meanf')
if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1
% only zero mean function implemented for Kronecker
% approximation
iKHb_m=zeros(n,1);
elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1
% only zero mean function implemented for FFT speed-up
iKHb_m=zeros(n,1);
else
K=K+H'*B_m*H;
ws=warning('off','MATLAB:singularMatrix');
iKHb_m=K\Hb_m;
warning(ws);
end
end
% Main Newton algorithm
tol = 1e-12;
a = f;
if isfield(gp,'meanf')
a = a-Hb_m;
end
% a vector to form the second gradient
g2 = gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);
g2sq=sqrt(g2);
ny=sum(y); % total number of observations
dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);
lp_new = gp.lik.fh.ll(gp.lik, y, f, z);
lp_old = -Inf;
iter=0;
while abs(lp_new - lp_old) > tol && iter < maxiter
iter = iter + 1;
lp_old = lp_new; a_old = a;
if ~isfield(gp,'meanf')
if strcmpi(gp.lik.type,'LGPC')
n1=gp.lik.gridn(1); n2=gp.lik.gridn(2);
b=zeros(n,1);
ny2=sum(reshape(y,fliplr(gp.lik.gridn)));
for k1=1:n1
b((1:n2)+(k1-1)*n2) = ny2(k1)*(g2((1:n2)+(k1-1)*n2).*f((1:n2)+(k1-1)*n2)-g2((1:n2)+(k1-1)*n2)*(g2((1:n2)+(k1-1)*n2)'*f((1:n2)+(k1-1)*n2)))+dlp((1:n2)+(k1-1)*n2);
end
else
b = ny*(g2.*f-g2*(g2'*f))+dlp;
%b = W.*f+dlp;
end
else
if strcmpi(gp.lik.type,'LGPC')
n1=gp.lik.gridn(1); n2=gp.lik.gridn(2);
b=zeros(n,1);
ny2=sum(reshape(y,fliplr(gp.lik.gridn)));
for k1=1:n1
b((1:n2)+(k1-1)*n2) = ny2(k1)*(g2((1:n2)+(k1-1)*n2).*f((1:n2)+(k1-1)*n2)-g2((1:n2)+(k1-1)*n2)*(g2((1:n2)+(k1-1)*n2)'*f((1:n2)+(k1-1)*n2)))+iKHb_m((1:n2)+(k1-1)*n2)+dlp((1:n2)+(k1-1)*n2);
end
else
b = ny*(g2.*f-g2*(g2'*f))+iKHb_m+dlp;
%b = W.*f+K\(H'*b_m)+dlp;
end
end
if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1
% Use Kronecker product structure in matrix vector
% multiplications
%-
% q=Kb*reshape(b,n2,n1)*Ka;
% Kg=q(:);
% Kg=Kg+gp.jitterSigma2*b;
%-
% OR use reduced-rank approximation for K
%-
Kg=Lb.*b+Vlr*(Dlr.*(Vlr'*b));
%-
if isfield(gp,'meanf')
Kg=Kg+H'*(B_m*(H*b));
end
% % Use Kronecker product structure
%-
% v=sqrt(ny)*(g2sq.*Kg-(g2*(g2'*Kg))./g2sq);
% % fast matrix vector multiplication with
% % Kronecker product for matrix inversion
% if isfield(gp,'meanf')
% [iSg,~]=pcg(@(z) mvm_kron(g2,ny,Ka,Kb,H,B_m,gp.jitterSigma2,z), v, gp.latent_opt.pcg_tol);
% else
% [iSg,~]=pcg(@(z) mvm_kron(g2,ny,Ka,Kb,[],[],gp.jitterSigma2,z), v, gp.latent_opt.pcg_tol);
% end
% a=b-sqrt(ny)*(g2sq.*iSg - g2*(g2'*(iSg./g2sq)));
%-
% use reduced-rank approximation for K
%-
Zt=1./(1+ny*g2.*Lb);
Ztsq=sqrt(Zt);
Ltmp=bsxfun(@times,Ztsq.*sqrt(ny).*g2sq,bsxfun(@times,Vt,sqrt(Dt)'));
Ltmp=Ltmp'*Ltmp;
Ltmp(1:(size(Dt,1)+1):end)=Ltmp(1:(size(Dt,1)+1):end)+1;
[L,notpositivedefinite] = chol(Ltmp,'lower');
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
EKg=ny*g2.*(Zt.*Kg)-sqrt(ny)*g2sq.*(Zt.*(sqrt(ny)*g2sq.*(Vt*(Dtsq.*(L'\(L\(Dtsq.*(Vt'*(sqrt(ny)*g2sq.*(Zt.*(sqrt(ny)*g2sq.*Kg)))))))))));
E1=ny*g2.*(Zt.*ones(n,1))-sqrt(ny)*g2sq.*(Zt.*(sqrt(ny)*g2sq.*(Vt*(Dtsq.*(L'\(L\(Dtsq.*(Vt'*(sqrt(ny)*g2sq.*(Zt.*(sqrt(ny)*g2sq.*ones(n,1))))))))))));
a=b-(EKg-E1*((E1'*Kg)./(ones(1,n)*E1)));
%-
elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1
% use FFT speed-up in matrix vector multiplications
if size(x,2)==1
gge=zeros(2*n,1);
gge(1:n)=b;
q=ifft(fftKcirc.*fft(gge'));
Kg=q(1:n)';
elseif size(x,2)==2
gge=zeros(2*n2,2*n1);
gge(1:n2,1:n1)=reshape(b,n2,n1);
q=ifft2(fftKcirc.*fft2(gge));
q=q(1:n2,1:n1);
Kg=q(:);
else
error('FFT speed-up implemented only for 1D and 2D cases.')
end
if isfield(gp,'meanf')
Kg=Kg+H'*(B_m*(H*b));
end
v=sqrt(ny)*(g2sq.*Kg-(g2*(g2'*Kg))./g2sq);
if isfield(gp,'meanf')
% fast matrix vector multiplication with fft for matrix inversion
[iSg,~]=pcg(@(z) mvm_fft(g2,ny,fftKcirc,H,B_m,z), v, gp.latent_opt.pcg_tol);
else
[iSg,~]=pcg(@(z) mvm_fft(g2,ny,fftKcirc,[],[],z), v, gp.latent_opt.pcg_tol);
end
a=b-sqrt(ny)*(g2sq.*iSg - g2*(g2'*(iSg./g2sq)));
else
if strcmpi(gp.lik.type,'LGPC')
R=zeros(n);
RKR=K;
for k1=1:n1
R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2)=sqrt(ny2(k1))*(diag(g2sq((1:n2)+(k1-1)*n2))-g2((1:n2)+(k1-1)*n2)*g2sq((1:n2)+(k1-1)*n2)');
RKR(:,(1:n2)+(k1-1)*n2)=RKR(:,(1:n2)+(k1-1)*n2)*R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2);
end
for k1=1:n1
RKR((1:n2)+(k1-1)*n2,:)=R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2)'*RKR((1:n2)+(k1-1)*n2,:);
end
%RKR=R'*K*R;
RKR(1:(n+1):end)=RKR(1:(n+1):end)+1;
[L,notpositivedefinite] = chol(RKR,'lower');
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
Kb=K*b;
RCb=R'*Kb;
iRCb=L'\(L\RCb);
a=b-R*iRCb;
else
%R=-g2*g2sq'; R(1:(n+1):end)=R(1:(n+1):end)+g2sq';
KR=bsxfun(@times,K,g2sq')-(K*g2)*g2sq';
RKR=ny*(bsxfun(@times,g2sq,KR)-g2sq*(g2'*KR));
RKR(1:(n+1):end)=RKR(1:(n+1):end)+1;
[L,notpositivedefinite] = chol(RKR,'lower');
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
Kb=K*b;
RCb=g2sq.*Kb-g2sq*(g2'*Kb);
iRCb=L'\(L\RCb);
a=b-ny*(g2sq.*iRCb-g2*(g2sq'*iRCb));
end
end
if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1
% % Use Kronecker product structure
%-
% f2=Kb*reshape(a,n2,n1)*Ka;
% f=f2(:);
% f=f+gp.jitterSigma2*a;
%-
% use reduced-rank approximation for K
%-
f=Lb.*a+Vlr*(Dlr.*(Vlr'*a));
%-
if isfield(gp,'meanf')
f=f+H'*(B_m*(H*a));
end
elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1
if size(x,2)==1
a2=zeros(2*n,1);
a2(1:n)=a;
f2=ifft(fftKcirc.*fft(a2'));
f=f2(1:n)';
if isfield(gp,'meanf')
f=f+H'*(B_m*(H*a));
end
elseif size(x,2)==2
a2=zeros(2*n2,2*n1);
a2(1:n2,1:n1)=reshape(a,n2,n1);
f2=ifft2(fftKcirc.*fft2(a2));
f2=f2(1:n2,1:n1);
f=f2(:);
if isfield(gp,'meanf')
f=f+H'*(B_m*(H*a));
end
else
error('FFT speed-up implemented only for 1D and 2D cases.')
end
else
f = K*a;
end
lp = gp.lik.fh.ll(gp.lik, y, f, z);
if ~isfield(gp,'meanf')
lp_new = -a'*f/2 + lp;
else
%lp_new = -(f-H'*b_m)'*(a-K\(H'*b_m))/2 + lp; %f^=f-H'*b_m,
lp_new = -(f-Hb_m)'*(a-iKHb_m)/2 + lp; %f^=f-Hb_m,
end
i = 0;
while i < 10 && lp_new < lp_old && ~isnan(sum(f))
% reduce step size by half
a = (a_old+a)/2;
if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1
% % Use Kronecker product structure
%-
% f2=Kb*reshape(a,n2,n1)*Ka;
% f=f2(:);
% f=f+gp.jitterSigma2*a;
%-
% use reduced-rank approximation for K
%-
f=Lb.*a+Vlr*(Dlr.*(Vlr'*a));
%-
if isfield(gp,'meanf')
f=f+H'*(B_m*(H*a));
end
elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1
if size(x,2)==1
a2=zeros(2*n,1);
a2(1:n)=a;
f2=ifft(fftKcirc.*fft(a2'));
f=f2(1:n)';
if isfield(gp,'meanf')
f=f+H'*(B_m*(H*a));
end
elseif size(x,2)==2
a2=zeros(2*n2,2*n1);
a2(1:n2,1:n1)=reshape(a,n2,n1);
f2=ifft2(fftKcirc.*fft2(a2));
f2=f2(1:n2,1:n1);
f=f2(:);
if isfield(gp,'meanf')
f=f+H'*(B_m*(H*a));
end
else
error('FFT speed-up implemented only for 1D and 2D cases.')
end
else
f = K*a;
end
lp = gp.lik.fh.ll(gp.lik, y, f, z);
if ~isfield(gp,'meanf')
lp_new = -a'*f/2 + lp;
else
%lp_new = -(f-H'*b_m)'*(a-K\(H'*b_m))/2 + lp;
lp_new = -(f-Hb_m)'*(a-iKHb_m)/2 + lp;
end
i = i+1;
end
g2 = gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);
g2sq=sqrt(g2);
dlp = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);
end
% evaluate the approximate log marginal likelihood
g2 = gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);
g2sq=sqrt(g2);
if ~isfield(gp,'meanf')
logZ = 0.5 *f'*a - gp.lik.fh.ll(gp.lik, y, f, z);
else
% logZ = 0.5 *((f-H'*b_m)'*(a-K\(H'*b_m))) - gp.lik.fh.ll(gp.lik, y, f, z);
logZ = 0.5 *((f-Hb_m)'*(a-iKHb_m)) - gp.lik.fh.ll(gp.lik, y, f, z);
end
if isfield(gp.latent_opt, 'kron') && gp.latent_opt.kron==1
% % Use Kronecker product structure
%-
% tmp=bsxfun(@times,Lb.^(-1/2),bsxfun(@times,Vt,sqrt(Dt)'));
% tmp=tmp'*tmp;
% tmp(1:size(tmp,1)+1:end)=tmp(1:size(tmp,1)+1:end)+1;
% logZa=sum(log(diag(chol(tmp,'lower'))));
%
% Lbt=ny*(g2)+1./Lb;
%
% St=[diag(1./Dt)+Vt'*bsxfun(@times,1./Lb,Vt) zeros(size(Dt,1),1); ...
% zeros(1,size(Dt,1)) 1];
% Pt=[bsxfun(@times,1./Lb,Vt) sqrt(ny)*g2];
%
% logZb=sum(log(diag(chol(St,'lower'))));
%
% Ptt=bsxfun(@times,1./sqrt(Lbt),Pt);
% logZc=sum(log(diag(chol(St-Ptt'*Ptt,'lower'))));
%
% edata = logZ + logZa - logZb + logZc + 0.5*sum(log(Lb)) + 0.5*sum(log(Lbt));
%-
% use reduced-rank approximation for K
%-
Zt=1./(1+ny*g2.*Lb);
Ztsq=sqrt(Zt);
Ltmp=bsxfun(@times,Ztsq.*sqrt(ny).*g2sq,bsxfun(@times,Vt,sqrt(Dt)'));
Ltmp=Ltmp'*Ltmp;
Ltmp(1:(size(Dt,1)+1):end)=Ltmp(1:(size(Dt,1)+1):end)+1;
[L,notpositivedefinite]=chol(Ltmp,'lower');
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
LTtmp=L\( Dtsq.*(Vt'*( (g2sq.*sqrt(ny)).*((1./(1+ny*g2.*Lb)).* (sqrt(ny)*g2sq) ) )) );
edata = logZ + sum(log(diag(L)))+0.5*sum(log(1+ny*g2.*Lb)) ...
-0.5*log(ny) + 0.5*log(sum(((g2*ny)./(ny*g2.*Lb+1)))-LTtmp'*LTtmp);
%-
elseif isfield(gp.latent_opt, 'fft') && gp.latent_opt.fft==1
K = gp_trcov(gp, x);
if isfield(gp,'meanf')
K=K+H'*B_m*H;
end
% exact determinant
KR=bsxfun(@times,K,g2sq')-(K*g2)*g2sq';
RKR=ny*(bsxfun(@times,g2sq,KR)-g2sq*(g2'*KR));
RKR(1:(n+1):end)=RKR(1:(n+1):end)+1;
[L,notpositivedefinite] = chol(RKR,'lower');
if notpositivedefinite
[edata,e,eprior,param,ch] = set_output_for_notpositivedefinite();
return
end
edata = logZ + sum(log(diag(L)));
% % determinant approximated using only the largest eigenvalues
% opts.issym = 1;
% Deig=eigs(@(z) mvm_fft(g2, ny, fftKcirc, H, B_m, z),n,round(n*0.05),'lm',opts);
% edata = logZ + 0.5*sum(log(Deig));
% L=[];
else
if strcmpi(gp.lik.type,'LGPC')
R=zeros(n);
RKR=K;
for k1=1:n1
R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2)=sqrt(ny2(k1))*(diag(g2sq((1:n2)+(k1-1)*n2))-g2((1:n2)+(k1-1)*n2)*g2sq((1:n2)+(k1-1)*n2)');
RKR(:,(1:n2)+(k1-1)*n2)=RKR(:,(1:n2)+(k1-1)*n2)*R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2);
end
for k1=1:n1
RKR((1:n2)+(k1-1)*n2,:)=R((1:n2)+(k1-1)*n2,(1:n2)+(k1-1)*n2)'*RKR((1:n2)+(k1-1)*n2,:);
end
%RKR=R'*K*R;