-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMMRF.java
4118 lines (3271 loc) · 110 KB
/
MMRF.java
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
/**
* Copyright 2015, 2016 (C) Inwoo Chung (gutomitai@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Base64;
import java.util.LinkedList;
/**
Minimize a continuous differentialble multivariate function. Starting point
is given by "X" (D by 1), and the function named in the string "f", must
return a function value and a vector of partial derivatives. The Polack-
Ribiere flavour of conjugate gradients is used to compute search directions,
and a line search using quadratic and cubic polynomial approximations and the
Wolfe-Powell stopping criteria is used together with the slope ratio method
for guessing initial step sizes. Additionally a bunch of checks are made to
make sure that exploration is taking place and that extrapolation will not
be unboundedly large. The "length" gives the length of the run: if it is
positive, it gives the maximum number of line searches, if negative its
absolute gives the maximum allowed number of function evaluations. You can
(optionally) give "length" a second component, which will indicate the
reduction in function value to be expected in the first line-search (defaults
to 1.0). The function returns when either its length is up, or if no further
progress can be made (ie, we are at a minimum, or so close that due to
numerical problems, we cannot get any closer). If the function terminates
within a few iterations, it could be an indication that the function value
and derivatives are not consistent (ie, there may be a bug in the
implementation of your "f" function). The function returns the found
solution "X", a vector of function values "fX" indicating the progress made
and "i" the number of iterations (line searches or function evaluations,
depending on the sign of "length") used.
Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5)
See also: checkgrad
Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13
(C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen
Permission is granted for anyone to copy, use, or modify these
programs and accompanying documents for purposes of research or
education, provided this copyright notice is retained, and note is
made of any changes that have been made.
These programs and documents are distributed without any warranty,
express or implied. As the programs were written for research
purposes only, they have not been tested to the degree that would be
advisable in any important application. All use of these programs is
entirely at the user's own risk.
[ml-class] Changes Made:
1) Function name and argument specifications
2) Output display
----------------------------------------------------------------------------
fmincg (octave) developed by Carl Edward Rasmussen is converted into
NonlinearCGOptimizer (java) by Inwoo Chung since Dec. 23, 2016.
*/
/**
* Nonlinear conjugate gradient optimizer extended from fmincg developed
* by Carl Edward Rasmussen.
*
* @author Inwoo Chung (gutomitai@gmail.com)
* @since Dec. 23, 2016
*/
class NonlinearCGOptimizer extends Optimizer {
/**
*
*/
private static final long serialVersionUID = 4990583252368987021L;
// Constants.
public static double RHO = 0.01;
public static double SIG = 0.5;
public static double INT = 0.1;
public static double EXT = 3.0;
public static int MAX = 20;
public static double RATIO = 100;
public Map<Integer, Matrix> fmincg(ICostFunction iCostFunc
, int clusterComputingMode
, int acceleratingComputingMode
, Matrix X
, Matrix Y
, Map<Integer, Matrix> thetas
, int numIter
, double lambda
, boolean isGradientChecking
, boolean JEstimationFlag
, double JEstimationRatio
, List<CostFunctionResult> costFunctionResults) {
// Check exception.
// Optimize the cost function.
int length = numIter;
CostFunctionResult r = null;
Matrix T = Utility.unroll(thetas); // Important! ??
int i = 0;
int is_failed = 0;
CostFunctionResult r1 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
r = r1;
double f1 = r1.J;
Matrix df1 = Utility.unroll(r1.thetaGrads);
i += length < 0 ? 1 : 0;
Matrix s = Matrix.constArithmeticalMultiply(-1.0, df1);
double d1 = -1.0 * Matrix.innerProduct(s.unrolledVector(), s.unrolledVector());
double z1 = 1.0 / (1.0 - d1);
int success = 0;
double f2 = 0.0;
Matrix df2 = null;
double z2 = 0.0;
double d2 = 0.0;
double f3 = 0.0;
double d3 = 0.0;
double z3 = 0.0;
Matrix T0 = null;
double f0 = 0;
Matrix df0 = null;
while (i < Math.abs(length)) {
i += length > 0 ? 1 : 0;
T0 = T.clone();
f0 = f1;
df0 = df1.clone();
T = T.plus(Matrix.constArithmeticalMultiply(z1, s));
CostFunctionResult r2 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
r = r2;
f2 = r2.J;
df2 = Utility.unroll(r2.thetaGrads);
z2 = 0.0;
i += length < 0 ? 1 : 0;
d2 = Matrix.innerProduct(df2.unrolledVector(), s.unrolledVector());
f3 = f1;
d3 = d1;
z3 = -1.0 * z1;
int M = 0;
if (length > 0) {
M = MAX;
} else {
M = Math.min(MAX, -1 * length - i);
}
double limit = -1.0;
while (true) {
while ((f2 > (f1 + z1 * RHO * d1) || (d2 > -1.0 * SIG * d1)) && (M > 0)) {
limit = z1;
if (f2 > f1) {
z2 = z3 - (0.5 * d3 * z3 * z3) / (d3 * z3 + f2 -f3);
} else {
double A = 6.0 * (f2 - f3) / z3 + 3.0 * (d2 + d3);
double B = 3.0 * (f3 - f2) -z3 * (d3 + 2 * d2);
z2 = (Math.sqrt(B * B - A * d2 * z3 * z3) - B) / A;
}
if (Double.isNaN(z2) || Double.isInfinite(z2)) {
z2 = z3 / 2.0;
}
z2 = Math.max(Math.min(z2, INT * z3), (1.0 - INT) * z3);
z1 = z1 + z2;
T = T.plus(Matrix.constArithmeticalMultiply(z2, s));
CostFunctionResult r3 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
r = r3;
f2 = r3.J;
df2 = Utility.unroll(r3.thetaGrads);
M = M - 1;
i += length < 0 ? 1 : 0;
d2 = Matrix.innerProduct(df2.unrolledVector(), s.unrolledVector());
z3 = z3 - z2;
}
if (f2 > (f1 + z1 * RHO * d1) || d2 > -1.0 *SIG * d1)
break;
else if (d2 > SIG * d1) {
success = 1;
break;
} else if (M == 0)
break;
double A = 6.0 * (f2 - f3) / z3 + 3.0 * (d2 + d3);
double B = 3.0 * (f3 - f2) -z3 * (d3 + 2 * d2);
z2 = -1.0 * d2 * z3 * z3 /(B + Math.sqrt(B * B - A * d2 * z3 * z3));
if (Double.isNaN(z2) || Double.isInfinite(z2) || z2 < 0.0) {
if (limit < -0.5) {
z2 = z1 * (EXT - 1.0);
} else {
z2 = (limit - z1) / 2.0;
}
} else if (limit > -0.5 && ((z2 + z1) > limit)) {
z2 = (limit - z1) / 2.0;
} else if (limit < -0.5 && ((z2 + z1) > (z1 * EXT))) {
z2 = z1 * (EXT - 1.0);
} else if (z2 < -1.0 * z3 * INT) {
z2 = -1.0 * z3 * INT;
} else if (limit > -0.5 && (z2 < (limit - z1) * (1.0 - INT))) {
z2 = (limit - z1) * (1.0 - INT);
}
f3 = f2;
d3 = d2;
z3 = -1.0 * z2;
z1 = z1 + z2;
T = T.plus(Matrix.constArithmeticalMultiply(z2, s));
CostFunctionResult r4 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
r = r4;
f2 = r4.J;
df2 = Utility.unroll(r4.thetaGrads);
M = M - 1;
i += length < 0 ? 1 : 0;
d2 = Matrix.innerProduct(df2.unrolledVector(), s.unrolledVector());
}
if (success == 1) {
costFunctionResults.add(r); //?
f1 = f2;
s = Matrix.constArithmeticalMultiply((Matrix.innerProduct(df2.unrolledVector(), df2.unrolledVector())
- Matrix.innerProduct(df1.unrolledVector(), df2.unrolledVector()))
/ (Matrix.innerProduct(df1.unrolledVector(), df1.unrolledVector())), s).minus(df2);
Matrix tmp = df1.clone();
df1 = df2.clone();
df2 = tmp;
d2 = Matrix.innerProduct(df1.unrolledVector(), s.unrolledVector());
if (d2 > 0) {
s = Matrix.constArithmeticalMultiply(-1.0, df1);
d2 = -1.0 * Matrix.innerProduct(s.unrolledVector(), s.unrolledVector());
}
z1 = z1 * Math.min(RATIO, d1 / (d2 - Double.MIN_VALUE));
d1 = d2;
is_failed = 0;
} else {
T = T0.clone();
f1 = f0;
df1 = df0.clone();
if (!(is_failed == 0 || i > Math.abs(length))) {
Matrix tmp = df1.clone();
df1 = df2.clone();
df2 = tmp;
s = Matrix.constArithmeticalMultiply(-1.0, df1);
d1 = -1.0 * Matrix.innerProduct(s.unrolledVector(), s.unrolledVector());
z1 = 1.0 / (1.0 - d1);
is_failed = 1;
}
}
}
return Utility.roll(T, thetas);
}
}
class CostFunctionResult {
/** Cost function value. */
public double J;
/** Theta gradient matrix. */
public Map<Integer, Matrix> thetaGrads = new HashMap<Integer, Matrix>();
/** Estimated theta gradient matrix. */
public Map<Integer, Matrix> eThetaGrads = new HashMap<Integer, Matrix>();
}
class LBFGSOptimizer extends Optimizer {
/**
* Minimize.
* @param iCostFunc
* @param sc
* @param clusterComputingMode
* @param acceleratingComputingMode
* @param X
* @param Y
* @param thetas
* @param lambda
* @param isGradientChecking
* @param JEstimationFlag
* @param JEstimationRatio
* @param costFunctionResults
* @return
*/
public Map<Integer, Matrix> minimize(ICostFunction iCostFunc
, int clusterComputingMode
, int acceleratingComputingMode
, Matrix X
, Matrix Y
, Map<Integer, Matrix> thetas
, int maxIter
, double lambda
, boolean isGradientChecking
, boolean JEstimationFlag
, double JEstimationRatio
, List<CostFunctionResult> costFunctionResults) {
// Input parameters are assumed to be valid.
// Conduct optimization.
// Calculate the initial gradient and inverse Hessian.
Matrix T0 = Utility.unroll(thetas);
CostFunctionResult r1 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T0, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T0, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
Matrix G0 = Utility.unroll(r1.thetaGrads);
Matrix H0 = Matrix.getIdentity(G0.rowLength());
Matrix P0 = Matrix.constArithmeticalMultiply(-1.0, H0.multiply(G0));
// Calculate an optimized step size.
double alpha = backtrackingLineSearch(T0
, G0
, P0
, iCostFunc
, clusterComputingMode
, acceleratingComputingMode
, X
, Y
, thetas
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
// Update the theta.
Matrix T1 = T0.plus(Matrix.constArithmeticalMultiply(alpha, P0));
CostFunctionResult r2 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T1, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T1, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
Matrix G1 = Utility.unroll(r2.thetaGrads);
costFunctionResults.add(r2);
// Check exception. (Bug??)
if (Double.isNaN(r2.J)) {
return Utility.roll(T0, thetas);
}
// Store values for inverse Hessian updating.
LinkedList<Matrix> ss = new LinkedList<Matrix>();
LinkedList<Matrix> ys = new LinkedList<Matrix>();
Matrix s = T1.minus(T0);
Matrix y = G1.minus(G0);
ss.add(s);
ys.add(y);
int count = 1;
while (count <= maxIter) {
// Calculate the next theta, gradient and inverse Hessian.
T0 = T1;
r1 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T0, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T0, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
G0 = Utility.unroll(r1.thetaGrads);
// Calculate a search direction.
P0 = calSearchDirection(ss, ys, G0);
// Calculate an optimized step size.
alpha = backtrackingLineSearch(T0
, G0
, P0
, iCostFunc
, clusterComputingMode
, acceleratingComputingMode
, X
, Y
, thetas
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
// Update the theta.
T1 = T0.plus(Matrix.constArithmeticalMultiply(alpha, P0));
r2 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T1, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T1, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
G1 = Utility.unroll(r2.thetaGrads);
costFunctionResults.add(r2);
// Check exception. (Bug??)
if (Double.isNaN(r2.J)) {
return Utility.roll(T0, thetas);
}
// Store values for inverse Hessian updating.
if (ss.size() == 30) {
ss.removeFirst();
ys.removeFirst();
ss.add(T1.minus(T0));
ys.add(G1.minus(G0));
} else {
ss.add(T1.minus(T0));
ys.add(G1.minus(G0));
}
count++;
}
return Utility.roll(T1, thetas);
}
// Calculate a search direction.
private Matrix calSearchDirection(LinkedList<Matrix> ss, LinkedList<Matrix> ys, Matrix G0) {
// Input parameters are assumed to be valid.
// Calculate P.
Matrix Q = G0.clone();
LinkedList<Double> as = new LinkedList<Double>();
for (int i = ss.size() - 1; i >= 0; i--) {
double rho = 1.0 / ys.get(i).transpose().multiply(ss.get(i)).getVal(1, 1); // Inner product.
double a = rho * ss.get(i).transpose().multiply(Q).getVal(1, 1);
as.add(a);
Q = Q.minus(Matrix.constArithmeticalMultiply(a, ys.get(i)));
}
double w = 1.0; //ys.getLast().transpose().multiply(ys.getLast()).getVal(1, 1)
// / ys.getLast().transpose().multiply(ss.getLast()).getVal(1, 1);
Matrix H0 = Matrix.constArithmeticalMultiply(w, Matrix.getIdentity(G0.rowLength())); //?
Matrix R = H0.multiply(Q);
for (int i = 0 ; i < ss.size(); i++) {
double rho = 1.0 / ys.get(i).transpose().multiply(ss.get(i)).getVal(1, 1);
double b = Matrix.constArithmeticalMultiply(rho, ys.get(i).transpose().multiply(R)).getVal(1, 1);
R = R.plus(Matrix.constArithmeticalMultiply(ss.get(i), as.get(as.size() - i - 1) - b));
}
return Matrix.constArithmeticalMultiply(-1.0, R);
}
// Conduct backtracking line search.
private double backtrackingLineSearch(Matrix T
, Matrix G
, Matrix P
, ICostFunction iCostFunc
, int clusterComputingMode
, int acceleratingComputingMode
, Matrix X
, Matrix Y
, Map<Integer, Matrix> thetas
, double lambda
, boolean isGradientChecking
, boolean JEstimationFlag
, double JEstimationRatio) {
// Input parameters are assumed to be valid.
// Calculate an optimized step size.
double alpha = 1.0;
double c = 0.5;
double gamma = 0.5;
CostFunctionResult r1 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
Matrix T1 = T.plus(Matrix.constArithmeticalMultiply(alpha, P));
CostFunctionResult r2 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T1, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T1, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
Matrix M = P.transpose().multiply(G);
double m = M.getVal(1, 1);
// Check the Armijo-Goldstein condition.
while (r1.J - r2.J < -1.0 * alpha * c * m) {
alpha = gamma * alpha;
T1 = T.plus(Matrix.constArithmeticalMultiply(alpha, P));
r2 = classRegType == 0 ? iCostFunc.costFunctionC(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T1, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio)
: iCostFunc.costFunctionR(clusterComputingMode
, acceleratingComputingMode
, X
, Y
, Utility.roll(T1, thetas)
, lambda
, isGradientChecking
, JEstimationFlag
, JEstimationRatio);
M = P.transpose().multiply(G);
m = M.getVal(1, 1);
} // Close condition?
return alpha;
}
}
interface ICostFunction {
public CostFunctionResult costFunctionC(int clusterComputingMode
, int acceratingComputingMode
, Matrix X
, Matrix Y
, final Map<Integer, Matrix> thetas
, double lambda
, boolean isGradientChecking
, boolean JEstimationFlag
, double JEstimationRatio);
public CostFunctionResult costFunctionR(int clusterComputingMode
, int acceratingComputingMode
, Matrix X
, Matrix Y
, final Map<Integer, Matrix> thetas
, double lambda
, boolean isGradientChecking
, boolean JEstimationFlag
, double JEstimationRatio);
}
abstract class Optimizer {
public int classRegType = 0;
}
class Utility {
/**
* Unroll a matrix map.
* @param matrixMap a matrix map.
* @return Unrolled matrix.
*/
public static Matrix unroll(Map<Integer, Matrix> matrixMap) {
// Check exception.
if (matrixMap == null)
throw new NullPointerException();
if (matrixMap.isEmpty())
throw new IllegalArgumentException();
// Unroll.
int count = 0;
Matrix unrolledM = null;
for (int i : matrixMap.keySet()) {
if (count == 0) {
double[] unrolledVec = matrixMap.get(i).unrolledVector();
unrolledM = new Matrix(unrolledVec.length, 1, unrolledVec);
count++;
} else {
double[] unrolledVec = matrixMap.get(i).unrolledVector();
unrolledM = unrolledM.verticalAdd(new Matrix(unrolledVec.length, 1, unrolledVec));
}
}
return unrolledM;
}
/**
* Unroll a Matrix.
* @param unrolledM
* @param matrixMapModel
* @return
*/
public static Map<Integer, Matrix> roll(Matrix unrolledM
, Map<Integer, Matrix> matrixMapModel) {
// Check exception.
if (unrolledM == null || matrixMapModel == null)
throw new NullPointerException();
// Input parameters are assumed to be valid.
// Roll.
Map<Integer, Matrix> matrixMap = new HashMap<Integer, Matrix>();
int rowIndexStart = 1;
for (int i : matrixMapModel.keySet()) {
int[] range = {rowIndexStart
, rowIndexStart + matrixMapModel.get(i).rowLength()
* matrixMapModel.get(i).colLength() - 1
, 1
, 1};
double[] pVec = unrolledM.getSubMatrix(range).unrolledVector();
Matrix pM = new Matrix(matrixMapModel.get(i).rowLength()
, matrixMapModel.get(i).colLength(), pVec);
matrixMap.put(i, pM);
rowIndexStart = rowIndexStart + matrixMapModel.get(i).rowLength()
* matrixMapModel.get(i).colLength();
}
return matrixMap;
}
/**
* Encode NN params. to Base64 string.
* @param nn
* @return
*/
public static String encodeNNParamsToBase64(AbstractNeuralNetwork nn) {
// Check exception.
if (nn == null)
throw new NullPointerException();
// Unroll a theta matrix map.
double[] unrolledTheta = unroll(nn.thetas).unrolledVector();
// Convert the unrolled theta into a byte array.
byte[] unrolledByteTheta = new byte[unrolledTheta.length * 8];
for (int i = 0; i < unrolledTheta.length; i++) {
// Convert a double value into a 8 byte long format value.
long lv = Double.doubleToLongBits(unrolledTheta[i]);
for (int j = 0; j < 8; j++) {
unrolledByteTheta[j + i * 8] = (byte)((lv >> ((7 - j) * 8)) & 0xff);
}
}
// Encode the unrolledByteTheta into the base64 string.
String base64Str = Base64.getEncoder().encodeToString(unrolledByteTheta);
return base64Str;
}
/**
* Decode Base64 string into a theta map of NN.
* @param nn
* @return
*/
public static void decodeNNParamsToBase64(String encodedBase64NNParams, AbstractNeuralNetwork nn) {
// Check exception.
if (nn == null && encodedBase64NNParams == null)
throw new NullPointerException();
// Input parameters are assumed to be valid.
// An NN theta model must be configured.
// Decode the encoded base64 NN params. string into a byte array.
byte[] unrolledByteTheta = Base64.getDecoder().decode(encodedBase64NNParams);
// Convert the byte array into an unrolled theta.
double[] unrolledTheta = new double[unrolledByteTheta.length / 8];
for (int i = 0; i < unrolledTheta.length; i++) {
// Convert 8 bytes into a 8 byte long format value.
long lv = 0;
for (int j = 0; j < 8; j++) {
long temp = ((long)(unrolledByteTheta[j + i * 8])) << ((7 - j) * 8);
lv = lv | temp;
}
unrolledTheta[i] = Double.longBitsToDouble(lv);
}
// Convert the unrolled theta into a NN theta map.
nn.thetas = roll(new Matrix(unrolledTheta.length, 1, unrolledTheta), nn.thetas);
}
}
class NeuralNetworkRegression extends AbstractNeuralNetwork {
public NeuralNetworkRegression(int clusterComputingMode, int acceleratingComputingMode,
int numLayers, int[] numActs, Optimizer optimizer) {
super(REGRESSION_TYPE, clusterComputingMode, acceleratingComputingMode, numLayers, numActs, optimizer);
}
/**
* Predict.
* @param Matrix of input values for prediction.
* @return Predicted result matrix.
*/
public Matrix predict(Matrix X) {
// Check exception.
// Null.
if (X == null)
throw new NullPointerException();
// X dimension.
if (X.colLength() < 1 || X.rowLength() != numActs[0])
throw new IllegalArgumentException();
return feedForwardR(X);
}
}
class Matrix{
/** Matrix number for parallel processing of Apache Spark. */
public int index;
// Matrix values.
protected double[][] m;
public class GaussElimination {
public final static String TAG = "GaussElimination";
private final boolean DEBUG = true;
/**
* Constructor.
*/
public GaussElimination() {
}
/**
* <p>
* Solve a linear system.
* </p>
* @param augMatrix
* @return Solution.
*/
public double[] solveLinearSystem(double[][] augMatrix) {
// Check exception.
if(augMatrix == null)
throw new IllegalArgumentException(TAG +
": Can't solve a linear system " +
"because an input augmented matrix is null.");
int rowSize = augMatrix.length;
int columnSize = augMatrix[0].length;
for(int i=1; i < rowSize; i++) {
if(columnSize != augMatrix[i].length)
throw new IllegalArgumentException(TAG +
": Can't solve a linear system " +
"because an input augmented matrix isn't valid.");
}
if(!(((rowSize >= 1) && (columnSize >= 2))
&& (rowSize + 1 == columnSize)))
throw new IllegalArgumentException(TAG +
": Can't solve a linear system " +
"because an input augmented matrix isn't valid.");
// Solve an input linear system with the Gauss elimination method.
double[] solution = new double[rowSize];
/*
* Make echelon form for the input linear system
* relevant augmented matrix.
*/
for(int i = 1; i <= rowSize - 1; i++) {
// Sort equation vectors.
// sortEquationVectors(augMatrix, i);
// Make zero coefficient.
makeZeroCoeff(augMatrix, i);
// Check whether it is possible to have only solution.
if(!checkSolution(augMatrix, i))
return null;
}
// Solve the linear system via back substitution.
for(int i = rowSize; i >= 1; i--) {
if(augMatrix[i - 1][i - 1] == 0.0)
return null;
solution[i - 1] =
augMatrix[i - 1][columnSize - 1]/augMatrix[i - 1][i - 1];
for(int j = rowSize; j > i; j--) {
solution[i - 1] -= solution[j - 1]*
augMatrix[i - 1][j - 1]/augMatrix[i - 1][i - 1];
}
}
return solution;
}