-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
TestOptimizers.java
1097 lines (883 loc) · 37.8 KB
/
TestOptimizers.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
package org.deeplearning4j.optimize.solver;
import org.nd4j.linalg.primitives.Pair;
import org.deeplearning4j.datasets.iterator.impl.IrisDataSetIterator;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.MaskState;
import org.deeplearning4j.nn.api.Model;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.CacheMode;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.conf.layers.RBM;
import org.deeplearning4j.nn.gradient.DefaultGradient;
import org.deeplearning4j.nn.gradient.Gradient;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.api.ConvexOptimizer;
import org.deeplearning4j.optimize.api.IterationListener;
import org.deeplearning4j.optimize.solvers.ConjugateGradient;
import org.deeplearning4j.optimize.solvers.LBFGS;
import org.deeplearning4j.optimize.solvers.LineGradientDescent;
import org.deeplearning4j.optimize.solvers.StochasticGradientDescent;
import org.deeplearning4j.optimize.stepfunctions.NegativeDefaultStepFunction;
import org.junit.Test;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.api.complex.IComplexNumber;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.Cos;
import org.nd4j.linalg.api.ops.impl.transforms.Sin;
import org.nd4j.linalg.api.rng.DefaultRandom;
import org.nd4j.linalg.api.rng.Random;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.conditions.Condition;
import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import static org.junit.Assert.assertTrue;
public class TestOptimizers {
//For debugging.
private static final boolean PRINT_OPT_RESULTS = true;
@Test
public void testOptimizersBasicMLPBackprop() {
//Basic tests of the 'does it throw an exception' variety.
DataSetIterator iter = new IrisDataSetIterator(5, 50);
OptimizationAlgorithm[] toTest =
{OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT, OptimizationAlgorithm.LINE_GRADIENT_DESCENT,
OptimizationAlgorithm.CONJUGATE_GRADIENT, OptimizationAlgorithm.LBFGS
//OptimizationAlgorithm.HESSIAN_FREE //Known to not work
};
for (OptimizationAlgorithm oa : toTest) {
MultiLayerNetwork network = new MultiLayerNetwork(getMLPConfigIris(oa, 1));
network.init();
iter.reset();
network.fit(iter);
}
}
@Test
public void testOptimizersMLP() {
//Check that the score actually decreases over time
DataSetIterator iter = new IrisDataSetIterator(150, 150);
OptimizationAlgorithm[] toTest =
{OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT, OptimizationAlgorithm.LINE_GRADIENT_DESCENT,
OptimizationAlgorithm.CONJUGATE_GRADIENT, OptimizationAlgorithm.LBFGS
//OptimizationAlgorithm.HESSIAN_FREE //Known to not work
};
DataSet ds = iter.next();
ds.normalizeZeroMeanZeroUnitVariance();
for (OptimizationAlgorithm oa : toTest) {
int nIter = 10;
MultiLayerNetwork network = new MultiLayerNetwork(getMLPConfigIris(oa, nIter));
network.init();
double score = network.score(ds);
assertTrue(score != 0.0 && !Double.isNaN(score));
if (PRINT_OPT_RESULTS)
System.out.println("testOptimizersMLP() - " + oa);
int nCallsToOptimizer = 30;
double[] scores = new double[nCallsToOptimizer + 1];
scores[0] = score;
for (int i = 0; i < nCallsToOptimizer; i++) {
network.fit(ds);
double scoreAfter = network.score(ds);
scores[i + 1] = scoreAfter;
assertTrue("Score is NaN after optimization", !Double.isNaN(scoreAfter));
assertTrue("OA= " + oa + ", before= " + score + ", after= " + scoreAfter, scoreAfter <= score);
score = scoreAfter;
}
if (PRINT_OPT_RESULTS)
System.out.println(oa + " - " + Arrays.toString(scores));
}
}
private static MultiLayerConfiguration getMLPConfigIris(OptimizationAlgorithm oa, int nIterations) {
MultiLayerConfiguration c = new NeuralNetConfiguration.Builder().optimizationAlgo(oa).iterations(nIterations)
.learningRate(1e-1).seed(12345L)
.list().layer(0,
new DenseLayer.Builder().nIn(4).nOut(3).weightInit(WeightInit.XAVIER)
.updater(Updater.ADAGRAD).activation(
Activation.RELU)
.build())
.layer(1, new OutputLayer.Builder(LossFunction.MCXENT).nIn(3).nOut(3)
.weightInit(WeightInit.XAVIER).updater(Updater.ADAGRAD)
.activation(Activation.SOFTMAX).build())
.backprop(true).pretrain(false).build();
return c;
}
//==================================================
// Sphere Function Optimizer Tests
@Test
public void testSphereFnOptStochGradDescent() {
testSphereFnOptHelper(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT, 5, 2);
testSphereFnOptHelper(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT, 5, 10);
testSphereFnOptHelper(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT, 5, 100);
}
@Test
public void testSphereFnOptLineGradDescent() {
//Test a single line search with calculated search direction (with multiple line search iterations)
int[] numLineSearchIter = {5, 10};
for (int n : numLineSearchIter)
testSphereFnOptHelper(OptimizationAlgorithm.LINE_GRADIENT_DESCENT, n, 2);
for (int n : numLineSearchIter)
testSphereFnOptHelper(OptimizationAlgorithm.LINE_GRADIENT_DESCENT, n, 10);
for (int n : numLineSearchIter)
testSphereFnOptHelper(OptimizationAlgorithm.LINE_GRADIENT_DESCENT, n, 100);
}
@Test
public void testSphereFnOptCG() {
//Test a single line search with calculated search direction (with multiple line search iterations)
int[] numLineSearchIter = {5, 10};
for (int n : numLineSearchIter)
testSphereFnOptHelper(OptimizationAlgorithm.CONJUGATE_GRADIENT, n, 2);
for (int n : numLineSearchIter)
testSphereFnOptHelper(OptimizationAlgorithm.CONJUGATE_GRADIENT, n, 10);
for (int n : numLineSearchIter)
testSphereFnOptHelper(OptimizationAlgorithm.CONJUGATE_GRADIENT, n, 100);
}
@Test
public void testSphereFnOptLBFGS() {
//Test a single line search with calculated search direction (with multiple line search iterations)
int[] numLineSearchIter = {5, 10};
for (int n : numLineSearchIter)
testSphereFnOptHelper(OptimizationAlgorithm.LBFGS, n, 2);
for (int n : numLineSearchIter)
testSphereFnOptHelper(OptimizationAlgorithm.LBFGS, n, 10);
for (int n : numLineSearchIter)
testSphereFnOptHelper(OptimizationAlgorithm.LBFGS, n, 100);
}
public void testSphereFnOptHelper(OptimizationAlgorithm oa, int numLineSearchIter, int nDimensions) {
if (PRINT_OPT_RESULTS)
System.out.println("---------\n Alg= " + oa + ", nIter= " + numLineSearchIter + ", nDimensions= "
+ nDimensions);
NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder().maxNumLineSearchIterations(numLineSearchIter)
.iterations(100).learningRate(1e-2)
.layer(new RBM.Builder().nIn(1).nOut(1).updater(Updater.SGD).build()).build();
conf.addVariable("W"); //Normally done by ParamInitializers, but obviously that isn't done here
Random rng = new DefaultRandom(12345L);
org.nd4j.linalg.api.rng.distribution.Distribution dist =
new org.nd4j.linalg.api.rng.distribution.impl.UniformDistribution(rng, -10, 10);
Model m = new SphereFunctionModel(nDimensions, dist, conf);
m.computeGradientAndScore();
double scoreBefore = m.score();
assertTrue(!Double.isNaN(scoreBefore) && !Double.isInfinite(scoreBefore));
if (PRINT_OPT_RESULTS) {
System.out.println("Before:");
System.out.println(scoreBefore);
System.out.println(m.params());
}
ConvexOptimizer opt = getOptimizer(oa, conf, m);
opt.setupSearchState(m.gradientAndScore());
opt.optimize();
m.computeGradientAndScore();
double scoreAfter = m.score();
assertTrue(!Double.isNaN(scoreAfter) && !Double.isInfinite(scoreAfter));
if (PRINT_OPT_RESULTS) {
System.out.println("After:");
System.out.println(scoreAfter);
System.out.println(m.params());
}
//Expected behaviour after optimization:
//(a) score is better (lower) after optimization.
//(b) Parameters are closer to minimum after optimization (TODO)
assertTrue("Score did not improve after optimization (b= " + scoreBefore + " ,a= " + scoreAfter + ")",
scoreAfter < scoreBefore);
}
private static ConvexOptimizer getOptimizer(OptimizationAlgorithm oa, NeuralNetConfiguration conf, Model m) {
switch (oa) {
case STOCHASTIC_GRADIENT_DESCENT:
return new StochasticGradientDescent(conf, new NegativeDefaultStepFunction(), null, m);
case LINE_GRADIENT_DESCENT:
return new LineGradientDescent(conf, new NegativeDefaultStepFunction(), null, m);
case CONJUGATE_GRADIENT:
return new ConjugateGradient(conf, new NegativeDefaultStepFunction(), null, m);
case LBFGS:
return new LBFGS(conf, new NegativeDefaultStepFunction(), null, m);
default:
throw new UnsupportedOperationException();
}
}
@Test
public void testSphereFnOptStochGradDescentMultipleSteps() {
//Earlier tests: only do a single line search, though each line search will do multiple iterations
// of line search algorithm.
//Here, do multiple optimization runs + multiple line search iterations within each run
//i.e., gradient is re-calculated at each step/run
//Single step tests earlier won't test storing of state between iterations
testSphereFnMultipleStepsHelper(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT, 100, 5);
}
@Test
public void testSphereFnOptLineGradDescentMultipleSteps() {
testSphereFnMultipleStepsHelper(OptimizationAlgorithm.LINE_GRADIENT_DESCENT, 100, 5);
}
@Test
public void testSphereFnOptCGMultipleSteps() {
testSphereFnMultipleStepsHelper(OptimizationAlgorithm.CONJUGATE_GRADIENT, 100, 5);
}
@Test
public void testSphereFnOptLBFGSMultipleSteps() {
testSphereFnMultipleStepsHelper(OptimizationAlgorithm.LBFGS, 100, 5);
}
private static void testSphereFnMultipleStepsHelper(OptimizationAlgorithm oa, int nOptIter,
int maxNumLineSearchIter) {
double[] scores = new double[nOptIter + 1];
for (int i = 0; i <= nOptIter; i++) {
Random rng = new DefaultRandom(12345L);
org.nd4j.linalg.api.rng.distribution.Distribution dist =
new org.nd4j.linalg.api.rng.distribution.impl.UniformDistribution(rng, -10, 10);
NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder()
.maxNumLineSearchIterations(maxNumLineSearchIter).iterations(i).learningRate(0.1)
.layer(new DenseLayer.Builder().nIn(1).nOut(1).updater(Updater.SGD).build()).build();
conf.addVariable("W"); //Normally done by ParamInitializers, but obviously that isn't done here
Model m = new SphereFunctionModel(100, dist, conf);
if (i == 0) {
m.computeGradientAndScore();
scores[0] = m.score(); //Before optimization
} else {
ConvexOptimizer opt = getOptimizer(oa, conf, m);
opt.optimize();
m.computeGradientAndScore();
scores[i] = m.score();
assertTrue(!Double.isNaN(scores[i]) && !Double.isInfinite(scores[i]));
}
}
if (PRINT_OPT_RESULTS) {
System.out.println("Multiple optimization iterations (" + nOptIter
+ " opt. iter.) score vs iteration, maxNumLineSearchIter=" + maxNumLineSearchIter + ": "
+ oa);
System.out.println(Arrays.toString(scores));
}
for (int i = 1; i < scores.length; i++) {
assertTrue(scores[i] <= scores[i - 1]);
}
assertTrue(scores[scores.length - 1] < 1.0); //Very easy function, expect score ~= 0 with any reasonable number of steps/numLineSearchIter
}
/** A non-NN optimization problem. Optimization function (cost function) is
* \sum_i x_i^2. Has minimum of 0.0 at x_i=0 for all x_i
* See: https://en.wikipedia.org/wiki/Test_functions_for_optimization
*/
private static class SphereFunctionModel extends SimpleOptimizableModel {
private static final long serialVersionUID = -6963606137417355405L;
private SphereFunctionModel(int nParams, org.nd4j.linalg.api.rng.distribution.Distribution distribution,
NeuralNetConfiguration conf) {
super(distribution.sample(new int[] {1, nParams}), conf);
}
@Override
public void computeGradientAndScore() {
// Gradients: d(x^2)/dx = 2x
INDArray gradient = parameters.mul(2);
Gradient g = new DefaultGradient();
g.gradientForVariable().put("W", this.gradientView);
this.gradient = g;
this.score = Nd4j.getBlasWrapper().dot(parameters, parameters); //sum_i x_i^2
this.gradientView.assign(gradient);
}
@Override
public int numParams(boolean backwards) {
return 0;
}
@Override
public void setParamsViewArray(INDArray params) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void setBackpropGradientsViewArray(INDArray gradients) {
throw new UnsupportedOperationException();
}
@Override
public void applyLearningRateScoreDecay() {
}
@Override
public void setCacheMode(CacheMode mode) {
throw new UnsupportedOperationException();
}
@Override
public void setListeners(IterationListener... listeners) {
}
@Override
public int getIndex() {
return 0;
}
@Override
public void setInput(INDArray input) {
}
@Override
public boolean isPretrainLayer() {
return false;
}
}
//==================================================
// Rastrigin Function Optimizer Tests
@Test
public void testRastriginFnOptStochGradDescentMultipleSteps() {
testRastriginFnMultipleStepsHelper(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT, 5, 20);
}
@Test
public void testRastriginFnOptLineGradDescentMultipleSteps() {
testRastriginFnMultipleStepsHelper(OptimizationAlgorithm.LINE_GRADIENT_DESCENT, 10, 20);
}
@Test
public void testRastriginFnOptCGMultipleSteps() {
testRastriginFnMultipleStepsHelper(OptimizationAlgorithm.CONJUGATE_GRADIENT, 10, 20);
}
@Test
public void testRastriginFnOptLBFGSMultipleSteps() {
testRastriginFnMultipleStepsHelper(OptimizationAlgorithm.LBFGS, 10, 20);
}
private static void testRastriginFnMultipleStepsHelper(OptimizationAlgorithm oa, int nOptIter,
int maxNumLineSearchIter) {
double[] scores = new double[nOptIter + 1];
for (int i = 0; i <= nOptIter; i++) {
NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder()
.maxNumLineSearchIterations(maxNumLineSearchIter).iterations(i).miniBatch(false)
.learningRate(1e-2)
.layer(new DenseLayer.Builder().nIn(1).nOut(1).updater(Updater.ADAGRAD).build()).build();
conf.addVariable("W"); //Normally done by ParamInitializers, but obviously that isn't done here
Model m = new RastriginFunctionModel(10, conf);
int nParams = m.numParams();
if (i == 0) {
m.computeGradientAndScore();
scores[0] = m.score(); //Before optimization
} else {
ConvexOptimizer opt = getOptimizer(oa, conf, m);
opt.getUpdater().setStateViewArray((Layer) m, Nd4j.create(new int[] {1, nParams}, 'c'), true);
opt.optimize();
m.computeGradientAndScore();
scores[i] = m.score();
assertTrue(!Double.isNaN(scores[i]) && !Double.isInfinite(scores[i]));
}
}
if (PRINT_OPT_RESULTS) {
System.out.println("Rastrigin: Multiple optimization iterations (" + nOptIter
+ " opt. iter.) score vs iteration, maxNumLineSearchIter=" + maxNumLineSearchIter + ": "
+ oa);
System.out.println(Arrays.toString(scores));
}
for (int i = 1; i < scores.length; i++) {
if (i == 1) {
assertTrue(scores[i] <= scores[i - 1]); //Require at least one step of improvement
} else {
assertTrue(scores[i] <= scores[i - 1]);
}
}
}
/** Rastrigin function: A much more complex non-NN multi-dimensional optimization problem.
* Global minimum of 0 at x_i = 0 for all x_i.
* Very large number of local minima. Can't expect to achieve global minimum with gradient-based (line search)
* optimizers, but can expect significant improvement in score/cost relative to initial parameters.
* This implementation has cost function = infinity if any parameters x_i are
* outside of range [-5.12,5.12]
* https://en.wikipedia.org/wiki/Rastrigin_function
*/
private static class RastriginFunctionModel extends SimpleOptimizableModel {
private static final long serialVersionUID = -1772954508787487941L;
private RastriginFunctionModel(int nDimensions, NeuralNetConfiguration conf) {
super(initParams(nDimensions), conf);
}
private static INDArray initParams(int nDimensions) {
Random rng = new DefaultRandom(12345L);
org.nd4j.linalg.api.rng.distribution.Distribution dist =
new org.nd4j.linalg.api.rng.distribution.impl.UniformDistribution(rng, -5.12, 5.12);
return dist.sample(new int[] {1, nDimensions});
}
@Override
public void computeGradientAndScore() {
//Gradient decomposes due to sum, so:
//d(x^2 - 10*cos(2*Pi*x))/dx
// = 2x + 20*pi*sin(2*Pi*x)
INDArray gradient = parameters.mul(2 * Math.PI);
Nd4j.getExecutioner().exec(new Sin(gradient));
gradient.muli(20 * Math.PI);
gradient.addi(parameters.mul(2));
Gradient g = new DefaultGradient(this.gradientView);
g.gradientForVariable().put("W", this.gradientView);
this.gradient = g;
//If any parameters are outside range [-5.12,5.12]: score = infinity
INDArray paramExceeds512 = parameters.cond(new Condition() {
@Override
public int condtionNum() {
return 0;
}
@Override
public double getValue() {
return 0;
}
@Override
public Boolean apply(Number input) {
return Math.abs(input.doubleValue()) > 5.12;
}
@Override
public Boolean apply(IComplexNumber input) {
throw new UnsupportedOperationException();
}
});
int nExceeds512 = paramExceeds512.sum(Integer.MAX_VALUE).getInt(0);
if (nExceeds512 > 0)
this.score = Double.POSITIVE_INFINITY;
//Otherwise:
double costFn = 10 * parameters.length();
costFn += Nd4j.getBlasWrapper().dot(parameters, parameters); //xi*xi
INDArray temp = parameters.mul(2.0 * Math.PI);
Nd4j.getExecutioner().exec(new Cos(temp));
temp.muli(-10.0); //After this: each element is -10*cos(2*Pi*xi)
costFn += temp.sum(Integer.MAX_VALUE).getDouble(0);
this.score = costFn;
this.gradientView.assign(gradient);
}
@Override
public int numParams(boolean backwards) {
return 0;
}
@Override
public void setParamsViewArray(INDArray params) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void setBackpropGradientsViewArray(INDArray gradients) {
throw new UnsupportedOperationException();
}
@Override
public void applyLearningRateScoreDecay() {
}
@Override
public void setCacheMode(CacheMode mode) {
throw new UnsupportedOperationException();
}
@Override
public void setListeners(IterationListener... listeners) {
}
@Override
public int getIndex() {
return 0;
}
@Override
public void setInput(INDArray input) {
}
@Override
public boolean isPretrainLayer() {
return false;
}
}
//==================================================
// Rosenbrock Function Optimizer Tests
@Test
public void testRosenbrockFnOptLineGradDescentMultipleSteps() {
testRosenbrockFnMultipleStepsHelper(OptimizationAlgorithm.LINE_GRADIENT_DESCENT, 20, 20);
}
@Test
public void testRosenbrockFnOptCGMultipleSteps() {
testRosenbrockFnMultipleStepsHelper(OptimizationAlgorithm.CONJUGATE_GRADIENT, 20, 20);
}
@Test
public void testRosenbrockFnOptLBFGSMultipleSteps() {
testRosenbrockFnMultipleStepsHelper(OptimizationAlgorithm.LBFGS, 20, 20);
}
private static void testRosenbrockFnMultipleStepsHelper(OptimizationAlgorithm oa, int nOptIter,
int maxNumLineSearchIter) {
double[] scores = new double[nOptIter + 1];
for (int i = 0; i <= nOptIter; i++) {
NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder()
.maxNumLineSearchIterations(maxNumLineSearchIter).iterations(i)
.stepFunction(new org.deeplearning4j.nn.conf.stepfunctions.NegativeDefaultStepFunction())
.learningRate(1e-1).layer(new RBM.Builder().nIn(1).nOut(1).updater(Updater.SGD).build())
.build();
conf.addVariable("W"); //Normally done by ParamInitializers, but obviously that isn't done here
Model m = new RosenbrockFunctionModel(100, conf);
if (i == 0) {
m.computeGradientAndScore();
scores[0] = m.score(); //Before optimization
} else {
ConvexOptimizer opt = getOptimizer(oa, conf, m);
opt.optimize();
m.computeGradientAndScore();
scores[i] = m.score();
assertTrue("NaN or infinite score: " + scores[i],
!Double.isNaN(scores[i]) && !Double.isInfinite(scores[i]));
}
}
if (PRINT_OPT_RESULTS) {
System.out.println("Rosenbrock: Multiple optimization iterations ( " + nOptIter
+ " opt. iter.) score vs iteration, maxNumLineSearchIter= " + maxNumLineSearchIter + ": "
+ oa);
System.out.println(Arrays.toString(scores));
}
for (int i = 1; i < scores.length; i++) {
if (i == 1) {
assertTrue(scores[i] < scores[i - 1]); //Require at least one step of improvement
} else {
assertTrue(scores[i] <= scores[i - 1]);
}
}
}
/**Rosenbrock function: a multi-dimensional 'valley' type function.
* Has a single local/global minimum of f(x)=0 at x_i=1 for all x_i.
* Expect gradient-based optimization functions to find global minimum eventually,
* but optimization may be slow due to nearly flat gradient along valley.
* Restricted here to the range [-5,5]. This implementation gives infinite cost/score
* if any parameter is outside of this range.
* Parameters initialized in range [-4,4]
* See: http://www.sfu.ca/~ssurjano/rosen.html
*/
private static class RosenbrockFunctionModel extends SimpleOptimizableModel {
private static final long serialVersionUID = -5129494342531033706L;
private RosenbrockFunctionModel(int nDimensions, NeuralNetConfiguration conf) {
super(initParams(nDimensions), conf);
}
private static INDArray initParams(int nDimensions) {
Random rng = new DefaultRandom(12345L);
org.nd4j.linalg.api.rng.distribution.Distribution dist =
new org.nd4j.linalg.api.rng.distribution.impl.UniformDistribution(rng, -4.0, 4.0);
return dist.sample(new int[] {1, nDimensions});
}
@Override
public void computeGradientAndScore() {
int nDims = parameters.length();
INDArray gradient = Nd4j.zeros(nDims);
double x0 = parameters.getDouble(0);
double x1 = parameters.getDouble(1);
double g0 = -400 * x0 * (x1 - x0 * x0) + 2 * (x0 - 1);
gradient.put(0, 0, g0);
for (int i = 1; i < nDims - 1; i++) {
double xim1 = parameters.getDouble(i - 1);
double xi = parameters.getDouble(i);
double xip1 = parameters.getDouble(i + 1);
double g = 200 * (xi - xim1 * xim1) - 400 * xi * (xip1 - xi * xi) + 2 * (xi - 1);
gradient.put(0, i, g);
}
double xl = parameters.getDouble(nDims - 1);
double xlm1 = parameters.getDouble(nDims - 2);
double gl = 200 * (xl - xlm1 * xlm1);
gradient.put(0, nDims - 1, gl);
Gradient g = new DefaultGradient();
g.gradientForVariable().put("W", gradient);
this.gradient = g;
INDArray paramExceeds5 = parameters.cond(new Condition() {
@Override
public int condtionNum() {
return 0;
}
@Override
public double getValue() {
return 0;
}
@Override
public Boolean apply(Number input) {
return Math.abs(input.doubleValue()) > 5.0;
}
@Override
public Boolean apply(IComplexNumber input) {
throw new UnsupportedOperationException();
}
});
int nExceeds5 = paramExceeds5.sum(Integer.MAX_VALUE).getInt(0);
if (nExceeds5 > 0)
this.score = Double.POSITIVE_INFINITY;
else {
double score = 0.0;
for (int i = 0; i < nDims - 1; i++) {
double xi = parameters.getDouble(i);
double xi1 = parameters.getDouble(i + 1);
score += 100.0 * Math.pow((xi1 - xi * xi), 2.0) + (xi - 1) * (xi - 1);
}
this.score = score;
}
}
@Override
public int numParams(boolean backwards) {
return 0;
}
@Override
public void setParamsViewArray(INDArray params) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void setBackpropGradientsViewArray(INDArray gradients) {
throw new UnsupportedOperationException();
}
@Override
public void applyLearningRateScoreDecay() {
}
@Override
public void setCacheMode(CacheMode mode) {
throw new UnsupportedOperationException();
}
@Override
public void setListeners(IterationListener... listeners) {
}
@Override
public int getIndex() {
return 0;
}
@Override
public void setInput(INDArray input) {
}
@Override
public boolean isPretrainLayer() {
return false;
}
}
/** Simple abstract class to deal with the fact that we don't care about the majority of the Model/Layer
* methods here. Classes extending this model for optimizer tests need only implement the score() and
* gradient() methods.
*/
private static abstract class SimpleOptimizableModel implements Model, Layer {
private static final long serialVersionUID = 4409380971404019303L;
protected INDArray parameters;
protected INDArray gradientView;
protected final NeuralNetConfiguration conf;
protected Gradient gradient;
protected double score;
/**@param parameterInit Initial parameters. Also determines dimensionality of problem. Should be row vector.
*/
private SimpleOptimizableModel(INDArray parameterInit, NeuralNetConfiguration conf) {
this.parameters = parameterInit.dup();
this.gradientView = Nd4j.create(parameterInit.shape());
this.conf = conf;
}
@Override
public void addListeners(IterationListener... listener) {
// no-op
}
/**
* Init the model
*/
@Override
public void init() {
}
@Override
public INDArray preOutput(INDArray x, TrainingMode training) {
return null;
}
@Override
public INDArray activate(TrainingMode training) {
return null;
}
@Override
public INDArray activate(INDArray input, TrainingMode training) {
return null;
}
@Override
public int getIndex() {
return 0;
}
@Override
public void setInput(INDArray input) {
}
@Override
public void fit() {
throw new UnsupportedOperationException();
}
@Override
public void update(INDArray gradient, String paramType) {
if (!"W".equals(paramType))
throw new UnsupportedOperationException();
parameters.subi(gradient);
}
@Override
public void setListeners(IterationListener... listeners) {
}
@Override
public void update(Gradient gradient) {
}
@Override
public INDArray preOutput(INDArray x, boolean training) {
return null;
}
@Override
public INDArray activate(boolean training) {
return null;
}
@Override
public INDArray activate(INDArray input, boolean training) {
return null;
}
@Override
public double score() {
return score;
}
@Override
public Gradient gradient() {
return gradient;
}
@Override
public double calcL2(boolean backpropParamsOnly) {
return 0;
}
@Override
public double calcL1(boolean backpropParamsOnly) {
return 0;
}
@Override
public void computeGradientAndScore() {
throw new UnsupportedOperationException("Ensure you implement this function.");
}
@Override
public void accumulateScore(double accum) {
throw new UnsupportedOperationException();
}
@Override
public INDArray params() {
return parameters;
}
@Override
public int numParams() {
return parameters.length();
}
@Override
public void setParams(INDArray params) {
this.parameters = params;
}
@Override
public void fit(INDArray data) {
throw new UnsupportedOperationException();
}
@Override
public void iterate(INDArray input) {
throw new UnsupportedOperationException();
}
@Override
public Pair<Gradient, Double> gradientAndScore() {
computeGradientAndScore();
return new Pair<>(gradient(), score());
}
@Override
public int batchSize() {
return 1;
}
@Override
public NeuralNetConfiguration conf() {
return conf;
}
@Override
public void setConf(NeuralNetConfiguration conf) {
throw new UnsupportedOperationException();
}
@Override
public INDArray input() {
//Work-around for BaseUpdater.postApply(): Uses Layer.input().size(0)
//in order to get mini-batch size. i.e., divide by 1 here.
return Nd4j.zeros(1);
}
@Override
public void validateInput() {}
@Override
public ConvexOptimizer getOptimizer() {
throw new UnsupportedOperationException();
}
@Override
public INDArray getParam(String param) {
return parameters;
}
@Override
public void initParams() {
throw new UnsupportedOperationException();
}
@Override
public Map<String, INDArray> paramTable() {
return Collections.singletonMap("W", getParam("W"));
}
@Override
public Map<String, INDArray> paramTable(boolean backpropParamsOnly) {
return paramTable();
}
@Override
public void setParamTable(Map<String, INDArray> paramTable) {
throw new UnsupportedOperationException();
}
@Override
public void setParam(String key, INDArray val) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Type type() {
throw new UnsupportedOperationException();
}
@Override
public Gradient error(INDArray input) {
throw new UnsupportedOperationException();
}
@Override