-
Notifications
You must be signed in to change notification settings - Fork 0
/
AOq.m
3615 lines (2913 loc) · 109 KB
/
AOq.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 [X,F,Cp,PP,Hist,params] = AO(funopts)
% A (Bayesian) gradient (curvature) descent optimisation routine, designed primarily
% for parameter estimation in nonlinear models.
%
% Getting started with default options:
%
% op = AO('options')
%
% op.fun = func; % function/model f(x0)
% op.x0 = x0(:); % start values: x0
% op.y = Y(:); % data we're fitting (for computation of objective fun, e.g. e = Y - f(x)
% op.V = V(:); % variance / step for each parameter, e.g. ones(length(x0),1)/8
%
% op.objective='gauss'; % select smooth Gaussian error function
%
% Run the routine:
% [X,F,CV,~,Hi] = AO(op);
%
% change objective to 'gaussmap' for MAP estimation or 'fe' to use the free
% energy objective function.
%
% The gauss and gaussmap objectives treat the underlying function as a
% Gaussian process, such that for a given function f and parameters x;
%
% y = f(x)
% y(i) s.t. N(mu[i],sigma[i])
%
% as such output y is formed (approximated) by a sum of multiple, univariate
% Gaussians (a 1D GMM). The Gauss objective is formally:
%
% D = Gfun(Y) - Gfun(f(x))
% e = norm(D*D');
%
% where Gfun is the function estimating a Gaussian process (matrix) from the
% input vector. The advantage here, is that because both the data we are fitting (Y)
% and model output f(x) are approximated as a set of Gaussians, the error is
% smooth and matrix D represents the residuals also as a set of Gaussians.
%
% On each iteration, an error matrix is updated using the Gauss function
% noted above;
%
% resid = Gfun( Y - f(x) )
% Q(i,j) = trace( resid(i,:)' * Q{n}(i,j) * resid(j,:) )
%
% this error matrix is then used for feature scoring of the parameter
% gradients (partial derivatives; J(n_param x n_out) );
%
% score(i,j) = trace(J(i,:)'*Q{n}(i,j)*J(j,:));
%
% this (information matrix) scoring is then used to weight the Hessian in
% the Newton update scheme (under default settings, though see GaussNewton
% and Trust methods also);
%
% H = score;
% dx = x - inv(H*H')*Jacobian
%
%-----------------------------------------------------------------
% By default the step in the descent is a vanilla GD, however you can
% flag the following in the input structure:
%
% op.isNewton = 1; ... switch to Newton's method
% op.isQuasiNewton = 0; ... switch to quasi-Newton
% op.isGaussNewton = 0; ... switch to Gauss Newton
% op.isTrust = 0; ... switch to a GN with trust region
%
% See jaco.m for options, although by default the gradients are computed using a
% finite difference approximation of the curvature, which retains the sign of the gradient:
%
% f0 = F(x[p]+h)
% fx = F(x[p] )
% f1 = F(x[p]-h)
%
% j(p,:) = (f0 - f1) / 2h
% ----------------------------
% (f0 - 2 * fx + f1) / h^2
%
% The algorithm computes the objective function itself based on user
% option; to retreive an empty options structure, do:
%
% opts = AO('options')
%
% Compulsory arguments are: (full list of optionals below)
%
% opts.y = data to fit
% opts.fun = model or function f(x)
% opts.x0 = parameter vector (initial guesses) for x in f(x)
% opts.V = Var vector, with initial variance for each elemtn of x
% opts.objective = the objective function selected from:
% {'sse' 'mse' 'rmse' 'mvgkl' 'gauss' 'gaussmap' 'gaussq' 'jsd' 'euclidean' 'gkld'}
%
% then to run the optmisation, pass the opts structure back into AO with
% these outputs:
%
% [X,F,Cp,PP,Hist,params] = AO(opts)
%
% Optional "step" methods (def 9: normal fixed step GD):
% -- op.step_method = 1 invokes steepest descent
% -- op.step_method = 3 or 4 invokes a vanilla dx = x + a*-J descent
% -- op.step_method = 6 invokes hyperparameter tuning of the step size.
% -- op.step_method = 7 invokes an eigen decomp of the Jacobian matrix
% -- op.step_method = 8 converts the routine to a mirror descent with
% Bregman proximity term.
%
% By default momentum is included (opts.im=1). The idea is that we can
% have more confidence in parameters that are repeatedly updated in the
% same direction, so we can take bigger steps for those parameters as the
% optimisation progresses.
%---------------------------------------------------------------------------
% The (best and default) objective function is you are unsure, is 'gauss'
% which is simply a smooth (approx Gaussian) error function, or 'gaussq'
% which is similar to gauss but implements a sort of pca.
%
% If you want true MAP estimates (or just to be Bayesian), use 'gaussmap'
% which implements a MAP routine:
%
% log(f(X|p)) + log(g(p))
%
% Other important stuff to know:
% -------------------------------------------------------------------------
% if your function f(x) generates a vector output (not a single value),
% then you can compute the partial gradients along each oputput, which is
% necessary for proper implementation of some functions e.g. GaussNewton;
% flag:
%
% opts.ismimo = 1;
%
% The gradient computation can be done in parallel if you have a cluster or
% multicore computer, set:
%
% opts.doparallel = 1;
%
% Set opts.hypertune = 1 to append an exponential cost function to the chosen
% objective function. This is defined as:
%
% c = t * exp(1/t * data - pred)
%
% where t is a (temperature) hyperparameter controlled through a separate gradient
% descent routine.
%
% ALSO SET:
%
% opts.memory_optimise = 1; to optimise the weighting of dx on the gradient flow and recent memories
% opts.opts.rungekutta = 1; to invoke a runge-kutta optimisation locally around the gradient predicted dx
% opts.updateQ = 1; to update the error weighting on the precision matrix
%
% Full list of input options / flags
%-------------------------------------------------------------------------
% X.step_method = 9;
% X.im = 1;
% X.objective = 'gauss';
% X.writelog = 0;
% X.order = 1;
% X.min_df = 0;
% X.criterion = 1e-3;
% X.Q = [];
% X.inner_loop = 1;
% X.maxit = 4;
% X.y = 0;
% X.V = [];
% X.x0 = [];
% X.fun = [];
% X.hyperparams = 1;
% X.hypertune = 0;
% X.force_ls = 0;
% X.doplot = 1;
% X.ismimo = 1;
% X.gradmemory = 0;
% X.doparallel = 0;
% X.fsd = 1;
% X.allow_worsen = 0;
% X.doimagesc = 0;
% X.EnforcePriorProb = 0;
% X.FS = [];
% X.userplotfun = [];
% X.corrweight = 0;
% X.WeightByProbability = 0;
% X.faster = 0;
% X.nocheck = 0;
% X.factorise_gradients = 0;
% X.normalise_gradients=0;
% X.sample_mvn = 0;
% X.steps_choice = [];
% X.rungekutta = 6;
% X.memory_optimise = 1;
% X.updateQ = 1;
% X.crit = [0 0 0 0 0 0 0 0];
% X.save_constant = 0;
% X.gradtol = 1e-4;
% X.orthogradient = 1;
% X.rklinesearch=0;
% X.verbose = 0;
% X.isNewton = 0;
% X.isNewtonReg = 0 ;
% X.isQuasiNewton = 0;
% X.isGaussNewton=0;
% X.lsqjacobian=0;
% X.forcenewton = 0;
% X.isTrust = 0;
%
% [X,F,Cp,PP,Hist] = AO(opts); % call the optimser, passing the options struct
%
% OUTPUTS:
%-------------------------------------------------------------------------
% X = posterior parameters
% F = fit value (depending on objective function specified)
% CP = parameter covariance
% Pp = posterior probabilites
% H = history
%
% *If the optimiser isn't working well, try making V smaller!
%
% Dependencies
%-------------------------------------------------------------------------
% atcm -> https://github.com/alexandershaw4/atcm
% spm -> https://github.com/spm/
%
% References
%-------------------------------------------------------------------------
% "SOLVING NONLINEAR LEAST-SQUARES PROBLEMS WITH THE GAUSS-NEWTON AND
% LEVENBERG-MARQUARDT METHODS" CROEZE, PITTMAN, AND REYNOLDS
% https://www.math.lsu.edu/system/files/MunozGroup1%20-%20Paper.pdf
%
% "Computing the objective function in DCM" Stephan, Friston & Penny
% https://www.fil.ion.ucl.ac.uk/spm/doc/papers/stephan_DCM_ObjFcn_tr05.pdf
%
% "The free energy principal: a rough guide to the brain?" Friston
% https://www.fil.ion.ucl.ac.uk/~karl/The%20free-energy%20principle%20-%20a%20rough%20guide%20to%20the%20brain.pdf
%
% "Likelihood and Bayesian Inference And Computation" Gelman & Hill
% http://www.stat.columbia.edu/~gelman/arm/chap18.pdf
%
% For the nonlinear least squares MLE / Gauss Newton:
% https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm
%
% For an explanation of momentum in gradient methods:
% https://distill.pub/2017/momentum/
%
% Approximation of derivaives by finite difference methods:
% https://www.ljll.math.upmc.fr/frey/cours/UdC/ma691/ma691_ch6.pdf
%
% For an explanation of normalised gradients in gradient descent
% https://jermwatt.github.io/machine_learning_refined/notes/3_First_order_methods/3_9_Normalized.html
%
% AS2019/2020/2021
% alexandershaw4@gmail.com
% Print the description of steps and exit
%--------------------------------------------------------------------------
if nargin == 1 && strcmp(lower(funopts),'help')
PrintHelp(); return;
end
if nargin == 1 && strcmp(lower(funopts),'options');
X = DefOpts; return;
end
% Inputs & Defaults...
%--------------------------------------------------------------------------
if isstruct(funopts)
parseinputstruct(funopts);
else
fprintf('You have to supply a funopts input struct now...\nTry AO(''options'')\n');
return;
end
% Set up log if requested
persistent loc ;
if writelog
name = datestr(now); name(name==' ') = '_';
name = [char(fun) '_' name '.txt'];
loc = fopen(name,'w');
else
loc = 1;
end
% If a feature selection function was passed, append it to the user fun
if ~isempty(FS) && isa(FS,'function_handle')
params.FS = FS;
end
% check functions, inputs, options... note: many of these are set/returned
% by the subfunctions parseinputstruct and DefOpts()
%--------------------------------------------------------------------------
aopt.x0x0 = x0;
aopt.order = order; % first or second order derivatives [-1,0,1,2]
aopt.fun = fun; % (objective?) function handle
aopt.yshape = y;
aopt.y = y(:); % truth / data to fit
aopt.pp = x0(:); % starting parameters
aopt.Q = Q; % precision matrix
aopt.history = []; % error history when y=e & arg min y = f(x)
aopt.memory = gradmemory;% incorporate previous gradients when recomputing
aopt.fixedstepderiv = fsd;% fixed or adjusted step for derivative calculation
aopt.ObjectiveMethod = objective; % 'sse' 'fe' 'mse' 'rmse' (def sse)
aopt.hyperparameters = hyperparams;
aopt.forcels = force_ls; % force line search
aopt.mimo = ismimo; % derivatives w.r.t multiple output fun
aopt.parallel = doparallel; % compute dpdy in parfor
aopt.doimagesc = doimagesc; % change plot to a surface
aopt.corrweight = corrweight;
aopt.factorise_gradients = factorise_gradients;
aopt.hypertune = hypertune;
aopt.verbose = verbose;
aopt.makevideo = makevideo;
IncMomentum = im; % Observe and use momentum data
givetol = allow_worsen; % Allow bad updates within a tolerance
EnforcePriorProb = EnforcePriorProb; % Force updates to comply with prior distribution
WeightByProbability = WeightByProbability; % weight parameter updates by probability
params.aopt = aopt;
params.userplotfun = userplotfun;
% save each iteration
if save_constant
name = ['optim_' date];
end
% if video, open project
if aopt.makevideo
aopt = setvideo(aopt);
end
% parameter and step vectors
x0 = full(x0(:));
V = full(V(:));
pC = diag(V);
% variance (in reduced space)
%--------------------------------------------------------------------------
V = eye(length(x0));
pC = V'*(pC)*V;
ipC = spm_inv(spm_cat(spm_diag({pC})));
red = (diag(pC));
% other start points
aopt.updateh = true; % update hyperpriors
aopt.pC = red; % store for derivative & objective function access
aopt.ipC = ipC; % store ^
red_x0 = red;
% initial probs
aopt.pt = zeros(length(x0),1) + (1/length(x0));
params.aopt = aopt;
% initial objective value (approx at this point as missing covariance data)
[e0] = obj(x0,params);
n = 0;
iterate = true;
Vb = V;
% initialise Q if running but empty
if isempty(Q) && updateQ
Qc = VtoGauss(real(y(:)));
fun = @(x) full(atcm.fun.HighResMeanFilt(diag(x),1,4));
for iq = 1:size(Qc,1);
Q{iq} = fun(Qc(iq,:));
end
aopt.Q = Q;
end
% initial error plot(s)
%--------------------------------------------------------------------------
if doplot
f = setfig(); params = makeplot(x0,x0,params); aopt.oerror = params.aopt.oerror;
pl_init(x0,params)
end
% initialise counters
%--------------------------------------------------------------------------
n_reject_consec = 0;
search = 0;
% Initial probability threshold for inclusion (i.e. update) of a parameter
Initial_JPDtol = 1e-10;
JPDtol = Initial_JPDtol;
etol = 0;
% parameters (in reduced space)
%--------------------------------------------------------------------------
np = size(V,2);
p = x0;
ip = (1:np)';
Ep = p;
dff = []; % tracks changes in error over iterations
localminflag = 0; % triggers when stuck in local minima
% print options before we start printing updates
fprintf('Using step-method: %d\n',step_method);
fprintf('Using Jaco (gradient) option: %d\n',order);
fprintf('User fun has %d varying parameters\n',length(find(red)));
% print start point - to console or logbook (loc)
refdate(loc);pupdate(loc,n,0,e0,e0,'start: ');
if step_method == 0
% step method can switch between 1 (big) and 3 (small) automatcically
autostep = 1;
else autostep = 0;
end
all_dx = [];
all_ex = [];
Hist.e = [];
%etol = 0;
% start optimisation loop
%==========================================================================
while iterate
% counter
%----------------------------------------------------------------------
n = n + 1; tic;
% Save each step if requested
if save_constant
save(name,'x0','Hist');
end
if WeightByProbability
aopt.pp = x0(:);
end
% update error covariance matrix for component n - to go into feature scoring
% Q{n}(i,j) = trace( g(resid(:,i)) * Q{n}(i,j) * g(resid(:,j))' )
%----------------------------------------------------------------------
if ~isempty(Q) && updateQ
if verbose; fprintf('| Updating Q...\n'); end
[~,~,erx] = obj(x0,params);
%erx = erx(1:length(Q));
Qer = VtoGauss(erx);
QQ = aopt.Q;
if ~iscell(QQ)
QQ = {QQ};
aopt.Q = [];
end
for iq = 1:length(QQ)
Q0 = QQ{iq};
if isfield(aopt,'h')
Q0 = Q0 * aopt.h(iq);
end
if isempty(Q0);Q0 = eye(length(y(:)));end
for i = 1:length(Qer)
for j = 1:length(Qer)
Qmat(i,j) = trace(Qer(i,:)'*Q0(i,j)*Qer(j,:));
end
end
Qmat = Qmat ./ norm(Qmat);
aopt.Q{iq} = Qmat;
end
Hist.QQ(n,:,:) = Qmat;
% Update graphic (1) - error comps
Qplot = cat(2,aopt.Q{:});
s = subplot(5,3,14);imagesc(real(Qplot));
ax = gca;
ax.XGrid = 'off';ax.YGrid = 'on';
s.YColor = [1 1 1];s.XColor = [1 1 1];s.Color = [.3 .3 .3];
title('Error Components','color','w','fontsize',18);drawnow;
% Update graphic (2) - precision comps
update_hyperparam_plot(y,aopt.Q)
end
% compute gradients J, & search directions
%----------------------------------------------------------------------
aopt.updatej = true; aopt.updateh = true; params.aopt = aopt;
if verbose; pupdate(loc,n,0,e0,e0,'gradnts',toc); end
% first order partial derivates of F w.r.t x0 using Jaco.m
[e0,df0,~,~,~,~,params] = obj(x0,params);
[e0,~,er] = obj(x0,params);
df0 = real(df0);
if normalise_gradients
df0 = df0./sum(df0);
end
% catch instabilities in the gradient - ie explosive parameters
df0(isinf(df0)) = 0;
% Update aopt structure and place in params
aopt = params.aopt;
aopt.er = er;
aopt.updateh = false;
params.aopt = aopt;
% print end of gradient computation (just so we know it's finished)
if verbose; pupdate(loc,n,0,e0,e0,'grd-fin',toc); end
% update hyperparameter tuning plot
%if hypertune; plot_hyper(params.hyper_tau,[Hist.e e0]); end
% update h_opt plot
if hyperparams; plot_h_opt(params.h_opt); drawnow; end
% Switching for different methods for calculating 'a' / step size
if autostep; search_method = autostepswitch(n,e0,Hist);
else; search_method = step_method;
end
% initial search direction (steepest) and slope
%----------------------------------------------------------------------
% Compute step, a, in scheme: dx = x0 + a*-J
if n == 1
a = red*0;
end
% Setting step size to 6 invokes low-dimensional hyperparameter tuning
if verbose
if search_method ~= 6
pupdate(loc,n,0,e0,e0,'stepsiz',toc);
else
pupdate(loc,n,0,e0,e0,'hyprprm',toc);
end
end
% Feature Scoring for MIMOs - using aopt.Q updated above
%----------------------------------------------------------------------
if orthogradient && ismimo
if verbose; fprintf('Orthogonalising Jacobian\n'); end
params.aopt.J = symmetric_orthogonalise(params.aopt.J);
end
% i.e. where J(np,nf) & nf > 1
if ismimo
if verbose; pupdate(loc,n,0,e0,e0,'scoring',toc); end
JJ = params.aopt.J;
%for i = 1:size(JJ,2)
% JJ(:,i) = rescale(JJ(:,i));
%end
Q1 = aopt.Q;
% repeat scoring for component, Q{n}
if ~iscell(Q1)
Q1 = {Q1};
end
for iq = 1:length(Q1)
Q0 = Q1{iq};
if isempty(Q0)
Q0 = eye(length(y(:)));
end
padQ = size(JJ,2) - length(Q0);
Q0(end+1:end+padQ,end+1:end+padQ)=mean(Q0(:))/10;
if orthogradient
Q0 = symmetric_orthogonalise(Q0);
end
for i = 1:np
for j = 1:np
% information score / approximate (weighted) Hessian
score(i,j) = trace(JJ(i,:).*Q0.*JJ(j,:)');
end
end
% store score for this Q-component
S{iq} = score;
end
% get component means - diagonals of aopt.Q
for iq = 1:length(Q1)
C(iq,:) = diag(Q1{iq});
end
[~,~,erx] = obj(x0,params);
% relative contribution of each Q to residual
qb = C'\erx(:);
qb = qb./sum(qb);
HQ = 0;
% assemble Q-weighted Hessian for second order methods
for iq = 1:length(Q1)
HQ = HQ + qb(iq)*S{iq};
end
end
% Select step size method
%----------------------------------------------------------------------
if ~ismimo
[a,J,nJ,L,D] = compute_step(df0,red,e0,search_method,params,x0,a,df0);
else
[a,J,nJ,L,D] = compute_step(params.aopt.J,red,e0,search_method,params,x0,a,df0);
J = -df0(:);
end
if verbose;
if search_method ~= 6
pupdate(loc,n,0,e0,e0,'stp-fin',toc);
else
pupdate(loc,n,0,e0,e0,'hyp-fin',toc);
end
end
% Log start of iteration (these are returned)
Hist.e(n) = e0;
Hist.p{n} = x0;
Hist.J{n} = df0;
Hist.a{n} = a;
if ismimo
Hist.Jfull{n} = aopt.J;
end
% Make copies of error and param set for inner while loops
x1 = x0;
e1 = e0;
% Start counters
improve = true;
nfun = 0;
% check norm of gradients (def gradtol = 1e-4)
%----------------------------------------------------------------------
if norm(J) < gradtol
fprintf('Gradient step below tolerance (%d)\n',norm(J));
[X,F,Cp,PP] = finishup(V,x0,ip,e0,doparallel,params,J,Ep,red,writelog,loc,aopt);
return;
end
Hist.red(n,:) = red;
% iterative descent on this (-gradient) trajectory
%======================================================================
while improve
% Log number of function calls on this iteration
nfun = nfun + 1;
% Compute The Parameter Step (from gradients and step sizes):
% % x[p,t+1] = x[p,t] + a[p]*-dfdx[p]
%------------------------------------------------------------------
% dx ~ x1 + ( a * J );
if search_method == 9
a = red;
end
% For most methods, compute dx using subfun...
dx = compute_dx(x1,a,J,red,search_method,params);
% section switches for Newton, GaussNewton and Quasi-Newton Schemes
%-----------------------------------------------------------------
% Newton's Method
%-----------------------------------------------------------------
if (isNewton && ismimo) || (isQuasiNewton && ismimo)
if verbose; pupdate(loc,n,nfun,e1,e1,'Newton ',toc); end
% by using the variance (red) as a lambda on the inverse
% Hessian, this becomes a relaxed or 'damped' Newton scheme
%for i = 1:size(J,1);
% for j = 1:size(J,1);
% H(i,j) = spm_trace(aopt.J(i,:),aopt.J(j,:));
% end
%end
% Norm Hessian - incl. hessnorm; fixes issue with large cond(H)
%H = (red.*H./norm(H));
H = HQ;
% since the feature score is itself a derivative, score*H is
% approximately the third derivative ("jerk")
%H = score.*H;
%H = H ./ norm(H);
% Quasi-Newton uses left singular values of H
if isQuasiNewton
[u,s0,v0] = svd(H);
H = pinv(u);
end
% the non-parallel finite different functions return gradients
% in reduced space - embed in full vector space
Jo = cat(1,aopt.Jo{:,1});
JJ = x0*0;
JJ(find(diag(pC))) = Jo;
% Compute step using matrix exponential (see spm_dx)
Hstep = red.*spm_dx(H,JJ,{-1});
Gdx = x1 - Hstep;
dx = Gdx;
if verbose; fprintf('Selected Newton Step\n'); end
end
% Newton's Method with tunable regularisation of inverse hessian
%------------------------------------------------------------------
if isNewtonReg && ismimo
if verbose; pupdate(loc,n,nfun,e1,e1,'Newton ',toc);end
% % by using the variance (red) as a lambda on the inverse
% % Hessian, this becomes a relaxed or 'damped' Newton scheme
% for i = 1:size(J,1);
% for j = 1:size(J,1);
% H(i,j) = spm_trace(aopt.J(i,:),aopt.J(j,:));
% end
% end
%
% % Norm Hessian
% H = (red.*H./norm(H));
H = HQ;
% the non-parallel finite different functions return gradients
% in reduced space - embed in full vector space
Jo = cat(1,aopt.Jo{:,1});
if length(Jo) ~= length(x1)
JJ = x0*0;
JJ(find(diag(pC))) = Jo;
else
JJ = Jo;
end
% essentially here we are tiuning this part of the Newton
% scheme:
% ______
% xhat = x - inv(H*L*H')*J
% tunable regularisation function
Gf = @(L) pinv(H*(L*eye(length(H)))*H');
Gff = @(x) obj(x1 - Gf(x)*JJ,params);
[XX] = fminsearch(Gff,1);
H0 = (H*(XX*eye(length(H)))*H');
Hstep = spm_dx(H0,JJ,{-4});
GRdx = x1 - Hstep;
dx = GRdx;
%if forcenewton
% dx = GRdx;
% if verbose; fprintf('Forced Newton Step\n');end
%end
end
% Now also give a Gauss-Newton option rather than just Newton
%------------------------------------------------------------------
if isGaussNewton && ismimo
if verbose; pupdate(loc,n,nfun,e1,e1,'Newton ',toc);end
% for i = 1:size(J,1);
% for j = 1:size(J,1);
% H(i,j) = spm_trace(aopt.J(i,:),aopt.J(j,:));
% end
% end
%
% % Norm Hessian
% H = (red.*H./norm(H));
H = HQ;
% get residual vector
[~,~,res,~] = obj(x1,params);
% components
Jx = aopt.J ./ norm(aopt.J);
res = res ./ norm(res);
ipC = diag(red);%spm_inv(score);
% dFdpp & dFdp
dFdpp = H - ipC ;
dFdp = Jx * res - ipC * x1;
dx = x1 - spm_dx(dFdpp,dFdp,{-4});
end
% For almost-linear systems, a lsq fit of the partial gradients to
% the data would give an estimate of the parameter update
%------------------------------------------------------------------
if lsqjacobian
jx = aopt.J'\y;
dx = x1 - jx;
end
% a Trust-Region method (a variation on GN scheme)
%------------------------------------------------------------------
if isTrust && ismimo
if n == 1; mu = 1e-2; end
% for i = 1:size(J,1);
% for j = 1:size(J,1);
% H(i,j) = spm_trace(aopt.J(i,:),aopt.J(j,:));
% end
% end
%
% % Norm Hessian
% H = (red.*H./norm(H));
H = HQ;
% get residual vector
[~,~,res,~] = obj(x1,params);
% components
Jx = aopt.J ./ norm(aopt.J);
res = res./norm(res);
ipC = diag(red);
if n == 1; del = 1; end
% solve trust problem
d = subproblem(H,J,del);
dr = J' * d + (1/2) * d' * H * d;
if n == 1; r = dr; end
% evaluate
fx0 = obj(x1,params);
fx1 = obj(x1 - d,params);
rk = (fx1 - fx0) / max((dr - r),1);
% adjust radius of trust region
rtol = 0;
if rk < rtol; del = 1.2 * del;
else; del = del * .8;
end
% accept update
if fx1 < fx0
pupdate(loc,n,nfun,e1,e1,'trust! ',toc);
dx = x1 - d;
r = dr;
end
% essentially the GN routine with a constraint [d]
% d = (0.5*(H + H') + mu^2*eye(length(H))) \ -Jx;
% d = d ./ norm(d);
% dFdpp = (d*d') - ipC;
% dFdp = Jx * res - ipC * x1;
% dx = x1 - spm_dx(dFdpp,dFdp,{-4});
%dx = x1 - ( (0.5*(d'*H*d) * Jx')' * (.5*res) );
mu = mu * 2;
end
% The following steps compute the relative probability of the new
% parameter estimates given the priors
%==================================================================
% Compute the probabilities of each (predicted) new parameter
% coming from the same distribution defined by the prior (last best)
dx = real(dx);
x1 = real(x1);
red = real(red);
% [Prior] distributions
pt = zeros(1,length(x1));
for i = 1:length(x1)
%vv = real(sqrt( red(i) ));
vv = real(sqrt( red(i) ))*2;
if vv <= 0 || isnan(vv) || isinf(vv); vv = 1/64; end
pd(i) = makedist('normal','mu', real(aopt.pp(i)),'sigma', vv);
end
% Curb parameter estimates trying to exceed their distirbution bounds
if EnforcePriorProb
odx = dx;
nst = 1;
for i = 1:length(x1)
if red(i)
if dx(i) < ( pd(i).mu - (nst*pd(i).sigma) )
dx(i) = pd(i).mu - (nst*pd(i).sigma);
elseif dx(i) > ( pd(i).mu + (nst*pd(i).sigma) )
dx(i) = pd(i).mu + (nst*pd(i).sigma);
end
end
end
end
% Compute relative change in cdf
pdx = pt*0;
for i = 1:length(x1)
if red(i)
%vv = real(sqrt( red(i) ));
vv = real(sqrt( red(i) ))*2;
if vv <= 0 || isnan(vv) || isinf(vv); vv = 1/64; end
pd(i) = makedist('normal','mu', real(aopt.pp(i)),'sigma', vv);
pdx(i) = normcdf(dx(i),pd(i).mu,pd(i).sigma);
%pdx(i) = (1./(1+exp(-pdf(pd(i),dx(i))))) ./ (1./(1+exp(-pdf(pd(i),aopt.pp(i)))));
else
end
end
pt = pdx;
prplot(pt);
aopt.pt = [aopt.pt pt(:)];
% If WeightByProbability is set, use p(dx) as a weight on dx
% iteratively until n% of p(dx[i]) are > threshold
% -------------------------------------------------------------
if WeightByProbability
dx = x1 + ( pt(:).*(dx-x1) );
if verbose; pupdate(loc,n,1,e1,e1,'OptP(p)',toc); end
optimise = true;
num_optloop = 0;
while optimise
pdx = pt*0;
num_optloop = num_optloop + 1;
for i = 1:length(x1)
if red(i)
vv = real(sqrt( red(i) ))*2;
if vv <= 0 || isnan(vv) || isinf(vv); vv = 1/64; end
pd(i) = makedist('normal','mu', real(aopt.pp(i)),'sigma', vv);
pdx(i) = normcdf(dx(i),pd(i).mu,pd(i).sigma);
%pdx(i) = (1./(1+exp(-pdf(pd(i),dx(i))))) ./ (1./(1+exp(-pdf(pd(i),aopt.pp(i)))));
else
end
end
% integrate (update) dx
dx = x1 + ( pt(:).*(dx-x1) );
% convergence
if length(find(pdx(~~red) > 0.8))./length(pdx(~~red)) > 0.7 || num_optloop > 2000
optimise = false;
end
end
end
% Save for computing gradient ascent on probabilities
p_hist(n,:) = pt;
Hist.pt(:,n) = pt;
% Update plot: probabilities
[~,oo] = sort(pt(:),'descend');
% (option) Momentum inclusion
%------------------------------------------------------------------
if n > 2 && IncMomentum
if verbose; pupdate(loc,n,nfun,e1,e1,'momentm',toc); end
% The idea here is that we can have more confidence in
% parameters that are repeatedly updated in the same direction,
% so we can take bigger steps for those parameters
imom = sum( diff(full(spm_cat(Hist.p))')' > 0 ,2);
dmom = sum( diff(full(spm_cat(Hist.p))')' < 0 ,2);
timom = imom >= (2);
tdmom = dmom >= (2);
moments = (timom .* imom) + (tdmom .* dmom);
if any(moments)
% parameter update
ddx = dx - x1;
dx = dx + ( ddx .* (moments./n) );
end
end
% Given (gradient) predictions, dx[i..n], optimise obj(dx)
% Either by:
% (1) just update all parameters
% (2) update all parameters whose updated value improves obj
% (3) update only parameters whose probability exceeds a threshold
%------------------------------------------------------------------
aopt.updatej = false; % switch off objective fun triggers
aopt.updateh = false;
params.aopt = aopt;
pupdate(loc,n,nfun,e1,e1,'eval dx',toc);
if (obj(dx,params) < obj(x1,params) && ~aopt.forcels) || nocheck
% Don't perform checks, assume all f(dx[i]) <= e1
% i.e. full gradient prediction over parameters is good and we
% don't want to be explicitly Bayesian about it ...
gp = ones(1,length(x0));
gpi = 1:length(x0);
de = obj(dx,params);
DFE = ones(1,length(x0))*de;
else
% Assess each new parameter estimate (step) individually
if (~faster) || nfun == 1 % Once per gradient computation?
if ~doparallel